repo_name
stringlengths 5
92
| path
stringlengths 4
232
| copies
stringclasses 19
values | size
stringlengths 4
7
| content
stringlengths 721
1.04M
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 15
997
| alpha_frac
float64 0.25
0.97
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|
wangheda/youtube-8m | youtube-8m-wangheda/all_frame_models/cnn_lstm_memory_multitask_model.py | 1 | 4575 | import sys
import models
import model_utils
import math
import numpy as np
import video_level_models
import tensorflow as tf
import utils
import tensorflow.contrib.slim as slim
from tensorflow import flags
FLAGS = flags.FLAGS
class CnnLstmMemoryMultiTaskModel(models.BaseModel):
def cnn(self,
model_input,
l2_penalty=1e-8,
num_filters = [1024, 1024, 1024],
filter_sizes = [1,2,3],
**unused_params):
max_frames = model_input.get_shape().as_list()[1]
num_features = model_input.get_shape().as_list()[2]
shift_inputs = []
for i in xrange(max(filter_sizes)):
if i == 0:
shift_inputs.append(model_input)
else:
shift_inputs.append(tf.pad(model_input, paddings=[[0,0],[i,0],[0,0]])[:,:max_frames,:])
cnn_outputs = []
for nf, fs in zip(num_filters, filter_sizes):
sub_input = tf.concat(shift_inputs[:fs], axis=2)
sub_filter = tf.get_variable("cnn-filter-len%d"%fs, shape=[num_features*fs, nf], dtype=tf.float32,
initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.1),
regularizer=tf.contrib.layers.l2_regularizer(l2_penalty))
cnn_outputs.append(tf.einsum("ijk,kl->ijl", sub_input, sub_filter))
cnn_output = tf.concat(cnn_outputs, axis=2)
return cnn_output
def create_model(self, model_input, vocab_size, num_frames, **unused_params):
"""Creates a model which uses a stack of LSTMs to represent the video.
Args:
model_input: A 'batch_size' x 'max_frames' x 'num_features' matrix of
input features.
vocab_size: The number of classes in the dataset.
num_frames: A vector of length 'batch' which indicates the number of
frames for each video (before padding).
Returns:
A dictionary with a tensor containing the probability predictions of the
model in the 'predictions' key. The dimensions of the tensor are
'batch_size' x 'num_classes'.
"""
lstm_size = int(FLAGS.lstm_cells)
number_of_layers = FLAGS.lstm_layers
max_frames = model_input.get_shape().as_list()[1]
cnn_output = self.cnn(model_input, num_filters=[1024,1024,1024], filter_sizes=[1,2,3])
normalized_cnn_output = tf.nn.l2_normalize(cnn_output, dim=2)
## Batch normalize the input
stacked_lstm = tf.contrib.rnn.MultiRNNCell(
[
tf.contrib.rnn.BasicLSTMCell(
lstm_size, forget_bias=1.0, state_is_tuple=True)
for _ in range(number_of_layers)
],
state_is_tuple=True)
loss = 0.0
with tf.variable_scope("RNN"):
outputs, state = tf.nn.dynamic_rnn(stacked_lstm, normalized_cnn_output,
sequence_length=num_frames,
swap_memory=FLAGS.rnn_swap_memory,
dtype=tf.float32)
final_state = tf.concat(map(lambda x: x.c, state), axis = 1)
mask = self.get_mask(max_frames, num_frames)
mean_cnn_output = tf.einsum("ijk,ij->ik", normalized_cnn_output, mask) \
/ tf.expand_dims(tf.cast(num_frames, dtype=tf.float32), dim=1)
support_model = getattr(video_level_models,
FLAGS.video_level_classifier_support_model)
support_predictions = support_model().create_model(
model_input=mean_cnn_output,
original_input=model_input,
vocab_size=vocab_size,
num_mixtures=2,
sub_scope="support",
**unused_params)
aggregated_model = getattr(video_level_models,
FLAGS.video_level_classifier_model)
predictions = aggregated_model().create_model(
model_input=final_state,
original_input=model_input,
vocab_size=vocab_size,
sub_scope="main",
**unused_params)
return {"predictions": predictions["predictions"],
"support_predictions": support_predictions["predictions"]}
def get_mask(self, max_frames, num_frames):
mask_array = []
for i in xrange(max_frames + 1):
tmp = [0.0] * max_frames
for j in xrange(i):
tmp[j] = 1.0
mask_array.append(tmp)
mask_array = np.array(mask_array)
mask_init = tf.constant_initializer(mask_array)
mask_emb = tf.get_variable("mask_emb", shape = [max_frames + 1, max_frames],
dtype = tf.float32, trainable = False, initializer = mask_init)
mask = tf.nn.embedding_lookup(mask_emb, num_frames)
return mask
| apache-2.0 | 3,650,115,153,585,511,400 | 38.102564 | 105 | 0.609617 | false |
shweta97/pyta | nodes/AsyncFor.py | 1 | 1115 | """
AsyncFor astroid node
Subclass of For astroid node. This node iterates over async code with a for-loop
like syntax. Asynchronous code doesn't wait for an operation to complete,
rather the code executes all operations in one go. Only valid in body of an
AsyncFunctionDef astroid node.
Attributes:
- target (Name | Tuple | List)
- Holds the variable(s) the loop assigns to as a single node.
- iter (Node)
- The single node to be looped over.
- body (List[Node])
- The node to be executed.
- orelse (List[Node] | None)
- Node will execute if the loop finished normally rather than via a
break statement.
Example:
- target -> Name(id='a', ctx=Store())
- iter -> Name(id='b', ctx=Load())
- body -> [If(test=Compare(left=Name(id='a', ctx=Load()), ops=[Gt()],
comparators=[Num(n=5)], [Break()]
- orelse -> [Continue()]
"""
async def fun():
"""Note coroutine function must be declared with async def."""
async for a in b:
if a > 5:
break
else:
continue
| gpl-3.0 | -8,221,801,120,053,697,000 | 31.794118 | 80 | 0.600897 | false |
protonyx/labtronyx-gui | labtronyxgui/widgets/__init__.py | 1 | 1053 | import Tkinter as Tk
__all__ = ["vw_entry", "vw_info", "vw_plots", "vw_state"]
class vw_Base(Tk.Frame):
PIXELS_PER_X = 30
PIXELS_PER_Y = 40
def __init__(self, master, units_x=8, units_y=1):
Tk.Frame.__init__(self, master, padx=2, pady=2, bd=1)
width = units_x * self.PIXELS_PER_X
height = units_y * self.PIXELS_PER_Y
self.config(width=width, height=height)
self.pack_propagate(0)
self.update_interval = None
def _schedule_update(self):
if self.update_interval is not None:
self.after(self.update_interval, self.e_update)
else:
try:
self.after(100, self.cb_update)
except:
pass
def e_update(self):
"""
Event to handle self-updating
"""
self.cb_update()
if self.update_interval is not None:
self._schedule_update()
def cb_update(self):
raise NotImplementedError | mit | 230,870,695,671,665,180 | 26.025641 | 61 | 0.51567 | false |
YeEmrick/learning | stanford-tensorflow/2017/examples/02_lazy_loading.py | 1 | 1199 | """ Example to demonstrate how the graph definition gets
bloated because of lazy loading
Author: Chip Huyen
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
cs20si.stanford.edu
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
########################################
## NORMAL LOADING ##
## print out a graph with 1 Add node ##
########################################
x = tf.Variable(10, name='x')
y = tf.Variable(20, name='y')
z = tf.add(x, y)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('./graphs/l2', sess.graph)
for _ in range(10):
sess.run(z)
print(tf.get_default_graph().as_graph_def())
writer.close()
########################################
## LAZY LOADING ##
## print out a graph with 10 Add nodes##
########################################
x = tf.Variable(10, name='x')
y = tf.Variable(20, name='y')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
writer = tf.summary.FileWriter('./graphs/l2', sess.graph)
for _ in range(10):
sess.run(tf.add(x, y))
print(tf.get_default_graph().as_graph_def())
writer.close() | apache-2.0 | -5,410,750,033,911,517,000 | 26.906977 | 71 | 0.582152 | false |
awagner83/doctools | doctools.py | 1 | 1692 | """Docblock manipulation utilities."""
from pprint import pformat
def append_to_docs(fn, text):
"""Append text to a functions existing docblock."""
if not text:
return
if fn.__doc__:
min_indent = _getindent(fn.__doc__)
fn.__doc__ = '%s\n\n%s' % (fn.__doc__, _indent(text, min_indent))
else:
fn.__doc__ = text
def append_var_to_docs(fn, label, value):
"""Append text & pformatted value to docblock."""
value_width = 76 - _getindent(fn.__doc__)
append_to_docs(
fn,
"%s:\n%s" % (
label,
_indent(pformat(value, width=value_width))
)
)
def include_docs_from(source_function):
"""Decorator copying documentation from one function onto another."""
def decorator(dest_function):
append_to_docs(dest_function, source_function.__doc__)
return dest_function
return decorator
def _indent(string, indent_level=4):
"""Indent each line by `indent_level` of spaces."""
return '\n'.join('%s%s' % (' '*indent_level, x) for x in
string.splitlines())
def _getindent(string):
try:
lines = string.splitlines()
# drop first line if it has no indent level
if _nspaces(lines[0]) == 0:
lines.pop(0)
indent_levels = (_nspaces(x) for x in lines if x)
return min(indent_levels) or 0
except (AttributeError, ValueError):
# Things that don't look like strings and strings with no
# indentation should report indentation of 0
return 0
def _nspaces(line):
for idx, char in enumerate(line):
if char != ' ':
return idx
| bsd-3-clause | -1,254,345,515,311,567,600 | 25.857143 | 73 | 0.575059 | false |
unor/schemaorg | scripts/buildsitemap.py | 1 | 6607 | #!/usr/bin/env python
import unittest
import os
from os import path, getenv
from os.path import expanduser
import logging # https://docs.python.org/2/library/logging.html#logging-levels
import glob
import argparse
import sys
import csv
from time import gmtime, strftime
sys.path.append( os.getcwd() )
sys.path.insert( 1, 'lib' ) #Pickup libs, rdflib etc., from shipped lib directory
# Ensure that the google.appengine.* packages are available
# in tests as well as all bundled third-party packages.
sdk_path = getenv('APP_ENGINE', expanduser("~") + '/google-cloud-sdk/platform/google_appengine/')
sys.path.insert(0, sdk_path) # add AppEngine SDK to path
import dev_appserver
dev_appserver.fix_sys_path()
from api import *
import rdflib
from rdflib.term import URIRef, Literal
from rdflib.parser import Parser
from rdflib.serializer import Serializer
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import graph_diff
from rdflib.namespace import RDFS, RDF
import threading
from api import setInTestHarness
setInTestHarness(True)
from api import inLayer, read_file, full_path, read_schemas, read_extensions, read_examples, namespaces, DataCache, getMasterStore
from apirdflib import getNss, getRevNss
from apimarkdown import Markdown
from sdordf2csv import sdordf2csv
rdflib.plugin.register("json-ld", Serializer, "rdflib_jsonld.serializer", "JsonLDSerializer")
# Ensure that the google.appengine.* packages are available
# in tests as well as all bundled third-party packages.
import dev_appserver
dev_appserver.fix_sys_path()
TODAY = strftime("%Y-%m-%d",gmtime())
parser = argparse.ArgumentParser()
parser.add_argument("-e","--exclude", default= [[]],action='append',nargs='*', help="Exclude graph(s) [core|extensions|all|bib|auto|meta|{etc} (Repeatable) - 'attic' always excluded")
parser.add_argument("-o","--output", default="docs/sitemap.xml", help="output file (default: docs/sitemap.xml)")
parser.add_argument("-s","--site", default="schema.org", help="site (default: schema.org)")
parser.add_argument("-d","--date", default=TODAY, help="modified date (defaut: %s)" % TODAY)
args = parser.parse_args()
#print "%s: Arguments: %s" % (sys.argv[0],args)
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
#Setup testharness state BEFORE importing sdoapp
import sdoapp
from sdoapp import ENABLED_EXTENSIONS
STATICPAGES = ["docs/schemas.html",
"docs/full.html",
"docs/gs.html",
"docs/about.html",
"docs/howwework.html",
"docs/releases.html",
"docs/faq.html",
"docs/datamodel.html",
"docs/developers.html",
"docs/extension.html",
"docs/meddocs.html",
"docs/hotels.html"]
class SiteMap():
def __init__(self):
self.today = "2017-01-19"
self.count = 0
self.openFile()
self.setSkips()
self.getGraphs()
self.loadGraphs()
self.listStatics()
self.closeFile()
def setSkips(self):
self.skiplist = ['']
for e in args.exclude:
for s in e:
if s == "core":
self.skiplist.append("http://schema.org/")
elif s == "extensions":
for i in sdoapp.ENABLED_EXTENSIONS:
self.skiplist.append(getNss(i))
elif s == "all":
self.skiplist.append("http://schema.org/")
for i in sdoapp.ENABLED_EXTENSIONS:
self.skiplist.append(getNss(i))
else:
self.skiplist.append(getNss(s))
if not getNss('attic') in self.skiplist: #Always skip attic by defualt
self.skiplist.append(getNss('attic'))
def openFile(self):
hdr = """<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
"""
self.file = open(args.output,'w')
self.file.write(hdr)
def closeFile(self):
self.file.write("\n</urlset>")
print("Wrote %s entries to %s" % (self.count,args.output))
self.file.close()
def getGraphs(self):
self.store = getMasterStore()
self.fullGraph = getQueryGraph()
read_schemas(loadExtensions=True)
read_extensions(sdoapp.ENABLED_EXTENSIONS)
self.graphs = list(self.store.graphs())
def loadGraphs(self):
self.outGraph = rdflib.ConjunctiveGraph()
gs = sorted(list(self.store.graphs()),key=lambda u: u.identifier)
for g in gs: #Put core first
if str(g.identifier) == "http://schema.org/":
gs.remove(g)
gs.insert(0,g)
break
for g in gs:
id = str(g.identifier)
if not id.startswith("http://"):#skip some internal graphs
continue
if id not in self.skiplist:
print("%s: Processing: %s (%s) " % (sys.argv[0],id,len(g)))
self.list(g)
self.access("",g.identifier)
def list(self, graph):
types = {}
props = {}
exts = []
for (s,p,o) in graph.triples((None,RDF.type,RDFS.Class)):
if s.startswith("http://schema.org"):
types.update({s:graph.identifier})
for t in sorted(types.keys()):
self.access(t,types[t])
for (s,p,o) in graph.triples((None,RDF.type,RDF.Property)):
if s.startswith("http://schema.org"):
props.update({s:graph.identifier})
for p in sorted(props.keys()):
self.access(p,props[p])
def listStatics(self):
for s in STATICPAGES:
self.access(s,"http://schema.org")
def access(self, id, ext):
if id.startswith("http://schema.org"):
id = id[18:]
ext = getRevNss(str(ext))
if ext == "core" or ext == "":
ext = ""
else:
ext = ext + "."
site = args.site
scheme = "http://"
if site.startswith("http://"):
site = site[7:]
elif site.startswith("https://"):
site = site[8:]
scheme = "https://"
#log.info("%s %s %s %s" % (scheme,ext,site,id))
path = "%s%s%s/%s" % (scheme,ext,site,id)
#log.info(path)
self.outputEntry(path)
def outputEntry(self,path,update=None):
if not update:
update = self.today
entry = """ <url>
<loc>%s</loc>
<lastmod>%s</lastmod>
</url>""" % (path,update)
self.output(entry)
def output(self,txt):
self.count +=1
self.file.write(txt)
if __name__ == "__main__":
ex = SiteMap()
| apache-2.0 | 4,015,487,790,302,308,000 | 29.307339 | 184 | 0.603602 | false |
beeftornado/sentry | src/sentry/deletions/defaults/organization.py | 1 | 2027 | from __future__ import absolute_import, print_function
from ..base import ModelDeletionTask, ModelRelation
class OrganizationDeletionTask(ModelDeletionTask):
def get_child_relations(self, instance):
from sentry.models import (
OrganizationMember,
Commit,
CommitAuthor,
CommitFileChange,
Environment,
Release,
ReleaseCommit,
ReleaseEnvironment,
ReleaseFile,
Distribution,
ReleaseHeadCommit,
Repository,
Team,
Project,
PullRequest,
Dashboard,
ExternalIssue,
PromptsActivity,
)
from sentry.incidents.models import AlertRule, Incident
from sentry.discover.models import DiscoverSavedQuery, KeyTransaction
# Team must come first
relations = [ModelRelation(Team, {"organization_id": instance.id})]
model_list = (
OrganizationMember,
CommitFileChange,
Commit,
PullRequest,
CommitAuthor,
Environment,
Repository,
Project,
Release, # Depends on Group deletions, a child of Project
ReleaseCommit,
ReleaseEnvironment,
ReleaseFile,
Distribution,
ReleaseHeadCommit,
Dashboard,
DiscoverSavedQuery,
KeyTransaction,
ExternalIssue,
PromptsActivity,
Incident,
AlertRule,
)
relations.extend([ModelRelation(m, {"organization_id": instance.id}) for m in model_list])
return relations
def mark_deletion_in_progress(self, instance_list):
from sentry.models import OrganizationStatus
for instance in instance_list:
if instance.status != OrganizationStatus.DELETION_IN_PROGRESS:
instance.update(status=OrganizationStatus.DELETION_IN_PROGRESS)
| bsd-3-clause | 4,699,830,374,963,154,000 | 29.712121 | 98 | 0.578688 | false |
shomy4/SuperKamp | reports/views.py | 1 | 20515 | from django.contrib.auth.decorators import login_required
from datetime import datetime
from django.shortcuts import render, redirect
from reports.forms import ReportChildrenPerMentorAndDestinationForm, ReportChildrenPerSchoolByDestinationAndShiftForm, \
ReportPaymentsByDateAndTypeForm, SumsByDestinationForm, \
Fin1Form, Fin2Form, Fin3Form, Fin4Form, Fin5Form, Fin6Form, Fin7Form, \
RoomingForm, D1, D2, D3, D4, D5, D6, D7, D8, SortingCashOnly, SortingMix, Revenue, Insuref1Form, Insuref2Form, \
ShirtsPerMentorAndShift
from reports import jasper_manager as jasper
from parameters.models import ParLine
from parameters import system_tables as ptables
@login_required
def show_reports(request):
reports = {
'/reports/children_per_mentor_and_destination': 'Deca na osnovu mentora i destinacije',
'/reports/hotel': 'Hotel',
'/reports/children_per_scholl_by_destination_and_shift': 'Deca na osnovu destinacije i smene',
'/reports/payments_by_date_and_type': 'Uplate na osnovu datuma i tipa',
'/reports/sums_by_destination': 'Suma na osnovu destinacije',
'/reports/rooming': 'Rooming',
'/reports/d1': "Kontakti nastavnika",
'/reports/d2': 'Nastavnici po smenama',
'/reports/d3': 'Nevracene uplate',
'/reports/d4': 'Popunjenost smena',
'/reports/d5': 'Brojno stanje dece po skolama',
'/reports/d6': 'Odustanci',
'/reports/d7': 'Naplata po smenama',
'/reports/d8': 'Prevoz',
'/reports/sorting_cash_only': 'Sortiranje - samo kes',
'/reports/sorting_mix': 'Sortiranje - mesovito',
'/reports/revenue': 'Prihodi',
'/reports/shirts_per_mentor_and_shift': 'Broj majica po smeni i nastavniku'
}
context = {'reports': reports}
return render(request, 'reports/show_reports.html', context)
def children_per_mentor_and_destination(request):
form = ReportChildrenPerMentorAndDestinationForm()
context = {'form' : form}
return render(request, 'reports/children_per_mentor_and_destination.html', context)
def children_per_mentor_and_destination_report(request, mentor='', destination=''):
if request.method == 'POST':
mentor = request.POST.get("mentor", "")
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("children_per_teacher_and_destination", report_type, {"DESTINATION_ID":destination, "MENTOR_ID":mentor, "SHIFT_ID":shift}))
def children_per_scholl_by_destination_and_shift(request):
form = ReportChildrenPerSchoolByDestinationAndShiftForm()
context = {'form' : form}
return render(request, 'reports/children_per_scholl_by_destination_and_shift.html', context)
def children_per_scholl_by_destination_and_shift_report(request, destination='', shift=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("Children_per_scholl_by_destination_and_shift", report_type, {"DESTINATION_ID":destination, "SHIFT_ID":shift}))
def payments_by_date_and_type(request):
form = ReportPaymentsByDateAndTypeForm()
context = {'form' : form}
return render(request, 'reports/payments_by_date_and_type.html', context)
def payments_by_date_and_type_report(request, destination='', shift=''):
if request.method == 'POST':
payment_type = request.POST.get("payment_type", "")
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
report_type = request.POST.get("report_type", "")
start_date = datetime.strptime(start_date, '%m/%d/%Y').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%m/%d/%Y').strftime("%m%d%Y")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("payments_by_date_and_type", report_type, {"PAYMENT_METHOD":payment_type, "DATE_START":start_date, "DATE_END":end_date}))
def sums_by_destination(request):
form = SumsByDestinationForm()
context = {'form': form}
return render(request, 'reports/sums_by_destination.html', context)
def sums_by_destination_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("sums_by_destination", report_type,
{"DESTINATION_ID": destination}))
def fin1(request):
form = Fin1Form()
context = {'form': form}
return render(request, 'reports/fin1.html', context)
def fin1_report(request, start_date='', end_date=''):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%d.%m.%Y.').strftime("%m%d%Y")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("fin1", report_type,
{"DATE_START":start_date, "DATE_END":end_date}))
def fin2(request):
form = Fin2Form()
context = {'form': form}
return render(request, 'reports/fin2.html', context)
def fin2_report(request, start_date=''):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("fin2", report_type,
{"DATE_START":start_date}))
def fin3(request):
form = Fin3Form()
context = {'form': form}
return render(request, 'reports/fin3.html', context)
def fin3_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
#money_return_border = ParLine.objects.filter(table_no=ptables.PT_9).order_by('-line_num2')[:1][0].line_num3
return (jasper.generateReport("fin3", report_type,
{"DESTINATION_ID": destination}))
def fin4(request):
form = Fin4Form()
context = {'form': form}
return render(request, 'reports/fin4.html', context)
def fin4_report(request, start_date=''):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%d.%m.%Y.').strftime("%m%d%Y")
report_type = request.POST.get("report_type", "")
creator_id = 9 # Dragana's user ID
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("fin4", report_type,
{"DATE_START": start_date,
"DATE_END": end_date,
"CREATOR_ID": creator_id}))
def fin5(request):
form = Fin5Form()
context = {'form': form}
return render(request, 'reports/fin5.html', context)
def fin5_report(request, start_date=''):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%d.%m.%Y.').strftime("%m%d%Y")
report_type = request.POST.get("report_type", "")
creator_id = 4 # Ana's user ID
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("fin5", report_type,
{"DATE_START": start_date,
"DATE_END": end_date,
"CREATOR_ID": creator_id}))
def fin6(request):
form = Fin6Form()
context = {'form': form}
return render(request, 'reports/fin6.html', context)
def fin6_report(request, start_date=''):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%d.%m.%Y.').strftime("%m%d%Y")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("fin6", report_type,
{"DATE_START": start_date,
"DATE_END": end_date}))
def fin7(request):
form = Fin7Form()
context = {'form': form}
return render(request, 'reports/fin7.html', context)
def fin7_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("fin7", report_type,
{"DESTINATION_ID": destination}))
def rooming(request):
form = RoomingForm()
context = {'form': form}
return render(request, 'reports/rooming.html', context)
def rooming_report(request, destination='', shift=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("rooming", report_type,
{"DESTINATION_ID": destination,
"SHIFT_ID": shift}))
def d1(request):
form = D1()
context = {'form' : form}
return render(request, 'reports/d1.html', context)
def d1_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "-1")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("mentors_data_and_contacts_by_shift", report_type,
{"DESTINATION_ID": destination, "SHIFT_ID": shift})
def d2(request):
form = D2()
context = {'form': form}
return render(request, 'reports/d2.html', context)
def d2_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("count_child_by_shift", report_type, {"DESTINATION_ID": destination})
def d3(request):
form = D3()
context = {'form' : form}
return render(request, 'reports/d3.html', context)
def d3_report(request, ):
if request.method == 'POST':
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("unreturned_payments", report_type, {})
def d4(request):
form = D4()
context = {'form' : form}
return render(request, 'reports/d4.html', context)
def d4_report(request, ):
if request.method == 'POST':
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("shift_occupancy", report_type, {})
def d5(request):
form = D5()
context = {'form': form}
return render(request, 'reports/d5.html', context)
def d5_report(request, school=''):
if request.method == 'POST':
school = request.POST.get("school", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no=ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("children_per_school", report_type,
{"SCHOOL_ID": school}))
def d6(request):
form = D6()
context = {'form' : form}
return render(request, 'reports/d6.html', context)
def d6_report(request, ):
if request.method == 'POST':
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("canceled_contracts", report_type, {})
def d7(request):
form = D7()
context = {'form' : form}
return render(request, 'reports/d7.html', context)
def d7_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "-1")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("payments_by_shift", report_type,
{"DESTINATION_ID": destination, "SHIFT_ID": shift})
def d8(request):
form = D8()
context = {'form' : form}
return render(request, 'reports/d8.html', context)
def d8_report(request, ):
if request.method == 'POST':
destination = request.POST.get("destination", "-1")
if destination == '':
destination = '-1'
shift = request.POST.get("shift", "-1")
if shift == '':
shift = '-1'
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("transport_report", report_type,
{"DESTINATION_ID": destination, "SHIFT_ID": shift})
def sorting_cash_only(request):
form = SortingCashOnly()
context = {'form' : form}
return render(request, 'reports/sorting_cash_only.html', context)
def sorting_cash_only_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
course_rate = request.POST.get("course_rate", "1")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("sorting_cash_only", report_type,
{"DESTINATION_ID": destination, "SHIFT_ID": shift, "COURSE_RATE" :course_rate})
def sorting_mix(request):
form = SortingMix()
context = {'form' : form}
return render(request, 'reports/sorting_mix.html', context)
def sorting_mix_report(request, destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
course_rate = request.POST.get("course_rate", "1")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("sorting_mix", report_type,
{"DESTINATION_ID": destination, "SHIFT_ID": shift, "COURSE_RATE" :course_rate})
def revenue(request):
form = Revenue()
context = {'form' : form}
return render(request, 'reports/revenue.html', context)
def revenue_report(request, ):
if request.method == 'POST':
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("revenue", report_type, {})
def insuref_1(request):
form = Insuref1Form()
context = {'form' : form}
return render(request, 'reports/insuref_1.html', context)
def insuref_1_report(request, ):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%d.%m.%Y.').strftime("%m%d%Y")
licence_number = request.POST.get("licence_number", "")
subject_name = request.POST.get("subject_name", "")
place_of_sale = request.POST.get("place_of_sale", "")
number_of_travelers = request.POST.get("number_of_travelers", "1")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("insuref_report_1", report_type, {
"DATE_START": start_date,
"DATE_END": end_date,
"LICENCE_NUMBER": licence_number,
"SUBJECT_NAME": subject_name,
"PLACE_OF_SALE": place_of_sale,
"NUMBER_OF_TRAVELERS": number_of_travelers
})
def insuref_2(request):
form = Insuref2Form()
context = {'form' : form}
return render(request, 'reports/insuref_2.html', context)
def insuref_2_report(request, ):
if request.method == 'POST':
start_date = request.POST.get("start_date", "")
end_date = request.POST.get("end_date", "")
start_date = datetime.strptime(start_date, '%d.%m.%Y.').strftime("%m%d%Y")
end_date = datetime.strptime(end_date, '%d.%m.%Y.').strftime("%m%d%Y")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return jasper.generateReport("insuref_report_2", report_type, {
"DATE_START": start_date,
"DATE_END": end_date,
})
def shirts_per_mentor_and_shift(request):
form = ShirtsPerMentorAndShift()
context = {'form' : form}
return render(request, 'reports/shirts_per_mentor_and_shift.html', context)
def shirts_per_mentor_and_shift_report(request, mentor='', destination=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
report_type = request.POST.get("report_type", "")
attribute_id = 4
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("shirts_per_mentor_and_shift", report_type, {"DESTINATION_ID": destination,
"ATTRIBUTE_ID": attribute_id,
"SHIFT_ID": shift}))
def hotel(request):
form = ShirtsPerMentorAndShift()
context = {'form' : form}
return render(request, 'reports/hotel.html', context)
def hotel_report(request, destination='', shift=''):
if request.method == 'POST':
destination = request.POST.get("destination", "")
shift = request.POST.get("shift", "")
report_type = request.POST.get("report_type", "")
report_type = ParLine.objects.get(table_no = ptables.PT_14, line_no=report_type).line_alpha1
return (jasper.generateReport("hotel", report_type, {"DESTINATION_ID": destination,
"SHIFT_ID": shift}))
| gpl-3.0 | -6,745,491,547,197,507,000 | 38.990253 | 157 | 0.624275 | false |
mareknetusil/twist | cbc/twist/problem_definitions.py | 1 | 7987 | __author__ = "Harish Narayanan"
__copyright__ = "Copyright (C) 2009 Simula Research Laboratory and %s" % __author__
__license__ = "GNU GPL Version 3 or any later version"
import fenics
from cbc.common import CBCProblem
from cbc.twist.solution_algorithms_static import StaticMomentumBalanceSolver_U
from cbc.twist.solution_algorithms_dynamic import CG1MomentumBalanceSolver
# from cbc.twist.solution_algorithms_static import \
# default_parameters as solver_parameters_static
# from cbc.twist.solution_algorithms_dynamic import \
# default_parameters as solver_parameters_dynamic
from cbc.common.CBCSolver import default_parameters as solver_parameters_static
solver_parameters_dynamic = solver_parameters_static
from cbc.twist.kinematics import GreenLagrangeStrain
from sys import exit
class StaticHyperelasticity(CBCProblem):
"""Base class for all static hyperelasticity problems"""
def __init__(self):
"""Create the static hyperelasticity problem"""
# Set up parameters
self.parameters = solver_parameters_static()
def solve(self):
"""Solve for and return the computed displacement field, u"""
# Create solver
formulation = self.parameters['problem_formulation']
if formulation == 'displacement':
self.solver = StaticMomentumBalanceSolver_U(self, self.parameters)
else:
fenics.error("%s formulation not supported." % formulation)
# Call solver
return self.solver.solve()
def body_force(self):
"""Return body force, B"""
return []
def body_force_u(self, u):
# FIXME: This is currently only implemented for the cG(1) solver
"""Return body force, B, depending on displacement u"""
return []
def dirichlet_values(self):
"""Return Dirichlet boundary conditions for the displacement field"""
return []
def dirichlet_boundaries(self):
"""Return boundaries over which Dirichlet conditions act"""
return []
def neumann_conditions(self):
"""Return Neumann boundary conditions for the stress field"""
return []
def neumann_boundaries(self):
"""Return boundaries over which Neumann conditions act"""
return []
def periodic_boundaries(self):
""" Return periodic boundaries """
return []
def material_model(self):
pass
def first_pk_stress(self, u):
"""Return the first Piola-Kirchhoff stress tensor, P, given a
displacement field, u"""
material_model = self.material_model()
if isinstance(material_model, tuple):
fpk_list = []
material_list, subdomains_list = material_model
for material in material_list:
fpk_list.append(material.first_pk_stress(u))
return fpk_list, subdomains_list
else:
return material_model.first_pk_stress(u)
def second_pk_stress(self, u):
"""Return the second Piola-Kirchhoff stress tensor, S, given a
displacement field, u"""
material_model = self.material_model()
if isinstance(material_model, tuple):
spk_list = []
material_list, subdomains_list = material_model
for material in material_list:
spk_list.append(material.second_pk_stress(u))
return spk_list, subdomains_list
else:
return self.material_model().second_pk_stress(u)
def strain_energy(self, u):
"""Return the strain (potential) energy density given a displacement
field, u"""
S = self.second_pk_stress(u)
E = GreenLagrangeStrain(u)
if isinstance(S, tuple):
S_list, subdomains_list = S
V = fenics.FunctionSpace(u.function_space().mesh(), 'DG', 0)
temp = fenics.Function(V)
psi = fenics.Function(V)
subdomains = subdomains_list[0]
for cell_no in range(len(subdomains[0].array())):
subdomain_no = subdomains[0].array()[cell_no]
temp = fenics.project(0.5 *
fenics.inner(S_list[int(subdomain_no - 1)],
E),
V)
psi.vector()[cell_no] = temp.vector()[cell_no][0]
else:
psi = 0.5 * fenics.inner(S, E)
return psi
def functional(self, u):
"""Return value of goal functional"""
return None
def reference(self):
"""Return reference value for the goal functional"""
return None
def __str__(self):
"""Return a short description of the problem"""
return "Static hyperelasticity problem"
class Hyperelasticity(StaticHyperelasticity):
"""Base class for all quasistatic/dynamic hyperelasticity
problems"""
def __init__(self):
"""Create the hyperelasticity problem"""
# Set up parameters
self.parameters = solver_parameters_dynamic()
# Create solver later
self.solver = None
def solve(self):
"""Solve for and return the computed displacement field, u"""
# Create solver
self._create_solver()
# Update solver parameters
self.solver.parameters.update(self.parameters)
# Call solver
return self.solver.solve()
def step(self, dt):
"Take a time step of size dt"
# Create solver
self._create_solver()
# Update solver parameters
self.solver.parameters.update(self.parameters)
# Call solver
return self.solver.step(dt)
def update(self):
"Propagate values to next time step"
return self.solver.update()
def solution(self):
"Return current solution values"
if self.solver is None:
self._create_solver()
return self.solver.solution()
def end_time(self):
"""Return the end time of the computation"""
pass
def time_step(self):
"""Return the time step size"""
pass
def is_dynamic(self):
"""Return True if the inertia term is to be considered, or
False if it is to be neglected (quasi-static)"""
return False
def time_stepping(self):
"""Set the default time-stepping scheme to
Hilber-Hughes-Taylor"""
return "HHT"
def reference_density(self):
"""Return the reference density of the material"""
return []
def initial_conditions(self):
"""Return initial conditions for displacement field, u0, and
velocity field, v0"""
return [], []
def dirichlet_values(self):
"""Return Dirichlet boundary conditions for the displacment
field"""
return []
def dirichlet_boundaries(self):
"""Return boundaries over which Dirichlet conditions act"""
return []
def neumann_conditions(self):
"""Return Neumann boundary conditions for the stress field"""
return []
def neumann_boundaries(self):
"""Return boundaries over which Neumann conditions act"""
return []
def kinetic_energy(self, v):
"""Return the kinetic energy given a velocity field, v"""
rho0 = self.reference_density()
ke = fenics.assemble(0.5 * rho0 * fenics.inner(v, v) * fenics.dx,
mesh=v.function_space().mesh())
return ke
def _create_solver(self):
"Create solver if not already created"
# Don't create solver if already created
if self.solver is not None: return
# Select solver
scheme = self.time_stepping()
if scheme is "CG1":
fenics.info("Using CG1 time-stepping.")
self.solver = CG1MomentumBalanceSolver(self, self.parameters)
else:
fenics.error("%s time-stepping scheme not supported." % str(
self.time_stepping()))
| gpl-3.0 | -8,395,993,149,155,302,000 | 31.336032 | 83 | 0.608614 | false |
skosukhin/spack | var/spack/repos/builtin/packages/py-unittest2/package.py | 1 | 1734 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PyUnittest2(PythonPackage):
"""unittest2 is a backport of the new features added to the unittest
testing framework in Python 2.7 and onwards."""
homepage = "https://pypi.python.org/pypi/unittest2"
url = "https://pypi.io/packages/source/u/unittest2/unittest2-1.1.0.tar.gz"
version('1.1.0', 'f72dae5d44f091df36b6b513305ea000')
depends_on('py-setuptools', type='build')
depends_on('py-enum34', when='^python@:3.3', type=('build', 'run'))
| lgpl-2.1 | 709,327,743,929,664,300 | 44.631579 | 83 | 0.675317 | false |
wellflat/cat-fancier | tools/clipper/clipper.py | 1 | 3809 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, g, request, render_template
import json
import os
import re
import sqlite3
import time
from pprint import pprint
app = Flask(__name__)
app.config.update(
DATABASE = 'db/samples.db',
#DATABASE = 'db/catcafe.db',
DEBUG = True
)
db = None
samples = None
def getdb():
global db
if db is None:
db = sqlite3.connect(app.config['DATABASE'])
db.row_factory = sqlite3.Row
return db
def querydb(query, args=(), one=False):
cur = getdb().execute(query, args)
rv = cur.fetchall()
cur.close()
return (rv[0] if rv else None) if one else rv
def getsamples(update=False):
global samples
if update or samples is None:
sql = 'SELECT id, filepath FROM samples'
samples = querydb(sql)
return samples
def getpos():
sql = 'SELECT pos FROM progress'
pos = querydb(sql, one=True)['pos']
return pos
def updatepos(pos):
sql = 'UPDATE progress SET pos=?'
db = getdb()
db.execute(sql, (pos,))
db.commit()
def getstatus(pos):
sql = 'SELECT status FROM samples WHERE id=?'
row = querydb(sql, (pos + 1,), one=True)
return (row['status'] if row else None)
def updatecoords(coords, pos):
sql = 'UPDATE samples SET x=?, y=?, width=?, height=?, status=?, updated_date=? WHERE id=?'
db = getdb()
db.execute(sql, (coords['x'], coords['y'], coords['w'], coords['h'], 200, time.strftime('%Y-%m-%d %H:%M:%S'), pos))
db.commit()
@app.route('/clipper')
def index():
message = 'ready to load images ok.'
samples = getsamples()
imgtotal = len(samples)
pos = getpos()
if pos == imgtotal:
message = 'complete !'
return render_template('index.html', progress=100, message=message)
try:
imgsrc = samples[pos]['filepath']
except IndexError as e:
imgsrc = None
status = getstatus(pos)
remain = imgtotal - pos
progress = 1.0*pos/imgtotal*100
return render_template('index.html', imgsrc=imgsrc, imgtotal=imgtotal, pos=pos, status=status, remain=remain, progress=progress, message=message)
@app.route('/clipper/next')
def next():
coords = json.loads(request.args.get('coords'))
isskip = request.args.get('skip')
samples = getsamples()
pos = getpos()
imgtotal = len(samples)
app.logger.debug(coords)
if coords is not None:
updatecoords(coords, pos + 1)
if pos < imgtotal:
pos += 1
updatepos(pos)
try:
imgsrc = samples[pos]['filepath']
except IndexError as e:
imgsrc = None
status = getstatus(pos)
remain = imgtotal - pos
progress = 1.0*pos/imgtotal*100
return jsonify(imgsrc=imgsrc, pos=pos, status=status, remain=remain, progress=progress)
@app.route('/clipper/prev')
def prev():
coords = json.loads(request.args.get('coords'))
samples = getsamples()
pos = getpos()
imgtotal = len(samples)
if pos > 0:
pos -= 1
updatepos(pos)
try:
imgsrc = samples[pos]['filepath']
except IndexError as e:
imgsrc = None
status = getstatus(pos)
remain = imgtotal - pos
progress = 1.0*pos/imgtotal*100
return jsonify(imgsrc=imgsrc, pos=pos, status=status, remain=remain, progress=progress)
@app.route('/clipper/progress', methods=['POST'])
def updateprogress():
pos = json.loads(request.form['pos'])
app.logger.debug(pos)
if pos is not None:
updatepos(pos)
return jsonify(status=200, message='ok')
@app.route('/clipper/sync', methods=['POST'])
def syncdatabase():
getsamples(update=True)
return jsonify(status=200, message='ok')
## main
if __name__ == '__main__':
app.run('0.0.0.0', port=5050)
| mit | -6,340,766,683,487,394,000 | 25.089041 | 149 | 0.615647 | false |
ImaginaryLandscape/iscape-jobboard | jobboard/models.py | 1 | 9517 | ################################################################################
# JobBoard: a simple Django-based job board
# Copyright (c) 2009, Imaginary Landscape
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Imaginary Landscape nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################
import datetime
from django.db import models
from django.conf import settings
################################################################################
## Utility functions
################################################################################
def calculate_post_expires():
"""
Generate an expiration date based on settings.JOBBOARD_POSTS_EXPIRE_DAYS
Returns:
A date object that is JOBBOARD_POSTS_EXPIRE_DAYS in the future
"""
post_expire_days = datetime.timedelta(
days=settings.JOBBOARD_POSTS_EXPIRE_DAYS)
return datetime.date.today() + post_expire_days
def default_position():
if Position.objects.count() == 1:
return Position.objects.all()[0]
else:
return None
################################################################################
## Models
################################################################################
class NotifyEmail(models.Model):
"""
An email address where job post notifications will be sent.
Field attributes:
email: the email address where the notification will be sent
"""
email = models.EmailField()
class Admin:
pass
def __unicode__(self):
return self.email
class Position(models.Model):
"""
An available position for working, be it a cook, waitress or
dental hygenist.
These appear on drop-down forms for those submitting job posts or
applicant posts.
Field Attributes:
name: The name of the position
"""
name = models.CharField(max_length=80)
class Admin:
pass
def __unicode__(self):
return self.name
class JobPost(models.Model):
"""
A post for an available job that people can apply to.
These are usually user-submitted, and then approved by an
administrator. Once they are approved, they should show up on the
job listing until the time they expire.
Field Attributes:
posters_name: The name of the person or company offering the job
work_hours: Whatever kind of hours the person might be working
(9-5, late shift, full time, part time, whatever)
description: Description of this job
position: Any one of the positions in models.Position
email: An email address relevant to this job (probably for
contact purposes)
contact_information: Any other contact information
when_posted: The timestamp for when this post was submitted
approved: Whether or not this application was approved to be
listed on the site.
expiration_date: The date on which this post will no longer show
up on the listing.
"""
approved = models.BooleanField(default=False)
when_posted = models.DateTimeField(default=datetime.datetime.today)
expiration_date = models.DateField(
default=calculate_post_expires,
help_text=(
"This field defaults to "
"%s days from user submission." %
settings.JOBBOARD_POSTS_EXPIRE_DAYS))
posters_name = models.CharField("Poster's name", max_length=80)
work_hours = models.CharField(max_length=80, blank=True)
description = models.TextField(blank=True)
position = models.ForeignKey(Position, default=default_position)
email = models.EmailField('e-mail', blank=True)
contact_information = models.TextField('How to apply')
class Meta:
ordering = ['-when_posted']
class Admin:
fields = (
('Approval Status',
{'fields': ['approved']}),
('Dates',
{'fields': ['when_posted', 'expiration_date']}),
('Details',
{'fields': ['posters_name', 'work_hours',
'description', 'position',
'email', 'contact_information']}))
list_filter = ['approved']
list_display = [
'posters_name', 'position',
'when_posted', 'expiration_date',
'approved']
def __unicode__(self):
return u"%s @ %s" % (
self.posters_name, self.when_posted.strftime('%m-%d-%Y %I:%M%p'))
class ApplicantPost(models.Model):
"""
A post for a person who is seeking employment.
These are usually user-submitted, and then approved by an
administrator. Once they are approved, they should show up on the
job listing until the time they expire.
Field Attributes:
first_name: First name of the person seeking employment
last_name: Last name of the person seeking employment
phone_number: A number at which this person can be contacted
email: An email address at which this person can be contacted
position: Any one of the positions in models.Position
resume: Plaintext version of this person's resume
full_time: Whether or not this person is interested in full time
employment
part_time: Whether or not this person is interested in part time
employment
when_posted: The timestamp for when this post was submitted
approved: Whether or not this application was approved to be
listed on the site.
expiration_date: The date on which this post will no longer show
up on the listing.
"""
approved = models.BooleanField(default=False)
when_posted = models.DateTimeField(default=datetime.datetime.today)
expiration_date = models.DateField(
default=calculate_post_expires,
help_text=(
"This field defaults to "
"%s days from user submission." %
settings.JOBBOARD_POSTS_EXPIRE_DAYS))
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
phone_number = models.CharField('phone', max_length=25)
email = models.EmailField('e-mail', blank=True)
position = models.ForeignKey(Position, default=default_position)
resume = models.TextField()
full_time = models.BooleanField('full-time')
part_time = models.BooleanField('part-time')
class Meta:
ordering = ['-when_posted']
class Admin:
fields = (
('Approval Status',
{'fields': ['approved']}),
('Dates',
{'fields': ['when_posted', 'expiration_date']}),
('Details',
{'fields': ['first_name', 'last_name',
'phone_number', 'email',
'position', 'resume',
'full_time', 'part_time']}))
list_filter = ['approved']
list_display = [
'full_name', 'position',
'when_posted', 'expiration_date',
'approved']
def hours_string(self):
"""
A nice, comma-joined list of the type of hours this person is
interested in.
If the user selected part_time and full_time for example,
this would show up as:
"part time, full_time"
If the user doesn't select anything, it will just return the
string "unspecified".
Returns:
Either a comma-joined string of the hours this person is
interested in, or "unspecified" if the user didn't select
any.
"""
hours = []
if self.full_time:
hours.append('full time')
if self.part_time:
hours.append('part time')
if hours:
return ', '.join(hours)
else:
return 'unspecified'
def __unicode__(self):
return u"%s %s @ %s" % (
self.first_name,
self.last_name,
self.when_posted.strftime('%m-%d-%Y %I:%M%p'))
def full_name(self):
return u"%s %s" % (self.first_name, self.last_name)
| bsd-3-clause | -3,085,676,571,152,319,000 | 35.745174 | 81 | 0.609436 | false |
fragaria/gap-resources | test_resources/run_tests.py | 1 | 1808 | #!/usr/bin/env python
'''
simple shortcut for running nosetests via python
replacement for *.bat or *.sh wrappers
'''
import sys
import os
from copy import copy
from os.path import dirname, realpath, join
import logging
extra_plugins=[]
import re
from gap.utils.setup import fix_sys_path
app_path = join(dirname(realpath(__file__)), 'app')
fix_sys_path(app_path)
os.chdir(dirname(__file__))
sys.path.insert(0, dirname(dirname(realpath(__file__))))
argv = copy(sys.argv)
try:
import nose
import webtest
from nosegae import NoseGAE
except ImportError:
if sys.__stdin__.isatty():
print "Missing testing requirements. Shell I install them for you? [Yn] "
resp = raw_input().strip().lower()
if not resp or resp in ['y', 'a']:
import pip
pip.main(['install', '-r', 'requirements.pip'])
import nose
import webtest
from nosegae import NoseGAE
else:
print "Quitting"
print "You can install requirements by `pip install -r tests/requirements.pip`"
print
sys.exit(255)
else:
raise
from nose.config import Config
from nose.plugins import DefaultPluginManager
CONFIG = Config(
files=['nose.cfg'],
plugins=DefaultPluginManager(plugins=[NoseGAE()])
)
try:
from rednose import RedNose
except ImportError:
pass
else:
extra_plugins.append(RedNose())
argv.append('--rednose')
def run_all():
logging.debug('Running tests with arguments: %r' % sys.argv)
nose.run_exit(
argv=argv,
config=CONFIG,
addplugins=extra_plugins,
)
class TestLoader(nose.loader.TestLoader):
def __init__(self):
super(self.__class__, self).__init__(config=CONFIG)
if __name__ == '__main__':
run_all()
| mit | 5,907,010,822,233,445,000 | 23.106667 | 91 | 0.632743 | false |
MadeInHaus/django-social | social/services/facebook.py | 1 | 2384 | import requests
import logging
log = logging.getLogger(__name__)
def get_id_from_username(username):
url = 'http://graph.facebook.com/{}'.format(username)
r = requests.get(url)
return r.json()['id']
def get_username_from_id(fb_id):
url = 'http://graph.facebook.com/{}'.format(fb_id)
r = requests.get(url)
return r.json()['username']
class FacebookAPI(object):
def __init__(self, app_id, app_secret):
self._app_id = app_id
self._app_secret = app_secret
self._access_token = None
self._get_access_token()
def _get_data_for_url(self, url):
data = requests.get(url)
return data.json()
def _get_access_token(self):
if self._app_id and self._app_secret:
url = 'https://graph.facebook.com/oauth/access_token?' \
'client_id={0}&' \
'client_secret={1}&' \
'grant_type=client_credentials'.format(self._app_id, self._app_secret)
r = requests.get(url)
self._access_token = r.text.split('=')[1];
def get_feed_for_account(self, account):
if self._access_token:
url = "https://graph.facebook.com/{0}/feed?access_token={1}&filter=2&since={2}"\
.format(account.get_id(), self._access_token, account.last_poll_time)
while url:
data = self._get_data_for_url(url)
messages = data.get('data', [])
for item in messages:
yield item
url = data.get('paging', {}).get('next')
def get_photo_data(self, msg):
if not 'object_id' in msg:
return None
url = "https://graph.facebook.com/{}?access_token={}"
data = self._get_data_for_url(url.format(msg['object_id'], self._access_token))
return data
def get_search(self, query):
if self._access_token:
url = "https://graph.facebook.com/search?access_token={0}&q={1}&type=post&since={2}"\
.format(self._access_token, query.search_term, query.last_poll_time)
while url:
print url
data = self._get_data_for_url(url)
messages = data.get('data', [])
for item in messages:
yield item
url = data.get('paging', {}).get('previous')
| mit | 1,045,508,686,747,079,000 | 33.057143 | 97 | 0.536913 | false |
jeremiah-c-leary/vhdl-style-guide | vsg/tests/attribute_specification/test_rule_101.py | 1 | 1207 |
import os
import unittest
from vsg.rules import attribute_specification
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_101_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_101_test_input.fixed.vhd'), lExpected, False)
class test_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
def test_rule_101(self):
oRule = attribute_specification.rule_101()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'attribute_specification')
self.assertEqual(oRule.identifier, '101')
lExpected = [8]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_101(self):
oRule = attribute_specification.rule_101()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
| gpl-3.0 | -7,141,964,302,644,125,000 | 25.822222 | 106 | 0.690141 | false |
masschallenge/impact-api | web/impact/impact/v0/api_data/startup_list_data.py | 1 | 2231 | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from impact.api_data import APIData
from accelerator.models import ProgramStartupStatus
class StartupListData(APIData):
ALPHA_ASC_ORDER = "AlphaAsc"
ALPHA_DSC_ORDER = "AlphaDsc"
RANDOM_ORDER = "Random"
ORDER_BY_VALUES = [ALPHA_ASC_ORDER, ALPHA_DSC_ORDER, RANDOM_ORDER]
STATUS_GROUP_PREFIX = "StatusGroup:"
INDUSTRY_GROUP_BY = "Industry"
ALL_INDUSTRY = "All"
def valid(self):
self.debug = (self.YES == self.validate_field("Debug",
[self.NO, self.YES]))
self.all_group = self.validate_field("IncludeAllGroup",
self.YES_NO_VALUES)
self.order_by = self.validate_field("OrderBy", self.ORDER_BY_VALUES)
self.program = self.validate_program()
self.startup_statuses = self._validate_startup_status()
self.group_by = self._validate_group_by()
return self.errors == []
def _validate_startup_status(self):
status = self.data.get("StartupStatus", None)
result = None
if status:
result = ProgramStartupStatus.objects.filter(
program=self.program,
startup_list_include=True,
startup_list_tab_id=status)
if not result:
self.record_invalid_value(status, "StartupStatus")
return result
def _validate_group_by(self):
group_by = self.data.get("GroupBy", None)
if group_by == self.INDUSTRY_GROUP_BY or group_by is None:
return group_by
if group_by.startswith(self.STATUS_GROUP_PREFIX):
return self._validate_status_group(group_by)
if group_by is not None:
self.record_invalid_value(group_by, "GroupBy")
return None
def _validate_status_group(self, group_by):
status_group = group_by[len(self.STATUS_GROUP_PREFIX):]
if status_group in ProgramStartupStatus.objects.filter(
startup_list_include=True
).values_list("status_group", flat=True):
return group_by
self.record_invalid_value(group_by, "StatusGroup")
return None
| mit | -3,941,520,739,259,218,000 | 38.140351 | 76 | 0.601076 | false |
jperla/webify | tests/apps/layouts/__init__.py | 1 | 1053 | #!/usr/bin/env python
from __future__ import with_statement
import webify
from webify.templates.helpers import html
# Layout template
@webify.template()
def page_layout(p, title, inside):
with p(html.html()):
with p(html.head()):
p(html.title(title))
with p(html.body()):
p.sub(inside)
app = webify.defaults.app()
# Controllers
@app.subapp()
@webify.urlable()
def hello(req, p):
name = req.params.get(u'name', u'world')
p(page_layout(u'Hello App', hello_template(name)))
# Templates
# This would normally be in a different file in a different module
@webify.template()
def hello_template(p, name):
with p(html.form(action=u'', method='GET')):
p(u'Hello, %s! <br />' % name)
p(u'Your name: %s' % html.input_text('name'))
p(html.input_submit('name'))
# Middleware
from webify.middleware import EvalException
wrapped_app = webify.wsgify(app, EvalException)
# Server
if __name__ == '__main__':
webify.http.server.serve(wrapped_app, host='127.0.0.1', port='8080')
| mit | 65,411,416,033,112,240 | 24.071429 | 72 | 0.643875 | false |
scylladb/scylla-cluster-tests | upgrade_test.py | 1 | 55768 | #!/usr/bin/env python
# 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 LICENSE for more details.
#
# Copyright (c) 2016 ScyllaDB
# pylint: disable=too-many-lines
import json
from pathlib import Path
import random
import time
import re
from functools import wraps
from pkg_resources import parse_version
from sdcm import wait
from sdcm.fill_db_data import FillDatabaseData
from sdcm.utils.version_utils import is_enterprise, get_node_supported_sstable_versions
from sdcm.sct_events.system import InfoEvent
from sdcm.sct_events.database import IndexSpecialColumnErrorEvent
from sdcm.sct_events.group_common_events import ignore_upgrade_schema_errors, ignore_ycsb_connection_refused
def truncate_entries(func):
@wraps(func)
def inner(self, *args, **kwargs):
# Perform validation of truncate entries in case the new version is 3.1 or more
node = args[0]
if self.truncate_entries_flag:
base_version = self.params.get('scylla_version')
system_truncated = bool(parse_version(base_version) >= parse_version('3.1')
and not is_enterprise(base_version))
with self.db_cluster.cql_connection_patient(node, keyspace='truncate_ks') as session:
self.cql_truncate_simple_tables(session=session, rows=self.insert_rows)
self.validate_truncated_entries_for_table(session=session, system_truncated=system_truncated)
func_result = func(self, *args, **kwargs)
result = node.remoter.run('scylla --version')
new_version = result.stdout
if new_version and parse_version(new_version) >= parse_version('3.1'):
# re-new connection
with self.db_cluster.cql_connection_patient(node, keyspace='truncate_ks') as session:
self.validate_truncated_entries_for_table(session=session, system_truncated=True)
self.read_data_from_truncated_tables(session=session)
self.cql_insert_data_to_simple_tables(session=session, rows=self.insert_rows)
return func_result
return inner
def check_reload_systemd_config(node):
for i in ['scylla-server', 'scylla-jmx']:
result = node.remoter.run('systemctl status %s' % i, ignore_status=True)
if ".service changed on disk. Run 'systemctl daemon-reload' to reload units" in result.stderr:
raise Exception("Systemd config is changed, but not reload automatically")
class UpgradeTest(FillDatabaseData):
"""
Test a Scylla cluster upgrade.
"""
orig_ver = None
new_ver = None
# `major_release` (eg: 2.1 <-> 2.2, 2017.1 <-> 2018.1)
# `reinstall` (opensource <-> enterprise, enterprise <-> opensource)
# `minor_release` (eg: 2.2.1 <-> 2.2.5, 2018.1.0 <-> 2018.1.1)
upgrade_rollback_mode = None
# expected format version after upgrade and nodetool upgradesstables called
# would be recalculated after all the cluster finish upgrade
expected_sstable_format_version = 'mc'
insert_rows = None
truncate_entries_flag = False
def read_data_from_truncated_tables(self, session):
session.execute("USE truncate_ks")
truncate_query = 'SELECT COUNT(*) FROM {}'
tables_name = self.get_tables_name_of_keyspace(session=session, keyspace_name='truncate_ks')
for table_name in tables_name:
count = self.rows_to_list(session.execute(truncate_query.format(table_name)))
self.assertEqual(str(count[0][0]), '0',
msg='Expected that there is no data in the table truncate_ks.{}, but found {} rows'
.format(table_name, count[0][0]))
def validate_truncated_entries_for_table(self, session, system_truncated=False): # pylint: disable=invalid-name
tables_id = self.get_tables_id_of_keyspace(session=session, keyspace_name='truncate_ks')
for table_id in tables_id:
if system_truncated:
# validate truncation entries in the system.truncated table - expected entry
truncated_time = self.get_truncated_time_from_system_truncated(session=session, table_id=table_id)
self.assertTrue(truncated_time,
msg='Expected truncated entry in the system.truncated table, but it\'s not found')
# validate truncation entries in the system.local table - not expected entry
truncated_time = self.get_truncated_time_from_system_local(session=session)
if system_truncated:
self.assertEqual(truncated_time, [[None]],
msg='Not expected truncated entry in the system.local table, but it\'s found')
else:
self.assertTrue(truncated_time,
msg='Expected truncated entry in the system.local table, but it\'s not found')
@truncate_entries
def upgrade_node(self, node, upgrade_sstables=True):
# pylint: disable=too-many-branches,too-many-statements
new_scylla_repo = self.params.get('new_scylla_repo')
new_version = self.params.get('new_version')
upgrade_node_packages = self.params.get('upgrade_node_packages')
self.log.info('Upgrading a Node')
node.upgrade_system()
# We assume that if update_db_packages is not empty we install packages from there.
# In this case we don't use upgrade based on new_scylla_repo(ignored sudo yum update scylla...)
result = node.remoter.run('scylla --version')
self.orig_ver = result.stdout
if upgrade_node_packages:
# update_scylla_packages
node.remoter.send_files(upgrade_node_packages, '/tmp/scylla', verbose=True)
# node.remoter.run('sudo yum update -y --skip-broken', connect_timeout=900)
node.remoter.run('sudo yum install python34-PyYAML -y')
# replace the packages
node.remoter.run(r'rpm -qa scylla\*')
# flush all memtables to SSTables
node.run_nodetool("drain", timeout=3600, coredump_on_timeout=True)
node.run_nodetool("snapshot")
node.stop_scylla_server()
# update *development* packages
node.remoter.run('sudo rpm -UvhR --oldpackage /tmp/scylla/*development*', ignore_status=True)
# and all the rest
node.remoter.run('sudo rpm -URvh --replacefiles /tmp/scylla/*.rpm | true')
node.remoter.run(r'rpm -qa scylla\*')
elif new_scylla_repo:
# backup the data
node.remoter.run('sudo cp /etc/scylla/scylla.yaml /etc/scylla/scylla.yaml-backup')
if node.is_rhel_like():
node.remoter.run('sudo cp /etc/yum.repos.d/scylla.repo ~/scylla.repo-backup')
node.remoter.run(
r'for conf in $( rpm -qc $(rpm -qa | grep scylla) | grep -v contains ); do sudo cp -v $conf $conf.autobackup; done')
else:
node.remoter.run('sudo cp /etc/apt/sources.list.d/scylla.list ~/scylla.list-backup')
node.remoter.run(
r'for conf in $(cat /var/lib/dpkg/info/scylla-*server.conffiles '
r'/var/lib/dpkg/info/scylla-*conf.conffiles '
r'/var/lib/dpkg/info/scylla-*jmx.conffiles | grep -v init ); do '
r'sudo cp -v $conf $conf.backup; done')
assert new_scylla_repo.startswith('http')
node.download_scylla_repo(new_scylla_repo)
# flush all memtables to SSTables
node.run_nodetool("drain", timeout=3600, coredump_on_timeout=True)
node.run_nodetool("snapshot")
node.stop_scylla_server(verify_down=False)
orig_is_enterprise = node.is_enterprise
if node.is_rhel_like():
result = node.remoter.run("sudo yum search scylla-enterprise 2>&1", ignore_status=True)
new_is_enterprise = bool('scylla-enterprise.x86_64' in result.stdout or
'No matches found' not in result.stdout)
else:
result = node.remoter.run("sudo apt-cache search scylla-enterprise", ignore_status=True)
new_is_enterprise = 'scylla-enterprise' in result.stdout
scylla_pkg = 'scylla-enterprise' if new_is_enterprise else 'scylla'
if orig_is_enterprise != new_is_enterprise:
self.upgrade_rollback_mode = 'reinstall'
ver_suffix = r'\*{}'.format(new_version) if new_version else ''
if self.upgrade_rollback_mode == 'reinstall':
if node.is_rhel_like():
node.remoter.run(r'sudo yum remove scylla\* -y')
node.remoter.run('sudo yum install {}{} -y'.format(scylla_pkg, ver_suffix))
node.remoter.run(
r'for conf in $( rpm -qc $(rpm -qa | grep scylla) | grep -v contains ); do sudo cp -v $conf.autobackup $conf; done')
else:
node.remoter.run(r'sudo apt-get remove scylla\* -y')
# fixme: add publick key
node.remoter.run(
r'sudo apt-get install {}{} -y '
r'-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" '.format(scylla_pkg, ver_suffix))
node.remoter.run(r'for conf in $(cat /var/lib/dpkg/info/scylla-*server.conffiles '
r'/var/lib/dpkg/info/scylla-*conf.conffiles '
r'/var/lib/dpkg/info/scylla-*jmx.conffiles'
r' | grep -v init ); do sudo cp -v $conf $conf.backup-2.1; done')
else:
if node.is_rhel_like():
node.remoter.run(r'sudo yum update {}{}\* -y'.format(scylla_pkg, ver_suffix))
else:
node.remoter.run('sudo apt-get update')
node.remoter.run(
r'sudo apt-get dist-upgrade {} -y '
r'-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" '.format(scylla_pkg))
if self.params.get('test_sst3'):
node.remoter.run("echo 'enable_sstables_mc_format: true' |sudo tee --append /etc/scylla/scylla.yaml")
if self.params.get('test_upgrade_from_installed_3_1_0'):
node.remoter.run("echo 'enable_3_1_0_compatibility_mode: true' |sudo tee --append /etc/scylla/scylla.yaml")
authorization_in_upgrade = self.params.get('authorization_in_upgrade')
if authorization_in_upgrade:
node.remoter.run("echo 'authorizer: \"%s\"' |sudo tee --append /etc/scylla/scylla.yaml" %
authorization_in_upgrade)
check_reload_systemd_config(node)
# Current default 300s aren't enough for upgrade test of Debian 9.
# Related issue: https://github.com/scylladb/scylla-cluster-tests/issues/1726
node.start_scylla_server(verify_up_timeout=500)
result = node.remoter.run('scylla --version')
new_ver = result.stdout
assert self.orig_ver != self.new_ver, "scylla-server version isn't changed"
self.new_ver = new_ver
if upgrade_sstables:
self.upgradesstables_if_command_available(node)
@truncate_entries
def rollback_node(self, node, upgrade_sstables=True):
# pylint: disable=too-many-branches,too-many-statements
self.log.info('Rollbacking a Node')
# fixme: auto identify new_introduced_pkgs, remove this parameter
new_introduced_pkgs = self.params.get('new_introduced_pkgs')
result = node.remoter.run('scylla --version')
orig_ver = result.stdout
# flush all memtables to SSTables
node.run_nodetool("drain", timeout=3600, coredump_on_timeout=True)
# backup the data
node.run_nodetool("snapshot")
node.stop_scylla_server(verify_down=False)
if node.is_rhel_like():
node.remoter.run('sudo cp ~/scylla.repo-backup /etc/yum.repos.d/scylla.repo')
node.remoter.run('sudo chown root.root /etc/yum.repos.d/scylla.repo')
node.remoter.run('sudo chmod 644 /etc/yum.repos.d/scylla.repo')
else:
node.remoter.run('sudo cp ~/scylla.list-backup /etc/apt/sources.list.d/scylla.list')
node.remoter.run('sudo chown root.root /etc/apt/sources.list.d/scylla.list')
node.remoter.run('sudo chmod 644 /etc/apt/sources.list.d/scylla.list')
node.update_repo_cache()
if re.findall(r'\d+.\d+', self.orig_ver)[0] == re.findall(r'\d+.\d+', self.new_ver)[0]:
self.upgrade_rollback_mode = 'minor_release'
if self.upgrade_rollback_mode == 'reinstall' or not node.is_rhel_like():
if node.is_rhel_like():
node.remoter.run(r'sudo yum remove scylla\* -y')
node.remoter.run(r'sudo yum install %s -y' % node.scylla_pkg())
node.remoter.run(
r'for conf in $( rpm -qc $(rpm -qa | grep scylla) | grep -v contains ); do sudo cp -v '
r'$conf.autobackup $conf; done')
else:
node.remoter.run(r'sudo apt-get remove scylla\* -y')
node.remoter.run(
r'sudo apt-get install %s\* -y '
r'-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" ' % node.scylla_pkg())
node.remoter.run(
r'for conf in $(cat /var/lib/dpkg/info/scylla-*server.conffiles '
r'/var/lib/dpkg/info/scylla-*conf.conffiles '
r'/var/lib/dpkg/info/scylla-*jmx.conffiles | grep -v init ); do '
r'sudo cp -v $conf.backup $conf; done')
node.remoter.run('sudo systemctl daemon-reload')
elif self.upgrade_rollback_mode == 'minor_release':
node.remoter.run(r'sudo yum downgrade scylla\*%s-\* -y' % self.orig_ver.split('-')[0])
else:
if new_introduced_pkgs:
node.remoter.run('sudo yum remove %s -y' % new_introduced_pkgs)
node.remoter.run(r'sudo yum downgrade scylla\* -y')
if new_introduced_pkgs:
node.remoter.run('sudo yum install %s -y' % node.scylla_pkg())
if node.is_rhel_like():
node.remoter.run(
r'for conf in $( rpm -qc $(rpm -qa | grep scylla) | grep -v contains ); do sudo cp -v $conf.autobackup $conf; done')
else:
node.remoter.run(
r'for conf in $(cat /var/lib/dpkg/info/scylla-*server.conffiles '
r'/var/lib/dpkg/info/scylla-*conf.conffiles '
r'/var/lib/dpkg/info/scylla-*jmx.conffiles | grep -v init ); do '
r'sudo cp -v $conf.backup $conf; done')
node.remoter.run('sudo systemctl daemon-reload')
node.remoter.run('sudo cp /etc/scylla/scylla.yaml-backup /etc/scylla/scylla.yaml')
result = node.remoter.run('sudo find /var/lib/scylla/data/system')
snapshot_name = re.findall(r"system/peers-[a-z0-9]+/snapshots/(\d+)\n", result.stdout)
# cmd = (
# r"DIR='/var/lib/scylla/data/system'; "
# r"for i in `sudo ls $DIR`; do "
# r" sudo test -e $DIR/$i/snapshots/%s && sudo find $DIR/$i/snapshots/%s -type f -exec sudo /bin/cp {} $DIR/$i/ \;; "
# r"done" % (snapshot_name[0], snapshot_name[0]))
# recover the system tables
if self.params.get('recover_system_tables'):
node.remoter.send_files('./data_dir/recover_system_tables.sh', '/tmp/')
node.remoter.run('bash /tmp/recover_system_tables.sh %s' % snapshot_name[0], verbose=True)
if self.params.get('test_sst3'):
node.remoter.run(
r'sudo sed -i -e "s/enable_sstables_mc_format:/#enable_sstables_mc_format:/g" /etc/scylla/scylla.yaml')
if self.params.get('test_upgrade_from_installed_3_1_0'):
node.remoter.run(
r'sudo sed -i -e "s/enable_3_1_0_compatibility_mode:/#enable_3_1_0_compatibility_mode:/g" /etc/scylla/scylla.yaml')
if self.params.get('remove_authorization_in_rollback'):
node.remoter.run('sudo sed -i -e "s/authorizer:/#authorizer:/g" /etc/scylla/scylla.yaml')
# Current default 300s aren't enough for upgrade test of Debian 9.
# Related issue: https://github.com/scylladb/scylla-cluster-tests/issues/1726
node.start_scylla_server(verify_up_timeout=500)
result = node.remoter.run('scylla --version')
new_ver = result.stdout
self.log.info('original scylla-server version is %s, latest: %s', orig_ver, new_ver)
assert orig_ver != new_ver, "scylla-server version isn't changed"
if upgrade_sstables:
self.upgradesstables_if_command_available(node)
def upgradesstables_if_command_available(self, node, queue=None): # pylint: disable=invalid-name
upgradesstables_available = False
upgradesstables_supported = node.remoter.run(
'nodetool help | grep -q upgradesstables && echo "yes" || echo "no"')
if "yes" in upgradesstables_supported.stdout:
upgradesstables_available = True
self.log.info("calling upgradesstables")
# NOTE: some 4.3.x and 4.4.x scylla images have nodetool with bug [1]
# that is not yet fixed [3] there.
# So, in such case we must use '/etc/scylla/cassandra' path for
# the 'cassandra-rackdc.properties' file instead of the expected
# one - '/etc/scylla' [2].
# Example of the error:
# WARN 16:42:29,831 Unable to read cassandra-rackdc.properties
# error: DC or rack not found in snitch properties,
# check your configuration in: cassandra-rackdc.properties
#
# [1] https://github.com/scylladb/scylla-tools-java/commit/3eca0e35
# [2] https://github.com/scylladb/scylla/issues/7930
# [3] https://github.com/scylladb/scylla-tools-java/pull/232
main_dir, subdir = Path("/etc/scylla"), "cassandra"
filename = "cassandra-rackdc.properties"
node.remoter.sudo(
f"cp {main_dir / filename} {main_dir / subdir / filename}")
node.run_nodetool(sub_cmd="upgradesstables", args="-a")
if queue:
queue.put(upgradesstables_available)
queue.task_done()
def get_highest_supported_sstable_version(self): # pylint: disable=invalid-name
"""
find the highest sstable format version supported in the cluster
:return:
"""
output = []
for node in self.db_cluster.nodes:
output.extend(get_node_supported_sstable_versions(node.system_log))
return max(set(output))
def wait_for_sstable_upgrade(self, node, queue=None):
all_tables_upgraded = True
def wait_for_node_to_finish():
try:
result = node.remoter.sudo(
r"find /var/lib/scylla/data/system -type f ! -path '*snapshots*' -printf %f\\n")
all_sstable_files = result.stdout.splitlines()
sstable_version_regex = re.compile(r'(\w+)-\d+-(.+)\.(db|txt|sha1|crc32)')
sstable_versions = {sstable_version_regex.search(f).group(
1) for f in all_sstable_files if sstable_version_regex.search(f)}
assert len(sstable_versions) == 1, "expected all table format to be the same found {}".format(sstable_versions)
assert list(sstable_versions)[0] == self.expected_sstable_format_version, (
"expected to format version to be '{}', found '{}'".format(
self.expected_sstable_format_version, list(sstable_versions)[0]))
except Exception as ex: # pylint: disable=broad-except
self.log.warning(ex)
return False
else:
return True
try:
self.log.info("Start waiting for upgardesstables to finish")
wait.wait_for(func=wait_for_node_to_finish, step=30, timeout=900, throw_exc=True,
text="Waiting until upgardesstables is finished")
except Exception: # pylint: disable=broad-except
all_tables_upgraded = False
finally:
if queue:
queue.put(all_tables_upgraded)
queue.task_done()
default_params = {'timeout': 650000}
def test_upgrade_cql_queries(self):
"""
Run a set of different cql queries against various types/tables before
and after upgrade of every node to check the consistency of data
"""
self.truncate_entries_flag = False # not perform truncate entries test
self.log.info('Populate DB with many types of tables and data')
self.fill_db_data()
self.log.info('Run some Queries to verify data BEFORE UPGRADE')
self.verify_db_data()
self.log.info('Starting c-s write workload to pupulate 10M paritions')
# YAML: stress_cmd: cassandra-stress write cl=QUORUM n=10000000 -schema 'replication(factor=3)' -port jmx=6868
# -mode cql3 native -rate threads=1000 -pop seq=1..10000000
stress_cmd = self._cs_add_node_flag(self.params.get('stress_cmd'))
self.run_stress_thread(stress_cmd=stress_cmd)
self.log.info('Sleeping for 360s to let cassandra-stress populate some data before the mixed workload')
time.sleep(600)
self.log.info('Starting c-s read workload for 60m')
# YAML: stress_cmd_1: cassandra-stress read cl=QUORUM duration=60m -schema 'replication(factor=3)'
# -port jmx=6868 -mode cql3 native -rate threads=100 -pop seq=1..10000000
stress_cmd_1 = self._cs_add_node_flag(self.params.get('stress_cmd_1'))
stress_queue = self.run_stress_thread(stress_cmd=stress_cmd_1)
self.log.info('Sleeping for 300s to let cassandra-stress start before the upgrade...')
time.sleep(300)
nodes_num = len(self.db_cluster.nodes)
# prepare an array containing the indexes
indexes = list(range(nodes_num))
# shuffle it so we will upgrade the nodes in a random order
random.shuffle(indexes)
# upgrade all the nodes in random order
for i in indexes:
self.db_cluster.node_to_upgrade = self.db_cluster.nodes[i]
self.log.info('Upgrade Node %s begin', self.db_cluster.node_to_upgrade.name)
self.upgrade_node(self.db_cluster.node_to_upgrade)
time.sleep(300)
self.log.info('Upgrade Node %s ended', self.db_cluster.node_to_upgrade.name)
self.log.info('Run some Queries to verify data AFTER UPGRADE')
self.verify_db_data()
self.verify_stress_thread(stress_queue)
def fill_and_verify_db_data(self, note, pre_fill=False, rewrite_data=True):
if pre_fill:
self.log.info('Populate DB with many types of tables and data')
self.fill_db_data()
self.log.info('Run some Queries to verify data %s', note)
self.verify_db_data()
if rewrite_data:
self.log.info('Re-Populate DB with many types of tables and data')
self.fill_db_data()
# Added to cover the issue #5621: upgrade from 3.1 to 3.2 fails on std::logic_error (Column idx_token doesn't exist
# in base and this view is not backing a secondary index)
# @staticmethod
def search_for_idx_token_error_after_upgrade(self, node, step):
self.log.debug('Search for idx_token error. Step {}'.format(step))
idx_token_error = list(node.follow_system_log(
patterns=["Column idx_token doesn't exist"], start_from_beginning=True))
if idx_token_error:
IndexSpecialColumnErrorEvent(
message=f'Node: {node.name}. Step: {step}. '
f'Found error: index special column "idx_token" is not recognized'
).publish()
def test_rolling_upgrade(self): # pylint: disable=too-many-locals,too-many-statements
"""
Upgrade half of nodes in the cluster, and start special read workload
during the stage. Checksum method is changed to xxhash from Scylla 2.2,
we want to use this case to verify the read (cl=ALL) workload works
well, upgrade all nodes to new version in the end.
"""
# In case the target version >= 3.1 we need to perform test for truncate entries
target_upgrade_version = self.params.get('target_upgrade_version')
self.truncate_entries_flag = False
if target_upgrade_version and parse_version(target_upgrade_version) >= parse_version('3.1') and \
not is_enterprise(target_upgrade_version):
self.truncate_entries_flag = True
self.log.info('pre-test - prepare test keyspaces and tables')
# prepare test keyspaces and tables before upgrade to avoid schema change during mixed cluster.
self.prepare_keyspaces_and_tables()
self.fill_and_verify_db_data('BEFORE UPGRADE', pre_fill=True)
# write workload during entire test
self.log.info('Starting c-s write workload during entire test')
write_stress_during_entire_test = self.params.get('write_stress_during_entire_test')
entire_write_cs_thread_pool = self.run_stress_thread(stress_cmd=write_stress_during_entire_test)
# Let to write_stress_during_entire_test complete the schema changes
self.metric_has_data(
metric_query='collectd_cassandra_stress_write_gauge{type="ops", keyspace="keyspace_entire_test"}', n=10)
# Prepare keyspace and tables for truncate test
if self.truncate_entries_flag:
self.insert_rows = 10
self.fill_db_data_for_truncate_test(insert_rows=self.insert_rows)
# Let to ks_truncate complete the schema changes
time.sleep(120)
# generate random order to upgrade
nodes_num = len(self.db_cluster.nodes)
# prepare an array containing the indexes
indexes = list(range(nodes_num))
# shuffle it so we will upgrade the nodes in a random order
random.shuffle(indexes)
self.log.info('pre-test - Run stress workload before upgrade')
# complex workload: prepare write
self.log.info('Starting c-s complex workload (5M) to prepare data')
stress_cmd_complex_prepare = self.params.get('stress_cmd_complex_prepare')
complex_cs_thread_pool = self.run_stress_thread(
stress_cmd=stress_cmd_complex_prepare, profile='data_dir/complex_schema.yaml')
# wait for the complex workload to finish
self.verify_stress_thread(complex_cs_thread_pool)
self.log.info('Will check paged query before upgrading nodes')
self.paged_query()
self.log.info('Done checking paged query before upgrading nodes')
# prepare write workload
self.log.info('Starting c-s prepare write workload (n=10000000)')
prepare_write_stress = self.params.get('prepare_write_stress')
prepare_write_cs_thread_pool = self.run_stress_thread(stress_cmd=prepare_write_stress)
self.log.info('Sleeping for 60s to let cassandra-stress start before the upgrade...')
self.metric_has_data(
metric_query='collectd_cassandra_stress_write_gauge{type="ops", keyspace="keyspace1"}', n=5)
# start gemini write workload
# and cdc log reader
if self.version_cdc_support():
self.log.info("Start gemini and cdc stressor during upgrade")
gemini_thread = self.run_gemini(self.params.get("gemini_cmd"))
# Let to write_stress_during_entire_test complete the schema changes
self.metric_has_data(
metric_query='gemini_cql_requests', n=10)
cdc_reader_thread = self.run_cdclog_reader_thread(self.params.get("stress_cdclog_reader_cmd"),
keyspace_name="ks1", base_table_name="table1")
with ignore_upgrade_schema_errors():
step = 'Step1 - Upgrade First Node '
self.log.info(step)
# upgrade first node
self.db_cluster.node_to_upgrade = self.db_cluster.nodes[indexes[0]]
self.log.info('Upgrade Node %s begin', self.db_cluster.node_to_upgrade.name)
self.upgrade_node(self.db_cluster.node_to_upgrade)
self.log.info('Upgrade Node %s ended', self.db_cluster.node_to_upgrade.name)
self.db_cluster.node_to_upgrade.check_node_health()
# wait for the prepare write workload to finish
self.verify_stress_thread(prepare_write_cs_thread_pool)
# read workload (cl=QUORUM)
self.log.info('Starting c-s read workload (cl=QUORUM n=10000000)')
stress_cmd_read_cl_quorum = self.params.get('stress_cmd_read_cl_quorum')
read_stress_queue = self.run_stress_thread(stress_cmd=stress_cmd_read_cl_quorum)
# wait for the read workload to finish
self.verify_stress_thread(read_stress_queue)
self.fill_and_verify_db_data('after upgraded one node')
self.search_for_idx_token_error_after_upgrade(node=self.db_cluster.node_to_upgrade,
step=step+' - after upgraded one node')
# read workload
self.log.info('Starting c-s read workload for 10m')
stress_cmd_read_10m = self.params.get('stress_cmd_read_10m')
read_10m_cs_thread_pool = self.run_stress_thread(stress_cmd=stress_cmd_read_10m)
self.log.info('Sleeping for 60s to let cassandra-stress start before the upgrade...')
time.sleep(60)
step = 'Step2 - Upgrade Second Node '
self.log.info(step)
# upgrade second node
self.db_cluster.node_to_upgrade = self.db_cluster.nodes[indexes[1]]
self.log.info('Upgrade Node %s begin', self.db_cluster.node_to_upgrade.name)
self.upgrade_node(self.db_cluster.node_to_upgrade)
self.log.info('Upgrade Node %s ended', self.db_cluster.node_to_upgrade.name)
self.db_cluster.node_to_upgrade.check_node_health()
# wait for the 10m read workload to finish
self.verify_stress_thread(read_10m_cs_thread_pool)
self.fill_and_verify_db_data('after upgraded two nodes')
self.search_for_idx_token_error_after_upgrade(node=self.db_cluster.node_to_upgrade,
step=step+' - after upgraded two nodes')
# read workload (60m)
self.log.info('Starting c-s read workload for 60m')
stress_cmd_read_60m = self.params.get('stress_cmd_read_60m')
read_60m_cs_thread_pool = self.run_stress_thread(stress_cmd=stress_cmd_read_60m)
self.log.info('Sleeping for 60s to let cassandra-stress start before the rollback...')
time.sleep(60)
self.log.info('Step3 - Rollback Second Node ')
# rollback second node
self.log.info('Rollback Node %s begin', self.db_cluster.nodes[indexes[1]].name)
self.rollback_node(self.db_cluster.nodes[indexes[1]])
self.log.info('Rollback Node %s ended', self.db_cluster.nodes[indexes[1]].name)
self.db_cluster.nodes[indexes[1]].check_node_health()
step = 'Step4 - Verify data during mixed cluster mode '
self.log.info(step)
self.fill_and_verify_db_data('after rollback the second node')
self.log.info('Repair the first upgraded Node')
self.db_cluster.nodes[indexes[0]].run_nodetool(sub_cmd='repair')
self.search_for_idx_token_error_after_upgrade(node=self.db_cluster.node_to_upgrade,
step=step)
with ignore_upgrade_schema_errors():
step = 'Step5 - Upgrade rest of the Nodes '
self.log.info(step)
for i in indexes[1:]:
self.db_cluster.node_to_upgrade = self.db_cluster.nodes[i]
self.log.info('Upgrade Node %s begin', self.db_cluster.node_to_upgrade.name)
self.upgrade_node(self.db_cluster.node_to_upgrade)
self.log.info('Upgrade Node %s ended', self.db_cluster.node_to_upgrade.name)
self.db_cluster.node_to_upgrade.check_node_health()
self.fill_and_verify_db_data('after upgraded %s' % self.db_cluster.node_to_upgrade.name)
self.search_for_idx_token_error_after_upgrade(node=self.db_cluster.node_to_upgrade,
step=step)
self.log.info('Step6 - Verify stress results after upgrade ')
self.log.info('Waiting for stress threads to complete after upgrade')
# wait for the 60m read workload to finish
self.verify_stress_thread(read_60m_cs_thread_pool)
self.verify_stress_thread(entire_write_cs_thread_pool)
self.log.info('Step7 - Upgrade sstables to latest supported version ')
# figure out what is the last supported sstable version
self.expected_sstable_format_version = self.get_highest_supported_sstable_version()
# run 'nodetool upgradesstables' on all nodes and check/wait for all file to be upgraded
upgradesstables = self.db_cluster.run_func_parallel(func=self.upgradesstables_if_command_available)
# only check sstable format version if all nodes had 'nodetool upgradesstables' available
if all(upgradesstables):
self.log.info('Upgrading sstables if new version is available')
tables_upgraded = self.db_cluster.run_func_parallel(func=self.wait_for_sstable_upgrade)
assert all(tables_upgraded), "Failed to upgrade the sstable format {}".format(tables_upgraded)
# Verify sstabledump
self.log.info('Starting sstabledump to verify correctness of sstables')
self.db_cluster.nodes[0].remoter.run(
'for i in `sudo find /var/lib/scylla/data/keyspace_complex/ -type f |grep -v manifest.json |'
'grep -v snapshots |head -n 1`; do echo $i; sudo sstabledump $i 1>/tmp/sstabledump.output || '
'exit 1; done', verbose=True)
self.log.info('Step8 - Run stress and verify after upgrading entire cluster ')
self.log.info('Starting verify_stress_after_cluster_upgrade')
verify_stress_after_cluster_upgrade = self.params.get( # pylint: disable=invalid-name
'verify_stress_after_cluster_upgrade')
verify_stress_cs_thread_pool = self.run_stress_thread(stress_cmd=verify_stress_after_cluster_upgrade)
self.verify_stress_thread(verify_stress_cs_thread_pool)
# complex workload: verify data by simple read cl=ALL
self.log.info('Starting c-s complex workload to verify data by simple read')
stress_cmd_complex_verify_read = self.params.get('stress_cmd_complex_verify_read')
complex_cs_thread_pool = self.run_stress_thread(
stress_cmd=stress_cmd_complex_verify_read, profile='data_dir/complex_schema.yaml')
# wait for the read complex workload to finish
self.verify_stress_thread(complex_cs_thread_pool)
self.log.info('Will check paged query after upgrading all nodes')
self.paged_query()
self.log.info('Done checking paged query after upgrading nodes')
# After adjusted the workloads, there is a entire write workload, and it uses a fixed duration for catching
# the data lose.
# But the execute time of workloads are not exact, so let only use basic prepare write & read verify for
# complex workloads,and comment two complex workloads.
#
# TODO: retest commented workloads and decide to enable or delete them.
#
# complex workload: verify data by multiple ops
# self.log.info('Starting c-s complex workload to verify data by multiple ops')
# stress_cmd_complex_verify_more = self.params.get('stress_cmd_complex_verify_more')
# complex_cs_thread_pool = self.run_stress_thread(stress_cmd=stress_cmd_complex_verify_more,
# profile='data_dir/complex_schema.yaml')
# wait for the complex workload to finish
# self.verify_stress_thread(complex_cs_thread_pool)
# complex workload: verify data by delete 1/10 data
# self.log.info('Starting c-s complex workload to verify data by delete')
# stress_cmd_complex_verify_delete = self.params.get('stress_cmd_complex_verify_delete')
# complex_cs_thread_pool = self.run_stress_thread(stress_cmd=stress_cmd_complex_verify_delete,
# profile='data_dir/complex_schema.yaml')
# wait for the complex workload to finish
# self.verify_stress_thread(complex_cs_thread_pool)
# During the test we filter and ignore some specific errors, but we want to allow only certain amount of them
step = 'Step9 - Search for errors that we filter during the test '
self.log.info(step)
self.log.info('Checking how many failed_to_load_schem errors happened during the test')
error_factor = 3
schema_load_error_num = self.count_log_errors(search_pattern='Failed to load schema version',
step=step)
# Warning example:
# workload prioritization - update_service_levels_from_distributed_data: an error occurred while retrieving
# configuration (exceptions::read_failure_exception (Operation failed for system_distributed.service_levels
# - received 0 responses and 1 failures from 1 CL=ONE.))
workload_prioritization_error_num = self.count_log_errors(search_pattern='workload prioritization.*read_failure_exception',
step=step, search_for_idx_token_error=False)
self.log.info('schema_load_error_num: %s; workload_prioritization_error_num: %s',
schema_load_error_num, workload_prioritization_error_num)
# Issue #https://github.com/scylladb/scylla-enterprise/issues/1391
# By Eliran's comment: For 'Failed to load schema version' error which is expected and non offensive is
# to count the 'workload prioritization' warning and subtract that amount from the amount of overall errors.
load_error_num = schema_load_error_num - workload_prioritization_error_num
assert load_error_num <= error_factor * 8 * \
len(self.db_cluster.nodes), 'Only allowing shards_num * %d schema load errors per host during the ' \
'entire test, actual: %d' % (
error_factor, schema_load_error_num)
self.log.info('Step10 - Verify that gemini and cdc stressor are not failed during upgrade')
if self.version_cdc_support():
self.verify_gemini_results(queue=gemini_thread)
self.verify_cdclog_reader_results(cdc_reader_thread)
self.log.info('all nodes were upgraded, and last workaround is verified.')
def test_generic_cluster_upgrade(self): # pylint: disable=too-many-locals,too-many-statements
"""
Upgrade half of nodes in the cluster, and start special read workload
during the stage. Checksum method is changed to xxhash from Scylla 2.2,
we want to use this case to verify the read (cl=ALL) workload works
well, upgrade all nodes to new version in the end.
"""
# prepare workload (stress_before_upgrade)
InfoEvent(message="Starting stress_before_upgrade - aka prepare step").publish()
stress_before_upgrade = self.params.get('stress_before_upgrade')
prepare_thread_pool = self.run_stress_thread(stress_cmd=stress_before_upgrade)
if self.params.get('alternator_port'):
self.pre_create_alternator_tables()
InfoEvent(message="Waiting for stress_before_upgrade to finish").publish()
self.verify_stress_thread(prepare_thread_pool)
# Starting workload during entire upgrade
InfoEvent(message="Starting stress_during_entire_upgrade workload").publish()
stress_during_entire_upgrade = self.params.get('stress_during_entire_upgrade')
stress_thread_pool = self.run_stress_thread(stress_cmd=stress_during_entire_upgrade)
self.log.info('Sleeping for 60s to let cassandra-stress start before the rollback...')
time.sleep(60)
num_nodes_to_rollback = self.params.get('num_nodes_to_rollback')
upgraded_nodes = []
# generate random order to upgrade
nodes_num = len(self.db_cluster.nodes)
# prepare an array containing the indexes
indexes = list(range(nodes_num))
# shuffle it so we will upgrade the nodes in a random order
random.shuffle(indexes)
upgrade_sstables = self.params.get('upgrade_sstables')
if num_nodes_to_rollback > 0:
# Upgrade all nodes that should be rollback later
for i in range(num_nodes_to_rollback):
InfoEvent(message=f"Step{i + 1} - Upgrade node{i + 1}").publish()
self.db_cluster.node_to_upgrade = self.db_cluster.nodes[indexes[i]]
self.log.info('Upgrade Node %s begins', self.db_cluster.node_to_upgrade.name)
with ignore_ycsb_connection_refused():
self.upgrade_node(self.db_cluster.node_to_upgrade, upgrade_sstables=upgrade_sstables)
self.log.info('Upgrade Node %s ended', self.db_cluster.node_to_upgrade.name)
self.db_cluster.node_to_upgrade.check_node_health()
upgraded_nodes.append(self.db_cluster.node_to_upgrade)
# Rollback all nodes that where upgraded (not necessarily in the same order)
random.shuffle(upgraded_nodes)
self.log.info('Upgraded Nodes to be rollback are: %s', upgraded_nodes)
for node in upgraded_nodes:
InfoEvent(
message=f"Step{num_nodes_to_rollback + upgraded_nodes.index(node) + 1} - "
f"Rollback node{upgraded_nodes.index(node) + 1}"
).publish()
self.log.info('Rollback Node %s begin', node)
with ignore_ycsb_connection_refused():
self.rollback_node(node, upgrade_sstables=upgrade_sstables)
self.log.info('Rollback Node %s ended', node)
node.check_node_health()
# Upgrade all nodes
for i in range(nodes_num):
InfoEvent(message=f"Step{num_nodes_to_rollback * 2 + i + 1} - Upgrade node{i + 1}").publish()
self.db_cluster.node_to_upgrade = self.db_cluster.nodes[indexes[i]]
self.log.info('Upgrade Node %s begins', self.db_cluster.node_to_upgrade.name)
with ignore_ycsb_connection_refused():
self.upgrade_node(self.db_cluster.node_to_upgrade, upgrade_sstables=upgrade_sstables)
self.log.info('Upgrade Node %s ended', self.db_cluster.node_to_upgrade.name)
self.db_cluster.node_to_upgrade.check_node_health()
upgraded_nodes.append(self.db_cluster.node_to_upgrade)
InfoEvent(message="All nodes were upgraded successfully").publish()
InfoEvent(message="Waiting for stress_during_entire_upgrade to finish").publish()
self.verify_stress_thread(stress_thread_pool)
InfoEvent(message="Starting stress_after_cluster_upgrade").publish()
stress_after_cluster_upgrade = self.params.get('stress_after_cluster_upgrade')
stress_after_cluster_upgrade_pool = self.run_stress_thread(stress_cmd=stress_after_cluster_upgrade)
self.verify_stress_thread(stress_after_cluster_upgrade_pool)
def test_kubernetes_scylla_upgrade(self):
"""
Run a set of different cql queries against various types/tables before
and after upgrade of every node to check the consistency of data
"""
self.truncate_entries_flag = False # not perform truncate entries test
self.log.info('Step1 - Populate DB with many types of tables and data')
target_upgrade_version = self.params.get('new_version')
if target_upgrade_version and parse_version(target_upgrade_version) >= parse_version('3.1') and \
not is_enterprise(target_upgrade_version):
self.truncate_entries_flag = True
self.prepare_keyspaces_and_tables()
self.log.info('Step2 - Populate some data before upgrading cluster')
self.fill_and_verify_db_data('', pre_fill=True)
self.log.info('Step3 - Starting c-s write workload')
self.verify_stress_thread(
self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_w'))
)
)
self.log.info('Step4 - Starting c-s read workload')
self.verify_stress_thread(
self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_r'))
)
)
self.log.info('Step5 - Upgrade cluster to %s', target_upgrade_version)
self.db_cluster.upgrade_scylla_cluster(target_upgrade_version)
self.log.info('Step6 - Wait till cluster got upgraded')
self.wait_till_scylla_is_upgraded_on_all_nodes(target_upgrade_version)
self.log.info('Step7 - Upgrade sstables')
if self.params.get('upgrade_sstables'):
self.expected_sstable_format_version = self.get_highest_supported_sstable_version()
upgradesstables = self.db_cluster.run_func_parallel(
func=self.upgradesstables_if_command_available)
# only check sstable format version if all nodes had 'nodetool upgradesstables' available
if all(upgradesstables):
self.log.info("Waiting until jmx is up across the board")
self.wait_till_jmx_on_all_nodes()
self.log.info('Upgrading sstables if new version is available')
tables_upgraded = self.db_cluster.run_func_parallel(
func=self.wait_for_sstable_upgrade)
assert all(tables_upgraded), f"Failed to upgrade the sstable format {tables_upgraded}"
else:
self.log.info("Upgrade of sstables is disabled")
self.log.info('Step8 - Verify data after upgrade')
self.fill_and_verify_db_data(note='after all nodes upgraded')
self.log.info('Step9 - Starting c-s read workload')
self.verify_stress_thread(
self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_r'))
)
)
self.log.info('Step10 - Starting c-s write workload')
self.verify_stress_thread(
self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_w'))
)
)
self.log.info('Step11 - Starting c-s read workload')
self.verify_stress_thread(
self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_r'))
)
)
self.log.info('Step12 - Search for errors in scylla log')
for node in self.db_cluster.nodes:
self.search_for_idx_token_error_after_upgrade(node=node, step=f'{str(node)} after upgrade')
self.log.info('Step13 - Checking how many failed_to_load_scheme errors happened during the test')
error_factor = 3
schema_load_error_num = self.count_log_errors(search_pattern='Failed to load schema version',
step='AFTER UPGRADE')
# Warning example:
# workload prioritization - update_service_levels_from_distributed_data: an error occurred while retrieving
# configuration (exceptions::read_failure_exception (Operation failed for system_distributed.service_levels
# - received 0 responses and 1 failures from 1 CL=ONE.))
workload_prioritization_error_num = self.count_log_errors(
search_pattern='workload prioritization.*read_failure_exception',
step='AFTER UPGRADE',
search_for_idx_token_error=False
)
self.log.info('schema_load_error_num: %s; workload_prioritization_error_num: %s',
schema_load_error_num, workload_prioritization_error_num)
# Issue #https://github.com/scylladb/scylla-enterprise/issues/1391
# By Eliran's comment: For 'Failed to load schema version' error which is expected and non offensive is
# to count the 'workload prioritization' warning and subtract that amount from the amount of overall errors.
load_error_num = schema_load_error_num-workload_prioritization_error_num
assert load_error_num <= error_factor * 8 * \
len(self.db_cluster.nodes), 'Only allowing shards_num * %d schema load errors per host during the ' \
'entire test, actual: %d' % (
error_factor, schema_load_error_num)
def _get_current_operator_image_tag(self):
return self.k8s_cluster.kubectl(
"get deployment scylla-operator -o custom-columns=:..image --no-headers",
namespace=self.k8s_cluster._scylla_operator_namespace # pylint: disable=protected-access
).stdout.strip().split(":")[-1]
def test_kubernetes_operator_upgrade(self):
self.log.info('Step1 - Populate DB with data')
self.prepare_keyspaces_and_tables()
self.fill_and_verify_db_data('', pre_fill=True)
self.log.info('Step2 - Run c-s write workload')
self.verify_stress_thread(self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_w'))))
self.log.info('Step3 - Run c-s read workload')
self.verify_stress_thread(self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_r'))))
self.log.info('Step4 - Upgrade scylla-operator')
base_docker_image_tag = self._get_current_operator_image_tag()
upgrade_docker_image = self.params.get('k8s_scylla_operator_upgrade_docker_image') or ''
self.k8s_cluster.upgrade_scylla_operator(
self.params.get('k8s_scylla_operator_upgrade_helm_repo') or self.params.get(
'k8s_scylla_operator_helm_repo'),
self.params.get('k8s_scylla_operator_upgrade_chart_version') or 'latest',
upgrade_docker_image)
self.log.info('Step5 - Validate scylla-operator version after upgrade')
actual_docker_image_tag = self._get_current_operator_image_tag()
self.assertNotEqual(base_docker_image_tag, actual_docker_image_tag)
expected_docker_image_tag = upgrade_docker_image.split(':')[-1]
if not expected_docker_image_tag:
operator_chart_info = self.k8s_cluster.helm(
f"ls -n {self.k8s_cluster._scylla_operator_namespace} -o json") # pylint: disable=protected-access
expected_docker_image_tag = json.loads(operator_chart_info)[0]["app_version"]
self.assertEqual(expected_docker_image_tag, actual_docker_image_tag)
self.log.info('Step6 - Wait for the update of Scylla cluster')
# NOTE: rollout starts with some delay which may take even 20 seconds.
# Also rollout itself takes more than 10 minutes for 3 Scylla members.
# So, sleep for some time to avoid race with presence of existing rollout process.
time.sleep(60)
self.k8s_cluster.kubectl(
f"rollout status statefulset/{self.params.get('k8s_scylla_cluster_name')}-"
f"{self.params.get('k8s_scylla_datacenter')}-{self.params.get('k8s_scylla_rack')}"
" --watch=true --timeout=20m",
timeout=1205,
namespace=self.k8s_cluster._scylla_namespace) # pylint: disable=protected-access
self.log.info('Step7 - Add new member to the Scylla cluster')
peer_db_node = self.db_cluster.nodes[0]
new_nodes = self.db_cluster.add_nodes(
count=1,
dc_idx=peer_db_node.dc_idx,
rack=peer_db_node.rack,
enable_auto_bootstrap=True)
self.db_cluster.wait_for_init(node_list=new_nodes, timeout=40 * 60)
self.db_cluster.wait_for_nodes_up_and_normal(nodes=new_nodes)
self.monitors.reconfigure_scylla_monitoring()
self.log.info('Step8 - Verify data in the Scylla cluster')
self.fill_and_verify_db_data(note='after operator upgrade and scylla member addition')
self.log.info('Step9 - Run c-s read workload')
self.verify_stress_thread(self.run_stress_thread(
stress_cmd=self._cs_add_node_flag(self.params.get('stress_cmd_r'))))
def wait_till_scylla_is_upgraded_on_all_nodes(self, target_version):
def _is_cluster_upgraded():
for node in self.db_cluster.nodes:
# NOTE: node.get_scylla_version() returns following structure of a scylla version:
# 4.4.1-0.20210406.00da6b5e9
full_version = node.get_scylla_version()
short_version = full_version.split("-")[0]
if target_version not in (full_version, short_version) or not node.db_up:
return False
return True
wait.wait_for(func=_is_cluster_upgraded, step=30, timeout=900, throw_exc=True,
text="Waiting until all nodes in the cluster are upgraded")
def wait_till_jmx_on_all_nodes(self):
for node in self.db_cluster.nodes:
node.wait_jmx_up(timeout=300)
def count_log_errors(self, search_pattern, step, search_for_idx_token_error=True):
schema_load_error_num = 0
for node in self.db_cluster.nodes:
errors = list(node.follow_system_log(patterns=[search_pattern], start_from_beginning=True))
schema_load_error_num += len(errors)
if search_for_idx_token_error:
self.search_for_idx_token_error_after_upgrade(node=node, step=step)
return schema_load_error_num
def get_email_data(self):
self.log.info('Prepare data for email')
email_data = self._get_common_email_data()
grafana_dataset = self.monitors.get_grafana_screenshot_and_snapshot(self.start_time) if self.monitors else {}
email_data.update({
"grafana_screenshots": grafana_dataset.get("screenshots", []),
"grafana_snapshots": grafana_dataset.get("snapshots", []),
"new_scylla_repo": self.params.get("new_scylla_repo"),
"new_version": self.params.get("new_version"),
"scylla_ami_id": self.params.get("ami_id_db_scylla") or "-",
})
return email_data
| agpl-3.0 | -2,831,030,781,541,779,500 | 53.62096 | 140 | 0.623171 | false |
whitehaven/Undulation-Devastation | Undulation-Devastation.py | 1 | 2482 | from __future__ import division
from random import uniform
from pyglet import clock, window
from pyglet.gl import *
import primitives
class Entity(object):
def __init__(self, id, size, x, y, rot):
self.id = id
self.circle = primitives.Circle(x=0, y=0, z=0, width=100, color=(1, 0, 0, 1), stroke=50)
def draw(self):
self.circle.render()
class World(object):
def __init__(self):
self.ents = {}
self.nextEntId = 0
clock.schedule_interval(self.spawnEntity, 0.25)
def spawnEntity(self, dt):
size = uniform(1.0, 100.0)
x = uniform(-100.0, 100.0)
y = uniform(-100.0, 100.0)
rot = uniform(0.0, 360.0)
ent = Entity(self.nextEntId, size, x, y, rot)
self.ents[ent.id] = ent
self.nextEntId += 1
return ent
def tick(self):
pass
def draw(self):
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
for ent in self.ents.values():
ent.draw()
class Camera(object):
def __init__(self, win, x=0.0, y=0.0, rot=0.0, zoom=1.0):
self.win = win
self.x = x
self.y = y
self.rot = rot
self.zoom = zoom
def worldProjection(self):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
widthRatio = self.win.width / self.win.height
gluOrtho2D(
-self.zoom * widthRatio,
self.zoom * widthRatio,
-self.zoom,
self.zoom)
def hudProjection(self):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluOrtho2D(0, self.win.width, 0, self.win.height)
class Hud(object):
def __init__(self, win):
self.fps = clock.ClockDisplay()
def draw(self):
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
self.fps.draw()
class App(object):
def __init__(self):
self.world = World()
self.win = window.Window(fullscreen=False, vsync=True)
self.camera = Camera(self.win, zoom=100.0)
self.hud = Hud(self.win)
clock.set_fps_limit(60)
def mainLoop(self):
while not self.win.has_exit:
self.win.dispatch_events()
self.world.tick()
self.camera.worldProjection()
self.world.draw()
self.camera.hudProjection()
self.hud.draw()
clock.tick()
self.win.flip()
app = App()
app.mainLoop()
| gpl-2.0 | -2,792,811,881,816,028,000 | 22.638095 | 96 | 0.556003 | false |
auag92/n2dm | Asap-3.8.4/Projects/NanoparticleMC/resume_amc_vac.py | 1 | 2344 | #PBS -l nodes=20:ppn=4:opteron4
#PBS -q verylong
#PBS -N amc_n100_conv1
#PBS -m ae
import os
from montecarlo import SurfaceMonteCarloData
from ase.cluster.cubic import FaceCenteredCubic
from ase.cluster import data
from asap3.MonteCarlo.Metropolis import Metropolis
from asap3.MonteCarlo.Moves import SurfaceMove
from asap3 import EMT
import numpy as np
from ase.visualize import view
from resizecluster import resizecluster
from ase.io.trajectory import PickleTrajectory
import sys
from atommontecarlodata import AtomMonteCarloData
from ase.parallel import world
from AdsCalc import adscalc
from time import time,sleep
import pickle
#Change note: Added gas option, check for indentation tab vs. spaces error.
#Added resume option.
#Arguments:
filename = sys.argv[1]
temperature = float(sys.argv[2])
nsteps = int(sys.argv[3])
outdir= sys.argv[4]
species = "AuO"
def read_and_do_montecarlo(filename):
d = SurfaceMonteCarloData()
d.read(filename)
print "Starting "+str(len(d))+" sims."
surfaces = data.fcc.surface_names
#for n in range(0,len(d)):
for n in range(world.rank,len(d),world.size):
file = outdir+"/a%05i.amc.gz" % n
if not os.path.exists(file):
layers = d[n][1] # Really d[n]["layers"]
atoms = FaceCenteredCubic(d.atomic_number,
surfaces, layers,latticeconstant=d.lattice_constant)
resizecluster(atoms, d.fitsize)
print "Resized number of atoms:", len(atoms)
do_monte_carlo(atoms,n,outdir)
world.barrier()#Let the cpu's wait until all in same state.
def do_monte_carlo(atoms,iteration,outdir):
tempcalc = EMT()
atoms.set_calculator(tempcalc)
Esmc = atoms.get_potential_energy()
mc = Metropolis(atoms=atoms,log=None)
surfmove =SurfaceMove()
mc.attach_move(surfmove)
outfilename = "a%05i.amc" % iteration
amcd = AtomMonteCarloData(atoms=atoms,surfmove=surfmove,temp=temperature,filename=outfilename,Esmc=Esmc)
mc.attach_observer(amcd.accept_move) #Because default event is at acceptmove
mc.attach_observer(amcd.reject_move, attime='reject')
amcd.accept_move() #We need to write the first configuration,
mc.run(nsteps, temp=temperature)
amcd.write(os.path.join(outdir,outfilename))
read_and_do_montecarlo(filename)
| mit | 8,054,333,485,439,922,000 | 31.109589 | 108 | 0.709471 | false |
test-pipeline/orthrus | orthrus/commands.py | 1 | 66101 | '''
Orthrus commands implementation
'''
import os
import sys
import shutil
import re
import subprocess
import random
import glob
import webbrowser
import tarfile
import time
import json
import string
from orthrusutils import orthrusutils as util
from builder import builder as b
from job import job as j
from spectrum.afl_sancov import AFLSancovReporter
from runtime.runtime import RuntimeAnalyzer
class OrthrusCreate(object):
def __init__(self, args, config, test=False):
self.args = args
self.config = config
self.test = test
self.orthrusdir = self.config['orthrus']['directory']
self.orthrus_subdirs = ['binaries', 'conf', 'logs', 'jobs', 'archive']
self.fail_msg_bin = "Could not find ELF binaries. While we cannot guarantee " \
"that all libraries were instrumented correctly, they most likely were."
def archive(self):
util.color_print_singleline(util.bcolors.OKGREEN, "\t\t[?] Rerun create? [y/n]...: ")
if not self.test and 'y' not in sys.stdin.readline()[0]:
return False
if not util.pprint_decorator_fargs(util.func_wrapper(shutil.move, '{}/binaries'.format(self.orthrusdir),
'{}/archive/binaries.{}'.format(self.orthrusdir,
time.strftime("%Y-%m-%d-%H:%M:%S"))),
'Archiving binaries to {}/archive'.format(self.orthrusdir), indent=2):
return False
return True
def verifycmd(self, cmd):
try:
subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError:
return False
return True
def verifyafl(self, binpath):
cmd = ['objdump -t ' + binpath + ' | grep __afl_maybe_log']
return self.verifycmd(cmd)
def verifyasan(self, binpath):
cmd = ['objdump -t ' + binpath + ' | grep __asan_get_shadow_mapping']
return self.verifycmd(cmd)
def verifyubsan(self, binpath):
cmd = ['objdump -t ' + binpath + ' | grep ubsan_init']
return self.verifycmd(cmd)
def verify_gcccov(self, binpath):
cmd = ['objdump -t ' + binpath + ' | grep gcov_write_block']
return self.verifycmd(cmd)
def verify_sancov(self, binpath):
cmd = ['objdump -t ' + binpath + ' | grep __sanitizer_cov_module_init']
return self.verifycmd(cmd)
def verify_asancov(self, binpath):
if not (self.verifyasan(binpath) and self.verify_sancov(binpath)):
return False
return True
def verify_ubsancov(self, binpath):
if not (self.verifyubsan(binpath) and self.verify_sancov(binpath)):
return False
return True
def verify(self, binpath, benv):
if 'afl' in benv.cc and not self.verifyafl(binpath):
return False
if ('-fsanitize=address' in benv.cflags or 'AFL_USE_ASAN=1' in benv.misc) and not self.verifyasan(binpath):
return False
if '-ftest-coverage' in benv.cflags and not self.verify_gcccov(binpath):
return False
if '-fsanitize-coverage' in benv.cflags and '-fsanitize=address' in benv.cflags and not self.verify_asancov(binpath):
return False
if '-fsanitize-coverage' in benv.cflags and '-fsanitize=undefined' in benv.cflags and not self.verify_ubsancov(binpath):
return False
return True
def create(self, dest, BEnv, logfn, gendict=False):
if not gendict:
install_path = dest
util.mkdir_p(install_path)
### Configure
config_flags = ['--prefix=' + os.path.abspath(install_path)] + \
self.args.configure_flags.split(" ")
else:
config_flags = self.args.configure_flags.split(" ")
builder = b.Builder(b.BuildEnv(BEnv),
config_flags,
self.config['orthrus']['directory'] + "/logs/" + logfn)
if not util.pprint_decorator(builder.configure, 'Configuring', 2):
return False
### Make install
if not gendict:
if not util.pprint_decorator(builder.make_install, 'Compiling', 2):
return False
util.copy_binaries(install_path + "bin/")
# Fixes https://github.com/test-pipeline/orthrus/issues/1
# Soft fail when no ELF binaries found.
binary_paths = util.return_elf_binaries(install_path + 'bin/')
if not util.pprint_decorator_fargs(binary_paths, 'Looking for ELF binaries', 2, fail_msg=self.fail_msg_bin):
return True
sample_binpath = random.choice(binary_paths)
if not util.pprint_decorator_fargs(util.func_wrapper(self.verify, sample_binpath, BEnv),
'Verifying instrumentation', 2):
return False
else:
if not util.pprint_decorator(builder.clang_sdict, 'Creating input dict via clang-sdict', 2):
return False
return True
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Creating Orthrus workspace")
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.config['orthrus']['directory']) is False,
'Checking if workspace exists', indent=2,
fail_msg='yes'):
if not self.archive():
return False
util.mkdir_p(self.config['orthrus']['directory'])
dirs = ['/{}/'.format(x) for x in self.orthrus_subdirs]
map(lambda x: util.mkdir_p(self.config['orthrus']['directory'] + x), dirs)
# AFL-ASAN
if self.args.afl_asan:
install_path = self.config['orthrus']['directory'] + "/binaries/afl-asan/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_afl_asan,
'afl-asan_inst.log'),
'Installing binaries for afl-fuzz with AddressSanitizer',
indent=1):
return False
#
# ASAN Debug
#
install_path = self.config['orthrus']['directory'] + "/binaries/asan-dbg/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_asan_debug,
'afl-asan_dbg.log'),
'Installing binaries for debug with AddressSanitizer',
indent=1):
return False
# AFL-ASAN-BLACKLIST
elif self.args.afl_asan_blacklist:
install_path = self.config['orthrus']['directory'] + "/binaries/afl-asan/"
is_blacklist = os.path.exists('asan_blacklist.txt')
if not util.pprint_decorator_fargs(is_blacklist, 'Checking if asan_blacklist.txt exists',
indent=2):
return False
if not util.pprint_decorator_fargs(
util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_afl_asan_blacklist,
'afl-asan_inst.log'),
'Installing binaries for afl-fuzz with AddressSanitizer (blacklist)',
indent=1):
return False
#
# ASAN Debug
#
install_path = self.config['orthrus']['directory'] + "/binaries/asan-dbg/"
if not util.pprint_decorator_fargs(
util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_asan_debug_blacklist,
'afl-asan_dbg.log'),
'Installing binaries for debug with AddressSanitizer (blacklist)',
indent=1):
return False
### AFL-HARDEN
if self.args.afl_harden:
install_path = self.config['orthrus']['directory'] + "/binaries/afl-harden/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_afl_harden,
'afl_harden.log'),
'Installing binaries for afl-fuzz in harden mode',
indent=1):
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path,
b.BuildEnv.BEnv_afl_harden_softfail,
'afl-harden_soft.log'),
'Retrying without the (sometimes problematic) AFL_HARDEN=1 setting',
indent=1):
return False
#
# Harden Debug
#
install_path = self.config['orthrus']['directory'] + "/binaries/harden-dbg/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_harden_debug,
'afl-harden_dbg.log'),
'Installing binaries for debug in harden mode',
indent=1):
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path,
b.BuildEnv.BEnv_harden_debug_softfail,
'afl-harden_dbg_soft.log'),
'Retrying without FORTIFY compilation flag',
indent=1):
return False
### Coverage
if self.args.coverage:
install_path = self.config['orthrus']['directory'] + "/binaries/coverage/gcc/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path, b.BuildEnv.BEnv_gcc_coverage,
'gcc_coverage.log'),
'Installing binaries for obtaining test coverage information',
indent=1):
return False
### SanitizerCoverage
if self.args.san_coverage:
if self.args.afl_asan:
install_path = self.config['orthrus']['directory'] + "/binaries/coverage/asan/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path,
b.BuildEnv.BEnv_asan_coverage,
'asan_coverage.log'),
'Installing binaries for obtaining ASAN coverage',
indent=1):
return False
if self.args.afl_harden:
install_path = self.config['orthrus']['directory'] + "/binaries/coverage/ubsan/"
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, install_path,
b.BuildEnv.BEnv_ubsan_coverage,
'ubsan_coverage.log'),
'Installing binaries for obtaining HARDEN coverage (via UBSAN)',
indent=1):
return False
if self.args.dictionary:
if not util.pprint_decorator_fargs(util.func_wrapper(self.create, None,
b.BuildEnv.BEnv_bear,
'bear.log', True),
'Generating input dictionary',
indent=1):
return False
return True
class OrthrusAdd(object):
def __init__(self, args, config):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
def copy_samples(self, jobroot_dir):
samplevalid = False
if os.path.isdir(self._args.sample):
for dirpath, dirnames, filenames in os.walk(self._args.sample):
for fn in filenames:
fpath = os.path.join(dirpath, fn)
if os.path.isfile(fpath):
shutil.copy(fpath, jobroot_dir + "/afl-in/")
if filenames:
samplevalid = True
elif os.path.isfile(self._args.sample):
samplevalid = True
shutil.copy(self._args.sample, jobroot_dir + "/afl-in/")
if not samplevalid:
return False
return True
def seed_job(self, rootdir, id):
if not util.pprint_decorator_fargs(util.func_wrapper(self.copy_samples, rootdir),
'Adding initial samples for job ID [{}]'.format(id), 2,
'seed dir or file invalid. No seeds copied'):
return False
return True
def write_asan_config(self, afl_in, afl_out, jobroot_dir, fuzzer=None, fuzzer_params=None):
## Create an afl-utils JSON config for AFL-ASAN fuzzing setting it as slave if AFL-HARDEN target exists
asanjob_config = {}
asanjob_config['input'] = afl_in
asanjob_config['output'] = afl_out
asanjob_config['target'] = ".orthrus/binaries/afl-asan/bin/{}".format(self.job.target)
asanjob_config['cmdline'] = self.job.params
# asanjob_config['file'] = "@@"
# asanjob_config.set("afl.ctrl", "file", ".orthrus/jobs/" + self.jobId + "/afl-out/.cur_input_asan")
asanjob_config['timeout'] = "3000+"
# See: https://github.com/mirrorer/afl/blob/master/docs/notes_for_asan.txt
asanjob_config['mem_limit'] = "none"
# if util.is64bit():
# asanjob_config['mem_limit'] = "none"
# else:
# asanjob_config['mem_limit'] = "none"
asanjob_config['session'] = "ASAN"
# https://github.com/rc0r/afl-utils/issues/34
# asanjob_config['interactive'] = False
if os.path.exists(self._config['orthrus']['directory'] + "/binaries/afl-harden"):
asanjob_config['master_instances'] = 0
if fuzzer:
asanjob_config['fuzzer'] = fuzzer
if fuzzer_params:
asanjob_config['afl_margs'] = fuzzer_params
self.write_config(asanjob_config, "{}/asan-job.conf".format(jobroot_dir))
def write_harden_config(self, afl_in, afl_out, jobroot_dir, fuzzer=None, fuzzer_params=None):
## Create an afl-utils JSON config for AFL-HARDEN
hardenjob_config = {}
hardenjob_config['input'] = afl_in
hardenjob_config['output'] = afl_out
hardenjob_config['target'] = ".orthrus/binaries/afl-harden/bin/{}".format(self.job.target)
hardenjob_config['cmdline'] = self.job.params
# hardenjob_config['file'] = "@@"
hardenjob_config['timeout'] = "3000+"
hardenjob_config['mem_limit'] = "none"
hardenjob_config['session'] = "HARDEN"
# hardenjob_config['interactive'] = False
if fuzzer:
hardenjob_config['fuzzer'] = fuzzer
if fuzzer_params:
hardenjob_config['afl_margs'] = fuzzer_params
self.write_config(hardenjob_config, "{}/harden-job.conf".format(jobroot_dir))
def write_config(self, config_dict, config_file):
with open(config_file, 'wb') as file:
json.dump(config_dict, file, indent=4)
def config_wrapper(self, afl_in, afl_out, jobroot_dir, fuzzer=None, fuzzer_params=None):
self.write_asan_config(afl_in, afl_out, jobroot_dir, fuzzer, fuzzer_params)
self.write_harden_config(afl_in, afl_out, jobroot_dir, fuzzer, fuzzer_params)
return True
def config_job(self, rootdir, id, fuzzer=None, fuzzer_params=None):
afl_dirs = [rootdir + '/{}'.format(dirname) for dirname in ['afl-in', 'afl-out']]
for dir in afl_dirs:
os.mkdir(dir)
# HT: http://stackoverflow.com/a/13694053/4712439
if not util.pprint_decorator_fargs(util.func_wrapper(self.config_wrapper, afl_dirs[0], afl_dirs[1],
rootdir, fuzzer, fuzzer_params),
'Configuring {} job for ID [{}]'.format(self.jobtype, id), 2):
return False
return True
def extract_job(self, jobroot_dir):
next_session = 0
if not tarfile.is_tarfile(self._args._import):
return False
if not os.path.exists(jobroot_dir + "/afl-out/"):
return False
syncDir = os.listdir(jobroot_dir + "/afl-out/")
for directory in syncDir:
if "SESSION" in directory:
next_session += 1
is_single = True
with tarfile.open(self._args._import, "r") as tar:
try:
info = tar.getmember("fuzzer_stats")
except KeyError:
is_single = False
if is_single:
outDir = jobroot_dir + "/afl-out/SESSION" + "{:03d}".format(next_session)
os.mkdir(outDir)
tar.extractall(outDir)
else:
tmpDir = jobroot_dir + "/tmp/"
os.mkdir(tmpDir)
tar.extractall(tmpDir)
for directory in os.listdir(jobroot_dir + "/tmp/"):
outDir = jobroot_dir + '/afl-out/'
shutil.move(tmpDir + directory, outDir)
shutil.rmtree(tmpDir)
return True
def import_job(self, rootdir, id, target, params):
if not util.pprint_decorator_fargs(util.func_wrapper(self.extract_job, rootdir),
'Importing afl sync dir for job ID [{}]'.format(id),
indent=2):
return False
util.minimize_and_reseed(self.orthrusdir, rootdir, id, target, params)
return True
def run_helper(self, rootdir, id, fuzzer, fuzzer_param):
if not self.config_job(rootdir, id, fuzzer, fuzzer_param):
return False
if self._args._import and not self.import_job(rootdir, id, self.job.target, self.job.params):
return False
if self._args.sample and not self.seed_job(rootdir, id):
return False
return True
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Adding new job to Orthrus workspace")
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir + "/binaries/"),
"Checking Orthrus workspace", 2,
'failed. Are you sure you did orthrus create -asan or -fuzz'):
return False
valid_jobtype = ((self._args.jobtype == 'routine') or (self._args.jobtype == 'abtests'))
if not util.pprint_decorator_fargs((self._args.jobtype and self._args.jobconf and valid_jobtype),
"Checking job type", 2,
'failed. --jobtype=[routine|abtests] or --jobconf argument missing, or'
' invalid job type.'):
return False
self.jobtype = self._args.jobtype
self.jobconf = self._args.jobconf
self.job = j.job(self._args.job, self.jobtype, self.orthrusdir, self.jobconf)
self.rootdirs = []
self.ids = []
self.fuzzers = []
self.fuzzer_param = []
if not util.pprint_decorator(self.job.materialize, 'Adding {} job'.format(self.jobtype), 2,
'Invalid a/b test configuration or existing job found!'):
return False
if self.jobtype == 'routine':
self.rootdirs.append(self.job.rootdir)
self.ids.append(self.job.id)
self.fuzzers.extend(self.job.fuzzers)
self.fuzzer_param.extend(self.job.fuzzer_args)
else:
self.rootdirs.extend(self.job.rootdir + '/{}'.format(id) for id in self.job.jobids)
self.ids.extend(self.job.jobids)
self.fuzzers.extend(self.job.fuzzers)
self.fuzzer_param.extend(self.job.fuzzer_args)
for rootdir, id, fuzzer, fuzzer_param in zip(self.rootdirs, self.ids, self.fuzzers, self.fuzzer_param):
if not self.run_helper(rootdir, id, fuzzer, fuzzer_param):
return False
return True
class OrthrusRemove(object):
fail_msg = "failed. Are you sure you have done orthrus add --job or passed the " \
"right job ID. orthrus show -j might help"
def __init__(self, args, config):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Removing job ID [{}]".format(self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Removing fuzzing job from Orthrus workspace")
job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(job_token.materialize, 'Retrieving job [{}]'.format(job_token.id), indent=2,
fail_msg=self.fail_msg):
return False
if not util.pprint_decorator_fargs(util.func_wrapper(shutil.move,
self.orthrusdir + "/jobs/{}/{}".format(job_token.type,
job_token.id),
self.orthrusdir + "/archive/" +
time.strftime("%Y-%m-%d-%H:%M:%S") + "-"
+ job_token.id),
'Archiving data for {} job [{}]'.format(job_token.type,job_token.id),
indent=2):
return False
j.remove_id_from_conf(job_token.jobsconf, job_token.id, job_token.type)
return True
class OrthrusStart(object):
def __init__(self, args, config, test=False):
self._args = args
self._config = config
self.test = test
self.orthrusdir = self._config['orthrus']['directory']
self.fail_msg = "failed. Are you sure you have done orthrus add --job or passed the " \
"right job ID. orthrus show -j might help"
self.is_harden = os.path.exists(self.orthrusdir + "/binaries/afl-harden")
self.is_asan = os.path.exists(self.orthrusdir + "/binaries/afl-asan")
def check_core_pattern(self):
cmd = ["cat /proc/sys/kernel/core_pattern"]
util.color_print_singleline(util.bcolors.OKGREEN, "\t\t[+] Checking core_pattern... ")
try:
if "core" not in subprocess.check_output(" ".join(cmd), shell=True, stderr=subprocess.STDOUT):
util.color_print(util.bcolors.FAIL, "failed")
util.color_print(util.bcolors.FAIL, "\t\t\t[-] Please do echo core | "
"sudo tee /proc/sys/kernel/core_pattern")
return False
except subprocess.CalledProcessError as e:
print e.output
return False
util.color_print(util.bcolors.OKGREEN, "done")
def print_cmd_diag(self, file):
output = open(self.orthrusdir + file, "r")
for line in output:
if "Starting master" in line or "Starting slave" in line:
util.color_print(util.bcolors.OKGREEN, "\t\t\t" + line)
if " Master " in line or " Slave " in line:
util.color_print_singleline(util.bcolors.OKGREEN, "\t\t\t\t" + "[+] " + line)
output.close()
def compute_cores_per_job(self, job_type):
if job_type == 'routine':
if self.is_harden and self.is_asan:
self.core_per_subjob = self.total_cores / 2
elif (self.is_harden and not self.is_asan) or (not self.is_harden and self.is_asan):
self.core_per_subjob = self.total_cores
else:
if self.is_harden and self.is_asan:
self.core_per_subjob = self.total_cores / (2 * self.job_token.num_jobs)
elif (self.is_harden and not self.is_asan) or (not self.is_harden and self.is_asan):
self.core_per_subjob = self.total_cores / self.job_token.num_jobs
def _start_fuzzers(self, jobroot_dir, job_type):
if os.listdir(jobroot_dir + "/afl-out/") == []:
start_cmd = "start"
add_cmd = "add"
else:
start_cmd = "resume"
add_cmd = "resume"
self.check_core_pattern()
env = os.environ.copy()
env.update({'AFL_SKIP_CPUFREQ': '1'})
if self.is_harden and self.is_asan:
harden_file = self.orthrusdir + "/logs/afl-harden.log"
cmd = ["afl-multicore", "--config={}".format(jobroot_dir) + "/harden-job.conf",
start_cmd, str(self.core_per_subjob), "-v"]
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_cmd, " ".join(cmd), env, harden_file),
'Starting AFL harden fuzzer as master', indent=2):
return False
self.print_cmd_diag("/logs/afl-harden.log")
# if self.is_asan:
asan_file = self.orthrusdir + "/logs/afl-asan.log"
cmd = ["afl-multicore", "--config={}".format(jobroot_dir) + "/asan-job.conf ", add_cmd, \
str(self.core_per_subjob), "-v"]
# This ensures SEGV crashes are named sig:11 and not sig:06
# See: https://groups.google.com/forum/#!topic/afl-users/aklNGdKbpkI
util.overrride_default_afl_asan_options(env)
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_cmd, " ".join(cmd), env, asan_file),
'Starting AFL ASAN fuzzer as slave', indent=2):
return False
self.print_cmd_diag("/logs/afl-asan.log")
elif (self.is_harden and not self.is_asan):
harden_file = self.orthrusdir + "/logs/afl-harden.log"
cmd = ["afl-multicore", "--config={}".format(jobroot_dir) + "/harden-job.conf",
start_cmd, str(self.core_per_subjob), "-v"]
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_cmd, " ".join(cmd), env, harden_file),
'Starting AFL harden fuzzer as master', indent=2):
return False
self.print_cmd_diag("/logs/afl-harden.log")
elif (not self.is_harden and self.is_asan):
asan_file = self.orthrusdir + "/logs/afl-asan.log"
cmd = ["afl-multicore", "--config={}".format(jobroot_dir) + "/asan-job.conf", start_cmd, \
str(self.core_per_subjob), "-v"]
# This ensures SEGV crashes are named sig:11 and not sig:06
# See: https://groups.google.com/forum/#!topic/afl-users/aklNGdKbpkI
util.overrride_default_afl_asan_options(env)
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_cmd, " ".join(cmd), env, asan_file),
'Starting AFL ASAN fuzzer as master', indent=2):
return False
self.print_cmd_diag("/logs/afl-asan.log")
return True
def start_and_cover(self):
for rootdir, id in zip(self.rootdirs, self.ids):
if not util.pprint_decorator_fargs(util.func_wrapper(self._start_fuzzers, rootdir, self.job_token.type),
'Starting fuzzer for {} job ID [{}]'.format(self.job_token.type,id),
indent=2):
try:
subprocess.call("pkill -9 afl-fuzz", shell=True, stderr=subprocess.STDOUT)
except OSError, subprocess.CalledProcessError:
return False
return False
# Live coverage is only supported for routine jobs
# To support live coverage for abtests jobs, we would need to create two code base dir each with a gcno file
# set due to the way gcov works.
if self._args.coverage:
if self.job_token.type == 'routine':
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_afl_cov, self.orthrusdir, rootdir,
self.job_token.target, self.job_token.params, True,
self.test),
'Starting afl-cov for {} job ID [{}]'.format(self.job_token.type, id),
indent=2):
return False
else:
util.color_print(util.bcolors.WARNING, "\t\t[+] Live coverage for a/b tests is not supported at the"
" moment")
return True
return True
def min_and_reseed(self):
for rootdir, id in zip(self.rootdirs, self.ids):
if len(os.listdir(rootdir + "/afl-out/")) > 0:
if not util.pprint_decorator_fargs(util.func_wrapper(util.minimize_and_reseed, self.orthrusdir, rootdir,
id, self.job_token.target, self.job_token.params),
'Minimizing afl sync dir for {} job ID [{}]'.
format(self.job_token.type,id),
indent=2):
return False
return True
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Starting fuzzers for job ID [{}]".
format(self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Starting fuzzing jobs")
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2, fail_msg=self.fail_msg):
return False
self.total_cores = int(util.getnproc())
'''
n = number of cores
Half the cores for AFL Harden (1 Master: n/2 - 1 slave)
Half the cores for AFL ASAN (n/2 slaves)
OR if asan only present
1 AFL ASAN Master, n-1 AFL ASAN slaves
In a/b test mode, each group has
Half the cores for AFL Harden (1 Master: n/4 - 1 slave)
Half the cores for AFL ASAN (n/4 slaves)
OR if asan only present
1 AFL ASAN Master, n/2 - 1 AFL ASAN slaves
'''
self.compute_cores_per_job(self.job_token.type)
if self.core_per_subjob == 0:
self.core_per_subjob = 1
if self.job_token.type != 'routine':
util.color_print(util.bcolors.WARNING, "\t\t\t[-] You do not have sufficient processor cores to carry"
" out a scientific a/b test. Consider a routine job instead.")
self.rootdirs = []
self.ids = []
if self.job_token.type == 'routine':
self.rootdirs.append(self.job_token.rootdir)
self.ids.append(self.job_token.id)
else:
self.rootdirs.extend(self.job_token.rootdir + '/{}'.format(id) for id in self.job_token.jobids)
self.ids.extend(self.job_token.jobids)
if self._args.minimize:
if not self.min_and_reseed():
return False
if not self.start_and_cover():
return False
# for rootdir, id in zip(self.rootdirs, self.ids):
# if not self.min_and_reseed(rootdir, id):
# return False
return True
class OrthrusStop(object):
def __init__(self, args, config, test=False):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
self.routinedir = self.orthrusdir + j.ROUTINEDIR
self.abtestsdir = self.orthrusdir + j.ABTESTSDIR
self.test = test
# NOTE: Supported for routine fuzzing jobs only
def get_afl_cov_pid(self):
pid_regex = re.compile(r'afl_cov_pid[^\d]+(?P<pid>\d+)')
jobs_dir = self.routinedir
jobs_list = os.walk(jobs_dir).next()[1]
pids = []
if not jobs_list:
return pids
for job in jobs_list:
dir = jobs_dir + "/" + job + "/afl-out/cov"
if not os.path.isdir(dir):
continue
file = dir + "/afl-cov-status"
if not os.path.isfile(file):
continue
with open(file) as f:
content = f.readline()
match = pid_regex.match(content)
if match:
pids.append(match.groups()[0])
return pids
def kill_fuzzers_test(self):
if self.job_token.type == 'routine':
return util.run_cmd("pkill -15 afl-fuzz")
else:
for fuzzer in self.job_token.fuzzers:
# FIXME: Silently failing
if not util.run_cmd("pkill -15 {}".format(fuzzer)):
return True
return True
def run_helper(self):
if self.test:
if not util.pprint_decorator(self.kill_fuzzers_test, "Stopping {} job for ID [{}]".format(
self.job_token.type, self.job_token.id), indent=2):
return False
else:
kill_cmd = ["afl-multikill -S HARDEN && afl-multikill -S ASAN"]
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_cmd, kill_cmd),
"Stopping {} job for ID [{}]".format(self.job_token.type,
self.job_token.id),
indent=2):
return False
## Kill afl-cov only for routine jobs
if self._args.coverage and self.job_token.type == 'routine':
util.color_print_singleline(util.bcolors.OKGREEN, "\t\t[+] Stopping afl-cov for {} job... ".
format(self.job_token.type))
for pid in self.get_afl_cov_pid():
kill_aflcov_cmd = ["kill", "-15", pid]
if not util.run_cmd(" ".join(kill_aflcov_cmd)):
return False
util.color_print(util.bcolors.OKGREEN, "done")
return True
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Stopping fuzzers for job ID [{}]".
format(self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Stopping fuzzing jobs")
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2):
return False
return self.run_helper()
class OrthrusShow(object):
def __init__(self, args, config, test=False):
self._args = args
self._config = config
self.test = test
self.orthrusdir = self._config['orthrus']['directory']
self.jobsconf = self.orthrusdir + j.JOBCONF
self.routinedir = self.orthrusdir + j.ROUTINEDIR
self.abtestsdir = self.orthrusdir + j.ABTESTSDIR
self.fail_msg = "No coverage info found. Have you run orthrus coverage or" \
" orthrus start -c already?"
def opencov(self, syncDir, job_type, job_id):
cov_web_indexhtml = syncDir + "/cov/web/index.html"
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, cov_web_indexhtml),
'Opening coverage html for {} job ID [{}]'.format(job_type, job_id),
indent=2, fail_msg=self.fail_msg):
return False
if self.test:
return True
webbrowser.open_new_tab(cov_web_indexhtml)
return True
# TODO: Add feature
# def opencov_abtests(self):
#
# control_sync = '{}/{}/afl-out'.format(self.job_token.rootdir, self.job_token.joba_id)
# exp_sync = '{}/{}/afl-out'.format(self.job_token.rootdir, self.job_token.jobb_id)
#
# if not self.opencov(control_sync, self.job_token.type, self.job_token.joba_id):
# return False
# if not self.opencov(exp_sync, self.job_token.type, self.job_token.jobb_id):
# return False
# return True
def whatsup(self, syncDir):
try:
output = subprocess.check_output(["afl-whatsup", "-s", syncDir])
except subprocess.CalledProcessError as e:
print e.output
return False
output = output[output.find("==\n\n") + 4:]
for line in output.splitlines():
util.color_print(util.bcolors.OKBLUE, "\t" + line)
triaged_unique = 0
unique_dir = syncDir + "/../unique"
if os.path.exists(unique_dir):
triaged_unique = len(glob.glob(unique_dir + "/asan/*id*sig*")) + \
len(glob.glob(unique_dir + "/harden/*id*sig*"))
util.color_print(util.bcolors.OKBLUE, "\t Triaged crashes : " + str(triaged_unique))
return True
def whatsup_abtests(self, sync_list):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "Multivariate test status")
for idx, val in enumerate(sync_list):
util.color_print(util.bcolors.OKBLUE, "Config {} [{}]".format(idx, self.job_token.jobids[idx]))
if not self.whatsup(val):
return False
return True
def show_job(self):
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2):
return False
if self.job_token.type == 'routine':
return self.whatsup('{}/afl-out'.format(self.job_token.rootdir))
else:
return self.whatsup_abtests('{}/{}/afl-out'.format(self.job_token.rootdir, id) for id in
self.job_token.jobids)
def show_conf(self):
with open(self.jobsconf, 'r') as jobconf_fp:
jobsconf_dict = json.load(jobconf_fp)
self.routine_list = jobsconf_dict['routine']
self.abtest_list = jobsconf_dict['abtests']
# self.routine_syncdirs = ['{}/{}'.format(self.routinedir,item['id']) for item in self.routine_list]
# self.abtest_rootdirs = ['{}/{}'.format(self.abtestsdir,item['id']) for item in self.abtest_list]
for idx, routine in enumerate(self.routine_list):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "Configured routine jobs:")
util.color_print(util.bcolors.OKBLUE, "\t" + str(idx) + ") [" + routine['id'] + "] " +
routine['target'] + " " + routine['params'])
for idx, abtest in enumerate(self.abtest_list):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "Configured multivariate tests:")
for i in range(0, abtest['num_jobs']):
alp_idx = string.ascii_uppercase[i]
util.color_print(util.bcolors.OKBLUE, "\t" + str(idx) + ") [" + abtest['id'] + "] " +
abtest['target'] + " " + abtest['params'])
util.color_print(util.bcolors.OKBLUE, "\t" + "Config {} [{}]".format(i, abtest['jobids'][i]))
util.color_print(util.bcolors.OKBLUE, "\t" + "Fuzzer {}: {}\t Fuzzer A args: {}".
format(alp_idx, abtest['fuzzers'][i],abtest['fuzzer_args'][i]))
return True
def show_cov(self):
# We have already processed the job
if self.job_token.type == 'routine':
util.color_print(util.bcolors.OKGREEN, "\t[+] Opening coverage in new browser tabs")
return self.opencov('{}/afl-out'.format(self.job_token.rootdir), self.job_token.type, self.job_token.id)
else:
util.color_print(util.bcolors.WARNING, "\t[+] Coverage interface for A/B tests is not supported at the "
"moment")
return True
# util.color_print(util.bcolors.OKGREEN, "\t[+] Opening A/B test coverage in new browser tabs")
# return self.opencov_abtests()
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Checking stats and config")
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
if self._args.job_id:
if not self.show_job():
return False
if self._args.cov and not self.show_cov():
return False
elif self._args.conf:
return self.show_conf()
return True
class OrthrusTriage(object):
def __init__(self, args, config, test=False):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
self.fail_msg = "failed. Are you sure you have done orthrus add --job or passed the " \
"right job ID? orthrus show -j might help."
self.fail_msg_asan = 'No ASAN binary found. Triage requires an ASAN binary to continue. Please do orthrus ' \
'create -asan'
self.is_harden = os.path.exists(self.orthrusdir + "/binaries/afl-harden")
self.is_asan = os.path.exists(self.orthrusdir + "/binaries/afl-asan")
self.jobsconf = self.orthrusdir + j.JOBCONF
self.routinedir = self.orthrusdir + j.ROUTINEDIR
self.abtestsdir = self.orthrusdir + j.ABTESTSDIR
self.test = test
def tidy(self, crash_dir):
dest = crash_dir + "/.scripts"
if not os.path.exists(dest):
os.mkdir(dest)
for script in glob.glob(crash_dir + "/gdb_script*"):
shutil.copy(script, dest)
os.remove(script)
return True
def triage(self, jobroot_dir, inst, indir=None, outdir=None):
env = os.environ.copy()
util.triage_asan_options(env)
if inst is 'harden':
prefix = 'HARDEN'
elif inst is 'asan' or inst is 'all':
prefix = 'ASAN'
inst = 'asan'
else:
util.color_print(util.bcolors.FAIL, "failed!")
return False
if not indir:
syncDir = jobroot_dir + "/afl-out/"
else:
syncDir = indir
if not outdir:
dirname = jobroot_dir + "/exploitable/" + "{}/".format(prefix) + "crashes"
if not os.path.exists(dirname):
os.makedirs(dirname)
triage_outDir = dirname
else:
triage_outDir = outdir
logfile = self.orthrusdir + "/logs/" + "afl-{}_dbg.log".format(inst)
launch = self.orthrusdir + "/binaries/{}-dbg/bin/".format(inst) + \
self.job_token.target + " " + \
self.job_token.params.replace("&", "\&")
cmd = " ".join(["afl-collect", "-r", "-j", util.getnproc(), "-e gdb_script",
syncDir, triage_outDir, "--", launch])
if not util.pprint_decorator_fargs(util.func_wrapper(util.run_cmd, "ulimit -c 0; " + cmd, env, logfile),
'Triaging {} job ID [{}]'.format(self.job_token.type, self.job_token.id),
indent=2):
return False
if not util.pprint_decorator_fargs(util.func_wrapper(self.tidy, triage_outDir), 'Tidying crash dir',
indent=2):
return False
return True
def prepare_for_rerun(self, jobroot_dir):
util.color_print_singleline(util.bcolors.OKGREEN, "[?] Rerun triaging? [y/n]...: ")
if not self.test and 'y' not in sys.stdin.readline()[0]:
return False
shutil.move(jobroot_dir + "/unique/", jobroot_dir + "/unique." + time.strftime("%Y-%m-%d-%H:%M:%S"))
os.mkdir(jobroot_dir + "/unique/")
# Archive exploitable crashes from prior triaging if necessary
exp_path = jobroot_dir + "/exploitable"
if os.path.exists(exp_path):
shutil.move(exp_path, "{}.{}".format(exp_path, time.strftime("%Y-%m-%d-%H:%M:%S")))
os.mkdir(exp_path)
return True
def make_unique_dirs(self, jobroot_dir):
unique_dir = '{}/unique'.format(jobroot_dir)
if not os.path.exists(unique_dir):
os.mkdir(unique_dir)
return True
else:
return False
def get_formatted_crashnames(self, path, prefix):
list = glob.glob('{}/{}/crashes/*id*sig*'.format(path, prefix))
## Rename files
for file in list:
head, fn = os.path.split(file)
newfn = '{}:{}'.format(prefix, fn)
shutil.move(file, os.path.join(head, newfn))
return glob.glob('{}/{}/crashes/*id*sig*'.format(path, prefix))
def triage_wrapper(self, jobroot_dir, job_id):
if not self.make_unique_dirs(jobroot_dir) and not self.prepare_for_rerun(jobroot_dir):
return False
if self.is_harden:
if not util.pprint_decorator_fargs(util.func_wrapper(self.triage, jobroot_dir, 'harden'),
'Triaging harden mode crashes for {} job ID [{}]'.format(
self.job_token.type, job_id), indent=2):
return False
if self.is_asan:
if not util.pprint_decorator_fargs(util.func_wrapper(self.triage, jobroot_dir, 'asan'),
'Triaging asan mode crashes for {} job ID [{}]'.format(
self.job_token.type, job_id), indent=2):
return False
# BUGFIX: Second pass may be suboptimal (eliminate HARDEN crashes). Instead simply copy all.
exp_path = jobroot_dir + "/exploitable"
uniq_path = jobroot_dir + "/unique"
if os.path.exists(exp_path):
exp_all = []
exp_asan_crashes = self.get_formatted_crashnames(exp_path, 'ASAN')
exp_harden_crashes = self.get_formatted_crashnames(exp_path, 'HARDEN')
exp_all.extend(exp_asan_crashes)
exp_all.extend(exp_harden_crashes)
for file in exp_all:
shutil.copy(file, uniq_path)
triaged_crashes = glob.glob(uniq_path + "/*id*sig*")
util.color_print(util.bcolors.OKGREEN, "\t\t[+] Triaged " + str(len(triaged_crashes)) + \
" crashes. See {}".format(uniq_path))
if not triaged_crashes:
util.color_print(util.bcolors.OKBLUE, "\t\t[+] Nothing to do")
return True
# Organize unique crashes
asan_crashes = glob.glob('{}/ASAN*id*sig*'.format(uniq_path))
harden_crashes = glob.glob('{}/HARDEN*id*sig*'.format(uniq_path))
if asan_crashes:
uniq_asan_dir = '{}/asan'.format(uniq_path)
util.mkdir_p(uniq_asan_dir)
for file in asan_crashes:
shutil.move(file, uniq_asan_dir)
if harden_crashes:
uniq_harden_dir = '{}/harden'.format(uniq_path)
util.mkdir_p(uniq_harden_dir)
for file in harden_crashes:
shutil.move(file, uniq_harden_dir)
return True
def triage_abtests(self):
count = 0
for rootdir,id in [('{}/{}'.format(self.job_token.rootdir, jobId), jobId) for jobId in self.job_token.jobids]:
group = 'Config {}'.format(count)
count += 1
if not util.pprint_decorator_fargs(util.func_wrapper(self.triage_wrapper, rootdir, id),
'Triaging crashes in {}'.format(group), indent=2):
return False
return True
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Triaging crashes for job ID [{}]".format(
self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
# if not util.pprint_decorator_fargs(self.is_asan, 'Looking for ASAN debug binary', indent=2,
# fail_msg=self.fail_msg_asan):
# return False
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2, fail_msg=self.fail_msg):
return False
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Triaging crashes for {} job ID [{}]".format(
self.job_token.type, self.job_token.id))
if self.job_token.type == 'routine':
return self.triage_wrapper(self.job_token.rootdir, self.job_token.id)
# return self.triage_routine()
else:
return self.triage_abtests()
class OrthrusCoverage(object):
def __init__(self, args, config):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
self.fail_msg = "failed. Are you sure you have done orthrus add --job or passed the " \
"right job ID? orthrus show -j might help."
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Checking coverage for job ID [{}]".format(
self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2, fail_msg=self.fail_msg):
return False
if self.job_token.type == 'abtests':
util.color_print(util.bcolors.WARNING, "\t[+] Coverage interface for A/B tests is not supported at the "
"moment")
return True
util.color_print(util.bcolors.OKGREEN, "\t\t[+] Checking test coverage for {} job ID [{}]".format(
self.job_token.type, self.job_token.id))
#run_afl_cov(orthrus_dir, jobroot_dir, target_arg, params, livemode=False, test=False):
util.run_afl_cov(self.orthrusdir, self.job_token.rootdir, self.job_token.target, self.job_token.params)
util.color_print(util.bcolors.OKGREEN, "\t\t[+] This might take a while. Please check {} for progress."
.format(self.job_token.rootdir + "/afl-out/cov/afl-cov.log"))
return True
class OrthrusSpectrum(object):
def __init__(self, args, config):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
self.fail_msg = "failed. Are you sure you have done orthrus add --job or passed the " \
"right job ID? orthrus show -j might help."
self.is_harden = os.path.exists(self.orthrusdir + "/binaries/coverage/ubsan")
self.is_asan = os.path.exists(self.orthrusdir + "/binaries/coverage/asan")
def run_afl_sancov(self, is_asan=False):
if is_asan:
bin_path = self.orthrusdir + "/binaries/coverage/asan/bin/{}".format(self.job_token.target)
crash_dir = self.job_token.rootdir + "/unique/asan"
sanitizer = 'asan'
target = self.orthrusdir + "/binaries/coverage/asan/bin/" + \
self.job_token.target + " " + self.job_token.params.replace("@@", "AFL_FILE")
else:
bin_path = self.orthrusdir + "/binaries/coverage/ubsan/bin/{}".format(self.job_token.target)
crash_dir = self.job_token.rootdir + "/unique/harden"
sanitizer = 'ubsan'
target = self.orthrusdir + "/binaries/coverage/ubsan/bin/" + \
self.job_token.target + " " + self.job_token.params.replace("@@", "AFL_FILE")
# def __init__(self, parsed_args, cov_cmd, bin_path, crash_dir, afl_out, sanitizer):
reporter = AFLSancovReporter(self._args, target, bin_path, crash_dir, '{}/afl-out'.format(self.job_token.rootdir),
sanitizer)
return reporter.run()
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Starting spectrum generation for job ID [{}]".format(
self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2, fail_msg=self.fail_msg):
return False
if self.job_token.type == 'abtests':
util.color_print(util.bcolors.WARNING, "\t[+] Spectrum generation for A/B tests is not supported at the "
"moment")
return True
if self._args.version:
reporter = AFLSancovReporter(self._args, None, None, None, None, None)
if reporter.run():
return False
return True
self.crash_dir = '{}/unique'.format(self.job_token.rootdir)
if not os.path.exists(self.crash_dir):
util.color_print(util.bcolors.WARNING, "\t\t[+] It looks like you are attempting to generate crash spectrum "
"before crash triage. Please triage first.")
return False
self.asan_crashes = glob.glob('{}/asan/*id*sig*'.format(self.crash_dir))
self.harden_crashes = glob.glob('{}/harden/*id*sig*'.format(self.crash_dir))
if not self.asan_crashes and not self.harden_crashes:
util.color_print(util.bcolors.INFO, "\t\t[+] There are no crashes to analyze!")
return True
if (self.asan_crashes and not self.is_asan) or (self.harden_crashes and not self.is_harden):
util.color_print(util.bcolors.WARNING, "\t\t[+] It looks like you are attempting to generate crash spectrum "
"without sanitizer coverage binaries. Did you run orthrus create "
"with -sancov argument?")
return False
self.is_second_run = os.path.exists('{}/crash-analysis/spectrum'.format(self.job_token.rootdir))
if self.is_second_run and not self._args.overwrite:
util.color_print(util.bcolors.WARNING, "\t\t[+] It looks like crash spectrum has already been generated. "
"Please pass --overwrite to regenerate. Old data will be lost unless "
"manually archived.")
return False
util.color_print(util.bcolors.OKGREEN, "\t\t[+] Generating crash spectrum {} job ID [{}]".format(
self.job_token.type, self.job_token.id))
if self.asan_crashes:
if self.run_afl_sancov(True):
return False
if self.harden_crashes:
if self.run_afl_sancov():
return False
return True
class OrthrusRuntime(object):
def __init__(self, args, config):
self._args = args
self._config = config
self.orthrusdir = self._config['orthrus']['directory']
self.is_harden = os.path.exists(self.orthrusdir + "/binaries/harden-dbg")
self.is_asan = os.path.exists(self.orthrusdir + "/binaries/asan-dbg")
self.fail_msg = "failed. Are you sure you have done orthrus add --job or passed the " \
"right job ID? orthrus show -j might help."
def analyze(self, job_rootdir, is_asan=False):
if is_asan:
bin_path = self.orthrusdir + "/binaries/asan-dbg/bin/{}".format(self.job_token.target)
crash_dir = job_rootdir + "/unique/asan"
sanitizer = 'asan'
target = self.orthrusdir + "/binaries/asan-dbg/bin/" + \
self.job_token.target + " " + self.job_token.params
else:
bin_path = self.orthrusdir + "/binaries/harden-dbg/bin/{}".format(self.job_token.target)
crash_dir = job_rootdir + "/unique/harden"
sanitizer = 'harden'
target = self.orthrusdir + "/binaries/harden-dbg/bin/" + \
self.job_token.target + " " + self.job_token.params
#__init__(self, job_token, crash_dir, sanitizer)
analyzer = RuntimeAnalyzer(job_rootdir, bin_path, target, crash_dir, sanitizer)
return analyzer.run()
def analyze_wrapper(self, job_rootdir, job_id):
crash_dir = '{}/unique'.format(job_rootdir)
if not os.path.exists(crash_dir):
util.color_print(util.bcolors.WARNING, "\t\t[+] It looks like you are attempting to analyze crashes you don't "
"have or not triaged. Please run triage!")
return False
asan_crashes = glob.glob('{}/asan/*id*sig*'.format(crash_dir))
harden_crashes = glob.glob('{}/harden/*id*sig*'.format(crash_dir))
if not asan_crashes and not harden_crashes:
util.color_print(util.bcolors.INFO, "\t\t[+] There are no crashes to analyze!")
return True
if (asan_crashes and not self.is_asan) or (harden_crashes and not self.is_harden):
util.color_print(util.bcolors.WARNING, "\t\t[+] It looks like you are attempting to invoke crash analysis "
"without sanitizer and/or debug binaries. Did you run orthrus create "
"with -asan -fuzz?")
return False
runtime_path = '{}/crash-analysis/runtime'.format(job_rootdir)
is_second_run = os.path.exists(runtime_path)
if is_second_run:
if not self._args.regenerate:
util.color_print(util.bcolors.WARNING, "\t\t[+] It looks like dynamic analysis results are already there. "
"Please pass --regenerate to regenerate. Old data will be archived.")
return False
else:
util.color_print(util.bcolors.OKGREEN, "\t\t[+] Archiving old analysis results.")
shutil.move(runtime_path, "{}.{}".format(runtime_path, time.strftime("%Y-%m-%d-%H:%M:%S")))
util.color_print(util.bcolors.OKGREEN, "\t\t[+] Performing dynamic analysis of crashes for {} job ID [{}]".format(
self.job_token.type, job_id))
if asan_crashes:
if not self.analyze(job_rootdir, True):
return False
if harden_crashes:
if not self.analyze(job_rootdir):
return False
return True
def runtime_abtests(self):
count = 0
for rootdir, id in [('{}/{}'.format(self.job_token.rootdir, jobId), jobId) for jobId in self.job_token.jobids]:
group = 'Config {}'.format(count)
count += 1
if not util.pprint_decorator_fargs(util.func_wrapper(self.analyze_wrapper, rootdir, id),
'Analyzing crashes in {} group'.format(group), indent=2):
return False
return True
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Starting dynamic analysis of all crashes for"
" job ID [{}]".format(self._args.job_id))
if not util.pprint_decorator_fargs(util.func_wrapper(os.path.exists, self.orthrusdir),
"Checking Orthrus workspace", 2,
'failed. Are you sure you ran orthrus create -asan -fuzz?'):
return False
self.job_token = j.jobtoken(self.orthrusdir, self._args.job_id)
if not util.pprint_decorator(self.job_token.materialize, 'Retrieving job ID [{}]'.format(self.job_token.id),
indent=2, fail_msg=self.fail_msg):
return False
if self.job_token.type == 'abtests':
return self.runtime_abtests()
else:
return self.analyze_wrapper(self.job_token.rootdir, self.job_token.id)
class OrthrusDestroy(object):
def __init__(self, args, config, testinput=None):
self._args = args
self._config = config
self.testinput = testinput
self.orthrusdir = self._config['orthrus']['directory']
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Destroy Orthrus workspace")
util.color_print_singleline(util.bcolors.OKGREEN, "\t[?] Delete complete workspace? [y/n]...: ")
if (self.testinput and 'y' in self.testinput) or 'y' in sys.stdin.readline()[0]:
if not util.pprint_decorator_fargs(util.func_wrapper(shutil.rmtree, self.orthrusdir),
'Deleting workspace', indent=2):
return False
return True
class OrthrusValidate(object):
def __init__(self, args, config):
self._args = args
self._config = config
self.success_msg = "\t\t[+] All requirements met. Orthrus is ready for use!"
def get_on(self):
return [item for item in self._config['dependencies'] if item[1] == 'on']
def run(self):
util.color_print(util.bcolors.BOLD + util.bcolors.HEADER, "[+] Validating Orthrus dependencies")
util.color_print(util.bcolors.OKGREEN, "\t\t[+] The following programs have been marked as required in " \
"~/.orthrus/orthrus.conf")
for prog, _ in self.get_on():
util.color_print(util.bcolors.OKGREEN, "\t\t\t[+] {}".format(prog))
if not util.pprint_decorator_fargs(util.func_wrapper(util.validate_inst, self._config),
'Checking if requirements are met', indent=2):
return False
util.color_print(util.bcolors.OKGREEN, self.success_msg)
return True | gpl-3.0 | 6,888,073,941,601,113,000 | 44.650552 | 128 | 0.535408 | false |
karih/Flask-HTTPAuth | setup.py | 1 | 1090 | """
Flask-HTTPAuth
--------------
Basic and Digest HTTP authentication for Flask routes.
"""
from setuptools import setup
setup(
name='Flask-HTTPAuth',
version='3.0.1',
url='http://github.com/miguelgrinberg/flask-httpauth/',
license='MIT',
author='Miguel Grinberg',
author_email='[email protected]',
description='Basic and Digest HTTP authentication for Flask routes',
long_description=__doc__,
py_modules=['flask_httpauth'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
test_suite="tests",
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
| mit | -3,904,473,348,168,233,500 | 27.684211 | 72 | 0.620183 | false |
hhanh/column-generation-framework | examples/survivable-net/report_ini.py | 1 | 2799 | import os
import ConfigParser
import glob
from prettytable import PrettyTable
import re
inputdir = "ini/N*s[2,3,4,5]*.ini"
inputdir = "ini/NSF*s1*.ini"
#inputdir = "ini/24NET-s1*.ini"
#inputdir = "ini/E*s1*.ini"
#inputdir = "ini/24NET-s*e90*.ini"
#inputdir = "ini/24NET-hs*e120*.ini"
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split('(\d+)', text) ]
if __name__ == "__main__" :
print "REPORT"
tableII = PrettyTable( ["INSTANCE" , "GEN-CONFIG" , "SEL-CONFIG" , "ZILP" , "GAP" , "MEAN" , "STD" ] )
tableIII = PrettyTable( ["INSTANCE" , "N-ISSUES" , "Fail-P-Link" , "ADD-ROUTE" , "ADD-PROTECT1" , "Ratio1" , "ADD-PROTECT2" , "Ratio2" ] )
listFile = glob.glob( inputdir )
for inifile in sorted( listFile , key = natural_keys ):
print "analyzing " , inifile
config = ConfigParser.ConfigParser()
config.read( inifile )
llink = float( config.get("INPUT", "LLINK"))
nconnect = "%.1f" % ( 100 * float( config.get("RESERVE","NCONNECT-ISSUES" )) / llink )
nconfiggen = config.get("COLUMN","CONFIG-GEN" )
nconfigsel = config.get("COLUMN","CONFIG-SEL" )
# maxfl = float( config.get("PROTECTION","MAX-PROTECT-FL" ) )
fperl = "%.1f" % float(config.get( "RESERVE" , "FAIL-PER-LINK" ))
gap_route = float( config.get("ADD-ROUTE" , "GAP" ) )
gap_protect = float( config.get( "PROTECTION" , "GAP" ))
gap_reserve = float( config.get("RESERVE","GAP" ))
gap_restore = float( config.get("RESTORE" , "GAP" ) )
gap = "%.1f" % (( gap_route + gap_protect + gap_reserve + gap_restore ) / 4.0 )
meanre = "%.1f" % float(config.get("WAVE" , "AVE-WAVE" ))
stdre = "%.1f" % float(config.get("WAVE" , "STD-WAVE" ))
addprotect1 = "%.1f" % float(config.get("RESERVE" , "ADD-PROTECT-PERCENT" ))
protectratio1 = "%.1f" % float( config.get("RESERVE" , "REDUNDANCY" ))
addprotect2 = "%.1f" % float(config.get("RESTORE" , "ADD-PROTECT-PERCENT" ))
protectratio2 = "%.1f" % float( config.get("RESTORE" , "REDUNDANCY" ))
zilp = "%.1f" % float(config.get( "RESERVE" , "WORK" ))
addroute = "%.1f" % float(config.get("RESTORE" , "ADD-ROUTING" ))
tableII.add_row( [ inifile , nconfiggen , nconfigsel , zilp , gap , meanre , stdre ] )
tableIII.add_row( [ inifile , nconnect , fperl , addroute , addprotect1 , protectratio1 , addprotect2 , protectratio2 ] )
# print table II
print tableII
print tableIII
| mit | 3,862,890,060,105,415,700 | 31.172414 | 142 | 0.586281 | false |
vathpela/anaconda | tests/nosetests/pyanaconda_tests/__init__.py | 1 | 4688 | #
# Copyright (C) 2017 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
import gi
gi.require_version("GLib", "2.0")
from gi.repository import GLib
from textwrap import dedent
from mock import Mock
from pyanaconda.modules.common.constants.interfaces import KICKSTART_MODULE
class run_in_glib(object):
"""Run the test methods in GLib.
:param timeout: Timeout in seconds when the loop will be killed.
"""
def __init__(self, timeout):
self._timeout = timeout
self._result = None
def __call__(self, func):
def kill_loop(loop):
loop.quit()
return False
def run_in_loop(*args, **kwargs):
self._result = func(*args, **kwargs)
def create_loop(*args, **kwargs):
loop = GLib.MainLoop()
GLib.idle_add(run_in_loop, *args, **kwargs)
GLib.timeout_add_seconds(self._timeout, kill_loop, loop)
loop.run()
return self._result
return create_loop
def check_kickstart_interface(test, interface, ks_in, ks_out, ks_valid=True, ks_tmp=None):
"""Test the parsing and generating of a kickstart module.
:param test: instance of TestCase
:param interface: instance of KickstartModuleInterface
:param ks_in: string with the input kickstart
:param ks_out: string with the output kickstart
:param ks_valid: True if the input kickstart is valid, otherwise False
:param ks_tmp: string with the temporary output kickstart
"""
callback = Mock()
interface.PropertiesChanged.connect(callback)
# Read a kickstart,
if ks_in is not None:
ks_in = dedent(ks_in).strip()
result = {k: v.unpack() for k, v in interface.ReadKickstart(ks_in).items()}
if ks_valid:
test.assertEqual(result, {"success": True})
else:
test.assertIn("success", result)
test.assertEqual(result["success"], False)
test.assertIn("line_number", result)
test.assertIn("error_message", result)
return
# Generate a kickstart
ks_out = dedent(ks_out).strip()
test.assertEqual(ks_out, interface.GenerateKickstart().strip())
# Test the properties changed callback.
if ks_in is not None:
callback.assert_any_call(KICKSTART_MODULE.interface_name, {'Kickstarted': True}, [])
else:
test.assertEqual(interface.Kickstarted, False)
callback.assert_not_called()
if ks_tmp is None:
ks_tmp = ks_out
test.assertEqual(ks_tmp, interface.GenerateTemporaryKickstart().strip())
def check_dbus_property(test, interface_id, interface, property_name,
in_value, out_value=None, getter=None, setter=None, changed=None):
"""Check DBus property.
:param test: instance of TestCase
:param interface_id: instance of DBusInterfaceIdentifier
:param interface: instance of a DBus interface
:param property_name: a DBus property name
:param in_value: an input value of the property
:param out_value: an output value of the property or None
:param getter: a property getter or None
:param setter: a property setter or None
:param changed: a dictionary of changed properties or None
"""
callback = Mock()
interface.PropertiesChanged.connect(callback)
if out_value is None:
out_value = in_value
# Set the property.
if not setter:
setter = getattr(interface, "Set{}".format(property_name))
setter(in_value)
if not changed:
changed = {property_name: out_value}
callback.assert_called_once_with(interface_id.interface_name, changed, [])
# Get the property.
if not getter:
getter = lambda: getattr(interface, property_name)
test.assertEqual(getter(), out_value)
| gpl-2.0 | -9,157,636,387,226,441,000 | 32.248227 | 92 | 0.672142 | false |
kdart/pycopia | aid/setup.py | 1 | 1235 | #!/usr/bin/python2.7
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
import os
from setuptools import setup
NAME = "pycopia-aid"
#REVISION = os.environ.get("PYCOPIA_REVISION", "0standalone")
VERSION = "1.0"
setup (name=NAME, version=VERSION,
namespace_packages = ["pycopia"],
packages = ["pycopia",],
test_suite = "test.AidTests",
author = "Keith Dart",
author_email = "[email protected]",
description = "General purpose objects that enhance Python's core modules.",
long_description = """General purpose objects that enhance Python's core modules.
You can use these modules in place of the standard modules with the same name.
This package is part of the collection of python packages known as pycopia.""",
license = "LGPL",
keywords = "pycopia framework Python extensions",
url = "http://www.pycopia.net/",
dependency_links = [
"http://www.pycopia.net/download/"
],
#download_url = "ftp://ftp.pycopia.net/pub/python/%s-%s.tar.gz" % (NAME, VERSION),
classifiers = ["Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Intended Audience :: Developers"],
)
| apache-2.0 | -2,782,851,439,800,748,500 | 33.305556 | 86 | 0.651012 | false |
cjaymes/pyscap | src/scap/model/oval_5/defs/windows/RegkeyEffectiveRights53Behaviors.py | 1 | 1075 | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>.
import logging
from scap.model.oval_5.defs.windows.RegistryBehaviors import RegistryBehaviors
logger = logging.getLogger(__name__)
class RegkeyEffectiveRights53Behaviors(RegistryBehaviors):
MODEL_MAP = {
'attributes': {
'include_group': {'type': 'BooleanType', 'default': True},
'resolve_group': {'type': 'BooleanType', 'default': False},
}
}
| gpl-3.0 | -1,732,871,684,196,633,300 | 34.833333 | 78 | 0.72 | false |
wger-project/wger | wger/gym/tests/test_contract_options.py | 1 | 2911 | # This file is part of wger Workout Manager.
#
# wger Workout Manager 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.
#
# wger Workout Manager 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 Affero General Public License
# Django
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
delete_testcase_add_methods,
)
from wger.gym.models import ContractOption
class AddContractOptionTestCase(WgerAddTestCase):
"""
Tests creating a new contract option
"""
object_class = ContractOption
url = reverse('gym:contract-option:add', kwargs={'gym_pk': 1})
data = {'name': 'Some name'}
user_success = (
'manager1',
'manager2',
)
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
class EditContractOptionTestCase(WgerEditTestCase):
"""
Tests editing a contract option
"""
pk = 1
object_class = ContractOption
url = 'gym:contract-option:edit'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
data = {'name': 'Standard contract 16-Gj'}
class DeleteContractOptionTestCase(WgerDeleteTestCase):
"""
Tests deleting a contract option
"""
pk = 1
object_class = ContractOption
url = 'gym:contract-option:delete'
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
delete_testcase_add_methods(DeleteContractOptionTestCase)
class AccessContractOptionOverviewTestCase(WgerAccessTestCase):
"""
Test accessing the contract option page
"""
url = reverse('gym:contract-option:list', kwargs={'gym_pk': 1})
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
| agpl-3.0 | 4,026,260,675,147,435,000 | 22.860656 | 78 | 0.608382 | false |
google/grr | colab/grr_colab/representer.py | 1 | 10790 | #!/usr/bin/env python
"""Module that contains representers for values returned by Python API."""
import ipaddress
import os
from typing import Dict, Text, List, Optional, Any, Union
import humanize
import IPython
from IPython.lib import pretty
from grr_colab import convert
from grr_colab._textify import client
from grr_colab._textify import stat
from grr_response_proto import jobs_pb2
from grr_response_proto import osquery_pb2
from grr_response_proto import sysinfo_pb2
def register_representers():
ipython = IPython.get_ipython()
pretty_formatter = ipython.display_formatter.formatters['text/plain']
pretty_formatter.for_type(jobs_pb2.StatEntry, stat_entry_pretty)
pretty_formatter.for_type(jobs_pb2.BufferReference, buffer_reference_pretty)
pretty_formatter.for_type(sysinfo_pb2.Process, process_pretty)
pretty_formatter.for_type(jobs_pb2.NetworkAddress, network_address_pretty)
pretty_formatter.for_type(jobs_pb2.Interface, interface_pretty)
pretty_formatter.for_type(osquery_pb2.OsqueryTable, osquery_table_pretty)
def stat_entry_pretty(stat_entry: jobs_pb2.StatEntry, p: pretty.PrettyPrinter,
cycle: bool) -> None:
del cycle # Unused.
p.text(str(_StatEntryData(stat_entry)))
def buffer_reference_pretty(ref: jobs_pb2.BufferReference,
p: pretty.PrettyPrinter, cycle: bool) -> None:
del cycle # Unused.
p.text(str(_BufferReferenceData(ref)))
def process_pretty(process: sysinfo_pb2.Process, p: pretty.PrettyPrinter,
cycle: bool) -> None:
del cycle # Unused.
p.text(str(_ProcessData(process)))
def network_address_pretty(address: jobs_pb2.NetworkAddress,
p: pretty.PrettyPrinter, cycle: bool) -> None:
del cycle # Unused.
p.text(str(_NetworkAddressData(address)))
def interface_pretty(iface: jobs_pb2.Interface, p: pretty.PrettyPrinter,
cycle: bool) -> None:
del cycle # Unused.
p.text(pretty.pretty(_InterfaceData(iface)))
def osquery_table_pretty(table: osquery_pb2.OsqueryTable,
p: pretty.PrettyPrinter, cycle: bool) -> None:
del cycle # Unused.
df = convert.from_osquery_table(table)
p.text(str(df))
class _RepresenterList(list):
"""Parent of representer lists that ensures that slices have the same type."""
def __getitem__(self, key: Union[int, slice]) -> Union[Any, List[Any]]:
if isinstance(key, slice):
return type(self)(super().__getitem__(key))
return super().__getitem__(key)
class StatEntryList(_RepresenterList):
"""Representer for a list of stat entries."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._hierarchy = None # type: Optional[Dict[Text, List]]
self._build_hierarchy()
def _build_hierarchy(self) -> None:
"""Builds hierarchy of stat entries in list.
Returns:
Nothing.
"""
self._hierarchy = {'': []}
items = sorted(self, key=lambda _: _.pathspec.path)
for stat_entry in items:
path = os.path.normpath(stat_entry.pathspec.path)
parent = os.path.dirname(path)
if parent not in self._hierarchy:
self._hierarchy[parent] = []
self._hierarchy[''].append((parent, None))
self._hierarchy[parent].append((path, stat_entry))
self._hierarchy[path] = []
def _repr_contents(self, root: Text, p: pretty.PrettyPrinter) -> None:
with p.group(4, '', ''):
p.group_stack[-1].want_break = True
for path, stat_entry in self._hierarchy[root]:
p.breakable()
p.text(str(_StatEntryData(stat_entry)))
self._repr_contents(path, p)
def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
"""Print list of stat entries in IPython.
Args:
p: Pretty printer to pass output to.
cycle: True, if printer detected a cycle.
Returns:
Nothing.
"""
if cycle:
raise AssertionError('Cycle in a stat entry list')
if not self:
p.text('No results.')
return
with p.group(0, '', ''):
p.group_stack[-1].want_break = True
for path, _ in self._hierarchy['']:
p.breakable()
p.text(path)
self._repr_contents(path, p)
p.breakable()
class BufferReferenceList(_RepresenterList):
"""Representer for a list of buffer references."""
def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
"""Print list of buffer references in IPython.
Args:
p: Pretty printer to pass output to.
cycle: True, if printer detected a cycle.
Returns:
Nothing.
"""
if cycle:
raise AssertionError('Cycle in a buffer reference list')
if not self:
p.text('No results.')
return
with p.group(0, '', ''):
p.group_stack[-1].want_break = True
for ref in self:
p.breakable()
p.text(str(_BufferReferenceData(ref)))
p.breakable()
class ClientList(_RepresenterList):
"""Representer for a list of clients."""
def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
"""Print list of clients in IPython.
Args:
p: Pretty printer to pass output to.
cycle: True, if printer detected a cycle.
Returns:
Nothing.
"""
if cycle:
raise AssertionError('Cycle in a client list')
if not self:
p.text('No results.')
return
with p.group(0, '', ''):
p.group_stack[-1].want_break = True
for c in self:
p.breakable()
p.text(pretty.pretty(c))
p.breakable()
class InterfaceList(_RepresenterList):
"""Representer for a list of interfaces."""
def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
"""Print list of interfaces in IPython.
Args:
p: Pretty printer to pass output to.
cycle: True, if printer detected a cycle.
Returns:
Nothing.
"""
if cycle:
raise AssertionError('Cycle in an interface list')
if not self:
p.text('No results.')
return
with p.group(0, '', ''):
p.group_stack[-1].want_break = True
for iface in self:
p.breakable()
p.text(pretty.pretty(_InterfaceData(iface)))
class ProcessList(_RepresenterList):
"""Representer for a list of processes."""
def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
"""Print list of processes in IPython.
Args:
p: Pretty printer to pass output to.
cycle: True, if printer detected a cycle.
Returns:
Nothing.
"""
if cycle:
raise AssertionError('Cycle in an process list')
if not self:
p.text('No results.')
return
header = (
'{pid:>6s} {user:9s} {ni:>3s} {virt:>5s} {res:>5s} {s:1s} {cpu:4s} '
'{mem:4s} {cmd}')
header = header.format(
pid='PID',
user='USER',
ni='NI',
virt='VIRT',
res='RES',
s='S',
cpu='CPU%',
mem='MEM%',
cmd='Command')
with p.group(0, '', ''):
p.group_stack[-1].want_break = True
p.breakable()
p.text(header[:p.max_width])
for process in self:
p.breakable()
p.text(str(_ProcessData(process))[:p.max_width])
p.breakable()
class _StatEntryData(object):
"""Class that encapsulates stat entry data displayed in IPython."""
def __init__(self, stat_entry: jobs_pb2.StatEntry) -> None:
self.size = stat.size(stat_entry)
self.abs_path = os.path.normpath(stat_entry.pathspec.path)
self.name = stat.name(stat_entry)
self.icon = stat.icon(stat_entry)
self.mode = stat.mode(stat_entry)
def __str__(self) -> Text:
return '{icon} {name} ({mode} {abs_path}, {size})'.format(
icon=self.icon,
name=self.name,
abs_path=self.abs_path,
size=self.size,
mode=self.mode)
class _BufferReferenceData(object):
"""Class that encapsulates buffer reference data displayed in IPython."""
def __init__(self, ref: jobs_pb2.BufferReference) -> None:
self.path = os.path.normpath(ref.pathspec.path)
self.start = ref.offset
self.end = ref.offset + ref.length
self.data = ref.data
def __str__(self) -> Text:
data_repr = repr(self.data)
return '{path}:{start}-{end}: {data}'.format(
path=self.path, start=self.start, end=self.end, data=data_repr)
class _InterfaceData(object):
"""Class that encapsulates interface data displayed in IPython."""
def __init__(self, iface: jobs_pb2.Interface) -> None:
self.name = iface.ifname
self.addresses = iface.addresses
self.mac = client.mac(iface.mac_address)
def _repr_pretty_(self, p: pretty.PrettyPrinter, cycle: bool) -> None:
"""Print interface in IPython.
Args:
p: Pretty printer to pass output to.
cycle: True, if printer detected a cycle.
Returns:
Nothing.
"""
del cycle # Unused.
iface_data = '{name} (MAC: {mac}):'.format(name=self.name, mac=self.mac)
with p.group(0, iface_data, ''):
p.group_stack[-1].want_break = True
with p.group(4, '', ''):
p.group_stack[-1].want_break = True
for addr in self.addresses:
p.breakable()
p.text(str(_NetworkAddressData(addr)))
p.breakable()
class _NetworkAddressData(object):
"""Class that encapsulates network address data displayed in IPython."""
def __init__(self, address: jobs_pb2.NetworkAddress) -> None:
if address.address_type == jobs_pb2.NetworkAddress.INET6:
self.type = 'inet6'
self.address = str(ipaddress.IPv6Address(address.packed_bytes))
else:
self.type = 'inet'
self.address = str(ipaddress.IPv4Address(address.packed_bytes))
def __str__(self) -> Text:
return '{type} {address}'.format(type=self.type, address=self.address)
class _ProcessData(object):
"""Class that encapsulates process data displayed in IPython."""
def __init__(self, process: sysinfo_pb2.Process) -> None:
self.pid = process.pid
self.user = process.username[:9]
self.nice = process.nice
self.virt = humanize.naturalsize(process.VMS_size, gnu=True, format='%.0f')
self.res = humanize.naturalsize(process.RSS_size, gnu=True, format='%.0f')
self.status = process.status[:1].upper()
self.cpu = '{:.1f}'.format(process.cpu_percent)
self.mem = '{:.1f}'.format(process.memory_percent)
self.command = process.exe
def __str__(self) -> Text:
data = ('{pid:6d} {user:9s} {ni:3d} {virt:>5s} {res:>5s} {s:1s} {cpu:>4s} '
'{mem:>4s} {cmd}')
return data.format(
pid=self.pid,
user=self.user,
ni=self.nice,
virt=str(self.virt),
res=str(self.res),
s=self.status,
cpu=self.cpu,
mem=self.mem,
cmd=self.command)
| apache-2.0 | 1,675,262,207,874,269,000 | 27.394737 | 80 | 0.626599 | false |
harry-7/addons-server | src/olympia/ratings/tests/test_serializers.py | 1 | 8787 | # -*- coding: utf-8 -*-
from mock import Mock
from rest_framework.test import APIRequestFactory
from olympia.amo.templatetags.jinja_helpers import absolutify
from olympia.amo.tests import TestCase, addon_factory, user_factory
from olympia.ratings.models import Rating
from olympia.ratings.serializers import RatingSerializer
class TestBaseRatingSerializer(TestCase):
def setUp(self):
self.request = APIRequestFactory().get('/')
self.view = Mock(spec=['get_addon_object'])
self.user = user_factory()
def serialize(self, **extra_context):
context = {
'request': self.request,
'view': self.view,
}
context.update(extra_context)
serializer = RatingSerializer(context=context)
return serializer.to_representation(self.rating)
def test_basic(self):
addon = addon_factory()
self.view.get_addon_object.return_value = addon
self.rating = Rating.objects.create(
addon=addon, user=self.user, rating=4,
version=addon.current_version, body=u'This is my rëview. Like ît?',
title=u'My Review Titlé')
result = self.serialize()
assert result['id'] == self.rating.pk
assert result['addon'] == {
'id': addon.pk,
'slug': addon.slug,
}
assert result['body'] == unicode(self.rating.body)
assert result['created'] == (
self.rating.created.replace(microsecond=0).isoformat() + 'Z')
assert result['title'] == unicode(self.rating.title)
assert result['previous_count'] == int(self.rating.previous_count)
assert result['is_latest'] == self.rating.is_latest
assert result['rating'] == int(self.rating.rating)
assert result['reply'] is None
assert result['user'] == {
'id': self.user.pk,
'name': unicode(self.user.name),
'url': None,
'username': self.user.username,
}
assert result['version'] == {
'id': self.rating.version.id,
'version': self.rating.version.version
}
self.rating.update(version=None)
result = self.serialize()
assert result['version'] is None
def test_url_for_yourself(self):
addon = addon_factory()
self.view.get_addon_object.return_value = addon
self.rating = Rating.objects.create(
addon=addon, user=self.user, rating=4,
version=addon.current_version, body=u'This is my rëview. Like ît?',
title=u'My Review Titlé')
# should include the account profile for your own requests
self.request.user = self.user
result = self.serialize()
assert result['user']['url'] == absolutify(self.user.get_url_path())
def test_url_for_admins(self):
addon = addon_factory()
self.view.get_addon_object.return_value = addon
self.rating = Rating.objects.create(
addon=addon, user=self.user, rating=4,
version=addon.current_version, body=u'This is my rëview. Like ît?',
title=u'My Review Titlé')
# should include account profile url for admins
admin = user_factory()
self.grant_permission(admin, 'Users:Edit')
self.request.user = admin
result = self.serialize()
assert result['user']['url'] == absolutify(self.user.get_url_path())
def test_addon_slug_even_if_view_doesnt_return_addon_object(self):
addon = addon_factory()
self.view.get_addon_object.return_value = None
self.rating = Rating.objects.create(
addon=addon, user=self.user, rating=4,
version=addon.current_version, body=u'This is my rëview. Like ît?',
title=u'My Review Titlé')
result = self.serialize()
assert result['id'] == self.rating.pk
assert result['addon'] == {
'id': addon.pk,
'slug': addon.slug,
}
def test_with_previous_count(self):
addon = addon_factory()
self.rating = Rating.objects.create(
addon=addon, user=self.user, rating=4,
version=addon.current_version, body=u'This is my rëview. Like ît?',
title=u'My Review Titlé')
self.rating.update(is_latest=False, previous_count=42)
result = self.serialize()
assert result['id'] == self.rating.pk
assert result['previous_count'] == 42
assert result['is_latest'] is False
def test_with_reply(self):
reply_user = user_factory()
addon = addon_factory(users=[reply_user])
self.rating = Rating.objects.create(
addon=addon, user=self.user, version=addon.current_version,
body=u'This is my rëview. Like ît ?', title=u'My Review Titlé')
reply = Rating.objects.create(
addon=addon, user=reply_user, version=addon.current_version,
body=u'Thîs is a reply.', title=u'My rèply', reply_to=self.rating)
result = self.serialize()
assert result['reply']
assert 'rating' not in result['reply']
assert 'reply' not in result['reply']
assert result['reply']['id'] == reply.pk
assert result['reply']['body'] == unicode(reply.body)
assert result['reply']['created'] == (
reply.created.replace(microsecond=0).isoformat() + 'Z')
assert result['reply']['title'] == unicode(reply.title)
assert result['reply']['user'] == {
'id': reply_user.pk,
'name': unicode(reply_user.name),
# should be the profile for a developer
'url': absolutify(reply_user.get_url_path()),
'username': reply_user.username,
}
def test_reply_profile_url_for_yourself(self):
addon = addon_factory()
reply_user = user_factory()
self.rating = Rating.objects.create(
addon=addon, user=self.user, version=addon.current_version,
body=u'This is my rëview. Like ît ?', title=u'My Review Titlé')
Rating.objects.create(
addon=addon, user=reply_user, version=addon.current_version,
body=u'Thîs is a reply.', title=u'My rèply', reply_to=self.rating)
# should be the profile for your own requests
self.request.user = reply_user
result = self.serialize()
assert result['reply']['user']['url'] == absolutify(
reply_user.get_url_path())
def test_with_deleted_reply(self):
addon = addon_factory()
reply_user = user_factory()
self.rating = Rating.objects.create(
addon=addon, user=self.user, version=addon.current_version,
body=u'This is my rëview. Like ît ?', title=u'My Review Titlé')
reply = Rating.objects.create(
addon=addon, user=reply_user, version=addon.current_version,
body=u'Thîs is a reply.', title=u'My rèply', reply_to=self.rating)
reply.delete()
result = self.serialize()
assert result['reply'] is None
def test_with_deleted_reply_but_view_allowing_it_to_be_shown(self):
reply_user = user_factory()
addon = addon_factory(users=[reply_user])
self.view.get_addon_object.return_value = addon
self.view.should_access_deleted_reviews = True
self.rating = Rating.objects.create(
addon=addon, user=self.user, version=addon.current_version,
body=u'This is my rëview. Like ît ?', title=u'My Review Titlé')
reply = Rating.objects.create(
addon=addon, user=reply_user, version=addon.current_version,
body=u'Thîs is a reply.', title=u'My rèply', reply_to=self.rating)
result = self.serialize()
assert result['reply']
assert 'rating' not in result['reply']
assert 'reply' not in result['reply']
assert result['reply']['id'] == reply.pk
assert result['reply']['body'] == unicode(reply.body)
assert result['reply']['created'] == (
reply.created.replace(microsecond=0).isoformat() + 'Z')
assert result['reply']['title'] == unicode(reply.title)
assert result['reply']['user'] == {
'id': reply_user.pk,
'name': unicode(reply_user.name),
'url': absolutify(reply_user.get_url_path()),
'username': reply_user.username,
}
def test_readonly_fields(self):
serializer = RatingSerializer(context={'request': self.request})
assert serializer.fields['created'].read_only is True
assert serializer.fields['id'].read_only is True
assert serializer.fields['reply'].read_only is True
assert serializer.fields['user'].read_only is True
| bsd-3-clause | 5,646,163,326,788,702,000 | 40.478673 | 79 | 0.602719 | false |
charlesthk/python-mailchimp | mailchimp3/entities/storecartlines.py | 3 | 5203 | # coding=utf-8
"""
The E-commerce Store Cart Lines endpoint API endpoint
Documentation: http://developer.mailchimp.com/documentation/mailchimp/reference/ecommerce/stores/carts/lines/
Schema: https://api.mailchimp.com/schema/3.0/Ecommerce/Stores/Carts/Lines/Instance.json
"""
from __future__ import unicode_literals
from mailchimp3.baseapi import BaseApi
class StoreCartLines(BaseApi):
"""
Each Cart contains one or more Cart Lines, which represent a specific
Product Variant that a Customer has added to their shopping cart.
"""
def __init__(self, *args, **kwargs):
"""
Initialize the endpoint
"""
super(StoreCartLines, self).__init__(*args, **kwargs)
self.endpoint = 'ecommerce/stores'
self.store_id = None
self.cart_id = None
self.line_id = None
def create(self, store_id, cart_id, data):
"""
Add a new line item to an existing cart.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param cart_id: The id for the cart.
:type cart_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"product_id": string*,
"product_variant_id": string*,
"quantity": integer*,
"price": number*
}
"""
self.store_id = store_id
self.cart_id = cart_id
if 'id' not in data:
raise KeyError('The cart line must have an id')
if 'product_id' not in data:
raise KeyError('The cart line must have a product_id')
if 'product_variant_id' not in data:
raise KeyError('The cart line must have a product_variant_id')
if 'quantity' not in data:
raise KeyError('The cart line must have a quantity')
if 'price' not in data:
raise KeyError('The cart line must have a price')
response = self._mc_client._post(url=self._build_path(store_id, 'carts', cart_id, 'lines'), data=data)
if response is not None:
self.line_id = response['id']
else:
self.line_id = None
return response
def all(self, store_id, cart_id, get_all=False, **queryparams):
"""
Get information about a cart’s line items.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param cart_id: The id for the cart.
:type cart_id: :py:class:`str`
:param get_all: Should the query get all results
:type get_all: :py:class:`bool`
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
queryparams['count'] = integer
queryparams['offset'] = integer
"""
self.store_id = store_id
self.cart_id = cart_id
self.line_id = None
if get_all:
return self._iterate(url=self._build_path(store_id, 'carts', cart_id, 'lines'), **queryparams)
else:
return self._mc_client._get(url=self._build_path(store_id, 'carts', cart_id, 'lines'), **queryparams)
def get(self, store_id, cart_id, line_id, **queryparams):
"""
Get information about a specific cart line item.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param cart_id: The id for the cart.
:type cart_id: :py:class:`str`
:param line_id: The id for the line item of a cart.
:type line_id: :py:class:`str`
:param queryparams: The query string parameters
queryparams['fields'] = []
queryparams['exclude_fields'] = []
"""
self.store_id = store_id
self.cart_id = cart_id
self.line_id = line_id
return self._mc_client._get(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id), **queryparams)
def update(self, store_id, cart_id, line_id, data):
"""
Update a specific cart line item.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param cart_id: The id for the cart.
:type cart_id: :py:class:`str`
:param line_id: The id for the line item of a cart.
:type line_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
"""
self.store_id = store_id
self.cart_id = cart_id
self.line_id = line_id
return self._mc_client._patch(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id), data=data)
def delete(self, store_id, cart_id, line_id):
"""
Delete a cart.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param cart_id: The id for the cart.
:type cart_id: :py:class:`str`
:param line_id: The id for the line item of a cart.
:type line_id: :py:class:`str`
"""
self.store_id = store_id
self.cart_id = cart_id
self.line_id = line_id
return self._mc_client._delete(url=self._build_path(store_id, 'carts', cart_id, 'lines', line_id))
| mit | -7,206,840,209,417,515,000 | 34.868966 | 118 | 0.578158 | false |
shanzi/tchelper | api/urls.py | 1 | 1114 | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from rest_framework.routers import DefaultRouter
from api.viewsets import (
UserProfileViewSet,
ProblemViewSet,
ProblemAssignmentViewSet,
ProblemSheetViewSet,
ProblemCommentViewSet,
)
router = DefaultRouter(trailing_slash=False)
router.register('profile', UserProfileViewSet)
router.register('problems', ProblemViewSet)
router.register('assignments', ProblemAssignmentViewSet)
router.register('sheets', ProblemSheetViewSet, base_name='sheet')
router.register('comments', ProblemCommentViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^test_html_email/(\d)$', 'api.views.test_html_email'),
url(r'^test_text_email/(\d)$', 'api.views.test_text_email'),
)
| bsd-2-clause | -1,496,908,478,364,556,500 | 33.8125 | 98 | 0.653501 | false |
liucode/tempest-master | tempest/api/compute/admin/test_live_migration.py | 1 | 7428 | # Copyright 2012 OpenStack Foundation
# 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 testtools
from tempest.api.compute import base
from tempest.common import waiters
from tempest import config
from tempest import test
CONF = config.CONF
class LiveBlockMigrationTestJSON(base.BaseV2ComputeAdminTest):
_host_key = 'OS-EXT-SRV-ATTR:host'
@classmethod
def skip_checks(cls):
super(LiveBlockMigrationTestJSON, cls).skip_checks()
if not CONF.compute_feature_enabled.live_migration:
skip_msg = ("%s skipped as live-migration is "
"not available" % cls.__name__)
raise cls.skipException(skip_msg)
if len(cls._get_compute_hostnames()) < 2:
raise cls.skipTest(
"Less than 2 compute nodes, skipping migration test.")
@classmethod
def setup_clients(cls):
super(LiveBlockMigrationTestJSON, cls).setup_clients()
cls.admin_hosts_client = cls.os_adm.hosts_client
cls.admin_servers_client = cls.os_adm.servers_client
cls.admin_migration_client = cls.os_adm.migrations_client
@classmethod
def _get_compute_hostnames(cls):
body = cls.admin_hosts_client.list_hosts()['hosts']
return [
host_record['host_name']
for host_record in body
if host_record['service'] == 'compute'
]
def _get_server_details(self, server_id):
body = self.admin_servers_client.show_server(server_id)['server']
return body
def _get_host_for_server(self, server_id):
return self._get_server_details(server_id)[self._host_key]
def _migrate_server_to(self, server_id, dest_host, volume_backed):
block_migration = (CONF.compute_feature_enabled.
block_migration_for_live_migration and
not volume_backed)
body = self.admin_servers_client.live_migrate_server(
server_id, host=dest_host, block_migration=block_migration,
disk_over_commit=False)
return body
def _get_host_other_than(self, host):
for target_host in self._get_compute_hostnames():
if host != target_host:
return target_host
def _get_server_status(self, server_id):
return self._get_server_details(server_id)['status']
def _create_server(self, volume_backed=False):
server = self.create_test_server(wait_until="ACTIVE",
volume_backed=volume_backed)
return server['id']
def _volume_clean_up(self, server_id, volume_id):
body = self.volumes_client.show_volume(volume_id)['volume']
if body['status'] == 'in-use':
self.servers_client.detach_volume(server_id, volume_id)
self.volumes_client.wait_for_volume_status(volume_id, 'available')
self.volumes_client.delete_volume(volume_id)
def _test_live_migration(self, state='ACTIVE', volume_backed=False):
"""Tests live migration between two hosts.
Requires CONF.compute_feature_enabled.live_migration to be True.
:param state: The vm_state the migrated server should be in before and
after the live migration. Supported values are 'ACTIVE'
and 'PAUSED'.
:param volume_backed: If the instance is volume backed or not. If
volume_backed, *block* migration is not used.
"""
# Live migrate an instance to another host
server_id = self._create_server(volume_backed=volume_backed)
actual_host = self._get_host_for_server(server_id)
target_host = self._get_host_other_than(actual_host)
if state == 'PAUSED':
self.admin_servers_client.pause_server(server_id)
waiters.wait_for_server_status(self.admin_servers_client,
server_id, state)
self._migrate_server_to(server_id, target_host, volume_backed)
waiters.wait_for_server_status(self.servers_client, server_id, state)
migration_list = (self.admin_migration_client.list_migrations()
['migrations'])
msg = ("Live Migration failed. Migrations list for Instance "
"%s: [" % server_id)
for live_migration in migration_list:
if (live_migration['instance_uuid'] == server_id):
msg += "\n%s" % live_migration
msg += "]"
self.assertEqual(target_host, self._get_host_for_server(server_id),
msg)
@test.idempotent_id('1dce86b8-eb04-4c03-a9d8-9c1dc3ee0c7b')
def test_live_block_migration(self):
self._test_live_migration()
@test.idempotent_id('1e107f21-61b2-4988-8f22-b196e938ab88')
@testtools.skipUnless(CONF.compute_feature_enabled.pause,
'Pause is not available.')
@testtools.skipUnless(CONF.compute_feature_enabled
.live_migrate_paused_instances,
'Live migration of paused instances is not '
'available.')
def test_live_block_migration_paused(self):
self._test_live_migration(state='PAUSED')
@test.idempotent_id('5071cf17-3004-4257-ae61-73a84e28badd')
@test.services('volume')
def test_volume_backed_live_migration(self):
self._test_live_migration(volume_backed=True)
@test.idempotent_id('e19c0cc6-6720-4ed8-be83-b6603ed5c812')
@testtools.skipIf(not CONF.compute_feature_enabled.
block_migration_for_live_migration,
'Block Live migration not available')
@testtools.skipIf(not CONF.compute_feature_enabled.
block_migrate_cinder_iscsi,
'Block Live migration not configured for iSCSI')
def test_iscsi_volume(self):
server_id = self._create_server()
actual_host = self._get_host_for_server(server_id)
target_host = self._get_host_other_than(actual_host)
volume = self.volumes_client.create_volume(
display_name='test')['volume']
self.volumes_client.wait_for_volume_status(volume['id'],
'available')
self.addCleanup(self._volume_clean_up, server_id, volume['id'])
# Attach the volume to the server
self.servers_client.attach_volume(server_id, volumeId=volume['id'],
device='/dev/xvdb')
self.volumes_client.wait_for_volume_status(volume['id'], 'in-use')
self._migrate_server_to(server_id, target_host)
waiters.wait_for_server_status(self.servers_client,
server_id, 'ACTIVE')
self.assertEqual(target_host, self._get_host_for_server(server_id))
| apache-2.0 | 6,596,039,230,838,728,000 | 41.445714 | 78 | 0.615778 | false |
bnewbold/diffoscope | diffoscope/comparators/__init__.py | 1 | 6526 | # -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2014-2015 Jérémy Bobbio <[email protected]>
# © 2015 Helmut Grohne <[email protected]>
#
# diffoscope 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.
#
# diffoscope 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 diffoscope. If not, see <http://www.gnu.org/licenses/>.
import magic
import operator
import os.path
import re
import sys
import tlsh
from diffoscope import logger, tool_required
from diffoscope.config import Config
from diffoscope.difference import Difference
from diffoscope.comparators.binary import \
File, FilesystemFile, NonExistingFile, compare_binary_files
from diffoscope.comparators.bzip2 import Bzip2File
from diffoscope.comparators.java import ClassFile
from diffoscope.comparators.cbfs import CbfsFile
from diffoscope.comparators.cpio import CpioFile
from diffoscope.comparators.deb import DebFile, Md5sumsFile, DebDataTarFile
from diffoscope.comparators.debian import DotChangesFile, DotDscFile
from diffoscope.comparators.device import Device
from diffoscope.comparators.directory import Directory, compare_directories
from diffoscope.comparators.elf import ElfFile, StaticLibFile
from diffoscope.comparators.fonts import TtfFile
from diffoscope.comparators.gettext import MoFile
from diffoscope.comparators.gzip import GzipFile
from diffoscope.comparators.haskell import HiFile
from diffoscope.comparators.ipk import IpkFile
from diffoscope.comparators.iso9660 import Iso9660File
from diffoscope.comparators.mono import MonoExeFile
from diffoscope.comparators.pdf import PdfFile
from diffoscope.comparators.png import PngFile
try:
from diffoscope.comparators.rpm import RpmFile
except ImportError as ex:
if hasattr(ex, 'message') and ex.message != 'No module named rpm': # Python 2
raise
if hasattr(ex, 'msg') and ex.msg != "No module named 'rpm'": # Python 3
raise
from diffoscope.comparators.rpm_fallback import RpmFile
from diffoscope.comparators.sqlite import Sqlite3Database
from diffoscope.comparators.squashfs import SquashfsFile
from diffoscope.comparators.symlink import Symlink
from diffoscope.comparators.text import TextFile
from diffoscope.comparators.tar import TarFile
from diffoscope.comparators.uimage import UimageFile
from diffoscope.comparators.xz import XzFile
from diffoscope.comparators.zip import ZipFile
def bail_if_non_existing(*paths):
if not all(map(os.path.lexists, paths)):
for path in paths:
if not os.path.lexists(path):
sys.stderr.write('%s: %s: No such file or directory\n' % (sys.argv[0], path))
sys.exit(2)
def compare_root_paths(path1, path2):
if not Config.general.new_file:
bail_if_non_existing(path1, path2)
if os.path.isdir(path1) and os.path.isdir(path2):
return compare_directories(path1, path2)
file1 = specialize(FilesystemFile(path1))
file2 = specialize(FilesystemFile(path2))
return compare_files(file1, file2)
def compare_files(file1, file2, source=None):
logger.debug('compare files %s and %s', file1, file2)
with file1.get_content(), file2.get_content():
if file1.has_same_content_as(file2):
logger.debug('same content, skipping')
return None
specialize(file1)
specialize(file2)
if isinstance(file1, NonExistingFile):
file1.other_file = file2
elif isinstance(file2, NonExistingFile):
file2.other_file = file1
elif file1.__class__.__name__ != file2.__class__.__name__:
return file1.compare_bytes(file2, source)
return file1.compare(file2, source)
def compare_commented_files(file1, file2, comment=None, source=None):
difference = compare_files(file1, file2, source=source)
if comment:
if difference is None:
difference = Difference(None, file1.name, file2.name)
difference.add_comment(comment)
return difference
# The order matters! They will be tried in turns.
FILE_CLASSES = (
Directory,
NonExistingFile,
Symlink,
Device,
DotChangesFile,
DotDscFile,
Md5sumsFile,
DebDataTarFile,
TextFile,
Bzip2File,
CbfsFile,
CpioFile,
DebFile,
ElfFile,
StaticLibFile,
Sqlite3Database,
TtfFile,
MoFile,
IpkFile,
GzipFile,
HiFile,
Iso9660File,
ClassFile,
MonoExeFile,
PdfFile,
PngFile,
RpmFile,
SquashfsFile,
TarFile,
UimageFile,
XzFile,
ZipFile
)
def specialize(file):
for cls in FILE_CLASSES:
if isinstance(file, cls):
logger.debug("%s is already specialized", file.name)
return file
if cls.recognizes(file):
logger.debug("Using %s for %s", cls.__name__, file.name)
new_cls = type(cls.__name__, (cls, type(file)), {})
file.__class__ = new_cls
return file
logger.debug('Unidentified file. Magic says: %s', file.magic_file_type)
return file
def perform_fuzzy_matching(members1, members2):
if Config.general.fuzzy_threshold == 0:
return
already_compared = set()
# Perform local copies because they will be modified by consumer
members1 = dict(members1)
members2 = dict(members2)
for name1, file1 in members1.items():
if file1.is_directory() or not file1.fuzzy_hash:
continue
comparisons = []
for name2, file2 in members2.items():
if name2 in already_compared or file2.is_directory() or not file2.fuzzy_hash:
continue
comparisons.append((tlsh.diff(file1.fuzzy_hash, file2.fuzzy_hash), name2))
if comparisons:
comparisons.sort(key=operator.itemgetter(0))
score, name2 = comparisons[0]
logger.debug('fuzzy top match %s %s: %d difference score', name1, name2, score)
if score < Config.general.fuzzy_threshold:
yield name1, name2, score
already_compared.add(name2)
| gpl-3.0 | -3,211,255,412,202,578,000 | 34.639344 | 93 | 0.702239 | false |
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/sklearn/model_selection/_split.py | 1 | 57413 | """
The :mod:`sklearn.model_selection._split` module includes classes and
functions to split the data based on a preset strategy.
"""
# Author: Alexandre Gramfort <[email protected]>,
# Gael Varoquaux <[email protected]>,
# Olivier Girsel <[email protected]>
# Raghav R V <[email protected]>
# License: BSD 3 clause
from __future__ import division
from __future__ import print_function
import numbers
import warnings
from abc import ABCMeta, abstractmethod
from collections import Iterable
from itertools import chain, combinations
from math import ceil, floor
import numpy as np
from scipy.misc import comb
from ..externals.six.moves import zip
from ..base import _pprint
from ..externals.six import with_metaclass
from ..gaussian_process.kernels import Kernel as GPKernel
from ..utils import indexable, check_random_state, safe_indexing
from ..utils.fixes import bincount
from ..utils.fixes import signature
from ..utils.multiclass import type_of_target
from ..utils.validation import _num_samples, column_or_1d
__all__ = ['BaseCrossValidator',
'KFold',
'LabelKFold',
'LeaveOneLabelOut',
'LeaveOneOut',
'LeavePLabelOut',
'LeavePOut',
'ShuffleSplit',
'LabelShuffleSplit',
'StratifiedKFold',
'StratifiedShuffleSplit',
'PredefinedSplit',
'train_test_split',
'check_cv']
class BaseCrossValidator(with_metaclass(ABCMeta)):
"""Base class for all cross-validators
Implementations must define `_iter_test_masks` or `_iter_test_indices`.
"""
def __init__(self):
# We need this for the build_repr to work properly in py2.7
# see #6304
pass
def split(self, X, y=None, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, of length n_samples
The target variable for supervised learning problems.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
X, y, labels = indexable(X, y, labels)
indices = np.arange(_num_samples(X))
for test_index in self._iter_test_masks(X, y, labels):
train_index = indices[np.logical_not(test_index)]
test_index = indices[test_index]
yield train_index, test_index
# Since subclasses must implement either _iter_test_masks or
# _iter_test_indices, neither can be abstract.
def _iter_test_masks(self, X=None, y=None, labels=None):
"""Generates boolean masks corresponding to test sets.
By default, delegates to _iter_test_indices(X, y, labels)
"""
for test_index in self._iter_test_indices(X, y, labels):
test_mask = np.zeros(_num_samples(X), dtype=np.bool)
test_mask[test_index] = True
yield test_mask
def _iter_test_indices(self, X=None, y=None, labels=None):
"""Generates integer indices corresponding to test sets."""
raise NotImplementedError
@abstractmethod
def get_n_splits(self, X=None, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator"""
def __repr__(self):
return _build_repr(self)
class LeaveOneOut(BaseCrossValidator):
"""Leave-One-Out cross-validator
Provides train/test indices to split data in train/test sets. Each
sample is used once as a test set (singleton) while the remaining
samples form the training set.
Note: ``LeaveOneOut()`` is equivalent to ``KFold(n_folds=n)`` and
``LeavePOut(p=1)`` where ``n`` is the number of samples.
Due to the high number of test sets (which is the same as the
number of samples) this cross-validation method can be very costly.
For large datasets one should favor :class:`KFold`, :class:`ShuffleSplit`
or :class:`StratifiedKFold`.
Read more in the :ref:`User Guide <cross_validation>`.
Examples
--------
>>> from sklearn.model_selection import LeaveOneOut
>>> X = np.array([[1, 2], [3, 4]])
>>> y = np.array([1, 2])
>>> loo = LeaveOneOut()
>>> loo.get_n_splits(X)
2
>>> print(loo)
LeaveOneOut()
>>> for train_index, test_index in loo.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
TRAIN: [1] TEST: [0]
[[3 4]] [[1 2]] [2] [1]
TRAIN: [0] TEST: [1]
[[1 2]] [[3 4]] [1] [2]
See also
--------
LeaveOneLabelOut
For splitting the data according to explicit, domain-specific
stratification of the dataset.
LabelKFold: K-fold iterator variant with non-overlapping labels.
"""
def _iter_test_indices(self, X, y=None, labels=None):
return range(_num_samples(X))
def get_n_splits(self, X, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
if X is None:
raise ValueError("The X parameter should not be None")
return _num_samples(X)
class LeavePOut(BaseCrossValidator):
"""Leave-P-Out cross-validator
Provides train/test indices to split data in train/test sets. This results
in testing on all distinct samples of size p, while the remaining n - p
samples form the training set in each iteration.
Note: ``LeavePOut(p)`` is NOT equivalent to
``KFold(n_folds=n_samples // p)`` which creates non-overlapping test sets.
Due to the high number of iterations which grows combinatorically with the
number of samples this cross-validation method can be very costly. For
large datasets one should favor :class:`KFold`, :class:`StratifiedKFold`
or :class:`ShuffleSplit`.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
p : int
Size of the test sets.
Examples
--------
>>> from sklearn.model_selection import LeavePOut
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> y = np.array([1, 2, 3, 4])
>>> lpo = LeavePOut(2)
>>> lpo.get_n_splits(X)
6
>>> print(lpo)
LeavePOut(p=2)
>>> for train_index, test_index in lpo.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [1 2] TEST: [0 3]
TRAIN: [0 3] TEST: [1 2]
TRAIN: [0 2] TEST: [1 3]
TRAIN: [0 1] TEST: [2 3]
"""
def __init__(self, p):
self.p = p
def _iter_test_indices(self, X, y=None, labels=None):
for combination in combinations(range(_num_samples(X)), self.p):
yield np.array(combination)
def get_n_splits(self, X, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
"""
if X is None:
raise ValueError("The X parameter should not be None")
return int(comb(_num_samples(X), self.p, exact=True))
class _BaseKFold(with_metaclass(ABCMeta, BaseCrossValidator)):
"""Base class for KFold and StratifiedKFold"""
@abstractmethod
def __init__(self, n_folds, shuffle, random_state):
if not isinstance(n_folds, numbers.Integral):
raise ValueError('The number of folds must be of Integral type. '
'%s of type %s was passed.'
% (n_folds, type(n_folds)))
n_folds = int(n_folds)
if n_folds <= 1:
raise ValueError(
"k-fold cross-validation requires at least one"
" train/test split by setting n_folds=2 or more,"
" got n_folds={0}.".format(n_folds))
if not isinstance(shuffle, bool):
raise TypeError("shuffle must be True or False;"
" got {0}".format(shuffle))
self.n_folds = n_folds
self.shuffle = shuffle
self.random_state = random_state
def split(self, X, y=None, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape (n_samples,)
The target variable for supervised learning problems.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
X, y, labels = indexable(X, y, labels)
n_samples = _num_samples(X)
if self.n_folds > n_samples:
raise ValueError(
("Cannot have number of folds n_folds={0} greater"
" than the number of samples: {1}.").format(self.n_folds,
n_samples))
for train, test in super(_BaseKFold, self).split(X, y, labels):
yield train, test
def get_n_splits(self, X=None, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
return self.n_folds
class KFold(_BaseKFold):
"""K-Folds cross-validator
Provides train/test indices to split data in train/test sets. Split
dataset into k consecutive folds (without shuffling by default).
Each fold is then used once as a validation while the k - 1 remaining
folds form the training set.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
n_folds : int, default=3
Number of folds. Must be at least 2.
shuffle : boolean, optional
Whether to shuffle the data before splitting into batches.
random_state : None, int or RandomState
When shuffle=True, pseudo-random number generator state used for
shuffling. If None, use default numpy RNG for shuffling.
Examples
--------
>>> from sklearn.model_selection import KFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4])
>>> kf = KFold(n_folds=2)
>>> kf.get_n_splits(X)
2
>>> print(kf) # doctest: +NORMALIZE_WHITESPACE
KFold(n_folds=2, random_state=None, shuffle=False)
>>> for train_index, test_index in kf.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]
Notes
-----
The first ``n_samples % n_folds`` folds have size
``n_samples // n_folds + 1``, other folds have size
``n_samples // n_folds``, where ``n_samples`` is the number of samples.
See also
--------
StratifiedKFold
Takes label information into account to avoid building folds with
imbalanced class distributions (for binary or multiclass
classification tasks).
LabelKFold: K-fold iterator variant with non-overlapping labels.
"""
def __init__(self, n_folds=3, shuffle=False,
random_state=None):
super(KFold, self).__init__(n_folds, shuffle, random_state)
def _iter_test_indices(self, X, y=None, labels=None):
n_samples = _num_samples(X)
indices = np.arange(n_samples)
if self.shuffle:
check_random_state(self.random_state).shuffle(indices)
n_folds = self.n_folds
fold_sizes = (n_samples // n_folds) * np.ones(n_folds, dtype=np.int)
fold_sizes[:n_samples % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
yield indices[start:stop]
current = stop
class LabelKFold(_BaseKFold):
"""K-fold iterator variant with non-overlapping labels.
The same label will not appear in two different folds (the number of
distinct labels has to be at least equal to the number of folds).
The folds are approximately balanced in the sense that the number of
distinct labels is approximately the same in each fold.
Parameters
----------
n_folds : int, default=3
Number of folds. Must be at least 2.
Examples
--------
>>> from sklearn.model_selection import LabelKFold
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> y = np.array([1, 2, 3, 4])
>>> labels = np.array([0, 0, 2, 2])
>>> label_kfold = LabelKFold(n_folds=2)
>>> label_kfold.get_n_splits(X, y, labels)
2
>>> print(label_kfold)
LabelKFold(n_folds=2)
>>> for train_index, test_index in label_kfold.split(X, y, labels):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
...
TRAIN: [0 1] TEST: [2 3]
[[1 2]
[3 4]] [[5 6]
[7 8]] [1 2] [3 4]
TRAIN: [2 3] TEST: [0 1]
[[5 6]
[7 8]] [[1 2]
[3 4]] [3 4] [1 2]
See also
--------
LeaveOneLabelOut
For splitting the data according to explicit domain-specific
stratification of the dataset.
"""
def __init__(self, n_folds=3):
super(LabelKFold, self).__init__(n_folds, shuffle=False,
random_state=None)
def _iter_test_indices(self, X, y, labels):
if labels is None:
raise ValueError("The labels parameter should not be None")
unique_labels, labels = np.unique(labels, return_inverse=True)
n_labels = len(unique_labels)
if self.n_folds > n_labels:
raise ValueError("Cannot have number of folds n_folds=%d greater"
" than the number of labels: %d."
% (self.n_folds, n_labels))
# Weight labels by their number of occurrences
n_samples_per_label = np.bincount(labels)
# Distribute the most frequent labels first
indices = np.argsort(n_samples_per_label)[::-1]
n_samples_per_label = n_samples_per_label[indices]
# Total weight of each fold
n_samples_per_fold = np.zeros(self.n_folds)
# Mapping from label index to fold index
label_to_fold = np.zeros(len(unique_labels))
# Distribute samples by adding the largest weight to the lightest fold
for label_index, weight in enumerate(n_samples_per_label):
lightest_fold = np.argmin(n_samples_per_fold)
n_samples_per_fold[lightest_fold] += weight
label_to_fold[indices[label_index]] = lightest_fold
indices = label_to_fold[labels]
for f in range(self.n_folds):
yield np.where(indices == f)[0]
class StratifiedKFold(_BaseKFold):
"""Stratified K-Folds cross-validator
Provides train/test indices to split data in train/test sets.
This cross-validation object is a variation of KFold that returns
stratified folds. The folds are made by preserving the percentage of
samples for each class.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
n_folds : int, default=3
Number of folds. Must be at least 2.
shuffle : boolean, optional
Whether to shuffle each stratification of the data before splitting
into batches.
random_state : None, int or RandomState
When shuffle=True, pseudo-random number generator state used for
shuffling. If None, use default numpy RNG for shuffling.
Examples
--------
>>> from sklearn.model_selection import StratifiedKFold
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> skf = StratifiedKFold(n_folds=2)
>>> skf.get_n_splits(X, y)
2
>>> print(skf) # doctest: +NORMALIZE_WHITESPACE
StratifiedKFold(n_folds=2, random_state=None, shuffle=False)
>>> for train_index, test_index in skf.split(X, y):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 3] TEST: [0 2]
TRAIN: [0 2] TEST: [1 3]
Notes
-----
All the folds have size ``trunc(n_samples / n_folds)``, the last one has
the complementary.
"""
def __init__(self, n_folds=3, shuffle=False, random_state=None):
super(StratifiedKFold, self).__init__(n_folds, shuffle, random_state)
def _make_test_folds(self, X, y=None, labels=None):
if self.shuffle:
rng = check_random_state(self.random_state)
else:
rng = self.random_state
y = np.asarray(y)
n_samples = y.shape[0]
unique_y, y_inversed = np.unique(y, return_inverse=True)
y_counts = bincount(y_inversed)
min_labels = np.min(y_counts)
if np.all(self.n_folds > y_counts):
raise ValueError("All the n_labels for individual classes"
" are less than %d folds."
% (self.n_folds))
if self.n_folds > min_labels:
warnings.warn(("The least populated class in y has only %d"
" members, which is too few. The minimum"
" number of labels for any class cannot"
" be less than n_folds=%d."
% (min_labels, self.n_folds)), Warning)
# pre-assign each sample to a test fold index using individual KFold
# splitting strategies for each class so as to respect the balance of
# classes
# NOTE: Passing the data corresponding to ith class say X[y==class_i]
# will break when the data is not 100% stratifiable for all classes.
# So we pass np.zeroes(max(c, n_folds)) as data to the KFold
per_cls_cvs = [
KFold(self.n_folds, shuffle=self.shuffle,
random_state=rng).split(np.zeros(max(count, self.n_folds)))
for count in y_counts]
test_folds = np.zeros(n_samples, dtype=np.int)
for test_fold_indices, per_cls_splits in enumerate(zip(*per_cls_cvs)):
for cls, (_, test_split) in zip(unique_y, per_cls_splits):
cls_test_folds = test_folds[y == cls]
# the test split can be too big because we used
# KFold(...).split(X[:max(c, n_folds)]) when data is not 100%
# stratifiable for all the classes
# (we use a warning instead of raising an exception)
# If this is the case, let's trim it:
test_split = test_split[test_split < len(cls_test_folds)]
cls_test_folds[test_split] = test_fold_indices
test_folds[y == cls] = cls_test_folds
return test_folds
def _iter_test_masks(self, X, y=None, labels=None):
test_folds = self._make_test_folds(X, y)
for i in range(self.n_folds):
yield test_folds == i
def split(self, X, y, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape (n_samples,)
The target variable for supervised learning problems.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
return super(StratifiedKFold, self).split(X, y, labels)
class LeaveOneLabelOut(BaseCrossValidator):
"""Leave One Label Out cross-validator
Provides train/test indices to split data according to a third-party
provided label. This label information can be used to encode arbitrary
domain specific stratifications of the samples as integers.
For instance the labels could be the year of collection of the samples
and thus allow for cross-validation against time-based splits.
Read more in the :ref:`User Guide <cross_validation>`.
Examples
--------
>>> from sklearn.model_selection import LeaveOneLabelOut
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> y = np.array([1, 2, 1, 2])
>>> labels = np.array([1, 1, 2, 2])
>>> lol = LeaveOneLabelOut()
>>> lol.get_n_splits(X, y, labels)
2
>>> print(lol)
LeaveOneLabelOut()
>>> for train_index, test_index in lol.split(X, y, labels):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
TRAIN: [2 3] TEST: [0 1]
[[5 6]
[7 8]] [[1 2]
[3 4]] [1 2] [1 2]
TRAIN: [0 1] TEST: [2 3]
[[1 2]
[3 4]] [[5 6]
[7 8]] [1 2] [1 2]
"""
def _iter_test_masks(self, X, y, labels):
if labels is None:
raise ValueError("The labels parameter should not be None")
# We make a copy of labels to avoid side-effects during iteration
labels = np.array(labels, copy=True)
unique_labels = np.unique(labels)
for i in unique_labels:
yield labels == i
def get_n_splits(self, X, y, labels):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
if labels is None:
raise ValueError("The labels parameter should not be None")
return len(np.unique(labels))
class LeavePLabelOut(BaseCrossValidator):
"""Leave P Labels Out cross-validator
Provides train/test indices to split data according to a third-party
provided label. This label information can be used to encode arbitrary
domain specific stratifications of the samples as integers.
For instance the labels could be the year of collection of the samples
and thus allow for cross-validation against time-based splits.
The difference between LeavePLabelOut and LeaveOneLabelOut is that
the former builds the test sets with all the samples assigned to
``p`` different values of the labels while the latter uses samples
all assigned the same labels.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
n_labels : int
Number of labels (``p``) to leave out in the test split.
Examples
--------
>>> from sklearn.model_selection import LeavePLabelOut
>>> X = np.array([[1, 2], [3, 4], [5, 6]])
>>> y = np.array([1, 2, 1])
>>> labels = np.array([1, 2, 3])
>>> lpl = LeavePLabelOut(n_labels=2)
>>> lpl.get_n_splits(X, y, labels)
3
>>> print(lpl)
LeavePLabelOut(n_labels=2)
>>> for train_index, test_index in lpl.split(X, y, labels):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
... print(X_train, X_test, y_train, y_test)
TRAIN: [2] TEST: [0 1]
[[5 6]] [[1 2]
[3 4]] [1] [1 2]
TRAIN: [1] TEST: [0 2]
[[3 4]] [[1 2]
[5 6]] [2] [1 1]
TRAIN: [0] TEST: [1 2]
[[1 2]] [[3 4]
[5 6]] [1] [2 1]
See also
--------
LabelKFold: K-fold iterator variant with non-overlapping labels.
"""
def __init__(self, n_labels):
self.n_labels = n_labels
def _iter_test_masks(self, X, y, labels):
if labels is None:
raise ValueError("The labels parameter should not be None")
labels = np.array(labels, copy=True)
unique_labels = np.unique(labels)
combi = combinations(range(len(unique_labels)), self.n_labels)
for indices in combi:
test_index = np.zeros(_num_samples(X), dtype=np.bool)
for l in unique_labels[np.array(indices)]:
test_index[labels == l] = True
yield test_index
def get_n_splits(self, X, y, labels):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
if labels is None:
raise ValueError("The labels parameter should not be None")
return int(comb(len(np.unique(labels)), self.n_labels, exact=True))
class BaseShuffleSplit(with_metaclass(ABCMeta)):
"""Base class for ShuffleSplit and StratifiedShuffleSplit"""
def __init__(self, n_iter=10, test_size=0.1, train_size=None,
random_state=None):
_validate_shuffle_split_init(test_size, train_size)
self.n_iter = n_iter
self.test_size = test_size
self.train_size = train_size
self.random_state = random_state
def split(self, X, y=None, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape (n_samples,)
The target variable for supervised learning problems.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
X, y, labels = indexable(X, y, labels)
for train, test in self._iter_indices(X, y, labels):
yield train, test
@abstractmethod
def _iter_indices(self, X, y=None, labels=None):
"""Generate (train, test) indices"""
def get_n_splits(self, X=None, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
return self.n_iter
def __repr__(self):
return _build_repr(self)
class ShuffleSplit(BaseShuffleSplit):
"""Random permutation cross-validator
Yields indices to split data into training and test sets.
Note: contrary to other cross-validation strategies, random splits
do not guarantee that all folds will be different, although this is
still very likely for sizeable datasets.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
n_iter : int (default 10)
Number of re-shuffling & splitting iterations.
test_size : float, int, or None, default 0.1
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the test split. If
int, represents the absolute number of test samples. If None,
the value is automatically set to the complement of the train size.
train_size : float, int, or None (default is None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the train split. If
int, represents the absolute number of train samples. If None,
the value is automatically set to the complement of the test size.
random_state : int or RandomState
Pseudo-random number generator state used for random sampling.
Examples
--------
>>> from sklearn.model_selection import ShuffleSplit
>>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
>>> y = np.array([1, 2, 1, 2])
>>> rs = ShuffleSplit(n_iter=3, test_size=.25, random_state=0)
>>> rs.get_n_splits(X)
3
>>> print(rs)
ShuffleSplit(n_iter=3, random_state=0, test_size=0.25, train_size=None)
>>> for train_index, test_index in rs.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... # doctest: +ELLIPSIS
TRAIN: [3 1 0] TEST: [2]
TRAIN: [2 1 3] TEST: [0]
TRAIN: [0 2 1] TEST: [3]
>>> rs = ShuffleSplit(n_iter=3, train_size=0.5, test_size=.25,
... random_state=0)
>>> for train_index, test_index in rs.split(X):
... print("TRAIN:", train_index, "TEST:", test_index)
... # doctest: +ELLIPSIS
TRAIN: [3 1] TEST: [2]
TRAIN: [2 1] TEST: [0]
TRAIN: [0 2] TEST: [3]
"""
def _iter_indices(self, X, y=None, labels=None):
n_samples = _num_samples(X)
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
rng = check_random_state(self.random_state)
for i in range(self.n_iter):
# random partition
permutation = rng.permutation(n_samples)
ind_test = permutation[:n_test]
ind_train = permutation[n_test:(n_test + n_train)]
yield ind_train, ind_test
class LabelShuffleSplit(ShuffleSplit):
'''Shuffle-Labels-Out cross-validation iterator
Provides randomized train/test indices to split data according to a
third-party provided label. This label information can be used to encode
arbitrary domain specific stratifications of the samples as integers.
For instance the labels could be the year of collection of the samples
and thus allow for cross-validation against time-based splits.
The difference between LeavePLabelOut and LabelShuffleSplit is that
the former generates splits using all subsets of size ``p`` unique labels,
whereas LabelShuffleSplit generates a user-determined number of random
test splits, each with a user-determined fraction of unique labels.
For example, a less computationally intensive alternative to
``LeavePLabelOut(p=10)`` would be
``LabelShuffleSplit(test_size=10, n_iter=100)``.
Note: The parameters ``test_size`` and ``train_size`` refer to labels, and
not to samples, as in ShuffleSplit.
Parameters
----------
n_iter : int (default 5)
Number of re-shuffling & splitting iterations.
test_size : float (default 0.2), int, or None
If float, should be between 0.0 and 1.0 and represent the
proportion of the labels to include in the test split. If
int, represents the absolute number of test labels. If None,
the value is automatically set to the complement of the train size.
train_size : float, int, or None (default is None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the labels to include in the train split. If
int, represents the absolute number of train labels. If None,
the value is automatically set to the complement of the test size.
random_state : int or RandomState
Pseudo-random number generator state used for random sampling.
'''
def __init__(self, n_iter=5, test_size=0.2, train_size=None,
random_state=None):
super(LabelShuffleSplit, self).__init__(
n_iter=n_iter,
test_size=test_size,
train_size=train_size,
random_state=random_state)
def _iter_indices(self, X, y, labels):
if labels is None:
raise ValueError("The labels parameter should not be None")
classes, label_indices = np.unique(labels, return_inverse=True)
for label_train, label_test in super(
LabelShuffleSplit, self)._iter_indices(X=classes):
# these are the indices of classes in the partition
# invert them into data indices
train = np.flatnonzero(np.in1d(label_indices, label_train))
test = np.flatnonzero(np.in1d(label_indices, label_test))
yield train, test
class StratifiedShuffleSplit(BaseShuffleSplit):
"""Stratified ShuffleSplit cross-validator
Provides train/test indices to split data in train/test sets.
This cross-validation object is a merge of StratifiedKFold and
ShuffleSplit, which returns stratified randomized folds. The folds
are made by preserving the percentage of samples for each class.
Note: like the ShuffleSplit strategy, stratified random splits
do not guarantee that all folds will be different, although this is
still very likely for sizeable datasets.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
n_iter : int (default 10)
Number of re-shuffling & splitting iterations.
test_size : float (default 0.1), int, or None
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the test split. If
int, represents the absolute number of test samples. If None,
the value is automatically set to the complement of the train size.
train_size : float, int, or None (default is None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the train split. If
int, represents the absolute number of train samples. If None,
the value is automatically set to the complement of the test size.
random_state : int or RandomState
Pseudo-random number generator state used for random sampling.
Examples
--------
>>> from sklearn.model_selection import StratifiedShuffleSplit
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> sss = StratifiedShuffleSplit(n_iter=3, test_size=0.5, random_state=0)
>>> sss.get_n_splits(X, y)
3
>>> print(sss) # doctest: +ELLIPSIS
StratifiedShuffleSplit(n_iter=3, random_state=0, ...)
>>> for train_index, test_index in sss.split(X, y):
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 2] TEST: [3 0]
TRAIN: [0 2] TEST: [1 3]
TRAIN: [0 2] TEST: [3 1]
"""
def __init__(self, n_iter=10, test_size=0.1, train_size=None,
random_state=None):
super(StratifiedShuffleSplit, self).__init__(
n_iter, test_size, train_size, random_state)
def _iter_indices(self, X, y, labels=None):
n_samples = _num_samples(X)
n_train, n_test = _validate_shuffle_split(n_samples, self.test_size,
self.train_size)
classes, y_indices = np.unique(y, return_inverse=True)
n_classes = classes.shape[0]
class_counts = bincount(y_indices)
if np.min(class_counts) < 2:
raise ValueError("The least populated class in y has only 1"
" member, which is too few. The minimum"
" number of labels for any class cannot"
" be less than 2.")
if n_train < n_classes:
raise ValueError('The train_size = %d should be greater or '
'equal to the number of classes = %d' %
(n_train, n_classes))
if n_test < n_classes:
raise ValueError('The test_size = %d should be greater or '
'equal to the number of classes = %d' %
(n_test, n_classes))
rng = check_random_state(self.random_state)
p_i = class_counts / float(n_samples)
n_i = np.round(n_train * p_i).astype(int)
t_i = np.minimum(class_counts - n_i,
np.round(n_test * p_i).astype(int))
for _ in range(self.n_iter):
train = []
test = []
for i, class_i in enumerate(classes):
permutation = rng.permutation(class_counts[i])
perm_indices_class_i = np.where((y == class_i))[0][permutation]
train.extend(perm_indices_class_i[:n_i[i]])
test.extend(perm_indices_class_i[n_i[i]:n_i[i] + t_i[i]])
# Because of rounding issues (as n_train and n_test are not
# dividers of the number of elements per class), we may end
# up here with less samples in train and test than asked for.
if len(train) < n_train or len(test) < n_test:
# We complete by affecting randomly the missing indexes
missing_indices = np.where(bincount(train + test,
minlength=len(y)) == 0)[0]
missing_indices = rng.permutation(missing_indices)
train.extend(missing_indices[:(n_train - len(train))])
test.extend(missing_indices[-(n_test - len(test)):])
train = rng.permutation(train)
test = rng.permutation(test)
yield train, test
def split(self, X, y, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training data, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape (n_samples,)
The target variable for supervised learning problems.
labels : array-like, with shape (n_samples,), optional
Group labels for the samples used while splitting the dataset into
train/test set.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
return super(StratifiedShuffleSplit, self).split(X, y, labels)
def _validate_shuffle_split_init(test_size, train_size):
"""Validation helper to check the test_size and train_size at init
NOTE This does not take into account the number of samples which is known
only at split
"""
if test_size is None and train_size is None:
raise ValueError('test_size and train_size can not both be None')
if test_size is not None:
if np.asarray(test_size).dtype.kind == 'f':
if test_size >= 1.:
raise ValueError(
'test_size=%f should be smaller '
'than 1.0 or be an integer' % test_size)
elif np.asarray(test_size).dtype.kind != 'i':
# int values are checked during split based on the input
raise ValueError("Invalid value for test_size: %r" % test_size)
if train_size is not None:
if np.asarray(train_size).dtype.kind == 'f':
if train_size >= 1.:
raise ValueError("train_size=%f should be smaller "
"than 1.0 or be an integer" % train_size)
elif (np.asarray(test_size).dtype.kind == 'f' and
(train_size + test_size) > 1.):
raise ValueError('The sum of test_size and train_size = %f, '
'should be smaller than 1.0. Reduce '
'test_size and/or train_size.' %
(train_size + test_size))
elif np.asarray(train_size).dtype.kind != 'i':
# int values are checked during split based on the input
raise ValueError("Invalid value for train_size: %r" % train_size)
def _validate_shuffle_split(n_samples, test_size, train_size):
"""
Validation helper to check if the test/test sizes are meaningful wrt to the
size of the data (n_samples)
"""
if (test_size is not None and np.asarray(test_size).dtype.kind == 'i'
and test_size >= n_samples):
raise ValueError('test_size=%d should be smaller than the number of '
'samples %d' % (test_size, n_samples))
if (train_size is not None and np.asarray(train_size).dtype.kind == 'i'
and train_size >= n_samples):
raise ValueError("train_size=%d should be smaller than the number of"
" samples %d" % (train_size, n_samples))
if np.asarray(test_size).dtype.kind == 'f':
n_test = ceil(test_size * n_samples)
elif np.asarray(test_size).dtype.kind == 'i':
n_test = float(test_size)
if train_size is None:
n_train = n_samples - n_test
elif np.asarray(train_size).dtype.kind == 'f':
n_train = floor(train_size * n_samples)
else:
n_train = float(train_size)
if test_size is None:
n_test = n_samples - n_train
if n_train + n_test > n_samples:
raise ValueError('The sum of train_size and test_size = %d, '
'should be smaller than the number of '
'samples %d. Reduce test_size and/or '
'train_size.' % (n_train + n_test, n_samples))
return int(n_train), int(n_test)
class PredefinedSplit(BaseCrossValidator):
"""Predefined split cross-validator
Splits the data into training/test set folds according to a predefined
scheme. Each sample can be assigned to at most one test set fold, as
specified by the user through the ``test_fold`` parameter.
Read more in the :ref:`User Guide <cross_validation>`.
Examples
--------
>>> from sklearn.model_selection import PredefinedSplit
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([0, 0, 1, 1])
>>> test_fold = [0, 1, -1, 1]
>>> ps = PredefinedSplit(test_fold)
>>> ps.get_n_splits()
2
>>> print(ps) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
PredefinedSplit(test_fold=array([ 0, 1, -1, 1]))
>>> for train_index, test_index in ps.split():
... print("TRAIN:", train_index, "TEST:", test_index)
... X_train, X_test = X[train_index], X[test_index]
... y_train, y_test = y[train_index], y[test_index]
TRAIN: [1 2 3] TEST: [0]
TRAIN: [0 2] TEST: [1 3]
"""
def __init__(self, test_fold):
self.test_fold = np.array(test_fold, dtype=np.int)
self.test_fold = column_or_1d(self.test_fold)
self.unique_folds = np.unique(self.test_fold)
self.unique_folds = self.unique_folds[self.unique_folds != -1]
def split(self, X=None, y=None, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
ind = np.arange(len(self.test_fold))
for test_index in self._iter_test_masks():
train_index = ind[np.logical_not(test_index)]
test_index = ind[test_index]
yield train_index, test_index
def _iter_test_masks(self):
"""Generates boolean masks corresponding to test sets."""
for f in self.unique_folds:
test_index = np.where(self.test_fold == f)[0]
test_mask = np.zeros(len(self.test_fold), dtype=np.bool)
test_mask[test_index] = True
yield test_mask
def get_n_splits(self, X=None, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
return len(self.unique_folds)
class _CVIterableWrapper(BaseCrossValidator):
"""Wrapper class for old style cv objects and iterables."""
def __init__(self, cv):
self.cv = cv
def get_n_splits(self, X=None, y=None, labels=None):
"""Returns the number of splitting iterations in the cross-validator
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
n_splits : int
Returns the number of splitting iterations in the cross-validator.
"""
return len(self.cv) # Both iterables and old-cv objects support len
def split(self, X=None, y=None, labels=None):
"""Generate indices to split data into training and test set.
Parameters
----------
X : object
Always ignored, exists for compatibility.
y : object
Always ignored, exists for compatibility.
labels : object
Always ignored, exists for compatibility.
Returns
-------
train : ndarray
The training set indices for that split.
test : ndarray
The testing set indices for that split.
"""
for train, test in self.cv:
yield train, test
def check_cv(cv=3, y=None, classifier=False):
"""Input checker utility for building a cross-validator
Parameters
----------
cv : int, cross-validation generator or an iterable, optional
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 3-fold cross-validation,
- integer, to specify the number of folds.
- An object to be used as a cross-validation generator.
- An iterable yielding train/test splits.
For integer/None inputs, if classifier is True and ``y`` is either
binary or multiclass, :class:`StratifiedKFold` used. In all other
cases, :class:`KFold` is used.
Refer :ref:`User Guide <cross_validation>` for the various
cross-validation strategies that can be used here.
y : array-like, optional
The target variable for supervised learning problems.
classifier : boolean, optional, default False
Whether the task is a classification task, in which case
stratified KFold will be used.
Returns
-------
checked_cv : a cross-validator instance.
The return value is a cross-validator which generates the train/test
splits via the ``split`` method.
"""
if cv is None:
cv = 3
if isinstance(cv, numbers.Integral):
if (classifier and (y is not None) and
(type_of_target(y) in ('binary', 'multiclass'))):
return StratifiedKFold(cv)
else:
return KFold(cv)
if not hasattr(cv, 'split') or isinstance(cv, str):
if not isinstance(cv, Iterable) or isinstance(cv, str):
raise ValueError("Expected cv as an integer, cross-validation "
"object (from sklearn.model_selection) "
"or an iterable. Got %s." % cv)
return _CVIterableWrapper(cv)
return cv # New style cv objects are passed without any modification
def train_test_split(*arrays, **options):
"""Split arrays or matrices into random train and test subsets
Quick utility that wraps input validation and
``next(ShuffleSplit().split(X, y))`` and application to input data
into a single call for splitting (and optionally subsampling) data in a
oneliner.
Read more in the :ref:`User Guide <cross_validation>`.
Parameters
----------
*arrays : sequence of indexables with same length / shape[0]
allowed inputs are lists, numpy arrays, scipy-sparse
matrices or pandas dataframes.
.. versionadded:: 0.16
preserves input type instead of always casting to numpy array.
test_size : float, int, or None (default is None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the test split. If
int, represents the absolute number of test samples. If None,
the value is automatically set to the complement of the train size.
If train size is also None, test size is set to 0.25.
train_size : float, int, or None (default is None)
If float, should be between 0.0 and 1.0 and represent the
proportion of the dataset to include in the train split. If
int, represents the absolute number of train samples. If None,
the value is automatically set to the complement of the test size.
random_state : int or RandomState
Pseudo-random number generator state used for random sampling.
stratify : array-like or None (default is None)
If not None, data is split in a stratified fashion, using this as
the labels array.
Returns
-------
splitting : list, length=2 * len(arrays)
List containing train-test split of inputs.
.. versionadded:: 0.16
Output type is the same as the input type.
Examples
--------
>>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
[2, 3],
[4, 5],
[6, 7],
[8, 9]])
>>> list(y)
[0, 1, 2, 3, 4]
>>> X_train, X_test, y_train, y_test = train_test_split(
... X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
[0, 1],
[6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
[8, 9]])
>>> y_test
[1, 4]
"""
n_arrays = len(arrays)
if n_arrays == 0:
raise ValueError("At least one array required as input")
test_size = options.pop('test_size', None)
train_size = options.pop('train_size', None)
random_state = options.pop('random_state', None)
stratify = options.pop('stratify', None)
if options:
raise TypeError("Invalid parameters passed: %s" % str(options))
if test_size is None and train_size is None:
test_size = 0.25
arrays = indexable(*arrays)
if stratify is not None:
CVClass = StratifiedShuffleSplit
else:
CVClass = ShuffleSplit
cv = CVClass(test_size=test_size,
train_size=train_size,
random_state=random_state)
train, test = next(cv.split(X=arrays[0], y=stratify))
return list(chain.from_iterable((safe_indexing(a, train),
safe_indexing(a, test)) for a in arrays))
train_test_split.__test__ = False # to avoid a pb with nosetests
def _safe_split(estimator, X, y, indices, train_indices=None):
"""Create subset of dataset and properly handle kernels."""
if (hasattr(estimator, 'kernel') and callable(estimator.kernel) and
not isinstance(estimator.kernel, GPKernel)):
# cannot compute the kernel values with custom function
raise ValueError("Cannot use a custom kernel function. "
"Precompute the kernel matrix instead.")
if not hasattr(X, "shape"):
if getattr(estimator, "_pairwise", False):
raise ValueError("Precomputed kernels or affinity matrices have "
"to be passed as arrays or sparse matrices.")
X_subset = [X[index] for index in indices]
else:
if getattr(estimator, "_pairwise", False):
# X is a precomputed square kernel matrix
if X.shape[0] != X.shape[1]:
raise ValueError("X should be a square kernel matrix")
if train_indices is None:
X_subset = X[np.ix_(indices, indices)]
else:
X_subset = X[np.ix_(indices, train_indices)]
else:
X_subset = safe_indexing(X, indices)
if y is not None:
y_subset = safe_indexing(y, indices)
else:
y_subset = None
return X_subset, y_subset
def _build_repr(self):
# XXX This is copied from BaseEstimator's get_params
cls = self.__class__
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
# Ignore varargs, kw and default values and pop self
init_signature = signature(init)
# Consider the constructor parameters excluding 'self'
if init is object.__init__:
args = []
else:
args = sorted([p.name for p in init_signature.parameters.values()
if p.name != 'self' and p.kind != p.VAR_KEYWORD])
class_name = self.__class__.__name__
params = dict()
for key in args:
# We need deprecation warnings to always be on in order to
# catch deprecated param values.
# This is set in utils/__init__.py but it gets overwritten
# when running under python3 somehow.
warnings.simplefilter("always", DeprecationWarning)
try:
with warnings.catch_warnings(record=True) as w:
value = getattr(self, key, None)
if len(w) and w[0].category == DeprecationWarning:
# if the parameter is deprecated, don't show it
continue
finally:
warnings.filters.pop(0)
params[key] = value
return '%s(%s)' % (class_name, _pprint(params, offset=len(class_name)))
| mit | -6,472,708,690,668,837,000 | 34.928035 | 79 | 0.593002 | false |
redhat-openstack/trove | trove/tests/unittests/guestagent/test_couchbase_manager.py | 1 | 6387 | # Copyright 2012 OpenStack Foundation
#
# 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 os
import stat
import tempfile
import mock
from mock import DEFAULT
from mock import MagicMock
from mock import Mock
from mock import patch
from oslo_utils import netutils
from trove.common import utils
from trove.guestagent import backup
from trove.guestagent.datastore.experimental.couchbase import (
manager as couch_manager)
from trove.guestagent.datastore.experimental.couchbase import (
service as couch_service)
from trove.guestagent import volume
from trove.tests.unittests import trove_testtools
class GuestAgentCouchbaseManagerTest(trove_testtools.TestCase):
def setUp(self):
super(GuestAgentCouchbaseManagerTest, self).setUp()
self.context = trove_testtools.TroveTestContext(self)
self.manager = couch_manager.Manager()
self.packages = 'couchbase-server'
app_patcher = patch.multiple(
couch_service.CouchbaseApp,
stop_db=DEFAULT, start_db=DEFAULT, restart=DEFAULT)
self.addCleanup(app_patcher.stop)
app_patcher.start()
netutils_patcher = patch.object(netutils, 'get_my_ipv4')
self.addCleanup(netutils_patcher.stop)
netutils_patcher.start()
def tearDown(self):
super(GuestAgentCouchbaseManagerTest, self).tearDown()
def test_update_status(self):
mock_status = MagicMock()
self.manager.appStatus = mock_status
self.manager.update_status(self.context)
mock_status.update.assert_any_call()
def test_prepare_device_path_true(self):
self._prepare_dynamic()
def test_prepare_from_backup(self):
self._prepare_dynamic(backup_id='backup_id_123abc')
@patch.multiple(couch_service.CouchbaseApp,
install_if_needed=DEFAULT,
start_db_with_conf_changes=DEFAULT,
initial_setup=DEFAULT)
@patch.multiple(volume.VolumeDevice,
format=DEFAULT,
mount=DEFAULT,
mount_points=Mock(return_value=[]))
@patch.object(backup, 'restore')
def _prepare_dynamic(self, device_path='/dev/vdb', backup_id=None,
*mocks, **kwmocks):
# covering all outcomes is starting to cause trouble here
backup_info = {'id': backup_id,
'location': 'fake-location',
'type': 'CbBackup',
'checksum': 'fake-checksum'} if backup_id else None
mock_status = MagicMock()
mock_status.begin_install = MagicMock(return_value=None)
self.manager.appStatus = mock_status
instance_ram = 2048
mount_point = '/var/lib/couchbase'
self.manager.prepare(self.context, self.packages, None,
instance_ram, None, device_path=device_path,
mount_point=mount_point,
backup_info=backup_info,
overrides=None,
cluster_config=None)
# verification/assertion
mock_status.begin_install.assert_any_call()
kwmocks['install_if_needed'].assert_any_call(self.packages)
if backup_info:
backup.restore.assert_any_call(self.context,
backup_info,
mount_point)
def test_restart(self):
mock_status = MagicMock()
self.manager.appStatus = mock_status
couch_service.CouchbaseApp.restart = MagicMock(return_value=None)
# invocation
self.manager.restart(self.context)
# verification/assertion
couch_service.CouchbaseApp.restart.assert_any_call()
def test_stop_db(self):
mock_status = MagicMock()
self.manager.appStatus = mock_status
couch_service.CouchbaseApp.stop_db = MagicMock(return_value=None)
# invocation
self.manager.stop_db(self.context)
# verification/assertion
couch_service.CouchbaseApp.stop_db.assert_any_call(
do_not_start_on_reboot=False)
def __fake_mkstemp(self):
self.tempfd, self.tempname = self.original_mkstemp()
return self.tempfd, self.tempname
def __fake_mkstemp_raise(self):
raise OSError(11, 'Resource temporarily unavailable')
def __cleanup_tempfile(self):
if self.tempname:
os.unlink(self.tempname)
@mock.patch.object(utils, 'execute_with_timeout',
Mock(return_value=('0', '')))
def test_write_password_to_file1(self):
self.original_mkstemp = tempfile.mkstemp
self.tempname = None
with mock.patch.object(tempfile,
'mkstemp',
self.__fake_mkstemp):
self.addCleanup(self.__cleanup_tempfile)
rootaccess = couch_service.CouchbaseRootAccess()
rootaccess.write_password_to_file('mypassword')
filepermissions = os.stat(self.tempname).st_mode
self.assertEqual(stat.S_IRUSR, filepermissions & 0o777)
@mock.patch.object(utils, 'execute_with_timeout',
Mock(return_value=('0', '')))
@mock.patch(
'trove.guestagent.datastore.experimental.couchbase.service.LOG')
def test_write_password_to_file2(self, mock_logging):
self.original_mkstemp = tempfile.mkstemp
self.tempname = None
with mock.patch.object(tempfile,
'mkstemp',
self.__fake_mkstemp_raise):
rootaccess = couch_service.CouchbaseRootAccess()
self.assertRaises(RuntimeError,
rootaccess.write_password_to_file,
'mypassword')
| apache-2.0 | -17,181,326,834,153,800 | 36.350877 | 78 | 0.616878 | false |
magestik/TuxStereoViewer | src/lib_freeview.py | 1 | 2380 | #!/usr/bin/python
# -*- coding:utf-8 -*-
import functions
import Image
import math
class Simple:
"FreeView support class"
def __init__(self):
self.vergence = 0 # Horizontal separation
self.vsep = 0 # Vertical separation
self.left = self.right = ''
self.height = self.width = 0
def __del__(self):
pass
def open(self, path, anaglyph=False):
try:
self.left, self.right = functions.set_sources_from_stereo(self, path, anaglyph)
self.oleft, self.oright = self.left, self.right # Back-up
size = self.left.size
self.height, self.width = size[1], size[0]
except:
print "Image doesn't exist !"
def open2(self, path='None', image='None'):
if path != 'None':
functions.set_sources_from_images(self, path[0], path[1])
elif image[0] != '':
self.left, self.right = image[0], image[1]
self.oleft, self.oright = image[0], image[1] # Back-up
taille = self.right.size
self.height, self.width = taille[1], taille[0]
def make(self, parent, fullscreen):
self.stereo = self.left
#pixbuf = functions.image_to_pixbuf(self, self.stereo)
drawable = functions.image_to_drawable(self, self.stereo)
if fullscreen == 0:
#parent.stereo.set_from_pixbuf(pixbuf) # Display in normal window
parent.stereo.window.clear()
x = (parent.max_width - self.width) / 2
y = (parent.max_height - self.height) / 2
parent.stereo.window.draw_drawable(parent.gc, drawable, 0, 0, x, y, -1, -1)
else:
parent.fs_image.set_from_pixbuf(pixbuf) # Display in fullscreen window
def swap_eyes(self):
self.left, self.right = self.right, self.left
def resize(self, maxw, maxh, force=0, normal=0):
if normal == 1: # Scale 1:1
self.right, self.left = self.oright, self.oleft # Backup
taille = self.right.size
self.height, self.width = taille[1], taille[0]
elif self.height > 0 and self.width > 0:
if self.height > maxh or self.width > maxw or force == 1:
qrh, qrw = (self.height + 0.00000000) / maxh, (self.width + 0.00000000) / maxw
qrmax = max(qrh, qrw)
height, width = int(math.ceil(self.height / qrmax)), int(math.ceil(self.width / qrmax))
self.right, self.left = self.oright, self.oleft # Backup
self.right, self.left = self.right.resize((width, height), Image.ANTIALIAS), self.left.resize((width, height), Image.ANTIALIAS)
self.height, self.width = height, width
| gpl-3.0 | 5,778,927,667,350,664,000 | 33.492754 | 132 | 0.659244 | false |
NCIP/python-api | pycabio/trunk/cabig/cabio/CaBioWSQueryService_server.py | 1 | 17682 | #L
# Copyright SAIC
#
# Distributed under the OSI-approved BSD 3-Clause License.
# See http://ncip.github.com/python-api/LICENSE.txt for details.
#L
##################################################
# file: CaBioWSQueryService_server.py
#
# skeleton generated by "ZSI.generate.wsdl2dispatch.ServiceModuleWriter"
# /usr/local/bin/cacore2py
#
##################################################
from ZSI.schema import GED, GTD
from ZSI.TCcompound import ComplexType, Struct
from CaBioWSQueryService_types import *
from ZSI.ServiceContainer import ServiceSOAPBinding
# Messages
_searchRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","search"), ofwhat=[ns0.SearchQuery_Def(pname="in0", aname="_in0", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class searchRequest:
typecode = _searchRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
in0 -- part in0
"""
self._in0 = kw.get("in0")
searchRequest.typecode.pyclass = searchRequest
_searchResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","searchResponse"), ofwhat=[ns1.ArrayOf_xsd_anyType_Def(pname="searchReturn", aname="_searchReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class searchResponse:
typecode = _searchResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
searchReturn -- part searchReturn
"""
self._searchReturn = kw.get("searchReturn")
searchResponse.typecode.pyclass = searchResponse
_getVersionRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getVersion"), ofwhat=[], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getVersionRequest:
typecode = _getVersionRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
"""
getVersionRequest.typecode.pyclass = getVersionRequest
_getVersionResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getVersionResponse"), ofwhat=[ZSI.TC.String(pname="getVersionReturn", aname="_getVersionReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getVersionResponse:
typecode = _getVersionResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
getVersionReturn -- part getVersionReturn
"""
self._getVersionReturn = kw.get("getVersionReturn")
getVersionResponse.typecode.pyclass = getVersionResponse
_existRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","exist"), ofwhat=[ZSI.TC.String(pname="in0", aname="_in0", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class existRequest:
typecode = _existRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
in0 -- part in0
"""
self._in0 = kw.get("in0")
existRequest.typecode.pyclass = existRequest
_existResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","existResponse"), ofwhat=[ZSI.TC.Boolean(pname="existReturn", aname="_existReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class existResponse:
typecode = _existResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
existReturn -- part existReturn
"""
self._existReturn = kw.get("existReturn")
existResponse.typecode.pyclass = existResponse
_getDataObjectRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getDataObject"), ofwhat=[ZSI.TC.String(pname="in0", aname="_in0", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getDataObjectRequest:
typecode = _getDataObjectRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
in0 -- part in0
"""
self._in0 = kw.get("in0")
getDataObjectRequest.typecode.pyclass = getDataObjectRequest
_getDataObjectResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getDataObjectResponse"), ofwhat=[ZSI.TC.AnyType(pname="getDataObjectReturn", aname="_getDataObjectReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getDataObjectResponse:
typecode = _getDataObjectResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
getDataObjectReturn -- part getDataObjectReturn
"""
self._getDataObjectReturn = kw.get("getDataObjectReturn")
getDataObjectResponse.typecode.pyclass = getDataObjectResponse
_queryRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","query"), ofwhat=[ZSI.TC.String(pname="targetClassName", aname="_targetClassName", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True), ZSI.TC.AnyType(pname="criteria", aname="_criteria", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True), ZSI.TCnumbers.Iint(pname="startIndex", aname="_startIndex", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class queryRequest:
typecode = _queryRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
targetClassName -- part targetClassName
criteria -- part criteria
startIndex -- part startIndex
"""
self._targetClassName = kw.get("targetClassName")
self._criteria = kw.get("criteria")
self._startIndex = kw.get("startIndex")
queryRequest.typecode.pyclass = queryRequest
_queryResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","queryResponse"), ofwhat=[ns1.ArrayOf_xsd_anyType_Def(pname="queryReturn", aname="_queryReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class queryResponse:
typecode = _queryResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
queryReturn -- part queryReturn
"""
self._queryReturn = kw.get("queryReturn")
queryResponse.typecode.pyclass = queryResponse
_getAssociationRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getAssociation"), ofwhat=[ZSI.TC.AnyType(pname="source", aname="_source", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True), ZSI.TC.String(pname="associationName", aname="_associationName", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True), ZSI.TCnumbers.Iint(pname="startIndex", aname="_startIndex", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getAssociationRequest:
typecode = _getAssociationRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
source -- part source
associationName -- part associationName
startIndex -- part startIndex
"""
self._source = kw.get("source")
self._associationName = kw.get("associationName")
self._startIndex = kw.get("startIndex")
getAssociationRequest.typecode.pyclass = getAssociationRequest
_getAssociationResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getAssociationResponse"), ofwhat=[ns1.ArrayOf_xsd_anyType_Def(pname="getAssociationReturn", aname="_getAssociationReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getAssociationResponse:
typecode = _getAssociationResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
getAssociationReturn -- part getAssociationReturn
"""
self._getAssociationReturn = kw.get("getAssociationReturn")
getAssociationResponse.typecode.pyclass = getAssociationResponse
_getRecordsPerQueryRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getRecordsPerQuery"), ofwhat=[], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getRecordsPerQueryRequest:
typecode = _getRecordsPerQueryRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
"""
getRecordsPerQueryRequest.typecode.pyclass = getRecordsPerQueryRequest
_getRecordsPerQueryResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getRecordsPerQueryResponse"), ofwhat=[ZSI.TCnumbers.Iint(pname="getRecordsPerQueryReturn", aname="_getRecordsPerQueryReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getRecordsPerQueryResponse:
typecode = _getRecordsPerQueryResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
getRecordsPerQueryReturn -- part getRecordsPerQueryReturn
"""
self._getRecordsPerQueryReturn = kw.get("getRecordsPerQueryReturn")
getRecordsPerQueryResponse.typecode.pyclass = getRecordsPerQueryResponse
_getMaximumRecordsPerQueryRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getMaximumRecordsPerQuery"), ofwhat=[], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getMaximumRecordsPerQueryRequest:
typecode = _getMaximumRecordsPerQueryRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
"""
getMaximumRecordsPerQueryRequest.typecode.pyclass = getMaximumRecordsPerQueryRequest
_getMaximumRecordsPerQueryResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getMaximumRecordsPerQueryResponse"), ofwhat=[ZSI.TCnumbers.Iint(pname="getMaximumRecordsPerQueryReturn", aname="_getMaximumRecordsPerQueryReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getMaximumRecordsPerQueryResponse:
typecode = _getMaximumRecordsPerQueryResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
getMaximumRecordsPerQueryReturn -- part getMaximumRecordsPerQueryReturn
"""
self._getMaximumRecordsPerQueryReturn = kw.get("getMaximumRecordsPerQueryReturn")
getMaximumRecordsPerQueryResponse.typecode.pyclass = getMaximumRecordsPerQueryResponse
_getTotalNumberOfRecordsRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getTotalNumberOfRecords"), ofwhat=[ZSI.TC.String(pname="targetClassName", aname="_targetClassName", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True), ZSI.TC.AnyType(pname="criteria", aname="_criteria", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getTotalNumberOfRecordsRequest:
typecode = _getTotalNumberOfRecordsRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
targetClassName -- part targetClassName
criteria -- part criteria
"""
self._targetClassName = kw.get("targetClassName")
self._criteria = kw.get("criteria")
getTotalNumberOfRecordsRequest.typecode.pyclass = getTotalNumberOfRecordsRequest
_getTotalNumberOfRecordsResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","getTotalNumberOfRecordsResponse"), ofwhat=[ZSI.TCnumbers.Iint(pname="getTotalNumberOfRecordsReturn", aname="_getTotalNumberOfRecordsReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class getTotalNumberOfRecordsResponse:
typecode = _getTotalNumberOfRecordsResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
getTotalNumberOfRecordsReturn -- part getTotalNumberOfRecordsReturn
"""
self._getTotalNumberOfRecordsReturn = kw.get("getTotalNumberOfRecordsReturn")
getTotalNumberOfRecordsResponse.typecode.pyclass = getTotalNumberOfRecordsResponse
_queryObjectRequestTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","queryObject"), ofwhat=[ZSI.TC.String(pname="targetClassName", aname="_targetClassName", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True), ZSI.TC.AnyType(pname="criteria", aname="_criteria", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class queryObjectRequest:
typecode = _queryObjectRequestTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
targetClassName -- part targetClassName
criteria -- part criteria
"""
self._targetClassName = kw.get("targetClassName")
self._criteria = kw.get("criteria")
queryObjectRequest.typecode.pyclass = queryObjectRequest
_queryObjectResponseTypecode = Struct(pname=("http://webservice.system.nci.nih.gov","queryObjectResponse"), ofwhat=[ns1.ArrayOf_xsd_anyType_Def(pname="queryObjectReturn", aname="_queryObjectReturn", typed=False, encoded=None, minOccurs=1, maxOccurs=1, nillable=True)], pyclass=None, encoded="http://webservice.system.nci.nih.gov")
class queryObjectResponse:
typecode = _queryObjectResponseTypecode
__metaclass__ = pyclass_type
def __init__(self, **kw):
"""Keyword parameters:
queryObjectReturn -- part queryObjectReturn
"""
self._queryObjectReturn = kw.get("queryObjectReturn")
queryObjectResponse.typecode.pyclass = queryObjectResponse
# Service Skeletons
class CaBioWSQueryService(ServiceSOAPBinding):
soapAction = {}
root = {}
def __init__(self, post='/cabio43/services/caBIOService', **kw):
ServiceSOAPBinding.__init__(self, post)
def soap_search(self, ps, **kw):
request = ps.Parse(searchRequest.typecode)
return request,searchResponse()
soapAction[''] = 'soap_search'
root[(searchRequest.typecode.nspname,searchRequest.typecode.pname)] = 'soap_search'
def soap_getVersion(self, ps, **kw):
request = ps.Parse(getVersionRequest.typecode)
return request,getVersionResponse()
soapAction[''] = 'soap_getVersion'
root[(getVersionRequest.typecode.nspname,getVersionRequest.typecode.pname)] = 'soap_getVersion'
def soap_exist(self, ps, **kw):
request = ps.Parse(existRequest.typecode)
return request,existResponse()
soapAction[''] = 'soap_exist'
root[(existRequest.typecode.nspname,existRequest.typecode.pname)] = 'soap_exist'
def soap_getDataObject(self, ps, **kw):
request = ps.Parse(getDataObjectRequest.typecode)
return request,getDataObjectResponse()
soapAction[''] = 'soap_getDataObject'
root[(getDataObjectRequest.typecode.nspname,getDataObjectRequest.typecode.pname)] = 'soap_getDataObject'
def soap_query(self, ps, **kw):
request = ps.Parse(queryRequest.typecode)
return request,queryResponse()
soapAction[''] = 'soap_query'
root[(queryRequest.typecode.nspname,queryRequest.typecode.pname)] = 'soap_query'
def soap_getAssociation(self, ps, **kw):
request = ps.Parse(getAssociationRequest.typecode)
return request,getAssociationResponse()
soapAction[''] = 'soap_getAssociation'
root[(getAssociationRequest.typecode.nspname,getAssociationRequest.typecode.pname)] = 'soap_getAssociation'
def soap_getRecordsPerQuery(self, ps, **kw):
request = ps.Parse(getRecordsPerQueryRequest.typecode)
return request,getRecordsPerQueryResponse()
soapAction[''] = 'soap_getRecordsPerQuery'
root[(getRecordsPerQueryRequest.typecode.nspname,getRecordsPerQueryRequest.typecode.pname)] = 'soap_getRecordsPerQuery'
def soap_getMaximumRecordsPerQuery(self, ps, **kw):
request = ps.Parse(getMaximumRecordsPerQueryRequest.typecode)
return request,getMaximumRecordsPerQueryResponse()
soapAction[''] = 'soap_getMaximumRecordsPerQuery'
root[(getMaximumRecordsPerQueryRequest.typecode.nspname,getMaximumRecordsPerQueryRequest.typecode.pname)] = 'soap_getMaximumRecordsPerQuery'
def soap_getTotalNumberOfRecords(self, ps, **kw):
request = ps.Parse(getTotalNumberOfRecordsRequest.typecode)
return request,getTotalNumberOfRecordsResponse()
soapAction[''] = 'soap_getTotalNumberOfRecords'
root[(getTotalNumberOfRecordsRequest.typecode.nspname,getTotalNumberOfRecordsRequest.typecode.pname)] = 'soap_getTotalNumberOfRecords'
def soap_queryObject(self, ps, **kw):
request = ps.Parse(queryObjectRequest.typecode)
return request,queryObjectResponse()
soapAction[''] = 'soap_queryObject'
root[(queryObjectRequest.typecode.nspname,queryObjectRequest.typecode.pname)] = 'soap_queryObject'
| bsd-3-clause | -7,140,755,335,672,836,000 | 53.239264 | 555 | 0.723561 | false |
tomv564/LSP | tests/test_views.py | 1 | 5029 | from LSP.plugin.core.protocol import Point
from LSP.plugin.core.url import filename_to_uri
from LSP.plugin.core.views import did_change
from LSP.plugin.core.views import did_open
from LSP.plugin.core.views import did_save
from LSP.plugin.core.views import MissingFilenameError
from LSP.plugin.core.views import point_to_offset
from LSP.plugin.core.views import text_document_formatting
from LSP.plugin.core.views import text_document_position_params
from LSP.plugin.core.views import text_document_range_formatting
from LSP.plugin.core.views import uri_from_view
from LSP.plugin.core.views import will_save
from LSP.plugin.core.views import will_save_wait_until
from LSP.plugin.core.views import location_to_encoded_filename
from unittest.mock import MagicMock
from unittesting import DeferrableTestCase
import sublime
class ViewsTest(DeferrableTestCase):
def setUp(self) -> None:
super().setUp()
self.view = sublime.active_window().new_file() # new_file() always returns a ready view
self.view.set_scratch(True)
self.mock_file_name = "C:/Windows" if sublime.platform() == "windows" else "/etc"
self.view.file_name = MagicMock(return_value=self.mock_file_name)
self.view.run_command("insert", {"characters": "hello world\nfoo bar baz"})
def tearDown(self) -> None:
self.view.close()
return super().tearDown()
def test_missing_filename(self) -> None:
self.view.file_name = MagicMock(return_value=None)
with self.assertRaises(MissingFilenameError):
uri_from_view(self.view)
def test_did_open(self) -> None:
self.assertEqual(did_open(self.view, "python").params, {
"textDocument": {
"uri": filename_to_uri(self.mock_file_name),
"languageId": "python",
"text": "hello world\nfoo bar baz",
"version": self.view.change_count()
}
})
def test_did_change_full(self) -> None:
self.assertEqual(did_change(self.view).params, {
"textDocument": {
"uri": filename_to_uri(self.mock_file_name),
"version": self.view.change_count()
},
"contentChanges": [{"text": "hello world\nfoo bar baz"}]
})
def test_will_save(self) -> None:
self.assertEqual(will_save(self.view, 42).params, {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)},
"reason": 42
})
def test_will_save_wait_until(self) -> None:
self.assertEqual(will_save_wait_until(self.view, 1337).params, {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)},
"reason": 1337
})
def test_did_save(self) -> None:
self.assertEqual(did_save(self.view, include_text=False).params, {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)}
})
self.assertEqual(did_save(self.view, include_text=True).params, {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)},
"text": "hello world\nfoo bar baz"
})
def test_text_document_position_params(self) -> None:
self.assertEqual(text_document_position_params(self.view, 2), {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)},
"position": {"line": 0, "character": 2}
})
def test_text_document_formatting(self) -> None:
self.view.settings = MagicMock(return_value={"translate_tabs_to_spaces": False, "tab_size": 1234})
self.assertEqual(text_document_formatting(self.view).params, {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)},
"options": {"tabSize": 1234, "insertSpaces": False}
})
def test_text_document_range_formatting(self) -> None:
self.view.settings = MagicMock(return_value={"tab_size": 4321})
self.assertEqual(text_document_range_formatting(self.view, sublime.Region(0, 2)).params, {
"textDocument": {"uri": filename_to_uri(self.mock_file_name)},
"options": {"tabSize": 4321, "insertSpaces": False},
"range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 2}}
})
def test_point_to_offset(self) -> None:
first_line_length = len(self.view.line(0))
self.assertEqual(point_to_offset(Point(1, 2), self.view), first_line_length + 3)
self.assertEqual(point_to_offset(Point(0, first_line_length + 9999), self.view), first_line_length)
def test_location_to_encoded_filename(self) -> None:
self.assertEqual(
location_to_encoded_filename(
{'uri': 'file:///foo/bar', 'range': {'start': {'line': 0, 'character': 5}}}),
'/foo/bar:1:6')
self.assertEqual(
location_to_encoded_filename(
{'targetUri': 'file:///foo/bar', 'targetSelectionRange': {'start': {'line': 1234, 'character': 4321}}}),
'/foo/bar:1235:4322')
| mit | 8,332,042,360,538,931,000 | 43.504425 | 120 | 0.621396 | false |
zephyru5/pythonchallenge | 18/18.py | 1 | 1079 | #!/bin/bash/python
#coding=utf-8
'''
#first try start
from PIL import Image
im=Image.open('balloons.jpg','wb')
w,h=im.size
diff=Image.new(im.mode,(w/2,h),0)
for i in range(w/2):
for j in range(h):
diff.putpixel((i,j),tuple([x[0]-x[1] for x in zip(im.getpixel((i,j)),im.getpixel((i+w//2,j)))]))
diff.save('diff.png')
#first try end
'''
import gzip,difflib,urllib2
h = gzip.open("deltas.gz")
part_1, part_2 = [], []
pic_1,pic_2, pic_3 = [], [], []
for line in h:
part_1.append(line[0:53])
part_2.append(line[56:-1])
h.close()
for line in list(difflib.Differ().compare(part_1, part_2)):
if line[0] == "+":
pic_1.append(line[2:])
elif line[0] == "-":
pic_2.append(line[2:])
else:
pic_3.append(line[2:])
for n, data in enumerate((pic_1, pic_2, pic_3)):
temp = []
for line in data:
temp.extend([chr(int(o, 16)) for o in line.strip().split(" ") if o])
h = open("%s.png" % (n + 1), "wb")
h.writelines(temp)
h.close()
| mit | 6,806,134,189,498,601,000 | 22.977778 | 104 | 0.522706 | false |
egustafson/sandbox | Python/sqlalchemy-core/table.py | 1 | 1551 | # -*- coding: utf-8 -*-
#
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.sql import select, func
metadata = MetaData()
users = Table('users', metadata,
Column('id', Integer, primary_key=True),
Column('username', String),
Column('realname', String),
)
addrs = Table('addresses', metadata,
Column('id', Integer, primary_key=True),
Column('user_id', None, ForeignKey('users.id')),
Column('email', String, nullable=False),
)
engine = create_engine('sqlite:///:memory:', echo=True)
metadata.create_all(engine)
ins = users.insert().values(username='jack', realname='Jack Hat')
conn = engine.connect()
conn.execute(ins)
ins = users.insert()
conn.execute(ins, username='hank', realname='Hank Hat')
conn.execute(users.insert(), [
{'username': 'user1', 'realname': 'User One'},
{'username': 'user2', 'realname': 'User Two'},
{'username': 'user3', 'realname': 'User Three'},
])
conn.execute(addrs.insert(), [
{'user_id': 1, 'email': '[email protected]'},
])
# --- Select ---
rs = conn.execute(select([users]))
for row in rs:
print(row)
sel = select([func.max(users.c.id)])
max = conn.execute(sel).scalar()
print("id max value: {}".format(max))
# --- Join ---
s = select([users.c.username, users.c.realname, addrs.c.email]).select_from(
users.join(addrs)).where(addrs.c.email != None)
rs = conn.execute(s)
for row in rs:
print(row)
| apache-2.0 | 5,134,627,254,167,216,000 | 24.85 | 76 | 0.617021 | false |
dragondjf/musicplayer | gui/mainwindow/simplewindow.py | 1 | 1875 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from gui.menus import SettingsMenu
from gui.dwidgets import DMainFrame
from gui.functionpages import SimpleTitleBar, SimpleMusicBottomBar
from gui.utils import collectView, setSkinForApp
from config import constants
import config
class SimpleWindow(DMainFrame):
viewID = "SimpleWindow"
@collectView
def __init__(self):
super(SimpleWindow, self).__init__()
self.setObjectName(self.viewID)
self.initUI()
def initUI(self):
self.initSize()
self.setWindowIcon(config.windowIcon)
self.setWindowTitle(config.windowTitle)
self.initMenus()
self.initCentralWidget()
def initSize(self):
self.resize(constants.SimpleWindow_Width, constants.SimpleWindow_Height)
self.moveCenter()
def initMenus(self):
self.settingsMenu = SettingsMenu(self)
def _initSystemTray(self):
pass
def initCentralWidget(self):
self.initTitleBar()
self.initSimpleStackPage()
self.initBottomBar()
centralWidget = QFrame(self)
mainLayout = QVBoxLayout()
mainLayout.addWidget(self.simpleTitleBar)
# mainLayout.addWidget(self.simpleStackPage)
mainLayout.addStretch()
mainLayout.addWidget(self.simpleMusicBottomBar)
mainLayout.setContentsMargins(0, 0, 0, 0)
mainLayout.setSpacing(0)
centralWidget.setLayout(mainLayout)
self.setCentralWidget(centralWidget)
def initTitleBar(self):
self.simpleTitleBar = SimpleTitleBar(self)
self.simpleTitleBar.settingDownButton.setMenu(self.settingsMenu)
def initSimpleStackPage(self):
pass
def initBottomBar(self):
self.simpleMusicBottomBar = SimpleMusicBottomBar()
| gpl-2.0 | -500,907,304,614,135,500 | 25.408451 | 80 | 0.690667 | false |
BovineJoni/WikidumpParser | article.py | 1 | 1662 | # -*- coding: utf-8 -*-
# WikidumpParser, Copyright 2014 Daniel Schneider.
# schneider.dnl(at)gmail.com
# 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 <http://www.gnu.org/licenses/>.
"""WikidumpParser - article module
-----------------------------------------------------------
Note:
Class for saving wikipedia articles. An article can
have multiple entries of multiple authors.
-----------------------------------------------------------
"""
from __future__ import division
class article(object):
def __init__(self, article_id, article_title):
self.article_id = article_id
self.article_title = article_title
self.authors = 0
self.entries = []
self.lines = 0
def append(self, entry):
"""Append new entry to article."""
self.entries.append(entry)
self.authors = len(set(map(lambda entry: entry.author_id, self.entries)))
self.lines += entry.len
def current_pos(self):
"""Return current length of the article."""
if len(self.entries) != 0:
return self.entries[-1].end
return 0 | gpl-3.0 | -2,410,109,321,182,158,300 | 34.382979 | 81 | 0.634777 | false |
lookup/lu-dj-utils | tests/test_test.py | 1 | 1096 | # coding: utf-8
"""Source: lookup_www.common.utils.tests.test_utils_test.
"""
from __future__ import absolute_import, print_function, unicode_literals
from django.test import SimpleTestCase, TestCase
from django.utils import six
class FunctionsTest(TestCase): # TODO: change to SimpleTestCase or unittest.TestCase?
def test_create_request(self):
from django.core.handlers.wsgi import WSGIRequest
from lu_dj_utils.test import create_request
req = create_request('my-path', 'get')
self.assertIsInstance(req, WSGIRequest)
self.assertEqual(req.META['PATH_INFO'], 'my-path')
self.assertEqual(req.META['REQUEST_METHOD'], 'GET')
data = {'x': 'y', 'a': 1}
req = create_request('something', 'post', data=data)
self.assertIsInstance(req, WSGIRequest)
self.assertEqual(req.META['PATH_INFO'], 'something')
self.assertEqual(req.META['REQUEST_METHOD'], 'POST')
six.assertCountEqual( # in Python2 = assertItemsEqual
self,
req.POST.items(),
[('x', 'y'), ('a', '1')])
| bsd-3-clause | -3,978,664,021,771,931,600 | 35.533333 | 86 | 0.643248 | false |
liw/daos | src/tests/ftest/pool/create_capacity_test.py | 1 | 2623 | #!/usr/bin/python3
"""
(C) Copyright 2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
"""
import time
from pool_test_base import PoolTestBase
from server_utils import ServerFailed
class PoolCreateTests(PoolTestBase):
# pylint: disable=too-many-ancestors,too-few-public-methods
"""Pool create tests.
All of the tests verify pool create performance with 7 servers and 1 client.
Each server should be configured with full compliment of NVDIMMs and SSDs.
:avocado: recursive
"""
def test_create_pool_quantity(self):
"""JIRA ID: DAOS-5114 / SRS-2 / SRS-4.
Test Description:
Create 200 pools on all of the servers.
Perform an orderly system shutdown via cmd line (dmg).
Restart the system via cmd line tool (dmg).
Verify that DAOS is ready to accept requests with in 2 minutes.
:avocado: tags=all,pr,daily_regression
:avocado: tags=hw,large
:avocado: tags=pool
:avocado: tags=pool_create_tests,create_performance
"""
# Create some number of pools each using a equal amount of 60% of the
# available capacity, e.g. 0.6% for 100 pools.
quantity = self.params.get("quantity", "/run/pool/*", 1)
self.add_pool_qty(quantity, create=False)
self.check_pool_creation(10)
# Verify DAOS can be restarted in less than 2 minutes
try:
self.server_managers[0].system_stop()
except ServerFailed as error:
self.fail(error)
start = float(time.time())
try:
self.server_managers[0].system_start()
except ServerFailed as error:
self.fail(error)
duration = float(time.time()) - start
self.assertLessEqual(
duration, 120,
"DAOS not ready to accept requests with in 2 minutes")
# Verify all the pools exists after the restart
detected_pools = [uuid.lower() for uuid in self.dmg.pool_list()]
missing_pools = []
for pool in self.pool:
pool_uuid = pool.uuid.lower()
if pool_uuid not in detected_pools:
missing_pools.append(pool_uuid)
if missing_pools:
self.fail(
"The following created pools were not detected in the pool "
"list after rebooting the servers:\n [{}]: {}".format(
len(missing_pools), ", ".join(missing_pools)))
self.assertEqual(
len(self.pool), len(detected_pools),
"Additional pools detected after rebooting the servers")
| apache-2.0 | -8,870,181,680,351,674,000 | 34.445946 | 80 | 0.614945 | false |
frmdstryr/enamlx | examples/occ_viewer/occ/algo.py | 1 | 12047 | '''
Created on Sep 28, 2016
@author: jrm
'''
from atom.api import (
Instance, ForwardInstance, Typed, ForwardTyped, ContainerList, Enum, Float, Bool, Coerced, observe
)
from enaml.core.declarative import d_
from .shape import ProxyShape, Shape
def WireFactory():
#: Deferred import of wire
from .draw import Wire
return Wire
class ProxyOperation(ProxyShape):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: Operation)
class ProxyBooleanOperation(ProxyOperation):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: BooleanOperation)
def set_shape1(self,shape):
raise NotImplementedError
def set_shape2(self,shape):
raise NotImplementedError
def set_pave_filler(self,pave_filler):
raise NotImplementedError
def _do_operation(self,shape1,shape2):
raise NotImplementedError
class ProxyCommon(ProxyBooleanOperation):
declaration = ForwardTyped(lambda: Common)
class ProxyCut(ProxyBooleanOperation):
declaration = ForwardTyped(lambda: Cut)
class ProxyFuse(ProxyBooleanOperation):
declaration = ForwardTyped(lambda: Fuse)
class ProxyFillet(ProxyOperation):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: Fillet)
def set_radius(self, r):
raise NotImplementedError
def set_edges(self, edges):
raise NotImplementedError
def set_shape(self, shape):
raise NotImplementedError
class ProxyChamfer(ProxyOperation):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: Chamfer)
def set_distance(self, d):
raise NotImplementedError
def set_distance2(self, d):
raise NotImplementedError
def set_edges(self, edges):
raise NotImplementedError
def set_faces(self, faces):
raise NotImplementedError
class ProxyOffset(ProxyOperation):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: Offset)
def set_offset(self, offset):
raise NotImplementedError
def set_offset_mode(self, mode):
raise NotImplementedError
def set_intersection(self, enabled):
raise NotImplementedError
def set_join_type(self, mode):
raise NotImplementedError
class ProxyThickSolid(ProxyOffset):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: ThickSolid)
def set_closing_faces(self, faces):
raise NotImplementedError
class ProxyPipe(ProxyOffset):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: Pipe)
def set_spline(self, spline):
raise NotImplementedError
def set_profile(self, profile):
raise NotImplementedError
def set_fill_mode(self, mode):
raise NotImplementedError
class ProxyAbstractRibSlot(ProxyOperation):
#: Abstract class
def set_shape(self, shape):
raise NotImplementedError
def set_contour(self, contour):
raise NotImplementedError
def set_plane(self, plane):
raise NotImplementedError
def set_fuse(self, fuse):
raise NotImplementedError
class ProxyLinearForm(ProxyAbstractRibSlot):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: LinearForm)
def set_direction(self, direction):
raise NotImplementedError
def set_direction1(self, direction):
raise NotImplementedError
def set_modify(self, modify):
raise NotImplementedError
class ProxyRevolutionForm(ProxyAbstractRibSlot):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: RevolutionForm)
def set_height1(self, direction):
raise NotImplementedError
def set_height2(self, direction):
raise NotImplementedError
def set_sliding(self, sliding):
raise NotImplementedError
class ProxyThruSections(ProxyOperation):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: ThruSections)
def set_solid(self, solid):
raise NotImplementedError
def set_ruled(self, ruled):
raise NotImplementedError
def set_precision(self, pres3d):
raise NotImplementedError
class ProxyTransform(ProxyOperation):
#: A reference to the Shape declaration.
declaration = ForwardTyped(lambda: Transform)
def set_shape(self, shape):
raise NotImplementedError
def set_mirror(self, axis):
raise NotImplementedError
def set_rotate(self, rotation):
raise NotImplementedError
def set_scale(self, scale):
raise NotImplementedError
def set_translate(self, translation):
raise NotImplementedError
class Operation(Shape):
#: Reference to the implementation control
proxy = Typed(ProxyOperation)
def _update_proxy(self, change):
if change['name']=='axis':
dx,dy,dz = self.x,self.y,self.z
if change.get('oldvalue',None):
old = change['oldvalue'].Location()
dx -= old.X()
dy -= old.Y()
dz -= old.Z()
for c in self.children:
if isinstance(c,Shape):
c.position = (c.x+dx,c.y+dy,c.z+dz)
else:
super(Operation, self)._update_proxy(change)
self.proxy.update_display(change)
class BooleanOperation(Operation):
shape1 = d_(Instance(object))
shape2 = d_(Instance(object))
#: Optional pave filler
pave_filler = d_(Instance(object))#BOPAlgo_PaveFiller))
@observe('shape1','shape2','pave_filler')
def _update_proxy(self, change):
super(BooleanOperation, self)._update_proxy(change)
class Common(BooleanOperation):
#: Reference to the implementation control
proxy = Typed(ProxyCommon)
class Cut(BooleanOperation):
#: Reference to the implementation control
proxy = Typed(ProxyCut)
class Fuse(BooleanOperation):
#: Reference to the implementation control
proxy = Typed(ProxyFuse)
class LocalOperation(Operation):
pass
class Fillet(LocalOperation):
""" Applies fillet to the first child shape"""
#: Reference to the implementation control
proxy = Typed(ProxyFillet)
#: Fillet shape type
shape = d_(Enum('rational','angular','polynomial')).tag(view=True, group='Fillet')
#: Radius of fillet
radius = d_(Float(1, strict=False)).tag(view=True, group='Fillet')
#: Edges to apply fillet to
#: Leave blank to use all edges of the shape
edges = d_(ContainerList(object)).tag(view=True, group='Fillet')
@observe('shape','radius','edges')
def _update_proxy(self, change):
super(Fillet, self)._update_proxy(change)
class Chamfer(LocalOperation):
#: Reference to the implementation control
proxy = Typed(ProxyChamfer)
#: Distance of chamfer
distance = d_(Float(1, strict=False)).tag(view=True, group='Chamfer')
#: Second of chamfer (leave 0 if not used)
distance2 = d_(Float(0, strict=False)).tag(view=True, group='Chamfer')
#: Edges to apply fillet to
#: Leave blank to use all edges of the shape
edges = d_(ContainerList()).tag(view=True, group='Chamfer')
faces = d_(ContainerList()).tag(view=True, group='Chamfer')
@observe('distance','distance2','edges','faces')
def _update_proxy(self, change):
super(Chamfer, self)._update_proxy(change)
class Offset(Operation):
#: Reference to the implementation control
proxy = Typed(ProxyOffset)
#: Offset
offset = d_(Float(1,strict=False)).tag(view=True, group='Offset')
#: Offset mode
offset_mode = d_(Enum('skin','pipe','recto_verso')).tag(view=True, group='Offset')
#: Intersection
intersection = d_(Bool(False)).tag(view=True, group='Offset')
#: Join type
join_type = d_(Enum('arc','tangent','intersection')).tag(view=True, group='Offset')
@observe('offset','offset_mode','intersection','join_type')
def _update_proxy(self, change):
super(Offset, self)._update_proxy(change)
class ThickSolid(Offset):
#: Reference to the implementation control
proxy = Typed(ProxyThickSolid)
#: Closing faces
closing_faces = d_(ContainerList()).tag(view=True, group='ThickSolid')
@observe('closing_faces')
def _update_proxy(self, change):
super(ThickSolid, self)._update_proxy(change)
class Pipe(Operation):
#: Reference to the implementation control
proxy = Typed(ProxyPipe)
#: Spline to make the pipe along
spline = d_(Instance(Shape))
#: Profile to make the pipe from
profile = d_(ForwardInstance(WireFactory))
#: Fill mode
fill_mode = d_(Enum(None,'corrected_frenet','fixed','frenet','constant_normal','darboux',
'guide_ac','guide_plan','guide_ac_contact','guide_plan_contact','discrete_trihedron')).tag(view=True, group='Pipe')
@observe('spline','profile','fill_mode')
def _update_proxy(self, change):
super(Pipe, self)._update_proxy(change)
class AbstractRibSlot(Operation):
#: Base shape
shape = d_(Instance(Shape))
#: Profile to make the pipe from
contour = d_(Instance(Shape))
#: Profile to make the pipe from
plane = d_(Instance(Shape))
#: Fuse (False to remove, True to add)
fuse = d_(Bool(False)).tag(view=True)
class LinearForm(AbstractRibSlot):
#: Reference to the implementation control
proxy = Typed(ProxyLinearForm)
#: Direction
direction1 = d_(Instance((list,tuple))).tag(view=True)
#: Modify
modify = d_(Bool(False)).tag(view=True)
class RevolutionForm(AbstractRibSlot):
#: Reference to the implementation control
proxy = Typed(ProxyRevolutionForm)
#: Height 1
height1 = d_(Float(1.0,strict=False)).tag(view=True)
#: Height 2
height2 = d_(Float(1.0,strict=False)).tag(view=True)
#: Sliding
sliding = d_(Bool(False)).tag(view=True)
class ThruSections(Operation):
#: Reference to the implementation control
proxy = Typed(ProxyThruSections)
#: isSolid is set to true if the construction algorithm is required
#: to build a solid or to false if it is required to build a shell (the default value),
solid = d_(Bool(False)).tag(view=True, group='Through Sections')
#: ruled is set to true if the faces generated between the edges
#: of two consecutive wires are ruled surfaces or to false (the default value)
#: if they are smoothed out by approximation
ruled = d_(Bool(False)).tag(view=True, group='Through Sections')
#: pres3d defines the precision criterion used by the approximation algorithm;
#: the default value is 1.0e-6. Use AddWire and AddVertex to define
#: the successive sections of the shell or solid to be built.
precision = d_(Float(1e-6)).tag(view=True, group='Through Sections')
@observe('solid','ruled','precision')
def _update_proxy(self, change):
super(ThruSections, self)._update_proxy(change)
class Transform(Operation):
#: Reference to the implementation control
proxy = Typed(ProxyTransform)
#: Shape to transform
#: if none is given the first child will be used
shape = d_(Instance(Shape))
#: Mirror
mirror = d_(Instance((tuple,list)))
#: Scale
scale = d_(Instance((tuple,list)))
#: Rotation
rotate = d_(Instance((tuple,list)))
#: Translation
translate = d_(Instance((tuple,list)))
@observe('shape','mirror','scale','rotate','translate')
def _update_proxy(self, change):
super(Transform, self)._update_proxy(change)
| mit | -3,666,099,048,140,562,000 | 28.748148 | 139 | 0.650618 | false |
lluxury/pcc_exercise | learning_logs/learning_logs/views.py | 1 | 3388 | from django.shortcuts import render
from django.http import HttpResponseRedirect, Http404
#from django.core.ulresolvers import reverse
from django.core.urlresolvers import reverse
#form django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import login_required
from .models import Topic, Entry
from .forms import TopicForm, EntryForm
# Create your views here.
def index(request):
'''学习笔记主页'''
return render(request, 'learning_logs/index.html')
@login_required
def topics(request):
'''显示所有主题'''
topics = Topic.objects.filter(owner=request.user).order_by('date_added')
context = {'topics' : topics}
return render(request, 'learning_logs/topics.html', context)
@login_required
def topic(request, topic_id):
'''显示单个主题及所有条目'''
topic = Topic.objects.get(id=topic_id)
#确认请求主题属于当前用户
if topic.owner !=request.user:
raise Http404
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
#context = ('topic': topic, 'entries': entries)
return render(request, 'learning_logs/topic.html', context)
@login_required
def new_topic(request):
'''添加新主题'''
if request.method != 'POST':
# 未提交数据: 创建一个新表单
form = TopicForm()
else:
# POST 提交数据, 对数据进行处理
form = TopicForm(request.POST)
if form.is_valid():
new_topic = form.save(commit=False)
new_topic.owner = request.user
new_topic.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
@login_required
def new_entry(request, topic_id):
'''在特定主题中添加新条目'''
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
'''未提交数据,建安空表单'''
form = EntryForm()
else:
#POST提交的数据,对数据进行处理
#from = EntryForm(data=request.POST)
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
new_entry.save()
return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id]))
context = {'topic': topic, 'form': form}
return render(request, 'learning_logs/new_entry.html', context)
@login_required
def edit_entry(request, entry_id):
'''edit entry'''
#entry = Entry.obejcts.get(id=entry_id)
entry = Entry.objects.get(id=entry_id)
topic = entry.topic
if topic.owner != request.user:
raise Http404
if request.method != 'POST':
#first requeest use current fill form
form = EntryForm(instance=entry)
else:
#POST提交的请求,对数据进行处理
form = EntryForm(instance=entry, data = request.POST)
if form.is_valid():
form.save()
#return HttpResponseRedirect(reverse{'learning_logs:topic', args=[topic.id]})
return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic.id]))
context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'learning_logs/edit_entry.html', context)
| mit | -28,531,902,864,089,668 | 31.701031 | 89 | 0.648802 | false |
mifads/pyscripts | emxemis/mkFFrescale.py | 1 | 1712 | #!/usr/bin/env python3
""" mkFFscale.py simply....
emissions given in eg moles/day or kg/hr, since we don't need to
allow for grid area.
UNFINISHED!!
"""
import argparse
import numpy as np
import netCDF4 as cdf
import os
import sys
#------------------ arguments ----------------------------------------------
parser=argparse.ArgumentParser()
parser.add_argument('-i','--ifile',help='Input file',required=True)
parser.add_argument('-s','--scale',help='scale factor file',required=True)
parser.add_argument('-d','--domain',help='domain wanted, i0 i1 j0 j1, e.g. "30 100 40 80"',required=False)
parser.add_argument('-o','--odir',help='output directory',default='.')
parser.add_argument('-V','--verbose',help='extra info',action='store_true')
args=parser.parse_args()
dtxt='CdfComp'
dbg=False
if args.verbose: dbg=True
if dbg: print(dtxt+'ARGS', args)
case=dict()
cases=[]
ifile=args.ifile
if os.path.isfile(ifile):
if dbg: print('TRY ', ifile)
else:
sys.exit('MISSING IFILE'+ifile)
ecdf=cdf.Dataset(ifile,'r',format='NETCDF4')
keys=ecdf.variables.keys()
wanted=[]
exclude='lon lat time map_factor_i map_factor_j'.split()
for k in keys:
if k in exclude: continue
wanted.append(k)
nwanted=len(wanted)
if dbg: print(' KEYS ', keys, len(keys), nwanted )
#
# New arrays for mkCdf
data = np.zeros([nwanted,
sys.exit()
#var = args.var
var='TMP'
if dbg: print(' VAR ', var )
if args.domain:
i0, i1, j0, j1 = [ int(i) for i in args.domain.split() ]
vals=ecdf.variables[var][:,j0:j1+1,i0:i1+1]
else:
i0, i1, j0, j1 = [ -1, -1, -1, -1 ]
vals=ecdf.variables[var][:,:,:]
if dbg: print(dtxt+' domain', i0, i1, j0, j1 )
vsum = np.sum(vals) # ,axis=(1,2))
print('Sum all values = ', vsum )
| gpl-3.0 | 4,669,483,891,239,769,000 | 26.612903 | 106 | 0.643692 | false |
quantumgraph/mongo-query-aggregator | tests/test_insert.py | 1 | 5148 | import unittest
import time
from pymongo import MongoClient
from moquag import MongoQueryAggregator
from time import sleep
from .settings import MONGO_DB_SETTINGS, logger
from collections import Counter
class TestBulk(unittest.TestCase):
def setUp(self):
self.conn = MongoClient(**MONGO_DB_SETTINGS)
self.conn.drop_database('testdb1')
self.conn.drop_database('testdb2')
self.conn.drop_database('testdb3')
def test_1(self):
'''inserting 2 document in interval of 0.1 sec'''
mongo_agg = MongoQueryAggregator(MONGO_DB_SETTINGS, 0.1, 10)
docs = [
{'name': 'User1', 'id': 1},
{'name': 'User2', 'id': 2}
]
x = mongo_agg.testdb1.profiles.insert(docs[0])
data = self.conn['testdb1'].profiles.find()
# added one doc to aggregator, it should not be inserted to DB yet
# as time interval 0.1 sec is not passed and doc limit of 10 is not crossed
self.assertEqual(self.conn['testdb1'].profiles.count(), 0)
time.sleep(0.1)
mongo_agg.testdb1.profiles.insert(docs[1])
# docs[1] is inserted after 0.1 sec so it should flush older data
# so docs[0] should be inserted to mongo
data = self.conn['testdb1'].profiles.find()
self.assertEqual(data.count(), 1)
for doc in data:
self.assertEqual(doc, docs[0])
def test_2(self):
'''inserting 6 documents with max_ops_limit=5
so first five docs shoulld be present in mongodb'''
mongo_agg = MongoQueryAggregator(MONGO_DB_SETTINGS, 1, 5)
docs = [
{'name': 'User1', 'id': 1},
{'name': 'User2', 'id': 2},
{'name': 'User3', 'id': 3},
{'name': 'User4', 'id': 4},
{'name': 'User5', 'id': 5},
{'name': 'User6', 'id': 6}
]
for doc in docs:
mongo_agg.testdb1.profiles.insert(doc)
# while inserting 6 records, 6th record will flush first 5 to db
data = self.conn['testdb1'].profiles.find().sort([('id', 1)])
mongo_docs = []
self.assertEqual(data.count(), 5)
for doc in data:
mongo_docs.append(doc)
self.assertListEqual(mongo_docs, docs[:5]) # checking first five in docs
def test_3(self):
'''inserting 6 documents with max_ops_limit=5
so first five docs should be present in mongodb
here inserting to multiple dbs'''
mongo_agg = MongoQueryAggregator(MONGO_DB_SETTINGS, 1, 5)
docs = [
{'name': 'User1', 'id': 1},
{'name': 'User2', 'id': 2},
{'name': 'User3', 'id': 3},
{'name': 'User4', 'id': 4},
{'name': 'User5', 'id': 5},
{'name': 'User6', 'id': 6}
]
for doc in docs[:6]:
# inserting first 6 records to db testdb1
mongo_agg.testdb1.profiles.insert(doc)
mongo_agg.testdb2.profiles.insert({'name': 'User1', 'id': 1})
# while inserting 6 records, 6th record will flush first 5 to db
data = self.conn['testdb1'].profiles.find().sort([('id', 1)])
docs_in_db = []
for doc in data:
docs_in_db.append(doc)
self.assertListEqual(docs_in_db, docs[:5])
aggregators_expected_results = {
('testdb1', 'profiles'): Counter({'nInserted': 5})
}
aggregators_results = mongo_agg.get_results()
self.assertEqual(aggregators_expected_results,aggregators_results)
def test_4(self):
'''inserting to multiple data to multiple dbs
and checking mongo data and aggregators resuts'''
mongo_agg = MongoQueryAggregator(MONGO_DB_SETTINGS, 0.1, 5)
dbs_to_data = {
'testdb1': [
{'name': 'User2', 'id': 1}, {'name': 'User2', 'id': 2}
],
'testdb2': [
{'name': 'User3', 'id': 3}
],
'testdb3': [
{'name': 'User5', 'id': 5},
{'name': 'User6', 'id': 6},
{'name': 'User7', 'id': 8}
]
}
for db_name in dbs_to_data:
for doc in dbs_to_data[db_name]:
mongo_agg[db_name].profiles.insert(doc)
time.sleep(0.1)
mongo_agg.testdb1.profiles.insert({'key': 1}) # dummy data to flush older data
projection = {'name': 1, 'id': 1, '_id': 0}
for db_name in dbs_to_data:
data = self.conn[db_name].profiles.find().sort([('id', 1)])
self.assertEqual(data.count(), len(dbs_to_data[db_name]))
docs_in_db = []
for doc in data:
docs_in_db.append(doc)
self.assertListEqual(docs_in_db, dbs_to_data[db_name])
aggregators_expected_results = {
('testdb1', 'profiles'): Counter({'nInserted': 2}),
('testdb3', 'profiles'): Counter({'nInserted': 3}),
('testdb2', 'profiles'): Counter({'nInserted': 1})
}
aggregators_results = mongo_agg.get_results()
self.assertEqual(aggregators_expected_results, aggregators_results)
| mit | 1,054,069,137,620,576,300 | 38 | 86 | 0.544289 | false |
ameihm0912/MozDef | alerts/auditd_sftp.py | 1 | 1886 | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2014 Mozilla Corporation
#
# Contributors:
# Anthony Verez [email protected]
# Jeff Bryner [email protected]
# Aaron Meihm [email protected]
# Michal Purzynski <[email protected]>
# Alicia Smith <[email protected]>
from lib.alerttask import AlertTask
from query_models import SearchQuery, TermMatch, PhraseMatch
class AlertSFTPEvent(AlertTask):
def main(self):
search_query = SearchQuery(minutes=5)
search_query.add_must([
TermMatch('_type', 'auditd'),
TermMatch('category', 'execve'),
TermMatch('processname', 'audisp-json'),
TermMatch('details.processname', 'ssh'),
PhraseMatch('details.parentprocess', 'sftp'),
])
self.filtersManual(search_query)
self.searchEventsSimple()
self.walkEvents()
# Set alert properties
def onEvent(self, event):
category = 'execve'
severity = 'NOTICE'
tags = ['audisp-json, audit']
srchost = 'unknown'
username = 'unknown'
directory = 'unknown'
x = event['_source']
if 'details' in x:
if 'hostname' in x['details']:
srchost = x['details']['hostname']
if 'originaluser' in x['details']:
username = x['details']['originaluser']
if 'cwd' in x['details']:
directory = x['details']['cwd']
summary = 'SFTP Event by {0} from host {1} in directory {2}'.format(username, srchost, directory)
# Create the alert object based on these properties
return self.createAlertDict(summary, category, tags, [event], severity)
| mpl-2.0 | -5,164,862,941,264,948,000 | 32.678571 | 105 | 0.620361 | false |
martijnvermaat/wiggelen | tests/test_distance.py | 1 | 1398 | """
Tests for the distance module.
"""
import os
from nose.tools import *
from wiggelen.distance import distance
from wiggelen.index import INDEX_SUFFIX, clear_cache
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
def open_(filename, mode='r'):
"""
Open a file from the test data.
"""
return open(os.path.join(DATA_DIR, filename), mode)
def remove_indices(keep_cache=False):
"""
Cleanup any index files for the test data.
"""
if not keep_cache:
clear_cache()
for file in os.listdir(DATA_DIR):
if file.endswith(INDEX_SUFFIX):
os.unlink(os.path.join(DATA_DIR, file))
class TestDistance(object):
"""
Tests for the distance module.
"""
@classmethod
def setup_class(cls):
remove_indices()
def teardown(self):
remove_indices()
def test_distance(self):
"""
Simple distance test on two tracks.
"""
track_a = open_('a.wig')
track_b = open_('b.wig')
assert_equal('%.3f' % distance(track_a, track_b)[1, 0],
'0.687')
def test_distance_threshold(self):
"""
Distance test with threshold on two tracks.
"""
track_a = open_('a.wig')
track_b = open_('b.wig')
assert_equal('%.3f' % distance(track_a, track_b, threshold=600)[1, 0],
'0.925')
| mit | 2,976,159,079,551,480,000 | 21.548387 | 78 | 0.566524 | false |
krujos/oohimtelling | app.py | 1 | 5031 | #!/usr/bin/env python
from __future__ import print_function
import json
import requests
import sys
import os
import time
from flask import Flask, request, Response
from flask import jsonify
from functools import wraps
Flask.get = lambda self, path: self.route(path, methods=['get'])
##################################The Setup###############################################
vcap_services = json.loads(os.getenv("VCAP_SERVICES"))
client_id = None
client_secret = None
uaa_uri = None
api = None
cache = dict()
port = 8003
expire_time = 0
token = None
sslVerify = (os.getenv("VERIFY_SSL") != "false" and os.getenv("VERIFY_SSL") != "FALSE")
print("Calling CF with sslVerify = " + str(sslVerify))
if 'PORT' in os.environ:
port = int(os.getenv("PORT"))
app = Flask(__name__)
for service in vcap_services['user-provided']:
if 'uaa' == service['name']:
client_id = service['credentials']['client_id']
client_secret = service['credentials']['client_secret']
uaa_uri = service['credentials']['uri']
elif 'cloud_controller' == service['name']:
api = service['credentials']['uri']
###################################The Auth##############################################
def check_auth(user, password):
return user == client_id and password == client_secret
def authenticate():
return Response('You must be authenticated to use this application', 401,
{"WWW-Authenticate": 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
##############################The bidness logic##########################################
def get_token():
global expire_time, token
if expire_time < time.time():
client_auth = requests.auth.HTTPBasicAuth(client_id, client_secret)
print("Getting token from " + uaa_uri)
r = requests.get(url=uaa_uri, headers={'accept': 'application/json'},
params={'grant_type': 'client_credentials'}, auth=client_auth,
verify=sslVerify)
print("Response code = " + str(r.status_code))
expire_time = time.time() + (int(r.json()['expires_in']) - 60)
token = r.json()['access_token']
print( "Token expires at " + str(expire_time))
return token
def cf(path):
access_token="bearer " + get_token()
hdr = {'Authorization': access_token}
print("Calling " + path)
r = requests.get(api + path, headers=hdr, verify=sslVerify)
if r.status_code != 200:
print("Failed to call CF API (" + path + ")", file=sys.stderr)
return r.json()
def api_cache(url):
if url not in cache:
cache[url] = cf(url)
return cache[url]
def get_apps():
apps = []
for app in cf('/v2/apps')['resources']:
a = dict()
a['name'] = app['entity']['name']
a['created_at'] = app['metadata']['created_at']
a['updated_at'] = app['metadata']['updated_at']
a['app_guid'] = app['metadata']['guid']
a['state'] = app['entity']['state']
a['buildpack'] = determine_buildpack(app)
space = api_cache(app['entity']['space_url'])
a['space'] = space['entity']['name']
org = api_cache(space['entity']['organization_url'])
a['org'] = org['entity']['name']
routes = cf(app['entity']['routes_url'])
a['routes'] = []
for route in routes['resources']:
a['routes'].append(determine_fqdn(route))
a['events'] = []
events = cf("/v2/events?q=actee:" + a['app_guid'])
for event in events['resources']:
a['events'].append(make_event(event))
apps.append([a])
return apps
def determine_fqdn(route):
host = route['entity']['host']
domain = api_cache(route['entity']['domain_url'])['entity']['name']
hostname = host + "." + domain
return hostname
def determine_buildpack(app):
buildpack = app['entity']['buildpack']
detected_buildpack = app['entity']['detected_buildpack']
if detected_buildpack is None and detected_buildpack is None:
buildpack = "CF HAS NO BUILDPACK INFO FOR THIS APP. INVESTIGATE!"
if buildpack is None:
buildpack = detected_buildpack
return buildpack
def make_event(event):
e = dict()
event_entity = event['entity']
e['event_type'] = event_entity['type']
e['actor_type'] = event_entity['actor_type']
e['actor'] = event_entity['actor_name']
e['time'] = event_entity['timestamp']
e['metadata'] = event_entity['metadata']
return e
###################################Controllers#################################
@app.get('/')
def root():
return "you probably want <a href='/apps'>/apps</a>"
@app.get('/apps')
@requires_auth
def apps():
return jsonify(apps=get_apps())
if __name__ == "__main__":
app.run(host='0.0.0.0', port=port, debug=True)
| apache-2.0 | -5,806,166,095,092,227,000 | 30.44375 | 90 | 0.575234 | false |
facelessuser/backrefs | tests/test_graphemeclusterbreak.py | 1 | 3019 | """Test `Grapheme Cluster Break`."""
import unittest
from backrefs import uniprops
import re
class TestGraphemeClusterBreak(unittest.TestCase):
"""Test `Grapheme Cluster Break` access."""
def test_table_integrity(self):
"""Test that there is parity between Unicode and ASCII tables."""
re_key = re.compile(r'^\^?[a-z0-9./]+$')
keys1 = set(uniprops.unidata.unicode_grapheme_cluster_break.keys())
keys2 = set(uniprops.unidata.ascii_grapheme_cluster_break.keys())
# Ensure all keys are lowercase (only need to check Unicode as the ASCII keys must match the Unicode later)
for k in keys1:
self.assertTrue(re_key.match(k) is not None)
# Ensure the same keys are in both the Unicode table as the ASCII table
self.assertEqual(keys1, keys2)
# Ensure each positive key has an inverse key
for key in keys1:
if not key.startswith('^'):
self.assertTrue('^' + key in keys1)
def test_graphemeclusterbreak(self):
"""Test `Grapheme Cluster Break` properties."""
for k, v in uniprops.unidata.unicode_grapheme_cluster_break.items():
result = uniprops.get_unicode_property('graphemeclusterbreak', k)
self.assertEqual(result, v)
def test_graphemeclusterbreak_ascii(self):
"""Test `Grapheme Cluster Break` ASCII properties."""
for k, v in uniprops.unidata.ascii_grapheme_cluster_break.items():
result = uniprops.get_unicode_property('graphemeclusterbreak', k, mode=uniprops.MODE_NORMAL)
self.assertEqual(result, v)
def test_graphemeclusterbreak_binary(self):
"""Test `Grapheme Cluster Break` ASCII properties."""
for k, v in uniprops.unidata.ascii_grapheme_cluster_break.items():
result = uniprops.get_unicode_property('graphemeclusterbreak', k, mode=uniprops.MODE_ASCII)
self.assertEqual(result, uniprops.fmt_string(v, True))
def test_bad_graphemeclusterbreak(self):
"""Test `Grapheme Cluster Break` property with bad value."""
with self.assertRaises(ValueError):
uniprops.get_unicode_property('graphemeclusterbreak', 'bad')
def test_alias(self):
"""Test aliases."""
alias = None
for k, v in uniprops.unidata.alias.unicode_alias['_'].items():
if v == 'graphemeclusterbreak':
alias = k
break
self.assertTrue(alias is not None)
# Ensure alias works
for k, v in uniprops.unidata.unicode_grapheme_cluster_break.items():
result = uniprops.get_unicode_property(alias, k)
self.assertEqual(result, v)
break
# Test aliases for values
for k, v in uniprops.unidata.alias.unicode_alias['graphemeclusterbreak'].items():
result1 = uniprops.get_unicode_property(alias, k)
result2 = uniprops.get_unicode_property(alias, v)
self.assertEqual(result1, result2)
| mit | 8,009,883,022,913,766,000 | 37.705128 | 115 | 0.641272 | false |
ttreeagency/PootleTypo3Org | pootle/apps/pootle_store/views.py | 1 | 42408 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Zuza Software Foundation
#
# This file is part of Pootle.
#
# 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 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 <http://www.gnu.org/licenses/>.
import os
import logging
from itertools import groupby
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.db.models import Q
from django.http import HttpResponse, Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template import loader, RequestContext
from django.utils.translation import to_locale, ugettext as _
from django.utils.translation.trans_real import parse_accept_lang_header
from django.utils import simplejson, timezone
from django.utils.encoding import iri_to_uri
from django.views.decorators.cache import never_cache
from translate.lang import data
from pootle.core.decorators import (get_translation_project,
set_request_context)
from pootle_app.models import Suggestion as SuggestionStat
from pootle_app.models.permissions import (get_matching_permissions,
check_permission,
check_profile_permission)
from pootle_misc.baseurl import redirect
from pootle_misc.checks import check_names, get_quality_check_failures
from pootle_misc.forms import make_search_form
from pootle_misc.stats import get_raw_stats
from pootle_misc.url_manip import ensure_uri, previous_view_url
from pootle_misc.util import paginate, ajax_required, jsonify
from pootle_profile.models import get_profile
from pootle_statistics.models import (Submission, SubmissionFields,
SubmissionTypes)
from .decorators import get_store_context, get_unit_context
from .models import Store, Unit
from .forms import (unit_comment_form_factory, unit_form_factory,
highlight_whitespace)
from .signals import translation_submitted
from .templatetags.store_tags import (highlight_diffs, pluralize_source,
pluralize_target)
from .util import (UNTRANSLATED, FUZZY, TRANSLATED, STATES_MAP,
absolute_real_path, find_altsrcs, get_sugg_list)
@get_store_context('view')
def export_as_xliff(request, store):
"""Export given file to xliff for offline translation."""
path = store.real_path
if not path:
# bug 2106
project = request.translation_project.project
if project.get_treestyle() == "gnu":
path = "/".join(store.pootle_path.split(os.path.sep)[2:])
else:
parts = store.pootle_path.split(os.path.sep)[1:]
path = "%s/%s/%s" % (parts[1], parts[0], "/".join(parts[2:]))
path, ext = os.path.splitext(path)
export_path = "/".join(['POOTLE_EXPORT', path + os.path.extsep + 'xlf'])
abs_export_path = absolute_real_path(export_path)
key = iri_to_uri("%s:export_as_xliff" % store.pootle_path)
last_export = cache.get(key)
if (not (last_export and last_export == store.get_mtime() and
os.path.isfile(abs_export_path))):
from pootle_app.project_tree import ensure_target_dir_exists
from translate.storage.poxliff import PoXliffFile
from pootle_misc import ptempfile as tempfile
import shutil
ensure_target_dir_exists(abs_export_path)
outputstore = store.convert(PoXliffFile)
outputstore.switchfile(store.name, createifmissing=True)
fd, tempstore = tempfile.mkstemp(prefix=store.name, suffix='.xlf')
os.close(fd)
outputstore.savefile(tempstore)
shutil.move(tempstore, abs_export_path)
cache.set(key, store.get_mtime(), settings.OBJECT_CACHE_TIMEOUT)
return redirect('/export/' + export_path)
@get_store_context('view')
def export_as_type(request, store, filetype):
"""Export given file to xliff for offline translation."""
from pootle_store.filetypes import factory_classes, is_monolingual
klass = factory_classes.get(filetype, None)
if (not klass or is_monolingual(klass) or
store.pootle_path.endswith(filetype)):
raise ValueError
path, ext = os.path.splitext(store.real_path)
export_path = os.path.join('POOTLE_EXPORT',
path + os.path.extsep + filetype)
abs_export_path = absolute_real_path(export_path)
key = iri_to_uri("%s:export_as_%s" % (store.pootle_path, filetype))
last_export = cache.get(key)
if (not (last_export and last_export == store.get_mtime() and
os.path.isfile(abs_export_path))):
from pootle_app.project_tree import ensure_target_dir_exists
from pootle_misc import ptempfile as tempfile
import shutil
ensure_target_dir_exists(abs_export_path)
outputstore = store.convert(klass)
fd, tempstore = tempfile.mkstemp(prefix=store.name,
suffix=os.path.extsep + filetype)
os.close(fd)
outputstore.savefile(tempstore)
shutil.move(tempstore, abs_export_path)
cache.set(key, store.get_mtime(), settings.OBJECT_CACHE_TIMEOUT)
return redirect('/export/' + export_path)
@get_store_context('view')
def download(request, store):
store.sync(update_translation=True)
return redirect('/export/' + store.real_path)
def get_filter_name(GET):
"""Gets current filter's human-readable name.
:param GET: A copy of ``request.GET``.
:return: Two-tuple with the filter name, and a list of extra arguments
passed to the current filter.
"""
filter = extra = None
if 'filter' in GET:
filter = GET['filter']
if filter.startswith('user-'):
extra = [GET.get('user', _('User missing'))]
elif filter == 'checks' and 'checks' in GET:
extra = map(lambda check: check_names.get(check, check),
GET['checks'].split(','))
elif 'search' in GET:
filter = 'search'
extra = [GET['search']]
if 'sfields' in GET:
extra.extend(GET['sfields'].split(','))
filter_name = {
'all': _('All'),
'translated': _('Translated'),
'untranslated': _('Untranslated'),
'fuzzy': _('Needs work'),
'incomplete': _('Incomplete'),
# Translators: This is the name of a filter
'search': _('Search'),
'checks': _('Checks'),
'user-submissions': _('Submissions'),
'user-submissions-overwritten': _('Overwritten submissions'),
}.get(filter)
return (filter_name, extra)
@get_translation_project
@set_request_context
def export_view(request, translation_project, dir_path, filename=None):
"""Displays a list of units with filters applied."""
current_path = translation_project.directory.pootle_path + dir_path
if filename:
current_path = current_path + filename
store = get_object_or_404(Store, pootle_path=current_path)
units_qs = store.units
else:
store = None
units_qs = translation_project.units.filter(
store__pootle_path__startswith=current_path,
)
filter_name, filter_extra = get_filter_name(request.GET)
units = get_step_query(request, units_qs)
unit_groups = [(path, list(units)) for path, units in
groupby(units, lambda x: x.store.path)]
ctx = {
'source_language': translation_project.project.source_language,
'language': translation_project.language,
'project': translation_project.project,
'unit_groups': unit_groups,
'filter_name': filter_name,
'filter_extra': filter_extra,
}
return render_to_response('store/list.html', ctx,
context_instance=RequestContext(request))
####################### Translate Page ##############################
def get_alt_src_langs(request, profile, translation_project):
language = translation_project.language
project = translation_project.project
source_language = project.source_language
langs = profile.alt_src_langs.exclude(
id__in=(language.id, source_language.id)
).filter(translationproject__project=project)
if not profile.alt_src_langs.count():
from pootle_language.models import Language
accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '')
for accept_lang, unused in parse_accept_lang_header(accept):
if accept_lang == '*':
continue
simplified = data.simplify_to_common(accept_lang)
normalized = to_locale(data.normalize_code(simplified))
code = to_locale(accept_lang)
if (normalized in
('en', 'en_US', source_language.code, language.code) or
code in ('en', 'en_US', source_language.code, language.code)):
continue
langs = Language.objects.filter(
code__in=(normalized, code),
translationproject__project=project,
)
if langs.count():
break
return langs
def get_non_indexed_search_step_query(form, units_queryset):
words = form.cleaned_data['search'].split()
result = units_queryset.none()
if 'source' in form.cleaned_data['sfields']:
subresult = units_queryset
for word in words:
subresult = subresult.filter(source_f__icontains=word)
result = result | subresult
if 'target' in form.cleaned_data['sfields']:
subresult = units_queryset
for word in words:
subresult = subresult.filter(target_f__icontains=word)
result = result | subresult
if 'notes' in form.cleaned_data['sfields']:
translator_subresult = units_queryset
developer_subresult = units_queryset
for word in words:
translator_subresult = translator_subresult.filter(
translator_comment__icontains=word,
)
developer_subresult = developer_subresult.filter(
developer_comment__icontains=word,
)
result = result | translator_subresult | developer_subresult
if 'locations' in form.cleaned_data['sfields']:
subresult = units_queryset
for word in words:
subresult = subresult.filter(locations__icontains=word)
result = result | subresult
return result
def get_search_step_query(translation_project, form, units_queryset):
"""Narrows down units query to units matching search string."""
if translation_project.indexer is None:
logging.debug(u"No indexer for %s, using database search",
translation_project)
return get_non_indexed_search_step_query(form, units_queryset)
logging.debug(u"Found %s indexer for %s, using indexed search",
translation_project.indexer.INDEX_DIRECTORY_NAME,
translation_project)
word_querylist = []
words = form.cleaned_data['search'].split()
fields = form.cleaned_data['sfields']
paths = units_queryset.order_by() \
.values_list('store__pootle_path', flat=True) \
.distinct()
path_querylist = [('pofilename', pootle_path)
for pootle_path in paths.iterator()]
cache_key = "search:%s" % str(hash((repr(path_querylist),
translation_project.get_mtime(),
repr(words),
repr(fields))))
dbids = cache.get(cache_key)
if dbids is None:
searchparts = []
# Split the search expression into single words. Otherwise Xapian and
# Lucene would interpret the whole string as an "OR" combination of
# words instead of the desired "AND".
for word in words:
# Generate a list for the query based on the selected fields
word_querylist = [(field, word) for field in fields]
textquery = translation_project.indexer.make_query(word_querylist,
False)
searchparts.append(textquery)
pathquery = translation_project.indexer.make_query(path_querylist,
False)
searchparts.append(pathquery)
limitedquery = translation_project.indexer.make_query(searchparts, True)
result = translation_project.indexer.search(limitedquery, ['dbid'])
dbids = [int(item['dbid'][0]) for item in result[:999]]
cache.set(cache_key, dbids, settings.OBJECT_CACHE_TIMEOUT)
return units_queryset.filter(id__in=dbids)
def get_step_query(request, units_queryset):
"""Narrows down unit query to units matching conditions in GET."""
if 'filter' in request.GET:
unit_filter = request.GET['filter']
username = request.GET.get('user', None)
profile = request.profile
if username:
try:
user = User.objects.get(username=username)
profile = user.get_profile()
except User.DoesNotExist:
pass
if unit_filter:
match_queryset = units_queryset.none()
if unit_filter == 'all':
match_queryset = units_queryset
elif unit_filter == 'translated':
match_queryset = units_queryset.filter(state=TRANSLATED)
elif unit_filter == 'untranslated':
match_queryset = units_queryset.filter(state=UNTRANSLATED)
elif unit_filter == 'fuzzy':
match_queryset = units_queryset.filter(state=FUZZY)
elif unit_filter == 'incomplete':
match_queryset = units_queryset.filter(
Q(state=UNTRANSLATED) | Q(state=FUZZY),
)
elif unit_filter == 'suggestions':
#FIXME: is None the most efficient query
match_queryset = units_queryset.exclude(suggestion=None)
elif unit_filter == 'user-suggestions':
match_queryset = units_queryset.filter(
suggestion__user=profile,
).distinct()
elif unit_filter == 'user-suggestions-accepted':
# FIXME: Oh, this is pretty lame, we need a completely
# different way to model suggestions
unit_ids = SuggestionStat.objects.filter(
suggester=profile,
state='accepted',
).values_list('unit', flat=True)
match_queryset = units_queryset.filter(
id__in=unit_ids,
).distinct()
elif unit_filter == 'user-suggestions-rejected':
# FIXME: Oh, this is as lame as above
unit_ids = SuggestionStat.objects.filter(
suggester=profile,
state='rejected',
).values_list('unit', flat=True)
match_queryset = units_queryset.filter(
id__in=unit_ids,
).distinct()
elif unit_filter == 'user-submissions':
match_queryset = units_queryset.filter(
submission__submitter=profile,
).distinct()
elif unit_filter == 'user-submissions-overwritten':
match_queryset = units_queryset.filter(
submission__submitter=profile,
).exclude(submitted_by=profile).distinct()
elif unit_filter == 'checks' and 'checks' in request.GET:
checks = request.GET['checks'].split(',')
if checks:
match_queryset = units_queryset.filter(
qualitycheck__false_positive=False,
qualitycheck__name__in=checks
).distinct()
units_queryset = match_queryset
if 'search' in request.GET and 'sfields' in request.GET:
# use the search form for validation only
search_form = make_search_form(request.GET)
if search_form.is_valid():
units_queryset = get_search_step_query(request.translation_project,
search_form, units_queryset)
return units_queryset
def translate_page(request):
cantranslate = check_permission("translate", request)
cansuggest = check_permission("suggest", request)
canreview = check_permission("review", request)
translation_project = request.translation_project
language = translation_project.language
project = translation_project.project
profile = request.profile
store = getattr(request, "store", None)
directory = getattr(request, "directory", None)
is_single_file = store and True or False
path = is_single_file and store.path or directory.path
pootle_path = (is_single_file and store.pootle_path or
directory.pootle_path)
is_terminology = (project.is_terminology or store and
store.is_terminology)
search_form = make_search_form(request=request,
terminology=is_terminology)
previous_overview_url = previous_view_url(request, ['overview'])
context = {
'cantranslate': cantranslate,
'cansuggest': cansuggest,
'canreview': canreview,
'search_form': search_form,
'store': store,
'store_id': store and store.id,
'directory': directory,
'directory_id': directory and directory.id,
'path': path,
'pootle_path': pootle_path,
'is_single_file': is_single_file,
'language': language,
'project': project,
'translation_project': translation_project,
'profile': profile,
'source_language': translation_project.project.source_language,
'previous_overview_url': previous_overview_url,
'MT_BACKENDS': settings.MT_BACKENDS,
'LOOKUP_BACKENDS': settings.LOOKUP_BACKENDS,
'AMAGAMA_URL': settings.AMAGAMA_URL,
}
return render_to_response('store/translate.html', context,
context_instance=RequestContext(request))
@get_store_context('view')
def translate(request, store):
return translate_page(request)
#
# Views used with XMLHttpRequest requests.
#
def _filter_ctx_units(units_qs, unit, how_many, gap=0):
"""Returns ``how_many``*2 units that are before and after ``index``."""
result = {'before': [], 'after': []}
if how_many and unit.index - gap > 0:
before = units_qs.filter(store=unit.store_id, index__lt=unit.index) \
.order_by('-index')[gap:how_many+gap]
result['before'] = _build_units_list(before, reverse=True)
result['before'].reverse()
#FIXME: can we avoid this query if length is known?
if how_many:
after = units_qs.filter(store=unit.store_id,
index__gt=unit.index)[gap:how_many+gap]
result['after'] = _build_units_list(after)
return result
def _build_units_list(units, reverse=False):
"""Given a list/queryset of units, builds a list with the unit data
contained in a dictionary ready to be returned as JSON.
:return: A list with unit id, source, and target texts. In case of
having plural forms, a title for the plural form is also provided.
"""
return_units = []
for unit in iter(units):
source_unit = []
target_unit = []
for i, source, title in pluralize_source(unit):
unit_dict = {'text': source}
if title:
unit_dict["title"] = title
source_unit.append(unit_dict)
for i, target, title in pluralize_target(unit):
unit_dict = {'text': target}
if title:
unit_dict["title"] = title
target_unit.append(unit_dict)
prev = None
next = None
if return_units:
if reverse:
return_units[-1]['prev'] = unit.id
next = return_units[-1]['id']
else:
return_units[-1]['next'] = unit.id
prev = return_units[-1]['id']
return_units.append({'id': unit.id,
'isfuzzy': unit.isfuzzy(),
'prev': prev,
'next': next,
'source': source_unit,
'target': target_unit})
return return_units
def _build_pager_dict(pager):
"""Given a pager object ``pager``, retrieves all the information needed
to build a pager.
:return: A dictionary containing necessary pager information to build
a pager.
"""
return {"number": pager.number,
"num_pages": pager.paginator.num_pages,
"per_page": pager.paginator.per_page
}
def _get_index_in_qs(qs, unit, store=False):
"""Given a queryset ``qs``, returns the position (index) of the unit
``unit`` within that queryset. ``store`` specifies if the queryset is
limited to a single store.
:return: Value representing the position of the unit ``unit``.
:rtype: int
"""
if store:
return qs.filter(index__lt=unit.index).count()
else:
store = unit.store
return (qs.filter(store=store, index__lt=unit.index) | \
qs.filter(store__pootle_path__lt=store.pootle_path)).count()
def get_view_units(request, units_queryset, store, limit=0):
"""Gets source and target texts excluding the editing unit.
:return: An object in JSON notation that contains the source and target
texts for units that will be displayed before and after editing
unit.
If asked by using the ``meta`` and ``pager`` parameters,
metadata and pager information will be calculated and returned
too.
"""
current_unit = None
json = {}
try:
limit = int(limit)
except ValueError:
limit = None
if not limit:
limit = request.profile.get_unit_rows()
step_queryset = get_step_query(request, units_queryset)
# Return metadata it has been explicitely requested
if request.GET.get('meta', False):
tp = request.translation_project
json["meta"] = {"source_lang": tp.project.source_language.code,
"source_dir": tp.project.source_language.get_direction(),
"target_lang": tp.language.code,
"target_dir": tp.language.get_direction(),
"project_style": tp.project.checkstyle}
# Maybe we are trying to load directly a specific unit, so we have
# to calculate its page number
uid = request.GET.get('uid', None)
if uid:
current_unit = units_queryset.get(id=uid)
preceding = _get_index_in_qs(step_queryset, current_unit, store)
page = preceding / limit + 1
else:
page = None
pager = paginate(request, step_queryset, items=limit, page=page)
json["units"] = _build_units_list(pager.object_list)
# Return paging information if requested to do so
if request.GET.get('pager', False):
json["pager"] = _build_pager_dict(pager)
if not current_unit:
try:
json["uid"] = json["units"][0]["id"]
except IndexError:
pass
else:
json["uid"] = current_unit.id
response = jsonify(json)
return HttpResponse(response, mimetype="application/json")
@ajax_required
@get_store_context('view')
def get_view_units_store(request, store, limit=0):
"""Gets source and target texts excluding the editing widget (store-level).
:return: An object in JSON notation that contains the source and target
texts for units that will be displayed before and after
unit ``uid``.
"""
return get_view_units(request, store.units, store=True, limit=limit)
def _is_filtered(request):
"""Checks if unit list is filtered."""
return ('filter' in request.GET or 'checks' in request.GET or
'user' in request.GET or
('search' in request.GET and 'sfields' in request.GET))
@ajax_required
@get_unit_context('view')
def get_more_context(request, unit):
"""Retrieves more context units.
:return: An object in JSON notation that contains the source and target
texts for units that are in the context of unit ``uid``.
"""
store = request.store
json = {}
gap = int(request.GET.get('gap', 0))
qty = int(request.GET.get('qty', 1))
json["ctx"] = _filter_ctx_units(store.units, unit, qty, gap)
rcode = 200
response = jsonify(json)
return HttpResponse(response, status=rcode, mimetype="application/json")
@never_cache
@get_unit_context('view')
def timeline(request, unit):
"""Returns a JSON-encoded string including the changes to the unit
rendered in HTML.
"""
timeline = Submission.objects.filter(unit=unit, field__in=[
SubmissionFields.TARGET, SubmissionFields.STATE,
SubmissionFields.COMMENT
])
timeline = timeline.select_related("submitter__user",
"translation_project__language")
context = {}
entries_group = []
import locale
from pootle_store.fields import to_python
for key, values in groupby(timeline, key=lambda x: x.creation_time):
entry_group = {
'datetime': key,
'datetime_str': key.strftime(locale.nl_langinfo(locale.D_T_FMT)),
'entries': [],
}
for item in values:
# Only add submitter information for the whole entry group once
entry_group.setdefault('submitter', item.submitter)
context.setdefault('language', item.translation_project.language)
entry = {
'field': item.field,
'field_name': SubmissionFields.NAMES_MAP[item.field],
}
if item.field == SubmissionFields.STATE:
entry['old_value'] = STATES_MAP[int(to_python(item.old_value))]
entry['new_value'] = STATES_MAP[int(to_python(item.new_value))]
else:
entry['new_value'] = to_python(item.new_value)
entry_group['entries'].append(entry)
entries_group.append(entry_group)
# Let's reverse the chronological order
entries_group.reverse()
# Remove first timeline item if it's solely a change to the target
if (entries_group and len(entries_group[0]['entries']) == 1 and
entries_group[0]['entries'][0]['field'] == SubmissionFields.TARGET):
del entries_group[0]
context['entries_group'] = entries_group
if request.is_ajax():
# The client will want to confirm that the response is relevant for
# the unit on screen at the time of receiving this, so we add the uid.
json = {'uid': unit.id}
t = loader.get_template('unit/xhr-timeline.html')
c = RequestContext(request, context)
json['timeline'] = t.render(c).replace('\n', '')
response = simplejson.dumps(json)
return HttpResponse(response, mimetype="application/json")
else:
return render_to_response('unit/timeline.html', context,
context_instance=RequestContext(request))
@ajax_required
@get_unit_context('translate')
def comment(request, unit):
"""Stores a new comment for the given ``unit``.
:return: If the form validates, the cleaned comment is returned.
An error message is returned otherwise.
"""
# Update current unit instance's attributes
unit.commented_by = request.profile
unit.commented_on = timezone.now()
language = request.translation_project.language
form = unit_comment_form_factory(language)(request.POST, instance=unit,
request=request)
if form.is_valid():
form.save()
context = {
'unit': unit,
'language': language,
}
t = loader.get_template('unit/comment.html')
c = RequestContext(request, context)
json = {'comment': t.render(c)}
rcode = 200
else:
json = {'msg': _("Comment submission failed.")}
rcode = 400
response = simplejson.dumps(json)
return HttpResponse(response, status=rcode, mimetype="application/json")
@never_cache
@ajax_required
@get_unit_context('view')
def get_edit_unit(request, unit):
"""Given a store path ``pootle_path`` and unit id ``uid``, gathers all the
necessary information to build the editing widget.
:return: A templatised editing widget is returned within the ``editor``
variable and paging information is also returned if the page
number has changed.
"""
json = {}
translation_project = request.translation_project
language = translation_project.language
if unit.hasplural():
snplurals = len(unit.source.strings)
else:
snplurals = None
form_class = unit_form_factory(language, snplurals, request)
form = form_class(instance=unit)
comment_form_class = unit_comment_form_factory(language)
comment_form = comment_form_class({}, instance=unit)
store = unit.store
directory = store.parent
profile = request.profile
alt_src_langs = get_alt_src_langs(request, profile, translation_project)
project = translation_project.project
report_target = ensure_uri(project.report_target)
suggestions = get_sugg_list(unit)
template_vars = {
'unit': unit,
'form': form,
'comment_form': comment_form,
'store': store,
'directory': directory,
'profile': profile,
'user': request.user,
'language': language,
'source_language': translation_project.project.source_language,
'cantranslate': check_profile_permission(profile, "translate",
directory),
'cansuggest': check_profile_permission(profile, "suggest", directory),
'canreview': check_profile_permission(profile, "review", directory),
'altsrcs': find_altsrcs(unit, alt_src_langs, store=store,
project=project),
'report_target': report_target,
'suggestions': suggestions,
}
if translation_project.project.is_terminology or store.is_terminology:
t = loader.get_template('unit/term_edit.html')
else:
t = loader.get_template('unit/edit.html')
c = RequestContext(request, template_vars)
json['editor'] = t.render(c)
rcode = 200
# Return context rows if filtering is applied but
# don't return any if the user has asked not to have it
current_filter = request.GET.get('filter', 'all')
show_ctx = request.COOKIES.get('ctxShow', 'true')
if ((_is_filtered(request) or current_filter not in ('all',)) and
show_ctx == 'true'):
# TODO: review if this first 'if' branch makes sense
if translation_project.project.is_terminology or store.is_terminology:
json['ctx'] = _filter_ctx_units(store.units, unit, 0)
else:
ctx_qty = int(request.COOKIES.get('ctxQty', 1))
json['ctx'] = _filter_ctx_units(store.units, unit, ctx_qty)
response = jsonify(json)
return HttpResponse(response, status=rcode, mimetype="application/json")
def get_failing_checks(request, pathobj):
"""Gets a list of failing checks for the current object.
:return: JSON string with a list of failing check categories which
include the actual checks that are failing.
"""
stats = get_raw_stats(pathobj)
failures = get_quality_check_failures(pathobj, stats, include_url=False)
response = jsonify(failures)
return HttpResponse(response, mimetype="application/json")
@ajax_required
@get_store_context('view')
def get_failing_checks_store(request, store):
return get_failing_checks(request, store)
@ajax_required
@get_unit_context('')
def submit(request, unit):
"""Processes translation submissions and stores them in the database.
:return: An object in JSON notation that contains the previous and last
units for the unit next to unit ``uid``.
"""
json = {}
cantranslate = check_permission("translate", request)
if not cantranslate:
raise PermissionDenied(_("You do not have rights to access "
"translation mode."))
translation_project = request.translation_project
language = translation_project.language
if unit.hasplural():
snplurals = len(unit.source.strings)
else:
snplurals = None
# Store current time so that it is the same for all submissions
current_time = timezone.now()
# Update current unit instance's attributes
unit.submitted_by = request.profile
unit.submitted_on = current_time
form_class = unit_form_factory(language, snplurals, request)
form = form_class(request.POST, instance=unit)
if form.is_valid():
if form.updated_fields:
for field, old_value, new_value in form.updated_fields:
sub = Submission(
creation_time=current_time,
translation_project=translation_project,
submitter=request.profile,
unit=unit,
field=field,
type=SubmissionTypes.NORMAL,
old_value=old_value,
new_value=new_value,
)
sub.save()
form.save()
translation_submitted.send(
sender=translation_project,
unit=form.instance,
profile=request.profile,
)
rcode = 200
else:
# Form failed
#FIXME: we should display validation errors here
rcode = 400
json["msg"] = _("Failed to process submission.")
response = jsonify(json)
return HttpResponse(response, status=rcode, mimetype="application/json")
@ajax_required
@get_unit_context('')
def suggest(request, unit):
"""Processes translation suggestions and stores them in the database.
:return: An object in JSON notation that contains the previous and last
units for the unit next to unit ``uid``.
"""
json = {}
cansuggest = check_permission("suggest", request)
if not cansuggest:
raise PermissionDenied(_("You do not have rights to access "
"translation mode."))
translation_project = request.translation_project
language = translation_project.language
if unit.hasplural():
snplurals = len(unit.source.strings)
else:
snplurals = None
form_class = unit_form_factory(language, snplurals, request)
form = form_class(request.POST, instance=unit)
if form.is_valid():
if form.instance._target_updated:
# TODO: Review if this hackish method is still necessary
#HACKISH: django 1.2 stupidly modifies instance on
# model form validation, reload unit from db
unit = Unit.objects.get(id=unit.id)
sugg = unit.add_suggestion(form.cleaned_data['target_f'],
request.profile)
if sugg:
SuggestionStat.objects.get_or_create(
translation_project=translation_project,
suggester=request.profile, state='pending', unit=unit.id
)
rcode = 200
else:
# Form failed
#FIXME: we should display validation errors here
rcode = 400
json["msg"] = _("Failed to process suggestion.")
response = jsonify(json)
return HttpResponse(response, status=rcode, mimetype="application/json")
@ajax_required
@get_unit_context('')
def reject_suggestion(request, unit, suggid):
json = {}
translation_project = request.translation_project
json["udbid"] = unit.id
json["sugid"] = suggid
if request.POST.get('reject'):
try:
sugg = unit.suggestion_set.get(id=suggid)
except ObjectDoesNotExist:
raise Http404
if (not check_permission('review', request) and
(not request.user.is_authenticated() or sugg and
sugg.user != request.profile)):
raise PermissionDenied(_("You do not have rights to access "
"review mode."))
success = unit.reject_suggestion(suggid)
if sugg is not None and success:
# FIXME: we need a totally different model for tracking stats, this
# is just lame
suggstat, created = SuggestionStat.objects.get_or_create(
translation_project=translation_project,
suggester=sugg.user,
state='pending',
unit=unit.id,
)
suggstat.reviewer = request.profile
suggstat.state = 'rejected'
suggstat.save()
response = jsonify(json)
return HttpResponse(response, mimetype="application/json")
@ajax_required
@get_unit_context('review')
def accept_suggestion(request, unit, suggid):
json = {
'udbid': unit.id,
'sugid': suggid,
}
translation_project = request.translation_project
if request.POST.get('accept'):
try:
suggestion = unit.suggestion_set.get(id=suggid)
except ObjectDoesNotExist:
raise Http404
old_target = unit.target
success = unit.accept_suggestion(suggid)
json['newtargets'] = [highlight_whitespace(target)
for target in unit.target.strings]
json['newdiffs'] = {}
for sugg in unit.get_suggestions():
json['newdiffs'][sugg.id] = \
[highlight_diffs(unit.target.strings[i], target)
for i, target in enumerate(sugg.target.strings)]
if suggestion is not None and success:
if suggestion.user:
translation_submitted.send(sender=translation_project,
unit=unit, profile=suggestion.user)
# FIXME: we need a totally different model for tracking stats, this
# is just lame
suggstat, created = SuggestionStat.objects.get_or_create(
translation_project=translation_project,
suggester=suggestion.user,
state='pending',
unit=unit.id,
)
suggstat.reviewer = request.profile
suggstat.state = 'accepted'
suggstat.save()
# For now assume the target changed
# TODO: check all fields for changes
creation_time = timezone.now()
sub = Submission(
creation_time=creation_time,
translation_project=translation_project,
submitter=suggestion.user,
from_suggestion=suggstat,
unit=unit,
field=SubmissionFields.TARGET,
type=SubmissionTypes.SUGG_ACCEPT,
old_value=old_target,
new_value=unit.target,
)
sub.save()
response = jsonify(json)
return HttpResponse(response, mimetype="application/json")
@ajax_required
def clear_vote(request, voteid):
json = {}
json["voteid"] = voteid
if request.POST.get('clear'):
try:
from voting.models import Vote
vote = Vote.objects.get(pk=voteid)
if vote.user != request.user:
# No i18n, will not go to UI
raise PermissionDenied("Users can only remove their own votes")
vote.delete()
except ObjectDoesNotExist:
raise Http404
response = jsonify(json)
return HttpResponse(response, mimetype="application/json")
@ajax_required
@get_unit_context('')
def vote_up(request, unit, suggid):
json = {}
json["suggid"] = suggid
if request.POST.get('up'):
try:
suggestion = unit.suggestion_set.get(id=suggid)
from voting.models import Vote
# Why can't it just return the vote object?
Vote.objects.record_vote(suggestion, request.user, +1)
json["voteid"] = Vote.objects.get_for_user(suggestion,
request.user).id
except ObjectDoesNotExist:
raise Http404(_("The suggestion or vote is not valid any more."))
response = jsonify(json)
return HttpResponse(response, mimetype="application/json")
@ajax_required
@get_unit_context('review')
def reject_qualitycheck(request, unit, checkid):
json = {}
json["udbid"] = unit.id
json["checkid"] = checkid
if request.POST.get('reject'):
try:
check = unit.qualitycheck_set.get(id=checkid)
check.false_positive = True
check.save()
# update timestamp
unit.save()
except ObjectDoesNotExist:
raise Http404
response = jsonify(json)
return HttpResponse(response, mimetype="application/json")
| gpl-2.0 | -624,292,103,243,381,500 | 35.844483 | 81 | 0.601113 | false |
rohe/otest | src/otest/rp/tool.py | 1 | 10814 | import logging
import os
from future.backports.urllib.parse import parse_qs
from oic.oauth2 import AuthorizationErrorResponse
from oic.oauth2 import AuthorizationRequest
from oic.oauth2 import PyoidcError
from oic.utils.http_util import Redirect
from oic.utils.http_util import Response
from otest import ConditionError
from otest import ConfigurationError
from otest import Done
from otest import exception_trace
from otest import tool
from otest.check import OK
from otest.check import State
from otest.conversation import Conversation
from otest.events import EV_CONDITION
from otest.events import EV_OPERATION
from otest.events import EV_PROTOCOL_REQUEST
from otest.events import EV_REQUEST
from otest.events import EV_RESPONSE
from otest.result import Result
from otest.result import safe_path
from otest.verify import Verify
logger = logging.getLogger(__name__)
class WebTester(tool.Tester):
def __init__(self, *args, **kwargs):
tool.Tester.__init__(self, *args, **kwargs)
try:
self.base_url = self.conv.entity.base_url
except AttributeError:
self.base_url = self.kwargs['base']
self.provider_cls = self.kwargs['provider_cls']
self.selected = {}
def fname(self, test_id):
_pname = '_'.join(self.profile)
try:
return safe_path(self.conv.entity_id, _pname, test_id)
except (AttributeError, KeyError):
return safe_path('dummy', _pname, test_id)
def match_profile(self, test_id, **kwargs):
_spec = self.flows[test_id]
# There must be an intersection between the two profile lists.
if self.sh.profile in _spec["usage"]["return_type"]:
return True
else:
return False
def setup(self, test_id, **kw_args):
if not self.match_profile(test_id):
return False
self.sh.session_setup(path=test_id)
_flow = self.flows[test_id]
try:
_cap = kw_args['op_profiles'][self.sh['test_conf']['profile']]
except KeyError:
_cap = None
_ent = self.provider_cls(capabilities=_cap, **kw_args['as_args'])
_ent.baseurl = os.path.join(_ent.baseurl, kw_args['sid'])
_ent.jwks_uri = os.path.join(_ent.baseurl,
kw_args['as_args']['jwks_name'])
_ent.name = _ent.baseurl
self.conv = Conversation(_flow, _ent,
msg_factory=kw_args["msg_factory"])
self.conv.sequence = self.sh["sequence"]
_ent.conv = self.conv
_ent.events = self.conv.events
self.sh["conv"] = self.conv
return True
def run(self, test_id, **kw_args):
if not self.setup(test_id, **kw_args):
raise ConfigurationError()
# noinspection PyTypeChecker
try:
return self.run_item(test_id, index=0, **kw_args)
except Exception as err:
exception_trace("", err, logger)
return self.inut.err_response("run", err)
def post_op(self, oper, res, test_id):
"""
should be done as late as possible, so all processing has been
:param oper:
:return:
"""
try:
oper.post_tests()
except ConditionError:
pass
self.conv.events.store(EV_CONDITION, State('Done', OK))
self.store_result(res)
def get_cls_and_func(self, index):
item = self.conv.sequence[index]
if isinstance(item, tuple):
cls, funcs = item
else:
cls = item
funcs = {}
return cls, funcs
def run_item(self, test_id, index, profiles=None, **kw_args):
logger.info("<=<=<=<=< %s >=>=>=>=>" % test_id)
_ss = self.sh
try:
_ss.test_flows.complete[test_id] = False
except KeyError:
pass
self.conv.test_id = test_id
res = Result(self.sh, self.kwargs['profile_handler'])
if index >= len(self.conv.sequence):
return None
try:
internal = kw_args['internal']
except KeyError:
internal = True
cls, funcs = self.get_cls_and_func(index)
try:
_name = cls.__name__
except AttributeError:
_name = 'none'
logger.info("<--<-- {} --- {} -->-->".format(index, _name))
self.conv.events.store(EV_OPERATION, _name, sender='run_flow')
try:
_oper = cls(conv=self.conv, inut=self.inut, sh=self.sh,
profile=self.profile, test_id=test_id,
funcs=funcs, check_factory=self.chk_factory,
cache=self.cache, internal=internal)
# self.conv.operation = _oper
if profiles:
profile_map = profiles.PROFILEMAP
else:
profile_map = None
_oper.setup(profile_map)
resp = _oper()
except ConditionError:
self.store_result(res)
return False
except Exception as err:
exception_trace('run_flow', err)
self.sh["index"] = index
return self.inut.err_response("run_sequence", err)
else:
if isinstance(resp, self.response_cls):
if self.conv.sequence[index+1] == Done:
self.post_op(_oper, res, test_id)
return resp
if resp:
if self.conv.sequence[index+1] == Done:
self.post_op(_oper, res, test_id)
return resp
# should be done as late as possible, so all processing has been
# done
try:
_oper.post_tests()
except ConditionError:
self.store_result(res)
return False
_ss['index'] = self.conv.index = index + 1
return True
def display_test_list(self, **kwargs):
try:
if self.sh.session_init():
return self.inut.flow_list()
else:
try:
resp = Redirect("%s/opresult#%s" % (
self.base_url, self.sh["testid"][0]))
except KeyError:
return self.inut.flow_list(**kwargs)
else:
return resp(self.inut.environ, self.inut.start_response)
except Exception as err:
exception_trace("display_test_list", err)
return self.inut.err_response("session_setup", err)
def handle_request(self, req, path='', **kwargs):
logging.debug('Raw request: {}'.format(req))
if req:
self.conv.events.store(EV_REQUEST, req)
func = getattr(self.conv.entity.server,
'parse_{}_request'.format(path))
msg = None
try:
if req[0] in ['{', '[']:
msg = func(req, sformat='json')
else:
if path in ['authorization', 'check_session']:
msg = func(query=req) # default urlencoded
elif path in ['token', 'refresh_token']:
msg = func(body=req)
else:
msg = func(req)
except PyoidcError as err:
logging.error('{}'.format(err))
if msg:
self.conv.events.store(EV_PROTOCOL_REQUEST, msg)
def do_config(self, sid='', start_page='', params='', **args):
resp = Response(mako_template="config.mako",
template_lookup=self.kwargs['lookup'], headers=[])
if sid:
_url = os.path.join(self.base_url, sid)
else:
_url = self.base_url
try:
test_id = args['test_id']
except KeyError:
test_id = ''
kwargs = {
'start_page': start_page,
'params': params,
'issuer': _url,
'profiles': list(self.kwargs['op_profiles'].keys()),
'selected': self.selected,
'sid':sid,
'base': self.base_url,
'test_id': test_id
}
return resp(self.inut.environ, self.inut.start_response, **kwargs)
def do_next(self, req, filename, path='', **kwargs):
sh = self.sh
self.conv = sh['conv']
cls, funcs = self.get_cls_and_func(self.conv.index+1)
if cls.endpoint != path:
if path == 'authorization': # Jumping the gun here
areq = AuthorizationRequest().from_urlencoded(req)
# send an error back to the redirect_uri
msg = AuthorizationErrorResponse(error='access_denied',
state=areq['state'])
_entity = self.conv.entity
redirect_uri = _entity.get_redirect_uri(areq)
_req_loc = msg.request(redirect_uri)
resp = _entity.server.http_request(_req_loc, 'GET')
ret = Response('Client need to reregister')
return ret
self.handle_request(req, path=path)
self.store_result()
self.conv.index += 1
try:
resp = self.run_item(self.conv.test_id, index=self.conv.index,
**kwargs)
except Exception as err:
raise
if isinstance(resp, Response):
self.store_result()
return resp
_done = False
for _cond in self.conv.events.get_data(EV_CONDITION):
if _cond.test_id == 'Done' and _cond.status == OK:
_done = True
break
if not _done:
self.conv.events.store(EV_CONDITION, State('Done', OK),
sender='do_next')
if 'assert' in self.conv.flow:
_ver = Verify(self.chk_factory, self.conv)
_ver.test_sequence(self.conv.flow["assert"])
self.store_result()
return self.inut.flow_list()
def get_response(self, resp):
try:
loc = resp.headers['location']
except (AttributeError, KeyError): # May be a dictionary
try:
return resp.response
except AttributeError:
try:
return resp.text
except AttributeError:
if isinstance(resp, dict):
return resp
else:
try:
_resp = dict(
[(k, v[0]) for k, v in parse_qs(loc.split('?')[1]).items()])
except IndexError:
return loc
else:
self.conv.events.store(EV_RESPONSE, _resp)
return _resp
| apache-2.0 | 4,131,522,242,920,512,000 | 32.583851 | 80 | 0.522841 | false |
houssine78/vertical-cooperative | easy_my_coop_dividend/__openerp__.py | 1 | 1645 | # -*- coding: utf-8 -*-
# Copyright (C) 2013-2018 Open Architects Consulting SPRL.
# Copyright (C) 2013-2018 Coop IT Easy SCRLfs.
#
# 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.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
##############################################################################
{
'name': 'Easy My Coop Dividend Engine',
'summary': """
Manage the dividend calculation for a fiscal year.
""",
'description': """
This module allows to calculate the dividend to give to a cooperator base
on the amount of his shares, the percentage allocated and for how long the
shares have been owned on prorata temporis calculation.
""",
'author': 'Houssine BAKKALI, <[email protected]>',
'license': 'AGPL-3',
'version': '9.0.1.0',
'website': "www.coopiteasy.be",
'category': 'Cooperative Management',
'depends': [
'easy_my_coop',
],
'data': [
'security/ir.model.access.csv',
'views/dividend_views.xml',
]
}
| agpl-3.0 | 6,795,841,509,229,372,000 | 32.571429 | 78 | 0.636474 | false |
stormi/tsunami | src/primaires/salle/commandes/etendue/creer.py | 1 | 2728 | # -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Fichier contenant le paramètre 'créer' de la commande 'étendue'."""
from primaires.interpreteur.masque.parametre import Parametre
class PrmCreer(Parametre):
"""Commande 'etendue créer'.
"""
def __init__(self):
"""Constructeur du paramètre"""
Parametre.__init__(self, "créer", "create")
self.schema = "<cle>"
self.aide_courte = "crée une étendue d'eau"
self.aide_longue = \
"Permet de créer une nouvelle étendue d'eau. Cette commande " \
"prend en paramètre la clé de l'étendue à créer (ne doit pas " \
"déjà exister)."
def interpreter(self, personnage, dic_masques):
"""Interprétation du paramètre"""
cle = dic_masques["cle"].cle
# On vérifie que cette étendue n'existe pas
if cle in type(self).importeur.salle.etendues.keys():
personnage << "|err|Cette clé {} existe déjà.|ff|".format(
repr(cle))
return
type(self).importeur.salle.creer_etendue(cle)
personnage << "L'étendue {} a bien été créée.".format(repr(cle))
| bsd-3-clause | 886,097,803,153,249,500 | 43.245902 | 79 | 0.698036 | false |
popravich/cantal_tools | cantal_tools/_fork.py | 1 | 3229 | import time
import cantal
from cantal import fork
from contextlib import contextmanager
class Branch(fork.Branch):
__slots__ = fork.Branch.__slots__ + ('_errors',)
def __init__(self, suffix, state, parent, **kwargs):
super(Branch, self).__init__(suffix, state, parent, **kwargs)
self._errors = cantal.Counter(state=state + '.' + suffix,
metric='errors', **kwargs)
def exit(self):
self._parent.exit_branch(self)
def enter(self, end_current=True):
self._parent.enter_branch(self, end_current=end_current)
@contextmanager
def context(self):
cur_branch = self._parent._branch
self._parent.enter_branch(self, end_current=False)
try:
yield
except Exception:
self._errors.incr(1)
raise
finally:
self.exit()
if cur_branch:
cur_branch.enter()
def _commit(self, start, fin, increment=True):
if increment:
self._counter.incr(1)
self._duration.incr(fin - start)
class Fork(fork.Fork):
"""Custom Fork class without branches argument, instead
ensure_branch must be used.
"""
def __init__(self, state, **kwargs):
self._state = cantal.State(state=state, **kwargs)
self._kwargs = kwargs
self._kwargs['state'] = state
self._branch = None
# We do our best not to crash any code which does accouning the
# wrong way. So to report the problems we use a separate counter
self._err = cantal.Counter(metric="err", **self._kwargs)
def enter_branch(self, branch, end_current=True):
ts = int(time.time()*1000)
if self._branch is not None:
self._branch._commit(self._timestamp, ts, increment=end_current)
self._state.enter(branch.name, _timestamp=ts)
self._timestamp = ts
self._branch = branch
def exit_branch(self, branch):
ts = int(time.time() * 1000)
if self._branch is None:
self._err.incr()
branch._commit(self._timestamp, ts)
self._state.enter('_')
self._timestamp = ts
self._branch = None
def ensure_branches(self, *branches):
ret = []
for name in branches:
branch = getattr(self, name, None)
assert branch is None or isinstance(branch, Branch), (name, branch)
if branch is None:
branch = Branch(name, parent=self, **self._kwargs)
setattr(self, name, branch)
ret.append(branch)
if len(branches) == 1:
return ret[0]
return ret
@contextmanager
def context(self):
if self._branch is not None:
self._err.incr()
self._branch = None
self._state.enter('_')
try:
yield
except Exception:
if self._branch is not None:
self._branch._errors.incr(1)
raise
finally:
ts = int(time.time()*1000)
if self._branch is not None:
self._branch._commit(self._timestamp, ts)
self._state.exit()
self._branch = None
| mit | 1,769,075,623,500,826,000 | 30.349515 | 79 | 0.554351 | false |
jackrzhang/zulip | zerver/management/commands/query_ldap.py | 4 | 1271 |
from argparse import ArgumentParser
from typing import Any
from django.conf import settings
from django.contrib.auth import get_backends
from django.core.management.base import BaseCommand
from django_auth_ldap.backend import LDAPBackend, _LDAPUser
# Quick tool to test whether you're correctly authenticating to LDAP
def query_ldap(**options: str) -> None:
email = options['email']
for backend in get_backends():
if isinstance(backend, LDAPBackend):
ldap_attrs = _LDAPUser(backend, backend.django_to_ldap_username(email)).attrs
if ldap_attrs is None:
print("No such user found")
else:
for django_field, ldap_field in settings.AUTH_LDAP_USER_ATTR_MAP.items():
print("%s: %s" % (django_field, ldap_attrs[ldap_field]))
if settings.LDAP_EMAIL_ATTR is not None:
print("%s: %s" % ('email', ldap_attrs[settings.LDAP_EMAIL_ATTR]))
class Command(BaseCommand):
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument('email', metavar='<email>', type=str,
help="email of user to query")
def handle(self, *args: Any, **options: str) -> None:
query_ldap(**options)
| apache-2.0 | -2,874,588,886,342,787,600 | 41.366667 | 89 | 0.638867 | false |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/ipv6_express_route_circuit_peering_config.py | 1 | 2352 | # 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.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class Ipv6ExpressRouteCircuitPeeringConfig(Model):
"""Contains IPv6 peering config.
:param primary_peer_address_prefix: The primary address prefix.
:type primary_peer_address_prefix: str
:param secondary_peer_address_prefix: The secondary address prefix.
:type secondary_peer_address_prefix: str
:param microsoft_peering_config: The Microsoft peering configuration.
:type microsoft_peering_config:
~azure.mgmt.network.v2017_11_01.models.ExpressRouteCircuitPeeringConfig
:param route_filter: The reference of the RouteFilter resource.
:type route_filter: ~azure.mgmt.network.v2017_11_01.models.RouteFilter
:param state: The state of peering. Possible values are: 'Disabled' and
'Enabled'. Possible values include: 'Disabled', 'Enabled'
:type state: str or
~azure.mgmt.network.v2017_11_01.models.ExpressRouteCircuitPeeringState
"""
_attribute_map = {
'primary_peer_address_prefix': {'key': 'primaryPeerAddressPrefix', 'type': 'str'},
'secondary_peer_address_prefix': {'key': 'secondaryPeerAddressPrefix', 'type': 'str'},
'microsoft_peering_config': {'key': 'microsoftPeeringConfig', 'type': 'ExpressRouteCircuitPeeringConfig'},
'route_filter': {'key': 'routeFilter', 'type': 'RouteFilter'},
'state': {'key': 'state', 'type': 'str'},
}
def __init__(self, **kwargs):
super(Ipv6ExpressRouteCircuitPeeringConfig, self).__init__(**kwargs)
self.primary_peer_address_prefix = kwargs.get('primary_peer_address_prefix', None)
self.secondary_peer_address_prefix = kwargs.get('secondary_peer_address_prefix', None)
self.microsoft_peering_config = kwargs.get('microsoft_peering_config', None)
self.route_filter = kwargs.get('route_filter', None)
self.state = kwargs.get('state', None)
| mit | -3,065,050,826,944,957,000 | 49.042553 | 114 | 0.664116 | false |
gpotter2/scapy | scapy/autorun.py | 1 | 6498 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <[email protected]>
# This program is published under a GPLv2 license
"""
Run commands when the Scapy interpreter starts.
"""
from __future__ import print_function
import code
import sys
import importlib
import logging
from scapy.config import conf
from scapy.themes import NoTheme, DefaultTheme, HTMLTheme2, LatexTheme2
from scapy.error import log_scapy, Scapy_Exception
from scapy.utils import tex_escape
import scapy.modules.six as six
#########################
# Autorun stuff #
#########################
class StopAutorun(Scapy_Exception):
code_run = ""
class ScapyAutorunInterpreter(code.InteractiveInterpreter):
def __init__(self, *args, **kargs):
code.InteractiveInterpreter.__init__(self, *args, **kargs)
self.error = 0
def showsyntaxerror(self, *args, **kargs):
self.error = 1
return code.InteractiveInterpreter.showsyntaxerror(self, *args, **kargs) # noqa: E501
def showtraceback(self, *args, **kargs):
self.error = 1
exc_type, exc_value, exc_tb = sys.exc_info()
if isinstance(exc_value, StopAutorun):
raise exc_value
return code.InteractiveInterpreter.showtraceback(self, *args, **kargs)
def autorun_commands(cmds, my_globals=None, ignore_globals=None, verb=None):
sv = conf.verb
try:
try:
if my_globals is None:
my_globals = importlib.import_module(".all", "scapy").__dict__
if ignore_globals:
for ig in ignore_globals:
my_globals.pop(ig, None)
if verb is not None:
conf.verb = verb
interp = ScapyAutorunInterpreter(my_globals)
cmd = ""
cmds = cmds.splitlines()
cmds.append("") # ensure we finish multi-line commands
cmds.reverse()
six.moves.builtins.__dict__["_"] = None
while True:
if cmd:
sys.stderr.write(sys.__dict__.get("ps2", "... "))
else:
sys.stderr.write(str(sys.__dict__.get("ps1", sys.ps1)))
line = cmds.pop()
print(line)
cmd += "\n" + line
if interp.runsource(cmd):
continue
if interp.error:
return 0
cmd = ""
if len(cmds) <= 1:
break
except SystemExit:
pass
finally:
conf.verb = sv
return _ # noqa: F821
class StringWriter(object):
"""Util to mock sys.stdout and sys.stderr, and
store their output in a 's' var."""
def __init__(self, debug=None):
self.s = ""
self.debug = debug
def write(self, x):
# Object can be in the middle of being destroyed.
if getattr(self, "debug", None):
self.debug.write(x)
if getattr(self, "s", None) is not None:
self.s += x
def flush(self):
if getattr(self, "debug", None):
self.debug.flush()
def autorun_get_interactive_session(cmds, **kargs):
"""Create an interactive session and execute the
commands passed as "cmds" and return all output
:param cmds: a list of commands to run
:returns: (output, returned) contains both sys.stdout and sys.stderr logs
"""
sstdout, sstderr = sys.stdout, sys.stderr
sw = StringWriter()
h_old = log_scapy.handlers[0]
log_scapy.removeHandler(h_old)
log_scapy.addHandler(logging.StreamHandler(stream=sw))
try:
try:
sys.stdout = sys.stderr = sw
res = autorun_commands(cmds, **kargs)
except StopAutorun as e:
e.code_run = sw.s
raise
finally:
sys.stdout, sys.stderr = sstdout, sstderr
log_scapy.removeHandler(log_scapy.handlers[0])
log_scapy.addHandler(h_old)
return sw.s, res
def autorun_get_interactive_live_session(cmds, **kargs):
"""Create an interactive session and execute the
commands passed as "cmds" and return all output
:param cmds: a list of commands to run
:returns: (output, returned) contains both sys.stdout and sys.stderr logs
"""
sstdout, sstderr = sys.stdout, sys.stderr
sw = StringWriter(debug=sstdout)
try:
try:
sys.stdout = sys.stderr = sw
res = autorun_commands(cmds, **kargs)
except StopAutorun as e:
e.code_run = sw.s
raise
finally:
sys.stdout, sys.stderr = sstdout, sstderr
return sw.s, res
def autorun_get_text_interactive_session(cmds, **kargs):
ct = conf.color_theme
try:
conf.color_theme = NoTheme()
s, res = autorun_get_interactive_session(cmds, **kargs)
finally:
conf.color_theme = ct
return s, res
def autorun_get_live_interactive_session(cmds, **kargs):
ct = conf.color_theme
try:
conf.color_theme = DefaultTheme()
s, res = autorun_get_interactive_live_session(cmds, **kargs)
finally:
conf.color_theme = ct
return s, res
def autorun_get_ansi_interactive_session(cmds, **kargs):
ct = conf.color_theme
try:
conf.color_theme = DefaultTheme()
s, res = autorun_get_interactive_session(cmds, **kargs)
finally:
conf.color_theme = ct
return s, res
def autorun_get_html_interactive_session(cmds, **kargs):
ct = conf.color_theme
to_html = lambda s: s.replace("<", "<").replace(">", ">").replace("#[#", "<").replace("#]#", ">") # noqa: E501
try:
try:
conf.color_theme = HTMLTheme2()
s, res = autorun_get_interactive_session(cmds, **kargs)
except StopAutorun as e:
e.code_run = to_html(e.code_run)
raise
finally:
conf.color_theme = ct
return to_html(s), res
def autorun_get_latex_interactive_session(cmds, **kargs):
ct = conf.color_theme
to_latex = lambda s: tex_escape(s).replace("@[@", "{").replace("@]@", "}").replace("@`@", "\\") # noqa: E501
try:
try:
conf.color_theme = LatexTheme2()
s, res = autorun_get_interactive_session(cmds, **kargs)
except StopAutorun as e:
e.code_run = to_latex(e.code_run)
raise
finally:
conf.color_theme = ct
return to_latex(s), res
| gpl-2.0 | 7,569,240,486,834,548,000 | 29.650943 | 121 | 0.576793 | false |
Warboss-rus/wargameengine | WargameEngine/freetype2/src/tools/glnames.py | 2 | 112194 | #!/usr/bin/env python
#
#
# FreeType 2 glyph name builder
#
# Copyright 1996-2017 by
# David Turner, Robert Wilhelm, and Werner Lemberg.
#
# This file is part of the FreeType project, and may only be used, modified,
# and distributed under the terms of the FreeType project license,
# LICENSE.TXT. By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
"""\
usage: %s <output-file>
This python script generates the glyph names tables defined in the
`psnames' module.
Its single argument is the name of the header file to be created.
"""
import sys, string, struct, re, os.path
# This table lists the glyphs according to the Macintosh specification.
# It is used by the TrueType Postscript names table.
#
# See
#
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
#
# for the official list.
#
mac_standard_names = \
[
# 0
".notdef", ".null", "nonmarkingreturn", "space", "exclam",
"quotedbl", "numbersign", "dollar", "percent", "ampersand",
# 10
"quotesingle", "parenleft", "parenright", "asterisk", "plus",
"comma", "hyphen", "period", "slash", "zero",
# 20
"one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "colon",
# 30
"semicolon", "less", "equal", "greater", "question",
"at", "A", "B", "C", "D",
# 40
"E", "F", "G", "H", "I",
"J", "K", "L", "M", "N",
# 50
"O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X",
# 60
"Y", "Z", "bracketleft", "backslash", "bracketright",
"asciicircum", "underscore", "grave", "a", "b",
# 70
"c", "d", "e", "f", "g",
"h", "i", "j", "k", "l",
# 80
"m", "n", "o", "p", "q",
"r", "s", "t", "u", "v",
# 90
"w", "x", "y", "z", "braceleft",
"bar", "braceright", "asciitilde", "Adieresis", "Aring",
# 100
"Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis",
"aacute", "agrave", "acircumflex", "adieresis", "atilde",
# 110
"aring", "ccedilla", "eacute", "egrave", "ecircumflex",
"edieresis", "iacute", "igrave", "icircumflex", "idieresis",
# 120
"ntilde", "oacute", "ograve", "ocircumflex", "odieresis",
"otilde", "uacute", "ugrave", "ucircumflex", "udieresis",
# 130
"dagger", "degree", "cent", "sterling", "section",
"bullet", "paragraph", "germandbls", "registered", "copyright",
# 140
"trademark", "acute", "dieresis", "notequal", "AE",
"Oslash", "infinity", "plusminus", "lessequal", "greaterequal",
# 150
"yen", "mu", "partialdiff", "summation", "product",
"pi", "integral", "ordfeminine", "ordmasculine", "Omega",
# 160
"ae", "oslash", "questiondown", "exclamdown", "logicalnot",
"radical", "florin", "approxequal", "Delta", "guillemotleft",
# 170
"guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde",
"Otilde", "OE", "oe", "endash", "emdash",
# 180
"quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide",
"lozenge", "ydieresis", "Ydieresis", "fraction", "currency",
# 190
"guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl",
"periodcentered", "quotesinglbase", "quotedblbase", "perthousand",
"Acircumflex",
# 200
"Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute",
"Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex",
# 210
"apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave",
"dotlessi", "circumflex", "tilde", "macron", "breve",
# 220
"dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek",
"caron", "Lslash", "lslash", "Scaron", "scaron",
# 230
"Zcaron", "zcaron", "brokenbar", "Eth", "eth",
"Yacute", "yacute", "Thorn", "thorn", "minus",
# 240
"multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf",
"onequarter", "threequarters", "franc", "Gbreve", "gbreve",
# 250
"Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute",
"Ccaron", "ccaron", "dcroat"
]
# The list of standard `SID' glyph names. For the official list,
# see Annex A of document at
#
# http://partners.adobe.com/public/developer/en/font/5176.CFF.pdf .
#
sid_standard_names = \
[
# 0
".notdef", "space", "exclam", "quotedbl", "numbersign",
"dollar", "percent", "ampersand", "quoteright", "parenleft",
# 10
"parenright", "asterisk", "plus", "comma", "hyphen",
"period", "slash", "zero", "one", "two",
# 20
"three", "four", "five", "six", "seven",
"eight", "nine", "colon", "semicolon", "less",
# 30
"equal", "greater", "question", "at", "A",
"B", "C", "D", "E", "F",
# 40
"G", "H", "I", "J", "K",
"L", "M", "N", "O", "P",
# 50
"Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z",
# 60
"bracketleft", "backslash", "bracketright", "asciicircum", "underscore",
"quoteleft", "a", "b", "c", "d",
# 70
"e", "f", "g", "h", "i",
"j", "k", "l", "m", "n",
# 80
"o", "p", "q", "r", "s",
"t", "u", "v", "w", "x",
# 90
"y", "z", "braceleft", "bar", "braceright",
"asciitilde", "exclamdown", "cent", "sterling", "fraction",
# 100
"yen", "florin", "section", "currency", "quotesingle",
"quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi",
# 110
"fl", "endash", "dagger", "daggerdbl", "periodcentered",
"paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright",
# 120
"guillemotright", "ellipsis", "perthousand", "questiondown", "grave",
"acute", "circumflex", "tilde", "macron", "breve",
# 130
"dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut",
"ogonek", "caron", "emdash", "AE", "ordfeminine",
# 140
"Lslash", "Oslash", "OE", "ordmasculine", "ae",
"dotlessi", "lslash", "oslash", "oe", "germandbls",
# 150
"onesuperior", "logicalnot", "mu", "trademark", "Eth",
"onehalf", "plusminus", "Thorn", "onequarter", "divide",
# 160
"brokenbar", "degree", "thorn", "threequarters", "twosuperior",
"registered", "minus", "eth", "multiply", "threesuperior",
# 170
"copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave",
"Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex",
# 180
"Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis",
"Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis",
# 190
"Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex",
"Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron",
# 200
"aacute", "acircumflex", "adieresis", "agrave", "aring",
"atilde", "ccedilla", "eacute", "ecircumflex", "edieresis",
# 210
"egrave", "iacute", "icircumflex", "idieresis", "igrave",
"ntilde", "oacute", "ocircumflex", "odieresis", "ograve",
# 220
"otilde", "scaron", "uacute", "ucircumflex", "udieresis",
"ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall",
# 230
"Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall",
"Acutesmall",
"parenleftsuperior", "parenrightsuperior", "twodotenleader",
"onedotenleader", "zerooldstyle",
# 240
"oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle",
"fiveoldstyle",
"sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle",
"commasuperior",
# 250
"threequartersemdash", "periodsuperior", "questionsmall", "asuperior",
"bsuperior",
"centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior",
# 260
"msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior",
"tsuperior", "ff", "ffi", "ffl", "parenleftinferior",
# 270
"parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall",
"Asmall",
"Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall",
# 280
"Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall",
"Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall",
# 290
"Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall",
"Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall",
# 300
"colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall",
"centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall",
"Dieresissmall",
# 310
"Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash",
"hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall",
"questiondownsmall",
# 320
"oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird",
"twothirds", "zerosuperior", "foursuperior", "fivesuperior",
"sixsuperior",
# 330
"sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior",
"oneinferior",
"twoinferior", "threeinferior", "fourinferior", "fiveinferior",
"sixinferior",
# 340
"seveninferior", "eightinferior", "nineinferior", "centinferior",
"dollarinferior",
"periodinferior", "commainferior", "Agravesmall", "Aacutesmall",
"Acircumflexsmall",
# 350
"Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall",
"Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall",
"Igravesmall",
# 360
"Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall",
"Ntildesmall",
"Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall",
"Odieresissmall",
# 370
"OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall",
"Ucircumflexsmall",
"Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall",
"001.000",
# 380
"001.001", "001.002", "001.003", "Black", "Bold",
"Book", "Light", "Medium", "Regular", "Roman",
# 390
"Semibold"
]
# This table maps character codes of the Adobe Standard Type 1
# encoding to glyph indices in the sid_standard_names table.
#
t1_standard_encoding = \
[
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, 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 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, 93, 94, 95, 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, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 0, 111, 112, 113,
114, 0, 115, 116, 117, 118, 119, 120, 121, 122,
0, 123, 0, 124, 125, 126, 127, 128, 129, 130,
131, 0, 132, 133, 0, 134, 135, 136, 137, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 138, 0, 139, 0, 0,
0, 0, 140, 141, 142, 143, 0, 0, 0, 0,
0, 144, 0, 0, 0, 145, 0, 0, 146, 147,
148, 149, 0, 0, 0, 0
]
# This table maps character codes of the Adobe Expert Type 1
# encoding to glyph indices in the sid_standard_names table.
#
t1_expert_encoding = \
[
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, 1, 229, 230, 0, 231, 232, 233, 234,
235, 236, 237, 238, 13, 14, 15, 99, 239, 240,
241, 242, 243, 244, 245, 246, 247, 248, 27, 28,
249, 250, 251, 252, 0, 253, 254, 255, 256, 257,
0, 0, 0, 258, 0, 0, 259, 260, 261, 262,
0, 0, 263, 264, 265, 0, 266, 109, 110, 267,
268, 269, 0, 270, 271, 272, 273, 274, 275, 276,
277, 278, 279, 280, 281, 282, 283, 284, 285, 286,
287, 288, 289, 290, 291, 292, 293, 294, 295, 296,
297, 298, 299, 300, 301, 302, 303, 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, 304, 305, 306, 0, 0, 307, 308, 309, 310,
311, 0, 312, 0, 0, 313, 0, 0, 314, 315,
0, 0, 316, 317, 318, 0, 0, 0, 158, 155,
163, 319, 320, 321, 322, 323, 324, 325, 0, 0,
326, 150, 164, 169, 327, 328, 329, 330, 331, 332,
333, 334, 335, 336, 337, 338, 339, 340, 341, 342,
343, 344, 345, 346, 347, 348, 349, 350, 351, 352,
353, 354, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 366, 367, 368, 369, 370, 371, 372,
373, 374, 375, 376, 377, 378
]
# This data has been taken literally from the files `glyphlist.txt'
# and `zapfdingbats.txt' version 2.0, Sept 2002. It is available from
#
# https://github.com/adobe-type-tools/agl-aglfn
#
adobe_glyph_list = """\
A;0041
AE;00C6
AEacute;01FC
AEmacron;01E2
AEsmall;F7E6
Aacute;00C1
Aacutesmall;F7E1
Abreve;0102
Abreveacute;1EAE
Abrevecyrillic;04D0
Abrevedotbelow;1EB6
Abrevegrave;1EB0
Abrevehookabove;1EB2
Abrevetilde;1EB4
Acaron;01CD
Acircle;24B6
Acircumflex;00C2
Acircumflexacute;1EA4
Acircumflexdotbelow;1EAC
Acircumflexgrave;1EA6
Acircumflexhookabove;1EA8
Acircumflexsmall;F7E2
Acircumflextilde;1EAA
Acute;F6C9
Acutesmall;F7B4
Acyrillic;0410
Adblgrave;0200
Adieresis;00C4
Adieresiscyrillic;04D2
Adieresismacron;01DE
Adieresissmall;F7E4
Adotbelow;1EA0
Adotmacron;01E0
Agrave;00C0
Agravesmall;F7E0
Ahookabove;1EA2
Aiecyrillic;04D4
Ainvertedbreve;0202
Alpha;0391
Alphatonos;0386
Amacron;0100
Amonospace;FF21
Aogonek;0104
Aring;00C5
Aringacute;01FA
Aringbelow;1E00
Aringsmall;F7E5
Asmall;F761
Atilde;00C3
Atildesmall;F7E3
Aybarmenian;0531
B;0042
Bcircle;24B7
Bdotaccent;1E02
Bdotbelow;1E04
Becyrillic;0411
Benarmenian;0532
Beta;0392
Bhook;0181
Blinebelow;1E06
Bmonospace;FF22
Brevesmall;F6F4
Bsmall;F762
Btopbar;0182
C;0043
Caarmenian;053E
Cacute;0106
Caron;F6CA
Caronsmall;F6F5
Ccaron;010C
Ccedilla;00C7
Ccedillaacute;1E08
Ccedillasmall;F7E7
Ccircle;24B8
Ccircumflex;0108
Cdot;010A
Cdotaccent;010A
Cedillasmall;F7B8
Chaarmenian;0549
Cheabkhasiancyrillic;04BC
Checyrillic;0427
Chedescenderabkhasiancyrillic;04BE
Chedescendercyrillic;04B6
Chedieresiscyrillic;04F4
Cheharmenian;0543
Chekhakassiancyrillic;04CB
Cheverticalstrokecyrillic;04B8
Chi;03A7
Chook;0187
Circumflexsmall;F6F6
Cmonospace;FF23
Coarmenian;0551
Csmall;F763
D;0044
DZ;01F1
DZcaron;01C4
Daarmenian;0534
Dafrican;0189
Dcaron;010E
Dcedilla;1E10
Dcircle;24B9
Dcircumflexbelow;1E12
Dcroat;0110
Ddotaccent;1E0A
Ddotbelow;1E0C
Decyrillic;0414
Deicoptic;03EE
Delta;2206
Deltagreek;0394
Dhook;018A
Dieresis;F6CB
DieresisAcute;F6CC
DieresisGrave;F6CD
Dieresissmall;F7A8
Digammagreek;03DC
Djecyrillic;0402
Dlinebelow;1E0E
Dmonospace;FF24
Dotaccentsmall;F6F7
Dslash;0110
Dsmall;F764
Dtopbar;018B
Dz;01F2
Dzcaron;01C5
Dzeabkhasiancyrillic;04E0
Dzecyrillic;0405
Dzhecyrillic;040F
E;0045
Eacute;00C9
Eacutesmall;F7E9
Ebreve;0114
Ecaron;011A
Ecedillabreve;1E1C
Echarmenian;0535
Ecircle;24BA
Ecircumflex;00CA
Ecircumflexacute;1EBE
Ecircumflexbelow;1E18
Ecircumflexdotbelow;1EC6
Ecircumflexgrave;1EC0
Ecircumflexhookabove;1EC2
Ecircumflexsmall;F7EA
Ecircumflextilde;1EC4
Ecyrillic;0404
Edblgrave;0204
Edieresis;00CB
Edieresissmall;F7EB
Edot;0116
Edotaccent;0116
Edotbelow;1EB8
Efcyrillic;0424
Egrave;00C8
Egravesmall;F7E8
Eharmenian;0537
Ehookabove;1EBA
Eightroman;2167
Einvertedbreve;0206
Eiotifiedcyrillic;0464
Elcyrillic;041B
Elevenroman;216A
Emacron;0112
Emacronacute;1E16
Emacrongrave;1E14
Emcyrillic;041C
Emonospace;FF25
Encyrillic;041D
Endescendercyrillic;04A2
Eng;014A
Enghecyrillic;04A4
Enhookcyrillic;04C7
Eogonek;0118
Eopen;0190
Epsilon;0395
Epsilontonos;0388
Ercyrillic;0420
Ereversed;018E
Ereversedcyrillic;042D
Escyrillic;0421
Esdescendercyrillic;04AA
Esh;01A9
Esmall;F765
Eta;0397
Etarmenian;0538
Etatonos;0389
Eth;00D0
Ethsmall;F7F0
Etilde;1EBC
Etildebelow;1E1A
Euro;20AC
Ezh;01B7
Ezhcaron;01EE
Ezhreversed;01B8
F;0046
Fcircle;24BB
Fdotaccent;1E1E
Feharmenian;0556
Feicoptic;03E4
Fhook;0191
Fitacyrillic;0472
Fiveroman;2164
Fmonospace;FF26
Fourroman;2163
Fsmall;F766
G;0047
GBsquare;3387
Gacute;01F4
Gamma;0393
Gammaafrican;0194
Gangiacoptic;03EA
Gbreve;011E
Gcaron;01E6
Gcedilla;0122
Gcircle;24BC
Gcircumflex;011C
Gcommaaccent;0122
Gdot;0120
Gdotaccent;0120
Gecyrillic;0413
Ghadarmenian;0542
Ghemiddlehookcyrillic;0494
Ghestrokecyrillic;0492
Gheupturncyrillic;0490
Ghook;0193
Gimarmenian;0533
Gjecyrillic;0403
Gmacron;1E20
Gmonospace;FF27
Grave;F6CE
Gravesmall;F760
Gsmall;F767
Gsmallhook;029B
Gstroke;01E4
H;0048
H18533;25CF
H18543;25AA
H18551;25AB
H22073;25A1
HPsquare;33CB
Haabkhasiancyrillic;04A8
Hadescendercyrillic;04B2
Hardsigncyrillic;042A
Hbar;0126
Hbrevebelow;1E2A
Hcedilla;1E28
Hcircle;24BD
Hcircumflex;0124
Hdieresis;1E26
Hdotaccent;1E22
Hdotbelow;1E24
Hmonospace;FF28
Hoarmenian;0540
Horicoptic;03E8
Hsmall;F768
Hungarumlaut;F6CF
Hungarumlautsmall;F6F8
Hzsquare;3390
I;0049
IAcyrillic;042F
IJ;0132
IUcyrillic;042E
Iacute;00CD
Iacutesmall;F7ED
Ibreve;012C
Icaron;01CF
Icircle;24BE
Icircumflex;00CE
Icircumflexsmall;F7EE
Icyrillic;0406
Idblgrave;0208
Idieresis;00CF
Idieresisacute;1E2E
Idieresiscyrillic;04E4
Idieresissmall;F7EF
Idot;0130
Idotaccent;0130
Idotbelow;1ECA
Iebrevecyrillic;04D6
Iecyrillic;0415
Ifraktur;2111
Igrave;00CC
Igravesmall;F7EC
Ihookabove;1EC8
Iicyrillic;0418
Iinvertedbreve;020A
Iishortcyrillic;0419
Imacron;012A
Imacroncyrillic;04E2
Imonospace;FF29
Iniarmenian;053B
Iocyrillic;0401
Iogonek;012E
Iota;0399
Iotaafrican;0196
Iotadieresis;03AA
Iotatonos;038A
Ismall;F769
Istroke;0197
Itilde;0128
Itildebelow;1E2C
Izhitsacyrillic;0474
Izhitsadblgravecyrillic;0476
J;004A
Jaarmenian;0541
Jcircle;24BF
Jcircumflex;0134
Jecyrillic;0408
Jheharmenian;054B
Jmonospace;FF2A
Jsmall;F76A
K;004B
KBsquare;3385
KKsquare;33CD
Kabashkircyrillic;04A0
Kacute;1E30
Kacyrillic;041A
Kadescendercyrillic;049A
Kahookcyrillic;04C3
Kappa;039A
Kastrokecyrillic;049E
Kaverticalstrokecyrillic;049C
Kcaron;01E8
Kcedilla;0136
Kcircle;24C0
Kcommaaccent;0136
Kdotbelow;1E32
Keharmenian;0554
Kenarmenian;053F
Khacyrillic;0425
Kheicoptic;03E6
Khook;0198
Kjecyrillic;040C
Klinebelow;1E34
Kmonospace;FF2B
Koppacyrillic;0480
Koppagreek;03DE
Ksicyrillic;046E
Ksmall;F76B
L;004C
LJ;01C7
LL;F6BF
Lacute;0139
Lambda;039B
Lcaron;013D
Lcedilla;013B
Lcircle;24C1
Lcircumflexbelow;1E3C
Lcommaaccent;013B
Ldot;013F
Ldotaccent;013F
Ldotbelow;1E36
Ldotbelowmacron;1E38
Liwnarmenian;053C
Lj;01C8
Ljecyrillic;0409
Llinebelow;1E3A
Lmonospace;FF2C
Lslash;0141
Lslashsmall;F6F9
Lsmall;F76C
M;004D
MBsquare;3386
Macron;F6D0
Macronsmall;F7AF
Macute;1E3E
Mcircle;24C2
Mdotaccent;1E40
Mdotbelow;1E42
Menarmenian;0544
Mmonospace;FF2D
Msmall;F76D
Mturned;019C
Mu;039C
N;004E
NJ;01CA
Nacute;0143
Ncaron;0147
Ncedilla;0145
Ncircle;24C3
Ncircumflexbelow;1E4A
Ncommaaccent;0145
Ndotaccent;1E44
Ndotbelow;1E46
Nhookleft;019D
Nineroman;2168
Nj;01CB
Njecyrillic;040A
Nlinebelow;1E48
Nmonospace;FF2E
Nowarmenian;0546
Nsmall;F76E
Ntilde;00D1
Ntildesmall;F7F1
Nu;039D
O;004F
OE;0152
OEsmall;F6FA
Oacute;00D3
Oacutesmall;F7F3
Obarredcyrillic;04E8
Obarreddieresiscyrillic;04EA
Obreve;014E
Ocaron;01D1
Ocenteredtilde;019F
Ocircle;24C4
Ocircumflex;00D4
Ocircumflexacute;1ED0
Ocircumflexdotbelow;1ED8
Ocircumflexgrave;1ED2
Ocircumflexhookabove;1ED4
Ocircumflexsmall;F7F4
Ocircumflextilde;1ED6
Ocyrillic;041E
Odblacute;0150
Odblgrave;020C
Odieresis;00D6
Odieresiscyrillic;04E6
Odieresissmall;F7F6
Odotbelow;1ECC
Ogoneksmall;F6FB
Ograve;00D2
Ogravesmall;F7F2
Oharmenian;0555
Ohm;2126
Ohookabove;1ECE
Ohorn;01A0
Ohornacute;1EDA
Ohorndotbelow;1EE2
Ohorngrave;1EDC
Ohornhookabove;1EDE
Ohorntilde;1EE0
Ohungarumlaut;0150
Oi;01A2
Oinvertedbreve;020E
Omacron;014C
Omacronacute;1E52
Omacrongrave;1E50
Omega;2126
Omegacyrillic;0460
Omegagreek;03A9
Omegaroundcyrillic;047A
Omegatitlocyrillic;047C
Omegatonos;038F
Omicron;039F
Omicrontonos;038C
Omonospace;FF2F
Oneroman;2160
Oogonek;01EA
Oogonekmacron;01EC
Oopen;0186
Oslash;00D8
Oslashacute;01FE
Oslashsmall;F7F8
Osmall;F76F
Ostrokeacute;01FE
Otcyrillic;047E
Otilde;00D5
Otildeacute;1E4C
Otildedieresis;1E4E
Otildesmall;F7F5
P;0050
Pacute;1E54
Pcircle;24C5
Pdotaccent;1E56
Pecyrillic;041F
Peharmenian;054A
Pemiddlehookcyrillic;04A6
Phi;03A6
Phook;01A4
Pi;03A0
Piwrarmenian;0553
Pmonospace;FF30
Psi;03A8
Psicyrillic;0470
Psmall;F770
Q;0051
Qcircle;24C6
Qmonospace;FF31
Qsmall;F771
R;0052
Raarmenian;054C
Racute;0154
Rcaron;0158
Rcedilla;0156
Rcircle;24C7
Rcommaaccent;0156
Rdblgrave;0210
Rdotaccent;1E58
Rdotbelow;1E5A
Rdotbelowmacron;1E5C
Reharmenian;0550
Rfraktur;211C
Rho;03A1
Ringsmall;F6FC
Rinvertedbreve;0212
Rlinebelow;1E5E
Rmonospace;FF32
Rsmall;F772
Rsmallinverted;0281
Rsmallinvertedsuperior;02B6
S;0053
SF010000;250C
SF020000;2514
SF030000;2510
SF040000;2518
SF050000;253C
SF060000;252C
SF070000;2534
SF080000;251C
SF090000;2524
SF100000;2500
SF110000;2502
SF190000;2561
SF200000;2562
SF210000;2556
SF220000;2555
SF230000;2563
SF240000;2551
SF250000;2557
SF260000;255D
SF270000;255C
SF280000;255B
SF360000;255E
SF370000;255F
SF380000;255A
SF390000;2554
SF400000;2569
SF410000;2566
SF420000;2560
SF430000;2550
SF440000;256C
SF450000;2567
SF460000;2568
SF470000;2564
SF480000;2565
SF490000;2559
SF500000;2558
SF510000;2552
SF520000;2553
SF530000;256B
SF540000;256A
Sacute;015A
Sacutedotaccent;1E64
Sampigreek;03E0
Scaron;0160
Scarondotaccent;1E66
Scaronsmall;F6FD
Scedilla;015E
Schwa;018F
Schwacyrillic;04D8
Schwadieresiscyrillic;04DA
Scircle;24C8
Scircumflex;015C
Scommaaccent;0218
Sdotaccent;1E60
Sdotbelow;1E62
Sdotbelowdotaccent;1E68
Seharmenian;054D
Sevenroman;2166
Shaarmenian;0547
Shacyrillic;0428
Shchacyrillic;0429
Sheicoptic;03E2
Shhacyrillic;04BA
Shimacoptic;03EC
Sigma;03A3
Sixroman;2165
Smonospace;FF33
Softsigncyrillic;042C
Ssmall;F773
Stigmagreek;03DA
T;0054
Tau;03A4
Tbar;0166
Tcaron;0164
Tcedilla;0162
Tcircle;24C9
Tcircumflexbelow;1E70
Tcommaaccent;0162
Tdotaccent;1E6A
Tdotbelow;1E6C
Tecyrillic;0422
Tedescendercyrillic;04AC
Tenroman;2169
Tetsecyrillic;04B4
Theta;0398
Thook;01AC
Thorn;00DE
Thornsmall;F7FE
Threeroman;2162
Tildesmall;F6FE
Tiwnarmenian;054F
Tlinebelow;1E6E
Tmonospace;FF34
Toarmenian;0539
Tonefive;01BC
Tonesix;0184
Tonetwo;01A7
Tretroflexhook;01AE
Tsecyrillic;0426
Tshecyrillic;040B
Tsmall;F774
Twelveroman;216B
Tworoman;2161
U;0055
Uacute;00DA
Uacutesmall;F7FA
Ubreve;016C
Ucaron;01D3
Ucircle;24CA
Ucircumflex;00DB
Ucircumflexbelow;1E76
Ucircumflexsmall;F7FB
Ucyrillic;0423
Udblacute;0170
Udblgrave;0214
Udieresis;00DC
Udieresisacute;01D7
Udieresisbelow;1E72
Udieresiscaron;01D9
Udieresiscyrillic;04F0
Udieresisgrave;01DB
Udieresismacron;01D5
Udieresissmall;F7FC
Udotbelow;1EE4
Ugrave;00D9
Ugravesmall;F7F9
Uhookabove;1EE6
Uhorn;01AF
Uhornacute;1EE8
Uhorndotbelow;1EF0
Uhorngrave;1EEA
Uhornhookabove;1EEC
Uhorntilde;1EEE
Uhungarumlaut;0170
Uhungarumlautcyrillic;04F2
Uinvertedbreve;0216
Ukcyrillic;0478
Umacron;016A
Umacroncyrillic;04EE
Umacrondieresis;1E7A
Umonospace;FF35
Uogonek;0172
Upsilon;03A5
Upsilon1;03D2
Upsilonacutehooksymbolgreek;03D3
Upsilonafrican;01B1
Upsilondieresis;03AB
Upsilondieresishooksymbolgreek;03D4
Upsilonhooksymbol;03D2
Upsilontonos;038E
Uring;016E
Ushortcyrillic;040E
Usmall;F775
Ustraightcyrillic;04AE
Ustraightstrokecyrillic;04B0
Utilde;0168
Utildeacute;1E78
Utildebelow;1E74
V;0056
Vcircle;24CB
Vdotbelow;1E7E
Vecyrillic;0412
Vewarmenian;054E
Vhook;01B2
Vmonospace;FF36
Voarmenian;0548
Vsmall;F776
Vtilde;1E7C
W;0057
Wacute;1E82
Wcircle;24CC
Wcircumflex;0174
Wdieresis;1E84
Wdotaccent;1E86
Wdotbelow;1E88
Wgrave;1E80
Wmonospace;FF37
Wsmall;F777
X;0058
Xcircle;24CD
Xdieresis;1E8C
Xdotaccent;1E8A
Xeharmenian;053D
Xi;039E
Xmonospace;FF38
Xsmall;F778
Y;0059
Yacute;00DD
Yacutesmall;F7FD
Yatcyrillic;0462
Ycircle;24CE
Ycircumflex;0176
Ydieresis;0178
Ydieresissmall;F7FF
Ydotaccent;1E8E
Ydotbelow;1EF4
Yericyrillic;042B
Yerudieresiscyrillic;04F8
Ygrave;1EF2
Yhook;01B3
Yhookabove;1EF6
Yiarmenian;0545
Yicyrillic;0407
Yiwnarmenian;0552
Ymonospace;FF39
Ysmall;F779
Ytilde;1EF8
Yusbigcyrillic;046A
Yusbigiotifiedcyrillic;046C
Yuslittlecyrillic;0466
Yuslittleiotifiedcyrillic;0468
Z;005A
Zaarmenian;0536
Zacute;0179
Zcaron;017D
Zcaronsmall;F6FF
Zcircle;24CF
Zcircumflex;1E90
Zdot;017B
Zdotaccent;017B
Zdotbelow;1E92
Zecyrillic;0417
Zedescendercyrillic;0498
Zedieresiscyrillic;04DE
Zeta;0396
Zhearmenian;053A
Zhebrevecyrillic;04C1
Zhecyrillic;0416
Zhedescendercyrillic;0496
Zhedieresiscyrillic;04DC
Zlinebelow;1E94
Zmonospace;FF3A
Zsmall;F77A
Zstroke;01B5
a;0061
aabengali;0986
aacute;00E1
aadeva;0906
aagujarati;0A86
aagurmukhi;0A06
aamatragurmukhi;0A3E
aarusquare;3303
aavowelsignbengali;09BE
aavowelsigndeva;093E
aavowelsigngujarati;0ABE
abbreviationmarkarmenian;055F
abbreviationsigndeva;0970
abengali;0985
abopomofo;311A
abreve;0103
abreveacute;1EAF
abrevecyrillic;04D1
abrevedotbelow;1EB7
abrevegrave;1EB1
abrevehookabove;1EB3
abrevetilde;1EB5
acaron;01CE
acircle;24D0
acircumflex;00E2
acircumflexacute;1EA5
acircumflexdotbelow;1EAD
acircumflexgrave;1EA7
acircumflexhookabove;1EA9
acircumflextilde;1EAB
acute;00B4
acutebelowcmb;0317
acutecmb;0301
acutecomb;0301
acutedeva;0954
acutelowmod;02CF
acutetonecmb;0341
acyrillic;0430
adblgrave;0201
addakgurmukhi;0A71
adeva;0905
adieresis;00E4
adieresiscyrillic;04D3
adieresismacron;01DF
adotbelow;1EA1
adotmacron;01E1
ae;00E6
aeacute;01FD
aekorean;3150
aemacron;01E3
afii00208;2015
afii08941;20A4
afii10017;0410
afii10018;0411
afii10019;0412
afii10020;0413
afii10021;0414
afii10022;0415
afii10023;0401
afii10024;0416
afii10025;0417
afii10026;0418
afii10027;0419
afii10028;041A
afii10029;041B
afii10030;041C
afii10031;041D
afii10032;041E
afii10033;041F
afii10034;0420
afii10035;0421
afii10036;0422
afii10037;0423
afii10038;0424
afii10039;0425
afii10040;0426
afii10041;0427
afii10042;0428
afii10043;0429
afii10044;042A
afii10045;042B
afii10046;042C
afii10047;042D
afii10048;042E
afii10049;042F
afii10050;0490
afii10051;0402
afii10052;0403
afii10053;0404
afii10054;0405
afii10055;0406
afii10056;0407
afii10057;0408
afii10058;0409
afii10059;040A
afii10060;040B
afii10061;040C
afii10062;040E
afii10063;F6C4
afii10064;F6C5
afii10065;0430
afii10066;0431
afii10067;0432
afii10068;0433
afii10069;0434
afii10070;0435
afii10071;0451
afii10072;0436
afii10073;0437
afii10074;0438
afii10075;0439
afii10076;043A
afii10077;043B
afii10078;043C
afii10079;043D
afii10080;043E
afii10081;043F
afii10082;0440
afii10083;0441
afii10084;0442
afii10085;0443
afii10086;0444
afii10087;0445
afii10088;0446
afii10089;0447
afii10090;0448
afii10091;0449
afii10092;044A
afii10093;044B
afii10094;044C
afii10095;044D
afii10096;044E
afii10097;044F
afii10098;0491
afii10099;0452
afii10100;0453
afii10101;0454
afii10102;0455
afii10103;0456
afii10104;0457
afii10105;0458
afii10106;0459
afii10107;045A
afii10108;045B
afii10109;045C
afii10110;045E
afii10145;040F
afii10146;0462
afii10147;0472
afii10148;0474
afii10192;F6C6
afii10193;045F
afii10194;0463
afii10195;0473
afii10196;0475
afii10831;F6C7
afii10832;F6C8
afii10846;04D9
afii299;200E
afii300;200F
afii301;200D
afii57381;066A
afii57388;060C
afii57392;0660
afii57393;0661
afii57394;0662
afii57395;0663
afii57396;0664
afii57397;0665
afii57398;0666
afii57399;0667
afii57400;0668
afii57401;0669
afii57403;061B
afii57407;061F
afii57409;0621
afii57410;0622
afii57411;0623
afii57412;0624
afii57413;0625
afii57414;0626
afii57415;0627
afii57416;0628
afii57417;0629
afii57418;062A
afii57419;062B
afii57420;062C
afii57421;062D
afii57422;062E
afii57423;062F
afii57424;0630
afii57425;0631
afii57426;0632
afii57427;0633
afii57428;0634
afii57429;0635
afii57430;0636
afii57431;0637
afii57432;0638
afii57433;0639
afii57434;063A
afii57440;0640
afii57441;0641
afii57442;0642
afii57443;0643
afii57444;0644
afii57445;0645
afii57446;0646
afii57448;0648
afii57449;0649
afii57450;064A
afii57451;064B
afii57452;064C
afii57453;064D
afii57454;064E
afii57455;064F
afii57456;0650
afii57457;0651
afii57458;0652
afii57470;0647
afii57505;06A4
afii57506;067E
afii57507;0686
afii57508;0698
afii57509;06AF
afii57511;0679
afii57512;0688
afii57513;0691
afii57514;06BA
afii57519;06D2
afii57534;06D5
afii57636;20AA
afii57645;05BE
afii57658;05C3
afii57664;05D0
afii57665;05D1
afii57666;05D2
afii57667;05D3
afii57668;05D4
afii57669;05D5
afii57670;05D6
afii57671;05D7
afii57672;05D8
afii57673;05D9
afii57674;05DA
afii57675;05DB
afii57676;05DC
afii57677;05DD
afii57678;05DE
afii57679;05DF
afii57680;05E0
afii57681;05E1
afii57682;05E2
afii57683;05E3
afii57684;05E4
afii57685;05E5
afii57686;05E6
afii57687;05E7
afii57688;05E8
afii57689;05E9
afii57690;05EA
afii57694;FB2A
afii57695;FB2B
afii57700;FB4B
afii57705;FB1F
afii57716;05F0
afii57717;05F1
afii57718;05F2
afii57723;FB35
afii57793;05B4
afii57794;05B5
afii57795;05B6
afii57796;05BB
afii57797;05B8
afii57798;05B7
afii57799;05B0
afii57800;05B2
afii57801;05B1
afii57802;05B3
afii57803;05C2
afii57804;05C1
afii57806;05B9
afii57807;05BC
afii57839;05BD
afii57841;05BF
afii57842;05C0
afii57929;02BC
afii61248;2105
afii61289;2113
afii61352;2116
afii61573;202C
afii61574;202D
afii61575;202E
afii61664;200C
afii63167;066D
afii64937;02BD
agrave;00E0
agujarati;0A85
agurmukhi;0A05
ahiragana;3042
ahookabove;1EA3
aibengali;0990
aibopomofo;311E
aideva;0910
aiecyrillic;04D5
aigujarati;0A90
aigurmukhi;0A10
aimatragurmukhi;0A48
ainarabic;0639
ainfinalarabic;FECA
aininitialarabic;FECB
ainmedialarabic;FECC
ainvertedbreve;0203
aivowelsignbengali;09C8
aivowelsigndeva;0948
aivowelsigngujarati;0AC8
akatakana;30A2
akatakanahalfwidth;FF71
akorean;314F
alef;05D0
alefarabic;0627
alefdageshhebrew;FB30
aleffinalarabic;FE8E
alefhamzaabovearabic;0623
alefhamzaabovefinalarabic;FE84
alefhamzabelowarabic;0625
alefhamzabelowfinalarabic;FE88
alefhebrew;05D0
aleflamedhebrew;FB4F
alefmaddaabovearabic;0622
alefmaddaabovefinalarabic;FE82
alefmaksuraarabic;0649
alefmaksurafinalarabic;FEF0
alefmaksurainitialarabic;FEF3
alefmaksuramedialarabic;FEF4
alefpatahhebrew;FB2E
alefqamatshebrew;FB2F
aleph;2135
allequal;224C
alpha;03B1
alphatonos;03AC
amacron;0101
amonospace;FF41
ampersand;0026
ampersandmonospace;FF06
ampersandsmall;F726
amsquare;33C2
anbopomofo;3122
angbopomofo;3124
angkhankhuthai;0E5A
angle;2220
anglebracketleft;3008
anglebracketleftvertical;FE3F
anglebracketright;3009
anglebracketrightvertical;FE40
angleleft;2329
angleright;232A
angstrom;212B
anoteleia;0387
anudattadeva;0952
anusvarabengali;0982
anusvaradeva;0902
anusvaragujarati;0A82
aogonek;0105
apaatosquare;3300
aparen;249C
apostrophearmenian;055A
apostrophemod;02BC
apple;F8FF
approaches;2250
approxequal;2248
approxequalorimage;2252
approximatelyequal;2245
araeaekorean;318E
araeakorean;318D
arc;2312
arighthalfring;1E9A
aring;00E5
aringacute;01FB
aringbelow;1E01
arrowboth;2194
arrowdashdown;21E3
arrowdashleft;21E0
arrowdashright;21E2
arrowdashup;21E1
arrowdblboth;21D4
arrowdbldown;21D3
arrowdblleft;21D0
arrowdblright;21D2
arrowdblup;21D1
arrowdown;2193
arrowdownleft;2199
arrowdownright;2198
arrowdownwhite;21E9
arrowheaddownmod;02C5
arrowheadleftmod;02C2
arrowheadrightmod;02C3
arrowheadupmod;02C4
arrowhorizex;F8E7
arrowleft;2190
arrowleftdbl;21D0
arrowleftdblstroke;21CD
arrowleftoverright;21C6
arrowleftwhite;21E6
arrowright;2192
arrowrightdblstroke;21CF
arrowrightheavy;279E
arrowrightoverleft;21C4
arrowrightwhite;21E8
arrowtableft;21E4
arrowtabright;21E5
arrowup;2191
arrowupdn;2195
arrowupdnbse;21A8
arrowupdownbase;21A8
arrowupleft;2196
arrowupleftofdown;21C5
arrowupright;2197
arrowupwhite;21E7
arrowvertex;F8E6
asciicircum;005E
asciicircummonospace;FF3E
asciitilde;007E
asciitildemonospace;FF5E
ascript;0251
ascriptturned;0252
asmallhiragana;3041
asmallkatakana;30A1
asmallkatakanahalfwidth;FF67
asterisk;002A
asteriskaltonearabic;066D
asteriskarabic;066D
asteriskmath;2217
asteriskmonospace;FF0A
asterisksmall;FE61
asterism;2042
asuperior;F6E9
asymptoticallyequal;2243
at;0040
atilde;00E3
atmonospace;FF20
atsmall;FE6B
aturned;0250
aubengali;0994
aubopomofo;3120
audeva;0914
augujarati;0A94
augurmukhi;0A14
aulengthmarkbengali;09D7
aumatragurmukhi;0A4C
auvowelsignbengali;09CC
auvowelsigndeva;094C
auvowelsigngujarati;0ACC
avagrahadeva;093D
aybarmenian;0561
ayin;05E2
ayinaltonehebrew;FB20
ayinhebrew;05E2
b;0062
babengali;09AC
backslash;005C
backslashmonospace;FF3C
badeva;092C
bagujarati;0AAC
bagurmukhi;0A2C
bahiragana;3070
bahtthai;0E3F
bakatakana;30D0
bar;007C
barmonospace;FF5C
bbopomofo;3105
bcircle;24D1
bdotaccent;1E03
bdotbelow;1E05
beamedsixteenthnotes;266C
because;2235
becyrillic;0431
beharabic;0628
behfinalarabic;FE90
behinitialarabic;FE91
behiragana;3079
behmedialarabic;FE92
behmeeminitialarabic;FC9F
behmeemisolatedarabic;FC08
behnoonfinalarabic;FC6D
bekatakana;30D9
benarmenian;0562
bet;05D1
beta;03B2
betasymbolgreek;03D0
betdagesh;FB31
betdageshhebrew;FB31
bethebrew;05D1
betrafehebrew;FB4C
bhabengali;09AD
bhadeva;092D
bhagujarati;0AAD
bhagurmukhi;0A2D
bhook;0253
bihiragana;3073
bikatakana;30D3
bilabialclick;0298
bindigurmukhi;0A02
birusquare;3331
blackcircle;25CF
blackdiamond;25C6
blackdownpointingtriangle;25BC
blackleftpointingpointer;25C4
blackleftpointingtriangle;25C0
blacklenticularbracketleft;3010
blacklenticularbracketleftvertical;FE3B
blacklenticularbracketright;3011
blacklenticularbracketrightvertical;FE3C
blacklowerlefttriangle;25E3
blacklowerrighttriangle;25E2
blackrectangle;25AC
blackrightpointingpointer;25BA
blackrightpointingtriangle;25B6
blacksmallsquare;25AA
blacksmilingface;263B
blacksquare;25A0
blackstar;2605
blackupperlefttriangle;25E4
blackupperrighttriangle;25E5
blackuppointingsmalltriangle;25B4
blackuppointingtriangle;25B2
blank;2423
blinebelow;1E07
block;2588
bmonospace;FF42
bobaimaithai;0E1A
bohiragana;307C
bokatakana;30DC
bparen;249D
bqsquare;33C3
braceex;F8F4
braceleft;007B
braceleftbt;F8F3
braceleftmid;F8F2
braceleftmonospace;FF5B
braceleftsmall;FE5B
bracelefttp;F8F1
braceleftvertical;FE37
braceright;007D
bracerightbt;F8FE
bracerightmid;F8FD
bracerightmonospace;FF5D
bracerightsmall;FE5C
bracerighttp;F8FC
bracerightvertical;FE38
bracketleft;005B
bracketleftbt;F8F0
bracketleftex;F8EF
bracketleftmonospace;FF3B
bracketlefttp;F8EE
bracketright;005D
bracketrightbt;F8FB
bracketrightex;F8FA
bracketrightmonospace;FF3D
bracketrighttp;F8F9
breve;02D8
brevebelowcmb;032E
brevecmb;0306
breveinvertedbelowcmb;032F
breveinvertedcmb;0311
breveinverteddoublecmb;0361
bridgebelowcmb;032A
bridgeinvertedbelowcmb;033A
brokenbar;00A6
bstroke;0180
bsuperior;F6EA
btopbar;0183
buhiragana;3076
bukatakana;30D6
bullet;2022
bulletinverse;25D8
bulletoperator;2219
bullseye;25CE
c;0063
caarmenian;056E
cabengali;099A
cacute;0107
cadeva;091A
cagujarati;0A9A
cagurmukhi;0A1A
calsquare;3388
candrabindubengali;0981
candrabinducmb;0310
candrabindudeva;0901
candrabindugujarati;0A81
capslock;21EA
careof;2105
caron;02C7
caronbelowcmb;032C
caroncmb;030C
carriagereturn;21B5
cbopomofo;3118
ccaron;010D
ccedilla;00E7
ccedillaacute;1E09
ccircle;24D2
ccircumflex;0109
ccurl;0255
cdot;010B
cdotaccent;010B
cdsquare;33C5
cedilla;00B8
cedillacmb;0327
cent;00A2
centigrade;2103
centinferior;F6DF
centmonospace;FFE0
centoldstyle;F7A2
centsuperior;F6E0
chaarmenian;0579
chabengali;099B
chadeva;091B
chagujarati;0A9B
chagurmukhi;0A1B
chbopomofo;3114
cheabkhasiancyrillic;04BD
checkmark;2713
checyrillic;0447
chedescenderabkhasiancyrillic;04BF
chedescendercyrillic;04B7
chedieresiscyrillic;04F5
cheharmenian;0573
chekhakassiancyrillic;04CC
cheverticalstrokecyrillic;04B9
chi;03C7
chieuchacirclekorean;3277
chieuchaparenkorean;3217
chieuchcirclekorean;3269
chieuchkorean;314A
chieuchparenkorean;3209
chochangthai;0E0A
chochanthai;0E08
chochingthai;0E09
chochoethai;0E0C
chook;0188
cieucacirclekorean;3276
cieucaparenkorean;3216
cieuccirclekorean;3268
cieuckorean;3148
cieucparenkorean;3208
cieucuparenkorean;321C
circle;25CB
circlemultiply;2297
circleot;2299
circleplus;2295
circlepostalmark;3036
circlewithlefthalfblack;25D0
circlewithrighthalfblack;25D1
circumflex;02C6
circumflexbelowcmb;032D
circumflexcmb;0302
clear;2327
clickalveolar;01C2
clickdental;01C0
clicklateral;01C1
clickretroflex;01C3
club;2663
clubsuitblack;2663
clubsuitwhite;2667
cmcubedsquare;33A4
cmonospace;FF43
cmsquaredsquare;33A0
coarmenian;0581
colon;003A
colonmonetary;20A1
colonmonospace;FF1A
colonsign;20A1
colonsmall;FE55
colontriangularhalfmod;02D1
colontriangularmod;02D0
comma;002C
commaabovecmb;0313
commaaboverightcmb;0315
commaaccent;F6C3
commaarabic;060C
commaarmenian;055D
commainferior;F6E1
commamonospace;FF0C
commareversedabovecmb;0314
commareversedmod;02BD
commasmall;FE50
commasuperior;F6E2
commaturnedabovecmb;0312
commaturnedmod;02BB
compass;263C
congruent;2245
contourintegral;222E
control;2303
controlACK;0006
controlBEL;0007
controlBS;0008
controlCAN;0018
controlCR;000D
controlDC1;0011
controlDC2;0012
controlDC3;0013
controlDC4;0014
controlDEL;007F
controlDLE;0010
controlEM;0019
controlENQ;0005
controlEOT;0004
controlESC;001B
controlETB;0017
controlETX;0003
controlFF;000C
controlFS;001C
controlGS;001D
controlHT;0009
controlLF;000A
controlNAK;0015
controlRS;001E
controlSI;000F
controlSO;000E
controlSOT;0002
controlSTX;0001
controlSUB;001A
controlSYN;0016
controlUS;001F
controlVT;000B
copyright;00A9
copyrightsans;F8E9
copyrightserif;F6D9
cornerbracketleft;300C
cornerbracketlefthalfwidth;FF62
cornerbracketleftvertical;FE41
cornerbracketright;300D
cornerbracketrighthalfwidth;FF63
cornerbracketrightvertical;FE42
corporationsquare;337F
cosquare;33C7
coverkgsquare;33C6
cparen;249E
cruzeiro;20A2
cstretched;0297
curlyand;22CF
curlyor;22CE
currency;00A4
cyrBreve;F6D1
cyrFlex;F6D2
cyrbreve;F6D4
cyrflex;F6D5
d;0064
daarmenian;0564
dabengali;09A6
dadarabic;0636
dadeva;0926
dadfinalarabic;FEBE
dadinitialarabic;FEBF
dadmedialarabic;FEC0
dagesh;05BC
dageshhebrew;05BC
dagger;2020
daggerdbl;2021
dagujarati;0AA6
dagurmukhi;0A26
dahiragana;3060
dakatakana;30C0
dalarabic;062F
dalet;05D3
daletdagesh;FB33
daletdageshhebrew;FB33
dalethatafpatah;05D3 05B2
dalethatafpatahhebrew;05D3 05B2
dalethatafsegol;05D3 05B1
dalethatafsegolhebrew;05D3 05B1
dalethebrew;05D3
dalethiriq;05D3 05B4
dalethiriqhebrew;05D3 05B4
daletholam;05D3 05B9
daletholamhebrew;05D3 05B9
daletpatah;05D3 05B7
daletpatahhebrew;05D3 05B7
daletqamats;05D3 05B8
daletqamatshebrew;05D3 05B8
daletqubuts;05D3 05BB
daletqubutshebrew;05D3 05BB
daletsegol;05D3 05B6
daletsegolhebrew;05D3 05B6
daletsheva;05D3 05B0
daletshevahebrew;05D3 05B0
dalettsere;05D3 05B5
dalettserehebrew;05D3 05B5
dalfinalarabic;FEAA
dammaarabic;064F
dammalowarabic;064F
dammatanaltonearabic;064C
dammatanarabic;064C
danda;0964
dargahebrew;05A7
dargalefthebrew;05A7
dasiapneumatacyrilliccmb;0485
dblGrave;F6D3
dblanglebracketleft;300A
dblanglebracketleftvertical;FE3D
dblanglebracketright;300B
dblanglebracketrightvertical;FE3E
dblarchinvertedbelowcmb;032B
dblarrowleft;21D4
dblarrowright;21D2
dbldanda;0965
dblgrave;F6D6
dblgravecmb;030F
dblintegral;222C
dbllowline;2017
dbllowlinecmb;0333
dbloverlinecmb;033F
dblprimemod;02BA
dblverticalbar;2016
dblverticallineabovecmb;030E
dbopomofo;3109
dbsquare;33C8
dcaron;010F
dcedilla;1E11
dcircle;24D3
dcircumflexbelow;1E13
dcroat;0111
ddabengali;09A1
ddadeva;0921
ddagujarati;0AA1
ddagurmukhi;0A21
ddalarabic;0688
ddalfinalarabic;FB89
dddhadeva;095C
ddhabengali;09A2
ddhadeva;0922
ddhagujarati;0AA2
ddhagurmukhi;0A22
ddotaccent;1E0B
ddotbelow;1E0D
decimalseparatorarabic;066B
decimalseparatorpersian;066B
decyrillic;0434
degree;00B0
dehihebrew;05AD
dehiragana;3067
deicoptic;03EF
dekatakana;30C7
deleteleft;232B
deleteright;2326
delta;03B4
deltaturned;018D
denominatorminusonenumeratorbengali;09F8
dezh;02A4
dhabengali;09A7
dhadeva;0927
dhagujarati;0AA7
dhagurmukhi;0A27
dhook;0257
dialytikatonos;0385
dialytikatonoscmb;0344
diamond;2666
diamondsuitwhite;2662
dieresis;00A8
dieresisacute;F6D7
dieresisbelowcmb;0324
dieresiscmb;0308
dieresisgrave;F6D8
dieresistonos;0385
dihiragana;3062
dikatakana;30C2
dittomark;3003
divide;00F7
divides;2223
divisionslash;2215
djecyrillic;0452
dkshade;2593
dlinebelow;1E0F
dlsquare;3397
dmacron;0111
dmonospace;FF44
dnblock;2584
dochadathai;0E0E
dodekthai;0E14
dohiragana;3069
dokatakana;30C9
dollar;0024
dollarinferior;F6E3
dollarmonospace;FF04
dollaroldstyle;F724
dollarsmall;FE69
dollarsuperior;F6E4
dong;20AB
dorusquare;3326
dotaccent;02D9
dotaccentcmb;0307
dotbelowcmb;0323
dotbelowcomb;0323
dotkatakana;30FB
dotlessi;0131
dotlessj;F6BE
dotlessjstrokehook;0284
dotmath;22C5
dottedcircle;25CC
doubleyodpatah;FB1F
doubleyodpatahhebrew;FB1F
downtackbelowcmb;031E
downtackmod;02D5
dparen;249F
dsuperior;F6EB
dtail;0256
dtopbar;018C
duhiragana;3065
dukatakana;30C5
dz;01F3
dzaltone;02A3
dzcaron;01C6
dzcurl;02A5
dzeabkhasiancyrillic;04E1
dzecyrillic;0455
dzhecyrillic;045F
e;0065
eacute;00E9
earth;2641
ebengali;098F
ebopomofo;311C
ebreve;0115
ecandradeva;090D
ecandragujarati;0A8D
ecandravowelsigndeva;0945
ecandravowelsigngujarati;0AC5
ecaron;011B
ecedillabreve;1E1D
echarmenian;0565
echyiwnarmenian;0587
ecircle;24D4
ecircumflex;00EA
ecircumflexacute;1EBF
ecircumflexbelow;1E19
ecircumflexdotbelow;1EC7
ecircumflexgrave;1EC1
ecircumflexhookabove;1EC3
ecircumflextilde;1EC5
ecyrillic;0454
edblgrave;0205
edeva;090F
edieresis;00EB
edot;0117
edotaccent;0117
edotbelow;1EB9
eegurmukhi;0A0F
eematragurmukhi;0A47
efcyrillic;0444
egrave;00E8
egujarati;0A8F
eharmenian;0567
ehbopomofo;311D
ehiragana;3048
ehookabove;1EBB
eibopomofo;311F
eight;0038
eightarabic;0668
eightbengali;09EE
eightcircle;2467
eightcircleinversesansserif;2791
eightdeva;096E
eighteencircle;2471
eighteenparen;2485
eighteenperiod;2499
eightgujarati;0AEE
eightgurmukhi;0A6E
eighthackarabic;0668
eighthangzhou;3028
eighthnotebeamed;266B
eightideographicparen;3227
eightinferior;2088
eightmonospace;FF18
eightoldstyle;F738
eightparen;247B
eightperiod;248F
eightpersian;06F8
eightroman;2177
eightsuperior;2078
eightthai;0E58
einvertedbreve;0207
eiotifiedcyrillic;0465
ekatakana;30A8
ekatakanahalfwidth;FF74
ekonkargurmukhi;0A74
ekorean;3154
elcyrillic;043B
element;2208
elevencircle;246A
elevenparen;247E
elevenperiod;2492
elevenroman;217A
ellipsis;2026
ellipsisvertical;22EE
emacron;0113
emacronacute;1E17
emacrongrave;1E15
emcyrillic;043C
emdash;2014
emdashvertical;FE31
emonospace;FF45
emphasismarkarmenian;055B
emptyset;2205
enbopomofo;3123
encyrillic;043D
endash;2013
endashvertical;FE32
endescendercyrillic;04A3
eng;014B
engbopomofo;3125
enghecyrillic;04A5
enhookcyrillic;04C8
enspace;2002
eogonek;0119
eokorean;3153
eopen;025B
eopenclosed;029A
eopenreversed;025C
eopenreversedclosed;025E
eopenreversedhook;025D
eparen;24A0
epsilon;03B5
epsilontonos;03AD
equal;003D
equalmonospace;FF1D
equalsmall;FE66
equalsuperior;207C
equivalence;2261
erbopomofo;3126
ercyrillic;0440
ereversed;0258
ereversedcyrillic;044D
escyrillic;0441
esdescendercyrillic;04AB
esh;0283
eshcurl;0286
eshortdeva;090E
eshortvowelsigndeva;0946
eshreversedloop;01AA
eshsquatreversed;0285
esmallhiragana;3047
esmallkatakana;30A7
esmallkatakanahalfwidth;FF6A
estimated;212E
esuperior;F6EC
eta;03B7
etarmenian;0568
etatonos;03AE
eth;00F0
etilde;1EBD
etildebelow;1E1B
etnahtafoukhhebrew;0591
etnahtafoukhlefthebrew;0591
etnahtahebrew;0591
etnahtalefthebrew;0591
eturned;01DD
eukorean;3161
euro;20AC
evowelsignbengali;09C7
evowelsigndeva;0947
evowelsigngujarati;0AC7
exclam;0021
exclamarmenian;055C
exclamdbl;203C
exclamdown;00A1
exclamdownsmall;F7A1
exclammonospace;FF01
exclamsmall;F721
existential;2203
ezh;0292
ezhcaron;01EF
ezhcurl;0293
ezhreversed;01B9
ezhtail;01BA
f;0066
fadeva;095E
fagurmukhi;0A5E
fahrenheit;2109
fathaarabic;064E
fathalowarabic;064E
fathatanarabic;064B
fbopomofo;3108
fcircle;24D5
fdotaccent;1E1F
feharabic;0641
feharmenian;0586
fehfinalarabic;FED2
fehinitialarabic;FED3
fehmedialarabic;FED4
feicoptic;03E5
female;2640
ff;FB00
ffi;FB03
ffl;FB04
fi;FB01
fifteencircle;246E
fifteenparen;2482
fifteenperiod;2496
figuredash;2012
filledbox;25A0
filledrect;25AC
finalkaf;05DA
finalkafdagesh;FB3A
finalkafdageshhebrew;FB3A
finalkafhebrew;05DA
finalkafqamats;05DA 05B8
finalkafqamatshebrew;05DA 05B8
finalkafsheva;05DA 05B0
finalkafshevahebrew;05DA 05B0
finalmem;05DD
finalmemhebrew;05DD
finalnun;05DF
finalnunhebrew;05DF
finalpe;05E3
finalpehebrew;05E3
finaltsadi;05E5
finaltsadihebrew;05E5
firsttonechinese;02C9
fisheye;25C9
fitacyrillic;0473
five;0035
fivearabic;0665
fivebengali;09EB
fivecircle;2464
fivecircleinversesansserif;278E
fivedeva;096B
fiveeighths;215D
fivegujarati;0AEB
fivegurmukhi;0A6B
fivehackarabic;0665
fivehangzhou;3025
fiveideographicparen;3224
fiveinferior;2085
fivemonospace;FF15
fiveoldstyle;F735
fiveparen;2478
fiveperiod;248C
fivepersian;06F5
fiveroman;2174
fivesuperior;2075
fivethai;0E55
fl;FB02
florin;0192
fmonospace;FF46
fmsquare;3399
fofanthai;0E1F
fofathai;0E1D
fongmanthai;0E4F
forall;2200
four;0034
fourarabic;0664
fourbengali;09EA
fourcircle;2463
fourcircleinversesansserif;278D
fourdeva;096A
fourgujarati;0AEA
fourgurmukhi;0A6A
fourhackarabic;0664
fourhangzhou;3024
fourideographicparen;3223
fourinferior;2084
fourmonospace;FF14
fournumeratorbengali;09F7
fouroldstyle;F734
fourparen;2477
fourperiod;248B
fourpersian;06F4
fourroman;2173
foursuperior;2074
fourteencircle;246D
fourteenparen;2481
fourteenperiod;2495
fourthai;0E54
fourthtonechinese;02CB
fparen;24A1
fraction;2044
franc;20A3
g;0067
gabengali;0997
gacute;01F5
gadeva;0917
gafarabic;06AF
gaffinalarabic;FB93
gafinitialarabic;FB94
gafmedialarabic;FB95
gagujarati;0A97
gagurmukhi;0A17
gahiragana;304C
gakatakana;30AC
gamma;03B3
gammalatinsmall;0263
gammasuperior;02E0
gangiacoptic;03EB
gbopomofo;310D
gbreve;011F
gcaron;01E7
gcedilla;0123
gcircle;24D6
gcircumflex;011D
gcommaaccent;0123
gdot;0121
gdotaccent;0121
gecyrillic;0433
gehiragana;3052
gekatakana;30B2
geometricallyequal;2251
gereshaccenthebrew;059C
gereshhebrew;05F3
gereshmuqdamhebrew;059D
germandbls;00DF
gershayimaccenthebrew;059E
gershayimhebrew;05F4
getamark;3013
ghabengali;0998
ghadarmenian;0572
ghadeva;0918
ghagujarati;0A98
ghagurmukhi;0A18
ghainarabic;063A
ghainfinalarabic;FECE
ghaininitialarabic;FECF
ghainmedialarabic;FED0
ghemiddlehookcyrillic;0495
ghestrokecyrillic;0493
gheupturncyrillic;0491
ghhadeva;095A
ghhagurmukhi;0A5A
ghook;0260
ghzsquare;3393
gihiragana;304E
gikatakana;30AE
gimarmenian;0563
gimel;05D2
gimeldagesh;FB32
gimeldageshhebrew;FB32
gimelhebrew;05D2
gjecyrillic;0453
glottalinvertedstroke;01BE
glottalstop;0294
glottalstopinverted;0296
glottalstopmod;02C0
glottalstopreversed;0295
glottalstopreversedmod;02C1
glottalstopreversedsuperior;02E4
glottalstopstroke;02A1
glottalstopstrokereversed;02A2
gmacron;1E21
gmonospace;FF47
gohiragana;3054
gokatakana;30B4
gparen;24A2
gpasquare;33AC
gradient;2207
grave;0060
gravebelowcmb;0316
gravecmb;0300
gravecomb;0300
gravedeva;0953
gravelowmod;02CE
gravemonospace;FF40
gravetonecmb;0340
greater;003E
greaterequal;2265
greaterequalorless;22DB
greatermonospace;FF1E
greaterorequivalent;2273
greaterorless;2277
greateroverequal;2267
greatersmall;FE65
gscript;0261
gstroke;01E5
guhiragana;3050
guillemotleft;00AB
guillemotright;00BB
guilsinglleft;2039
guilsinglright;203A
gukatakana;30B0
guramusquare;3318
gysquare;33C9
h;0068
haabkhasiancyrillic;04A9
haaltonearabic;06C1
habengali;09B9
hadescendercyrillic;04B3
hadeva;0939
hagujarati;0AB9
hagurmukhi;0A39
haharabic;062D
hahfinalarabic;FEA2
hahinitialarabic;FEA3
hahiragana;306F
hahmedialarabic;FEA4
haitusquare;332A
hakatakana;30CF
hakatakanahalfwidth;FF8A
halantgurmukhi;0A4D
hamzaarabic;0621
hamzadammaarabic;0621 064F
hamzadammatanarabic;0621 064C
hamzafathaarabic;0621 064E
hamzafathatanarabic;0621 064B
hamzalowarabic;0621
hamzalowkasraarabic;0621 0650
hamzalowkasratanarabic;0621 064D
hamzasukunarabic;0621 0652
hangulfiller;3164
hardsigncyrillic;044A
harpoonleftbarbup;21BC
harpoonrightbarbup;21C0
hasquare;33CA
hatafpatah;05B2
hatafpatah16;05B2
hatafpatah23;05B2
hatafpatah2f;05B2
hatafpatahhebrew;05B2
hatafpatahnarrowhebrew;05B2
hatafpatahquarterhebrew;05B2
hatafpatahwidehebrew;05B2
hatafqamats;05B3
hatafqamats1b;05B3
hatafqamats28;05B3
hatafqamats34;05B3
hatafqamatshebrew;05B3
hatafqamatsnarrowhebrew;05B3
hatafqamatsquarterhebrew;05B3
hatafqamatswidehebrew;05B3
hatafsegol;05B1
hatafsegol17;05B1
hatafsegol24;05B1
hatafsegol30;05B1
hatafsegolhebrew;05B1
hatafsegolnarrowhebrew;05B1
hatafsegolquarterhebrew;05B1
hatafsegolwidehebrew;05B1
hbar;0127
hbopomofo;310F
hbrevebelow;1E2B
hcedilla;1E29
hcircle;24D7
hcircumflex;0125
hdieresis;1E27
hdotaccent;1E23
hdotbelow;1E25
he;05D4
heart;2665
heartsuitblack;2665
heartsuitwhite;2661
hedagesh;FB34
hedageshhebrew;FB34
hehaltonearabic;06C1
heharabic;0647
hehebrew;05D4
hehfinalaltonearabic;FBA7
hehfinalalttwoarabic;FEEA
hehfinalarabic;FEEA
hehhamzaabovefinalarabic;FBA5
hehhamzaaboveisolatedarabic;FBA4
hehinitialaltonearabic;FBA8
hehinitialarabic;FEEB
hehiragana;3078
hehmedialaltonearabic;FBA9
hehmedialarabic;FEEC
heiseierasquare;337B
hekatakana;30D8
hekatakanahalfwidth;FF8D
hekutaarusquare;3336
henghook;0267
herutusquare;3339
het;05D7
hethebrew;05D7
hhook;0266
hhooksuperior;02B1
hieuhacirclekorean;327B
hieuhaparenkorean;321B
hieuhcirclekorean;326D
hieuhkorean;314E
hieuhparenkorean;320D
hihiragana;3072
hikatakana;30D2
hikatakanahalfwidth;FF8B
hiriq;05B4
hiriq14;05B4
hiriq21;05B4
hiriq2d;05B4
hiriqhebrew;05B4
hiriqnarrowhebrew;05B4
hiriqquarterhebrew;05B4
hiriqwidehebrew;05B4
hlinebelow;1E96
hmonospace;FF48
hoarmenian;0570
hohipthai;0E2B
hohiragana;307B
hokatakana;30DB
hokatakanahalfwidth;FF8E
holam;05B9
holam19;05B9
holam26;05B9
holam32;05B9
holamhebrew;05B9
holamnarrowhebrew;05B9
holamquarterhebrew;05B9
holamwidehebrew;05B9
honokhukthai;0E2E
hookabovecomb;0309
hookcmb;0309
hookpalatalizedbelowcmb;0321
hookretroflexbelowcmb;0322
hoonsquare;3342
horicoptic;03E9
horizontalbar;2015
horncmb;031B
hotsprings;2668
house;2302
hparen;24A3
hsuperior;02B0
hturned;0265
huhiragana;3075
huiitosquare;3333
hukatakana;30D5
hukatakanahalfwidth;FF8C
hungarumlaut;02DD
hungarumlautcmb;030B
hv;0195
hyphen;002D
hypheninferior;F6E5
hyphenmonospace;FF0D
hyphensmall;FE63
hyphensuperior;F6E6
hyphentwo;2010
i;0069
iacute;00ED
iacyrillic;044F
ibengali;0987
ibopomofo;3127
ibreve;012D
icaron;01D0
icircle;24D8
icircumflex;00EE
icyrillic;0456
idblgrave;0209
ideographearthcircle;328F
ideographfirecircle;328B
ideographicallianceparen;323F
ideographiccallparen;323A
ideographiccentrecircle;32A5
ideographicclose;3006
ideographiccomma;3001
ideographiccommaleft;FF64
ideographiccongratulationparen;3237
ideographiccorrectcircle;32A3
ideographicearthparen;322F
ideographicenterpriseparen;323D
ideographicexcellentcircle;329D
ideographicfestivalparen;3240
ideographicfinancialcircle;3296
ideographicfinancialparen;3236
ideographicfireparen;322B
ideographichaveparen;3232
ideographichighcircle;32A4
ideographiciterationmark;3005
ideographiclaborcircle;3298
ideographiclaborparen;3238
ideographicleftcircle;32A7
ideographiclowcircle;32A6
ideographicmedicinecircle;32A9
ideographicmetalparen;322E
ideographicmoonparen;322A
ideographicnameparen;3234
ideographicperiod;3002
ideographicprintcircle;329E
ideographicreachparen;3243
ideographicrepresentparen;3239
ideographicresourceparen;323E
ideographicrightcircle;32A8
ideographicsecretcircle;3299
ideographicselfparen;3242
ideographicsocietyparen;3233
ideographicspace;3000
ideographicspecialparen;3235
ideographicstockparen;3231
ideographicstudyparen;323B
ideographicsunparen;3230
ideographicsuperviseparen;323C
ideographicwaterparen;322C
ideographicwoodparen;322D
ideographiczero;3007
ideographmetalcircle;328E
ideographmooncircle;328A
ideographnamecircle;3294
ideographsuncircle;3290
ideographwatercircle;328C
ideographwoodcircle;328D
ideva;0907
idieresis;00EF
idieresisacute;1E2F
idieresiscyrillic;04E5
idotbelow;1ECB
iebrevecyrillic;04D7
iecyrillic;0435
ieungacirclekorean;3275
ieungaparenkorean;3215
ieungcirclekorean;3267
ieungkorean;3147
ieungparenkorean;3207
igrave;00EC
igujarati;0A87
igurmukhi;0A07
ihiragana;3044
ihookabove;1EC9
iibengali;0988
iicyrillic;0438
iideva;0908
iigujarati;0A88
iigurmukhi;0A08
iimatragurmukhi;0A40
iinvertedbreve;020B
iishortcyrillic;0439
iivowelsignbengali;09C0
iivowelsigndeva;0940
iivowelsigngujarati;0AC0
ij;0133
ikatakana;30A4
ikatakanahalfwidth;FF72
ikorean;3163
ilde;02DC
iluyhebrew;05AC
imacron;012B
imacroncyrillic;04E3
imageorapproximatelyequal;2253
imatragurmukhi;0A3F
imonospace;FF49
increment;2206
infinity;221E
iniarmenian;056B
integral;222B
integralbottom;2321
integralbt;2321
integralex;F8F5
integraltop;2320
integraltp;2320
intersection;2229
intisquare;3305
invbullet;25D8
invcircle;25D9
invsmileface;263B
iocyrillic;0451
iogonek;012F
iota;03B9
iotadieresis;03CA
iotadieresistonos;0390
iotalatin;0269
iotatonos;03AF
iparen;24A4
irigurmukhi;0A72
ismallhiragana;3043
ismallkatakana;30A3
ismallkatakanahalfwidth;FF68
issharbengali;09FA
istroke;0268
isuperior;F6ED
iterationhiragana;309D
iterationkatakana;30FD
itilde;0129
itildebelow;1E2D
iubopomofo;3129
iucyrillic;044E
ivowelsignbengali;09BF
ivowelsigndeva;093F
ivowelsigngujarati;0ABF
izhitsacyrillic;0475
izhitsadblgravecyrillic;0477
j;006A
jaarmenian;0571
jabengali;099C
jadeva;091C
jagujarati;0A9C
jagurmukhi;0A1C
jbopomofo;3110
jcaron;01F0
jcircle;24D9
jcircumflex;0135
jcrossedtail;029D
jdotlessstroke;025F
jecyrillic;0458
jeemarabic;062C
jeemfinalarabic;FE9E
jeeminitialarabic;FE9F
jeemmedialarabic;FEA0
jeharabic;0698
jehfinalarabic;FB8B
jhabengali;099D
jhadeva;091D
jhagujarati;0A9D
jhagurmukhi;0A1D
jheharmenian;057B
jis;3004
jmonospace;FF4A
jparen;24A5
jsuperior;02B2
k;006B
kabashkircyrillic;04A1
kabengali;0995
kacute;1E31
kacyrillic;043A
kadescendercyrillic;049B
kadeva;0915
kaf;05DB
kafarabic;0643
kafdagesh;FB3B
kafdageshhebrew;FB3B
kaffinalarabic;FEDA
kafhebrew;05DB
kafinitialarabic;FEDB
kafmedialarabic;FEDC
kafrafehebrew;FB4D
kagujarati;0A95
kagurmukhi;0A15
kahiragana;304B
kahookcyrillic;04C4
kakatakana;30AB
kakatakanahalfwidth;FF76
kappa;03BA
kappasymbolgreek;03F0
kapyeounmieumkorean;3171
kapyeounphieuphkorean;3184
kapyeounpieupkorean;3178
kapyeounssangpieupkorean;3179
karoriisquare;330D
kashidaautoarabic;0640
kashidaautonosidebearingarabic;0640
kasmallkatakana;30F5
kasquare;3384
kasraarabic;0650
kasratanarabic;064D
kastrokecyrillic;049F
katahiraprolongmarkhalfwidth;FF70
kaverticalstrokecyrillic;049D
kbopomofo;310E
kcalsquare;3389
kcaron;01E9
kcedilla;0137
kcircle;24DA
kcommaaccent;0137
kdotbelow;1E33
keharmenian;0584
kehiragana;3051
kekatakana;30B1
kekatakanahalfwidth;FF79
kenarmenian;056F
kesmallkatakana;30F6
kgreenlandic;0138
khabengali;0996
khacyrillic;0445
khadeva;0916
khagujarati;0A96
khagurmukhi;0A16
khaharabic;062E
khahfinalarabic;FEA6
khahinitialarabic;FEA7
khahmedialarabic;FEA8
kheicoptic;03E7
khhadeva;0959
khhagurmukhi;0A59
khieukhacirclekorean;3278
khieukhaparenkorean;3218
khieukhcirclekorean;326A
khieukhkorean;314B
khieukhparenkorean;320A
khokhaithai;0E02
khokhonthai;0E05
khokhuatthai;0E03
khokhwaithai;0E04
khomutthai;0E5B
khook;0199
khorakhangthai;0E06
khzsquare;3391
kihiragana;304D
kikatakana;30AD
kikatakanahalfwidth;FF77
kiroguramusquare;3315
kiromeetorusquare;3316
kirosquare;3314
kiyeokacirclekorean;326E
kiyeokaparenkorean;320E
kiyeokcirclekorean;3260
kiyeokkorean;3131
kiyeokparenkorean;3200
kiyeoksioskorean;3133
kjecyrillic;045C
klinebelow;1E35
klsquare;3398
kmcubedsquare;33A6
kmonospace;FF4B
kmsquaredsquare;33A2
kohiragana;3053
kohmsquare;33C0
kokaithai;0E01
kokatakana;30B3
kokatakanahalfwidth;FF7A
kooposquare;331E
koppacyrillic;0481
koreanstandardsymbol;327F
koroniscmb;0343
kparen;24A6
kpasquare;33AA
ksicyrillic;046F
ktsquare;33CF
kturned;029E
kuhiragana;304F
kukatakana;30AF
kukatakanahalfwidth;FF78
kvsquare;33B8
kwsquare;33BE
l;006C
labengali;09B2
lacute;013A
ladeva;0932
lagujarati;0AB2
lagurmukhi;0A32
lakkhangyaothai;0E45
lamaleffinalarabic;FEFC
lamalefhamzaabovefinalarabic;FEF8
lamalefhamzaaboveisolatedarabic;FEF7
lamalefhamzabelowfinalarabic;FEFA
lamalefhamzabelowisolatedarabic;FEF9
lamalefisolatedarabic;FEFB
lamalefmaddaabovefinalarabic;FEF6
lamalefmaddaaboveisolatedarabic;FEF5
lamarabic;0644
lambda;03BB
lambdastroke;019B
lamed;05DC
lameddagesh;FB3C
lameddageshhebrew;FB3C
lamedhebrew;05DC
lamedholam;05DC 05B9
lamedholamdagesh;05DC 05B9 05BC
lamedholamdageshhebrew;05DC 05B9 05BC
lamedholamhebrew;05DC 05B9
lamfinalarabic;FEDE
lamhahinitialarabic;FCCA
laminitialarabic;FEDF
lamjeeminitialarabic;FCC9
lamkhahinitialarabic;FCCB
lamlamhehisolatedarabic;FDF2
lammedialarabic;FEE0
lammeemhahinitialarabic;FD88
lammeeminitialarabic;FCCC
lammeemjeeminitialarabic;FEDF FEE4 FEA0
lammeemkhahinitialarabic;FEDF FEE4 FEA8
largecircle;25EF
lbar;019A
lbelt;026C
lbopomofo;310C
lcaron;013E
lcedilla;013C
lcircle;24DB
lcircumflexbelow;1E3D
lcommaaccent;013C
ldot;0140
ldotaccent;0140
ldotbelow;1E37
ldotbelowmacron;1E39
leftangleabovecmb;031A
lefttackbelowcmb;0318
less;003C
lessequal;2264
lessequalorgreater;22DA
lessmonospace;FF1C
lessorequivalent;2272
lessorgreater;2276
lessoverequal;2266
lesssmall;FE64
lezh;026E
lfblock;258C
lhookretroflex;026D
lira;20A4
liwnarmenian;056C
lj;01C9
ljecyrillic;0459
ll;F6C0
lladeva;0933
llagujarati;0AB3
llinebelow;1E3B
llladeva;0934
llvocalicbengali;09E1
llvocalicdeva;0961
llvocalicvowelsignbengali;09E3
llvocalicvowelsigndeva;0963
lmiddletilde;026B
lmonospace;FF4C
lmsquare;33D0
lochulathai;0E2C
logicaland;2227
logicalnot;00AC
logicalnotreversed;2310
logicalor;2228
lolingthai;0E25
longs;017F
lowlinecenterline;FE4E
lowlinecmb;0332
lowlinedashed;FE4D
lozenge;25CA
lparen;24A7
lslash;0142
lsquare;2113
lsuperior;F6EE
ltshade;2591
luthai;0E26
lvocalicbengali;098C
lvocalicdeva;090C
lvocalicvowelsignbengali;09E2
lvocalicvowelsigndeva;0962
lxsquare;33D3
m;006D
mabengali;09AE
macron;00AF
macronbelowcmb;0331
macroncmb;0304
macronlowmod;02CD
macronmonospace;FFE3
macute;1E3F
madeva;092E
magujarati;0AAE
magurmukhi;0A2E
mahapakhhebrew;05A4
mahapakhlefthebrew;05A4
mahiragana;307E
maichattawalowleftthai;F895
maichattawalowrightthai;F894
maichattawathai;0E4B
maichattawaupperleftthai;F893
maieklowleftthai;F88C
maieklowrightthai;F88B
maiekthai;0E48
maiekupperleftthai;F88A
maihanakatleftthai;F884
maihanakatthai;0E31
maitaikhuleftthai;F889
maitaikhuthai;0E47
maitholowleftthai;F88F
maitholowrightthai;F88E
maithothai;0E49
maithoupperleftthai;F88D
maitrilowleftthai;F892
maitrilowrightthai;F891
maitrithai;0E4A
maitriupperleftthai;F890
maiyamokthai;0E46
makatakana;30DE
makatakanahalfwidth;FF8F
male;2642
mansyonsquare;3347
maqafhebrew;05BE
mars;2642
masoracirclehebrew;05AF
masquare;3383
mbopomofo;3107
mbsquare;33D4
mcircle;24DC
mcubedsquare;33A5
mdotaccent;1E41
mdotbelow;1E43
meemarabic;0645
meemfinalarabic;FEE2
meeminitialarabic;FEE3
meemmedialarabic;FEE4
meemmeeminitialarabic;FCD1
meemmeemisolatedarabic;FC48
meetorusquare;334D
mehiragana;3081
meizierasquare;337E
mekatakana;30E1
mekatakanahalfwidth;FF92
mem;05DE
memdagesh;FB3E
memdageshhebrew;FB3E
memhebrew;05DE
menarmenian;0574
merkhahebrew;05A5
merkhakefulahebrew;05A6
merkhakefulalefthebrew;05A6
merkhalefthebrew;05A5
mhook;0271
mhzsquare;3392
middledotkatakanahalfwidth;FF65
middot;00B7
mieumacirclekorean;3272
mieumaparenkorean;3212
mieumcirclekorean;3264
mieumkorean;3141
mieumpansioskorean;3170
mieumparenkorean;3204
mieumpieupkorean;316E
mieumsioskorean;316F
mihiragana;307F
mikatakana;30DF
mikatakanahalfwidth;FF90
minus;2212
minusbelowcmb;0320
minuscircle;2296
minusmod;02D7
minusplus;2213
minute;2032
miribaarusquare;334A
mirisquare;3349
mlonglegturned;0270
mlsquare;3396
mmcubedsquare;33A3
mmonospace;FF4D
mmsquaredsquare;339F
mohiragana;3082
mohmsquare;33C1
mokatakana;30E2
mokatakanahalfwidth;FF93
molsquare;33D6
momathai;0E21
moverssquare;33A7
moverssquaredsquare;33A8
mparen;24A8
mpasquare;33AB
mssquare;33B3
msuperior;F6EF
mturned;026F
mu;00B5
mu1;00B5
muasquare;3382
muchgreater;226B
muchless;226A
mufsquare;338C
mugreek;03BC
mugsquare;338D
muhiragana;3080
mukatakana;30E0
mukatakanahalfwidth;FF91
mulsquare;3395
multiply;00D7
mumsquare;339B
munahhebrew;05A3
munahlefthebrew;05A3
musicalnote;266A
musicalnotedbl;266B
musicflatsign;266D
musicsharpsign;266F
mussquare;33B2
muvsquare;33B6
muwsquare;33BC
mvmegasquare;33B9
mvsquare;33B7
mwmegasquare;33BF
mwsquare;33BD
n;006E
nabengali;09A8
nabla;2207
nacute;0144
nadeva;0928
nagujarati;0AA8
nagurmukhi;0A28
nahiragana;306A
nakatakana;30CA
nakatakanahalfwidth;FF85
napostrophe;0149
nasquare;3381
nbopomofo;310B
nbspace;00A0
ncaron;0148
ncedilla;0146
ncircle;24DD
ncircumflexbelow;1E4B
ncommaaccent;0146
ndotaccent;1E45
ndotbelow;1E47
nehiragana;306D
nekatakana;30CD
nekatakanahalfwidth;FF88
newsheqelsign;20AA
nfsquare;338B
ngabengali;0999
ngadeva;0919
ngagujarati;0A99
ngagurmukhi;0A19
ngonguthai;0E07
nhiragana;3093
nhookleft;0272
nhookretroflex;0273
nieunacirclekorean;326F
nieunaparenkorean;320F
nieuncieuckorean;3135
nieuncirclekorean;3261
nieunhieuhkorean;3136
nieunkorean;3134
nieunpansioskorean;3168
nieunparenkorean;3201
nieunsioskorean;3167
nieuntikeutkorean;3166
nihiragana;306B
nikatakana;30CB
nikatakanahalfwidth;FF86
nikhahitleftthai;F899
nikhahitthai;0E4D
nine;0039
ninearabic;0669
ninebengali;09EF
ninecircle;2468
ninecircleinversesansserif;2792
ninedeva;096F
ninegujarati;0AEF
ninegurmukhi;0A6F
ninehackarabic;0669
ninehangzhou;3029
nineideographicparen;3228
nineinferior;2089
ninemonospace;FF19
nineoldstyle;F739
nineparen;247C
nineperiod;2490
ninepersian;06F9
nineroman;2178
ninesuperior;2079
nineteencircle;2472
nineteenparen;2486
nineteenperiod;249A
ninethai;0E59
nj;01CC
njecyrillic;045A
nkatakana;30F3
nkatakanahalfwidth;FF9D
nlegrightlong;019E
nlinebelow;1E49
nmonospace;FF4E
nmsquare;339A
nnabengali;09A3
nnadeva;0923
nnagujarati;0AA3
nnagurmukhi;0A23
nnnadeva;0929
nohiragana;306E
nokatakana;30CE
nokatakanahalfwidth;FF89
nonbreakingspace;00A0
nonenthai;0E13
nonuthai;0E19
noonarabic;0646
noonfinalarabic;FEE6
noonghunnaarabic;06BA
noonghunnafinalarabic;FB9F
noonhehinitialarabic;FEE7 FEEC
nooninitialarabic;FEE7
noonjeeminitialarabic;FCD2
noonjeemisolatedarabic;FC4B
noonmedialarabic;FEE8
noonmeeminitialarabic;FCD5
noonmeemisolatedarabic;FC4E
noonnoonfinalarabic;FC8D
notcontains;220C
notelement;2209
notelementof;2209
notequal;2260
notgreater;226F
notgreaternorequal;2271
notgreaternorless;2279
notidentical;2262
notless;226E
notlessnorequal;2270
notparallel;2226
notprecedes;2280
notsubset;2284
notsucceeds;2281
notsuperset;2285
nowarmenian;0576
nparen;24A9
nssquare;33B1
nsuperior;207F
ntilde;00F1
nu;03BD
nuhiragana;306C
nukatakana;30CC
nukatakanahalfwidth;FF87
nuktabengali;09BC
nuktadeva;093C
nuktagujarati;0ABC
nuktagurmukhi;0A3C
numbersign;0023
numbersignmonospace;FF03
numbersignsmall;FE5F
numeralsigngreek;0374
numeralsignlowergreek;0375
numero;2116
nun;05E0
nundagesh;FB40
nundageshhebrew;FB40
nunhebrew;05E0
nvsquare;33B5
nwsquare;33BB
nyabengali;099E
nyadeva;091E
nyagujarati;0A9E
nyagurmukhi;0A1E
o;006F
oacute;00F3
oangthai;0E2D
obarred;0275
obarredcyrillic;04E9
obarreddieresiscyrillic;04EB
obengali;0993
obopomofo;311B
obreve;014F
ocandradeva;0911
ocandragujarati;0A91
ocandravowelsigndeva;0949
ocandravowelsigngujarati;0AC9
ocaron;01D2
ocircle;24DE
ocircumflex;00F4
ocircumflexacute;1ED1
ocircumflexdotbelow;1ED9
ocircumflexgrave;1ED3
ocircumflexhookabove;1ED5
ocircumflextilde;1ED7
ocyrillic;043E
odblacute;0151
odblgrave;020D
odeva;0913
odieresis;00F6
odieresiscyrillic;04E7
odotbelow;1ECD
oe;0153
oekorean;315A
ogonek;02DB
ogonekcmb;0328
ograve;00F2
ogujarati;0A93
oharmenian;0585
ohiragana;304A
ohookabove;1ECF
ohorn;01A1
ohornacute;1EDB
ohorndotbelow;1EE3
ohorngrave;1EDD
ohornhookabove;1EDF
ohorntilde;1EE1
ohungarumlaut;0151
oi;01A3
oinvertedbreve;020F
okatakana;30AA
okatakanahalfwidth;FF75
okorean;3157
olehebrew;05AB
omacron;014D
omacronacute;1E53
omacrongrave;1E51
omdeva;0950
omega;03C9
omega1;03D6
omegacyrillic;0461
omegalatinclosed;0277
omegaroundcyrillic;047B
omegatitlocyrillic;047D
omegatonos;03CE
omgujarati;0AD0
omicron;03BF
omicrontonos;03CC
omonospace;FF4F
one;0031
onearabic;0661
onebengali;09E7
onecircle;2460
onecircleinversesansserif;278A
onedeva;0967
onedotenleader;2024
oneeighth;215B
onefitted;F6DC
onegujarati;0AE7
onegurmukhi;0A67
onehackarabic;0661
onehalf;00BD
onehangzhou;3021
oneideographicparen;3220
oneinferior;2081
onemonospace;FF11
onenumeratorbengali;09F4
oneoldstyle;F731
oneparen;2474
oneperiod;2488
onepersian;06F1
onequarter;00BC
oneroman;2170
onesuperior;00B9
onethai;0E51
onethird;2153
oogonek;01EB
oogonekmacron;01ED
oogurmukhi;0A13
oomatragurmukhi;0A4B
oopen;0254
oparen;24AA
openbullet;25E6
option;2325
ordfeminine;00AA
ordmasculine;00BA
orthogonal;221F
oshortdeva;0912
oshortvowelsigndeva;094A
oslash;00F8
oslashacute;01FF
osmallhiragana;3049
osmallkatakana;30A9
osmallkatakanahalfwidth;FF6B
ostrokeacute;01FF
osuperior;F6F0
otcyrillic;047F
otilde;00F5
otildeacute;1E4D
otildedieresis;1E4F
oubopomofo;3121
overline;203E
overlinecenterline;FE4A
overlinecmb;0305
overlinedashed;FE49
overlinedblwavy;FE4C
overlinewavy;FE4B
overscore;00AF
ovowelsignbengali;09CB
ovowelsigndeva;094B
ovowelsigngujarati;0ACB
p;0070
paampssquare;3380
paasentosquare;332B
pabengali;09AA
pacute;1E55
padeva;092A
pagedown;21DF
pageup;21DE
pagujarati;0AAA
pagurmukhi;0A2A
pahiragana;3071
paiyannoithai;0E2F
pakatakana;30D1
palatalizationcyrilliccmb;0484
palochkacyrillic;04C0
pansioskorean;317F
paragraph;00B6
parallel;2225
parenleft;0028
parenleftaltonearabic;FD3E
parenleftbt;F8ED
parenleftex;F8EC
parenleftinferior;208D
parenleftmonospace;FF08
parenleftsmall;FE59
parenleftsuperior;207D
parenlefttp;F8EB
parenleftvertical;FE35
parenright;0029
parenrightaltonearabic;FD3F
parenrightbt;F8F8
parenrightex;F8F7
parenrightinferior;208E
parenrightmonospace;FF09
parenrightsmall;FE5A
parenrightsuperior;207E
parenrighttp;F8F6
parenrightvertical;FE36
partialdiff;2202
paseqhebrew;05C0
pashtahebrew;0599
pasquare;33A9
patah;05B7
patah11;05B7
patah1d;05B7
patah2a;05B7
patahhebrew;05B7
patahnarrowhebrew;05B7
patahquarterhebrew;05B7
patahwidehebrew;05B7
pazerhebrew;05A1
pbopomofo;3106
pcircle;24DF
pdotaccent;1E57
pe;05E4
pecyrillic;043F
pedagesh;FB44
pedageshhebrew;FB44
peezisquare;333B
pefinaldageshhebrew;FB43
peharabic;067E
peharmenian;057A
pehebrew;05E4
pehfinalarabic;FB57
pehinitialarabic;FB58
pehiragana;307A
pehmedialarabic;FB59
pekatakana;30DA
pemiddlehookcyrillic;04A7
perafehebrew;FB4E
percent;0025
percentarabic;066A
percentmonospace;FF05
percentsmall;FE6A
period;002E
periodarmenian;0589
periodcentered;00B7
periodhalfwidth;FF61
periodinferior;F6E7
periodmonospace;FF0E
periodsmall;FE52
periodsuperior;F6E8
perispomenigreekcmb;0342
perpendicular;22A5
perthousand;2030
peseta;20A7
pfsquare;338A
phabengali;09AB
phadeva;092B
phagujarati;0AAB
phagurmukhi;0A2B
phi;03C6
phi1;03D5
phieuphacirclekorean;327A
phieuphaparenkorean;321A
phieuphcirclekorean;326C
phieuphkorean;314D
phieuphparenkorean;320C
philatin;0278
phinthuthai;0E3A
phisymbolgreek;03D5
phook;01A5
phophanthai;0E1E
phophungthai;0E1C
phosamphaothai;0E20
pi;03C0
pieupacirclekorean;3273
pieupaparenkorean;3213
pieupcieuckorean;3176
pieupcirclekorean;3265
pieupkiyeokkorean;3172
pieupkorean;3142
pieupparenkorean;3205
pieupsioskiyeokkorean;3174
pieupsioskorean;3144
pieupsiostikeutkorean;3175
pieupthieuthkorean;3177
pieuptikeutkorean;3173
pihiragana;3074
pikatakana;30D4
pisymbolgreek;03D6
piwrarmenian;0583
plus;002B
plusbelowcmb;031F
pluscircle;2295
plusminus;00B1
plusmod;02D6
plusmonospace;FF0B
plussmall;FE62
plussuperior;207A
pmonospace;FF50
pmsquare;33D8
pohiragana;307D
pointingindexdownwhite;261F
pointingindexleftwhite;261C
pointingindexrightwhite;261E
pointingindexupwhite;261D
pokatakana;30DD
poplathai;0E1B
postalmark;3012
postalmarkface;3020
pparen;24AB
precedes;227A
prescription;211E
primemod;02B9
primereversed;2035
product;220F
projective;2305
prolongedkana;30FC
propellor;2318
propersubset;2282
propersuperset;2283
proportion;2237
proportional;221D
psi;03C8
psicyrillic;0471
psilipneumatacyrilliccmb;0486
pssquare;33B0
puhiragana;3077
pukatakana;30D7
pvsquare;33B4
pwsquare;33BA
q;0071
qadeva;0958
qadmahebrew;05A8
qafarabic;0642
qaffinalarabic;FED6
qafinitialarabic;FED7
qafmedialarabic;FED8
qamats;05B8
qamats10;05B8
qamats1a;05B8
qamats1c;05B8
qamats27;05B8
qamats29;05B8
qamats33;05B8
qamatsde;05B8
qamatshebrew;05B8
qamatsnarrowhebrew;05B8
qamatsqatanhebrew;05B8
qamatsqatannarrowhebrew;05B8
qamatsqatanquarterhebrew;05B8
qamatsqatanwidehebrew;05B8
qamatsquarterhebrew;05B8
qamatswidehebrew;05B8
qarneyparahebrew;059F
qbopomofo;3111
qcircle;24E0
qhook;02A0
qmonospace;FF51
qof;05E7
qofdagesh;FB47
qofdageshhebrew;FB47
qofhatafpatah;05E7 05B2
qofhatafpatahhebrew;05E7 05B2
qofhatafsegol;05E7 05B1
qofhatafsegolhebrew;05E7 05B1
qofhebrew;05E7
qofhiriq;05E7 05B4
qofhiriqhebrew;05E7 05B4
qofholam;05E7 05B9
qofholamhebrew;05E7 05B9
qofpatah;05E7 05B7
qofpatahhebrew;05E7 05B7
qofqamats;05E7 05B8
qofqamatshebrew;05E7 05B8
qofqubuts;05E7 05BB
qofqubutshebrew;05E7 05BB
qofsegol;05E7 05B6
qofsegolhebrew;05E7 05B6
qofsheva;05E7 05B0
qofshevahebrew;05E7 05B0
qoftsere;05E7 05B5
qoftserehebrew;05E7 05B5
qparen;24AC
quarternote;2669
qubuts;05BB
qubuts18;05BB
qubuts25;05BB
qubuts31;05BB
qubutshebrew;05BB
qubutsnarrowhebrew;05BB
qubutsquarterhebrew;05BB
qubutswidehebrew;05BB
question;003F
questionarabic;061F
questionarmenian;055E
questiondown;00BF
questiondownsmall;F7BF
questiongreek;037E
questionmonospace;FF1F
questionsmall;F73F
quotedbl;0022
quotedblbase;201E
quotedblleft;201C
quotedblmonospace;FF02
quotedblprime;301E
quotedblprimereversed;301D
quotedblright;201D
quoteleft;2018
quoteleftreversed;201B
quotereversed;201B
quoteright;2019
quoterightn;0149
quotesinglbase;201A
quotesingle;0027
quotesinglemonospace;FF07
r;0072
raarmenian;057C
rabengali;09B0
racute;0155
radeva;0930
radical;221A
radicalex;F8E5
radoverssquare;33AE
radoverssquaredsquare;33AF
radsquare;33AD
rafe;05BF
rafehebrew;05BF
ragujarati;0AB0
ragurmukhi;0A30
rahiragana;3089
rakatakana;30E9
rakatakanahalfwidth;FF97
ralowerdiagonalbengali;09F1
ramiddlediagonalbengali;09F0
ramshorn;0264
ratio;2236
rbopomofo;3116
rcaron;0159
rcedilla;0157
rcircle;24E1
rcommaaccent;0157
rdblgrave;0211
rdotaccent;1E59
rdotbelow;1E5B
rdotbelowmacron;1E5D
referencemark;203B
reflexsubset;2286
reflexsuperset;2287
registered;00AE
registersans;F8E8
registerserif;F6DA
reharabic;0631
reharmenian;0580
rehfinalarabic;FEAE
rehiragana;308C
rehyehaleflamarabic;0631 FEF3 FE8E 0644
rekatakana;30EC
rekatakanahalfwidth;FF9A
resh;05E8
reshdageshhebrew;FB48
reshhatafpatah;05E8 05B2
reshhatafpatahhebrew;05E8 05B2
reshhatafsegol;05E8 05B1
reshhatafsegolhebrew;05E8 05B1
reshhebrew;05E8
reshhiriq;05E8 05B4
reshhiriqhebrew;05E8 05B4
reshholam;05E8 05B9
reshholamhebrew;05E8 05B9
reshpatah;05E8 05B7
reshpatahhebrew;05E8 05B7
reshqamats;05E8 05B8
reshqamatshebrew;05E8 05B8
reshqubuts;05E8 05BB
reshqubutshebrew;05E8 05BB
reshsegol;05E8 05B6
reshsegolhebrew;05E8 05B6
reshsheva;05E8 05B0
reshshevahebrew;05E8 05B0
reshtsere;05E8 05B5
reshtserehebrew;05E8 05B5
reversedtilde;223D
reviahebrew;0597
reviamugrashhebrew;0597
revlogicalnot;2310
rfishhook;027E
rfishhookreversed;027F
rhabengali;09DD
rhadeva;095D
rho;03C1
rhook;027D
rhookturned;027B
rhookturnedsuperior;02B5
rhosymbolgreek;03F1
rhotichookmod;02DE
rieulacirclekorean;3271
rieulaparenkorean;3211
rieulcirclekorean;3263
rieulhieuhkorean;3140
rieulkiyeokkorean;313A
rieulkiyeoksioskorean;3169
rieulkorean;3139
rieulmieumkorean;313B
rieulpansioskorean;316C
rieulparenkorean;3203
rieulphieuphkorean;313F
rieulpieupkorean;313C
rieulpieupsioskorean;316B
rieulsioskorean;313D
rieulthieuthkorean;313E
rieultikeutkorean;316A
rieulyeorinhieuhkorean;316D
rightangle;221F
righttackbelowcmb;0319
righttriangle;22BF
rihiragana;308A
rikatakana;30EA
rikatakanahalfwidth;FF98
ring;02DA
ringbelowcmb;0325
ringcmb;030A
ringhalfleft;02BF
ringhalfleftarmenian;0559
ringhalfleftbelowcmb;031C
ringhalfleftcentered;02D3
ringhalfright;02BE
ringhalfrightbelowcmb;0339
ringhalfrightcentered;02D2
rinvertedbreve;0213
rittorusquare;3351
rlinebelow;1E5F
rlongleg;027C
rlonglegturned;027A
rmonospace;FF52
rohiragana;308D
rokatakana;30ED
rokatakanahalfwidth;FF9B
roruathai;0E23
rparen;24AD
rrabengali;09DC
rradeva;0931
rragurmukhi;0A5C
rreharabic;0691
rrehfinalarabic;FB8D
rrvocalicbengali;09E0
rrvocalicdeva;0960
rrvocalicgujarati;0AE0
rrvocalicvowelsignbengali;09C4
rrvocalicvowelsigndeva;0944
rrvocalicvowelsigngujarati;0AC4
rsuperior;F6F1
rtblock;2590
rturned;0279
rturnedsuperior;02B4
ruhiragana;308B
rukatakana;30EB
rukatakanahalfwidth;FF99
rupeemarkbengali;09F2
rupeesignbengali;09F3
rupiah;F6DD
ruthai;0E24
rvocalicbengali;098B
rvocalicdeva;090B
rvocalicgujarati;0A8B
rvocalicvowelsignbengali;09C3
rvocalicvowelsigndeva;0943
rvocalicvowelsigngujarati;0AC3
s;0073
sabengali;09B8
sacute;015B
sacutedotaccent;1E65
sadarabic;0635
sadeva;0938
sadfinalarabic;FEBA
sadinitialarabic;FEBB
sadmedialarabic;FEBC
sagujarati;0AB8
sagurmukhi;0A38
sahiragana;3055
sakatakana;30B5
sakatakanahalfwidth;FF7B
sallallahoualayhewasallamarabic;FDFA
samekh;05E1
samekhdagesh;FB41
samekhdageshhebrew;FB41
samekhhebrew;05E1
saraaathai;0E32
saraaethai;0E41
saraaimaimalaithai;0E44
saraaimaimuanthai;0E43
saraamthai;0E33
saraathai;0E30
saraethai;0E40
saraiileftthai;F886
saraiithai;0E35
saraileftthai;F885
saraithai;0E34
saraothai;0E42
saraueeleftthai;F888
saraueethai;0E37
saraueleftthai;F887
sarauethai;0E36
sarauthai;0E38
sarauuthai;0E39
sbopomofo;3119
scaron;0161
scarondotaccent;1E67
scedilla;015F
schwa;0259
schwacyrillic;04D9
schwadieresiscyrillic;04DB
schwahook;025A
scircle;24E2
scircumflex;015D
scommaaccent;0219
sdotaccent;1E61
sdotbelow;1E63
sdotbelowdotaccent;1E69
seagullbelowcmb;033C
second;2033
secondtonechinese;02CA
section;00A7
seenarabic;0633
seenfinalarabic;FEB2
seeninitialarabic;FEB3
seenmedialarabic;FEB4
segol;05B6
segol13;05B6
segol1f;05B6
segol2c;05B6
segolhebrew;05B6
segolnarrowhebrew;05B6
segolquarterhebrew;05B6
segoltahebrew;0592
segolwidehebrew;05B6
seharmenian;057D
sehiragana;305B
sekatakana;30BB
sekatakanahalfwidth;FF7E
semicolon;003B
semicolonarabic;061B
semicolonmonospace;FF1B
semicolonsmall;FE54
semivoicedmarkkana;309C
semivoicedmarkkanahalfwidth;FF9F
sentisquare;3322
sentosquare;3323
seven;0037
sevenarabic;0667
sevenbengali;09ED
sevencircle;2466
sevencircleinversesansserif;2790
sevendeva;096D
seveneighths;215E
sevengujarati;0AED
sevengurmukhi;0A6D
sevenhackarabic;0667
sevenhangzhou;3027
sevenideographicparen;3226
seveninferior;2087
sevenmonospace;FF17
sevenoldstyle;F737
sevenparen;247A
sevenperiod;248E
sevenpersian;06F7
sevenroman;2176
sevensuperior;2077
seventeencircle;2470
seventeenparen;2484
seventeenperiod;2498
seventhai;0E57
sfthyphen;00AD
shaarmenian;0577
shabengali;09B6
shacyrillic;0448
shaddaarabic;0651
shaddadammaarabic;FC61
shaddadammatanarabic;FC5E
shaddafathaarabic;FC60
shaddafathatanarabic;0651 064B
shaddakasraarabic;FC62
shaddakasratanarabic;FC5F
shade;2592
shadedark;2593
shadelight;2591
shademedium;2592
shadeva;0936
shagujarati;0AB6
shagurmukhi;0A36
shalshelethebrew;0593
shbopomofo;3115
shchacyrillic;0449
sheenarabic;0634
sheenfinalarabic;FEB6
sheeninitialarabic;FEB7
sheenmedialarabic;FEB8
sheicoptic;03E3
sheqel;20AA
sheqelhebrew;20AA
sheva;05B0
sheva115;05B0
sheva15;05B0
sheva22;05B0
sheva2e;05B0
shevahebrew;05B0
shevanarrowhebrew;05B0
shevaquarterhebrew;05B0
shevawidehebrew;05B0
shhacyrillic;04BB
shimacoptic;03ED
shin;05E9
shindagesh;FB49
shindageshhebrew;FB49
shindageshshindot;FB2C
shindageshshindothebrew;FB2C
shindageshsindot;FB2D
shindageshsindothebrew;FB2D
shindothebrew;05C1
shinhebrew;05E9
shinshindot;FB2A
shinshindothebrew;FB2A
shinsindot;FB2B
shinsindothebrew;FB2B
shook;0282
sigma;03C3
sigma1;03C2
sigmafinal;03C2
sigmalunatesymbolgreek;03F2
sihiragana;3057
sikatakana;30B7
sikatakanahalfwidth;FF7C
siluqhebrew;05BD
siluqlefthebrew;05BD
similar;223C
sindothebrew;05C2
siosacirclekorean;3274
siosaparenkorean;3214
sioscieuckorean;317E
sioscirclekorean;3266
sioskiyeokkorean;317A
sioskorean;3145
siosnieunkorean;317B
siosparenkorean;3206
siospieupkorean;317D
siostikeutkorean;317C
six;0036
sixarabic;0666
sixbengali;09EC
sixcircle;2465
sixcircleinversesansserif;278F
sixdeva;096C
sixgujarati;0AEC
sixgurmukhi;0A6C
sixhackarabic;0666
sixhangzhou;3026
sixideographicparen;3225
sixinferior;2086
sixmonospace;FF16
sixoldstyle;F736
sixparen;2479
sixperiod;248D
sixpersian;06F6
sixroman;2175
sixsuperior;2076
sixteencircle;246F
sixteencurrencydenominatorbengali;09F9
sixteenparen;2483
sixteenperiod;2497
sixthai;0E56
slash;002F
slashmonospace;FF0F
slong;017F
slongdotaccent;1E9B
smileface;263A
smonospace;FF53
sofpasuqhebrew;05C3
softhyphen;00AD
softsigncyrillic;044C
sohiragana;305D
sokatakana;30BD
sokatakanahalfwidth;FF7F
soliduslongoverlaycmb;0338
solidusshortoverlaycmb;0337
sorusithai;0E29
sosalathai;0E28
sosothai;0E0B
sosuathai;0E2A
space;0020
spacehackarabic;0020
spade;2660
spadesuitblack;2660
spadesuitwhite;2664
sparen;24AE
squarebelowcmb;033B
squarecc;33C4
squarecm;339D
squarediagonalcrosshatchfill;25A9
squarehorizontalfill;25A4
squarekg;338F
squarekm;339E
squarekmcapital;33CE
squareln;33D1
squarelog;33D2
squaremg;338E
squaremil;33D5
squaremm;339C
squaremsquared;33A1
squareorthogonalcrosshatchfill;25A6
squareupperlefttolowerrightfill;25A7
squareupperrighttolowerleftfill;25A8
squareverticalfill;25A5
squarewhitewithsmallblack;25A3
srsquare;33DB
ssabengali;09B7
ssadeva;0937
ssagujarati;0AB7
ssangcieuckorean;3149
ssanghieuhkorean;3185
ssangieungkorean;3180
ssangkiyeokkorean;3132
ssangnieunkorean;3165
ssangpieupkorean;3143
ssangsioskorean;3146
ssangtikeutkorean;3138
ssuperior;F6F2
sterling;00A3
sterlingmonospace;FFE1
strokelongoverlaycmb;0336
strokeshortoverlaycmb;0335
subset;2282
subsetnotequal;228A
subsetorequal;2286
succeeds;227B
suchthat;220B
suhiragana;3059
sukatakana;30B9
sukatakanahalfwidth;FF7D
sukunarabic;0652
summation;2211
sun;263C
superset;2283
supersetnotequal;228B
supersetorequal;2287
svsquare;33DC
syouwaerasquare;337C
t;0074
tabengali;09A4
tackdown;22A4
tackleft;22A3
tadeva;0924
tagujarati;0AA4
tagurmukhi;0A24
taharabic;0637
tahfinalarabic;FEC2
tahinitialarabic;FEC3
tahiragana;305F
tahmedialarabic;FEC4
taisyouerasquare;337D
takatakana;30BF
takatakanahalfwidth;FF80
tatweelarabic;0640
tau;03C4
tav;05EA
tavdages;FB4A
tavdagesh;FB4A
tavdageshhebrew;FB4A
tavhebrew;05EA
tbar;0167
tbopomofo;310A
tcaron;0165
tccurl;02A8
tcedilla;0163
tcheharabic;0686
tchehfinalarabic;FB7B
tchehinitialarabic;FB7C
tchehmedialarabic;FB7D
tchehmeeminitialarabic;FB7C FEE4
tcircle;24E3
tcircumflexbelow;1E71
tcommaaccent;0163
tdieresis;1E97
tdotaccent;1E6B
tdotbelow;1E6D
tecyrillic;0442
tedescendercyrillic;04AD
teharabic;062A
tehfinalarabic;FE96
tehhahinitialarabic;FCA2
tehhahisolatedarabic;FC0C
tehinitialarabic;FE97
tehiragana;3066
tehjeeminitialarabic;FCA1
tehjeemisolatedarabic;FC0B
tehmarbutaarabic;0629
tehmarbutafinalarabic;FE94
tehmedialarabic;FE98
tehmeeminitialarabic;FCA4
tehmeemisolatedarabic;FC0E
tehnoonfinalarabic;FC73
tekatakana;30C6
tekatakanahalfwidth;FF83
telephone;2121
telephoneblack;260E
telishagedolahebrew;05A0
telishaqetanahebrew;05A9
tencircle;2469
tenideographicparen;3229
tenparen;247D
tenperiod;2491
tenroman;2179
tesh;02A7
tet;05D8
tetdagesh;FB38
tetdageshhebrew;FB38
tethebrew;05D8
tetsecyrillic;04B5
tevirhebrew;059B
tevirlefthebrew;059B
thabengali;09A5
thadeva;0925
thagujarati;0AA5
thagurmukhi;0A25
thalarabic;0630
thalfinalarabic;FEAC
thanthakhatlowleftthai;F898
thanthakhatlowrightthai;F897
thanthakhatthai;0E4C
thanthakhatupperleftthai;F896
theharabic;062B
thehfinalarabic;FE9A
thehinitialarabic;FE9B
thehmedialarabic;FE9C
thereexists;2203
therefore;2234
theta;03B8
theta1;03D1
thetasymbolgreek;03D1
thieuthacirclekorean;3279
thieuthaparenkorean;3219
thieuthcirclekorean;326B
thieuthkorean;314C
thieuthparenkorean;320B
thirteencircle;246C
thirteenparen;2480
thirteenperiod;2494
thonangmonthothai;0E11
thook;01AD
thophuthaothai;0E12
thorn;00FE
thothahanthai;0E17
thothanthai;0E10
thothongthai;0E18
thothungthai;0E16
thousandcyrillic;0482
thousandsseparatorarabic;066C
thousandsseparatorpersian;066C
three;0033
threearabic;0663
threebengali;09E9
threecircle;2462
threecircleinversesansserif;278C
threedeva;0969
threeeighths;215C
threegujarati;0AE9
threegurmukhi;0A69
threehackarabic;0663
threehangzhou;3023
threeideographicparen;3222
threeinferior;2083
threemonospace;FF13
threenumeratorbengali;09F6
threeoldstyle;F733
threeparen;2476
threeperiod;248A
threepersian;06F3
threequarters;00BE
threequartersemdash;F6DE
threeroman;2172
threesuperior;00B3
threethai;0E53
thzsquare;3394
tihiragana;3061
tikatakana;30C1
tikatakanahalfwidth;FF81
tikeutacirclekorean;3270
tikeutaparenkorean;3210
tikeutcirclekorean;3262
tikeutkorean;3137
tikeutparenkorean;3202
tilde;02DC
tildebelowcmb;0330
tildecmb;0303
tildecomb;0303
tildedoublecmb;0360
tildeoperator;223C
tildeoverlaycmb;0334
tildeverticalcmb;033E
timescircle;2297
tipehahebrew;0596
tipehalefthebrew;0596
tippigurmukhi;0A70
titlocyrilliccmb;0483
tiwnarmenian;057F
tlinebelow;1E6F
tmonospace;FF54
toarmenian;0569
tohiragana;3068
tokatakana;30C8
tokatakanahalfwidth;FF84
tonebarextrahighmod;02E5
tonebarextralowmod;02E9
tonebarhighmod;02E6
tonebarlowmod;02E8
tonebarmidmod;02E7
tonefive;01BD
tonesix;0185
tonetwo;01A8
tonos;0384
tonsquare;3327
topatakthai;0E0F
tortoiseshellbracketleft;3014
tortoiseshellbracketleftsmall;FE5D
tortoiseshellbracketleftvertical;FE39
tortoiseshellbracketright;3015
tortoiseshellbracketrightsmall;FE5E
tortoiseshellbracketrightvertical;FE3A
totaothai;0E15
tpalatalhook;01AB
tparen;24AF
trademark;2122
trademarksans;F8EA
trademarkserif;F6DB
tretroflexhook;0288
triagdn;25BC
triaglf;25C4
triagrt;25BA
triagup;25B2
ts;02A6
tsadi;05E6
tsadidagesh;FB46
tsadidageshhebrew;FB46
tsadihebrew;05E6
tsecyrillic;0446
tsere;05B5
tsere12;05B5
tsere1e;05B5
tsere2b;05B5
tserehebrew;05B5
tserenarrowhebrew;05B5
tserequarterhebrew;05B5
tserewidehebrew;05B5
tshecyrillic;045B
tsuperior;F6F3
ttabengali;099F
ttadeva;091F
ttagujarati;0A9F
ttagurmukhi;0A1F
tteharabic;0679
ttehfinalarabic;FB67
ttehinitialarabic;FB68
ttehmedialarabic;FB69
tthabengali;09A0
tthadeva;0920
tthagujarati;0AA0
tthagurmukhi;0A20
tturned;0287
tuhiragana;3064
tukatakana;30C4
tukatakanahalfwidth;FF82
tusmallhiragana;3063
tusmallkatakana;30C3
tusmallkatakanahalfwidth;FF6F
twelvecircle;246B
twelveparen;247F
twelveperiod;2493
twelveroman;217B
twentycircle;2473
twentyhangzhou;5344
twentyparen;2487
twentyperiod;249B
two;0032
twoarabic;0662
twobengali;09E8
twocircle;2461
twocircleinversesansserif;278B
twodeva;0968
twodotenleader;2025
twodotleader;2025
twodotleadervertical;FE30
twogujarati;0AE8
twogurmukhi;0A68
twohackarabic;0662
twohangzhou;3022
twoideographicparen;3221
twoinferior;2082
twomonospace;FF12
twonumeratorbengali;09F5
twooldstyle;F732
twoparen;2475
twoperiod;2489
twopersian;06F2
tworoman;2171
twostroke;01BB
twosuperior;00B2
twothai;0E52
twothirds;2154
u;0075
uacute;00FA
ubar;0289
ubengali;0989
ubopomofo;3128
ubreve;016D
ucaron;01D4
ucircle;24E4
ucircumflex;00FB
ucircumflexbelow;1E77
ucyrillic;0443
udattadeva;0951
udblacute;0171
udblgrave;0215
udeva;0909
udieresis;00FC
udieresisacute;01D8
udieresisbelow;1E73
udieresiscaron;01DA
udieresiscyrillic;04F1
udieresisgrave;01DC
udieresismacron;01D6
udotbelow;1EE5
ugrave;00F9
ugujarati;0A89
ugurmukhi;0A09
uhiragana;3046
uhookabove;1EE7
uhorn;01B0
uhornacute;1EE9
uhorndotbelow;1EF1
uhorngrave;1EEB
uhornhookabove;1EED
uhorntilde;1EEF
uhungarumlaut;0171
uhungarumlautcyrillic;04F3
uinvertedbreve;0217
ukatakana;30A6
ukatakanahalfwidth;FF73
ukcyrillic;0479
ukorean;315C
umacron;016B
umacroncyrillic;04EF
umacrondieresis;1E7B
umatragurmukhi;0A41
umonospace;FF55
underscore;005F
underscoredbl;2017
underscoremonospace;FF3F
underscorevertical;FE33
underscorewavy;FE4F
union;222A
universal;2200
uogonek;0173
uparen;24B0
upblock;2580
upperdothebrew;05C4
upsilon;03C5
upsilondieresis;03CB
upsilondieresistonos;03B0
upsilonlatin;028A
upsilontonos;03CD
uptackbelowcmb;031D
uptackmod;02D4
uragurmukhi;0A73
uring;016F
ushortcyrillic;045E
usmallhiragana;3045
usmallkatakana;30A5
usmallkatakanahalfwidth;FF69
ustraightcyrillic;04AF
ustraightstrokecyrillic;04B1
utilde;0169
utildeacute;1E79
utildebelow;1E75
uubengali;098A
uudeva;090A
uugujarati;0A8A
uugurmukhi;0A0A
uumatragurmukhi;0A42
uuvowelsignbengali;09C2
uuvowelsigndeva;0942
uuvowelsigngujarati;0AC2
uvowelsignbengali;09C1
uvowelsigndeva;0941
uvowelsigngujarati;0AC1
v;0076
vadeva;0935
vagujarati;0AB5
vagurmukhi;0A35
vakatakana;30F7
vav;05D5
vavdagesh;FB35
vavdagesh65;FB35
vavdageshhebrew;FB35
vavhebrew;05D5
vavholam;FB4B
vavholamhebrew;FB4B
vavvavhebrew;05F0
vavyodhebrew;05F1
vcircle;24E5
vdotbelow;1E7F
vecyrillic;0432
veharabic;06A4
vehfinalarabic;FB6B
vehinitialarabic;FB6C
vehmedialarabic;FB6D
vekatakana;30F9
venus;2640
verticalbar;007C
verticallineabovecmb;030D
verticallinebelowcmb;0329
verticallinelowmod;02CC
verticallinemod;02C8
vewarmenian;057E
vhook;028B
vikatakana;30F8
viramabengali;09CD
viramadeva;094D
viramagujarati;0ACD
visargabengali;0983
visargadeva;0903
visargagujarati;0A83
vmonospace;FF56
voarmenian;0578
voicediterationhiragana;309E
voicediterationkatakana;30FE
voicedmarkkana;309B
voicedmarkkanahalfwidth;FF9E
vokatakana;30FA
vparen;24B1
vtilde;1E7D
vturned;028C
vuhiragana;3094
vukatakana;30F4
w;0077
wacute;1E83
waekorean;3159
wahiragana;308F
wakatakana;30EF
wakatakanahalfwidth;FF9C
wakorean;3158
wasmallhiragana;308E
wasmallkatakana;30EE
wattosquare;3357
wavedash;301C
wavyunderscorevertical;FE34
wawarabic;0648
wawfinalarabic;FEEE
wawhamzaabovearabic;0624
wawhamzaabovefinalarabic;FE86
wbsquare;33DD
wcircle;24E6
wcircumflex;0175
wdieresis;1E85
wdotaccent;1E87
wdotbelow;1E89
wehiragana;3091
weierstrass;2118
wekatakana;30F1
wekorean;315E
weokorean;315D
wgrave;1E81
whitebullet;25E6
whitecircle;25CB
whitecircleinverse;25D9
whitecornerbracketleft;300E
whitecornerbracketleftvertical;FE43
whitecornerbracketright;300F
whitecornerbracketrightvertical;FE44
whitediamond;25C7
whitediamondcontainingblacksmalldiamond;25C8
whitedownpointingsmalltriangle;25BF
whitedownpointingtriangle;25BD
whiteleftpointingsmalltriangle;25C3
whiteleftpointingtriangle;25C1
whitelenticularbracketleft;3016
whitelenticularbracketright;3017
whiterightpointingsmalltriangle;25B9
whiterightpointingtriangle;25B7
whitesmallsquare;25AB
whitesmilingface;263A
whitesquare;25A1
whitestar;2606
whitetelephone;260F
whitetortoiseshellbracketleft;3018
whitetortoiseshellbracketright;3019
whiteuppointingsmalltriangle;25B5
whiteuppointingtriangle;25B3
wihiragana;3090
wikatakana;30F0
wikorean;315F
wmonospace;FF57
wohiragana;3092
wokatakana;30F2
wokatakanahalfwidth;FF66
won;20A9
wonmonospace;FFE6
wowaenthai;0E27
wparen;24B2
wring;1E98
wsuperior;02B7
wturned;028D
wynn;01BF
x;0078
xabovecmb;033D
xbopomofo;3112
xcircle;24E7
xdieresis;1E8D
xdotaccent;1E8B
xeharmenian;056D
xi;03BE
xmonospace;FF58
xparen;24B3
xsuperior;02E3
y;0079
yaadosquare;334E
yabengali;09AF
yacute;00FD
yadeva;092F
yaekorean;3152
yagujarati;0AAF
yagurmukhi;0A2F
yahiragana;3084
yakatakana;30E4
yakatakanahalfwidth;FF94
yakorean;3151
yamakkanthai;0E4E
yasmallhiragana;3083
yasmallkatakana;30E3
yasmallkatakanahalfwidth;FF6C
yatcyrillic;0463
ycircle;24E8
ycircumflex;0177
ydieresis;00FF
ydotaccent;1E8F
ydotbelow;1EF5
yeharabic;064A
yehbarreearabic;06D2
yehbarreefinalarabic;FBAF
yehfinalarabic;FEF2
yehhamzaabovearabic;0626
yehhamzaabovefinalarabic;FE8A
yehhamzaaboveinitialarabic;FE8B
yehhamzaabovemedialarabic;FE8C
yehinitialarabic;FEF3
yehmedialarabic;FEF4
yehmeeminitialarabic;FCDD
yehmeemisolatedarabic;FC58
yehnoonfinalarabic;FC94
yehthreedotsbelowarabic;06D1
yekorean;3156
yen;00A5
yenmonospace;FFE5
yeokorean;3155
yeorinhieuhkorean;3186
yerahbenyomohebrew;05AA
yerahbenyomolefthebrew;05AA
yericyrillic;044B
yerudieresiscyrillic;04F9
yesieungkorean;3181
yesieungpansioskorean;3183
yesieungsioskorean;3182
yetivhebrew;059A
ygrave;1EF3
yhook;01B4
yhookabove;1EF7
yiarmenian;0575
yicyrillic;0457
yikorean;3162
yinyang;262F
yiwnarmenian;0582
ymonospace;FF59
yod;05D9
yoddagesh;FB39
yoddageshhebrew;FB39
yodhebrew;05D9
yodyodhebrew;05F2
yodyodpatahhebrew;FB1F
yohiragana;3088
yoikorean;3189
yokatakana;30E8
yokatakanahalfwidth;FF96
yokorean;315B
yosmallhiragana;3087
yosmallkatakana;30E7
yosmallkatakanahalfwidth;FF6E
yotgreek;03F3
yoyaekorean;3188
yoyakorean;3187
yoyakthai;0E22
yoyingthai;0E0D
yparen;24B4
ypogegrammeni;037A
ypogegrammenigreekcmb;0345
yr;01A6
yring;1E99
ysuperior;02B8
ytilde;1EF9
yturned;028E
yuhiragana;3086
yuikorean;318C
yukatakana;30E6
yukatakanahalfwidth;FF95
yukorean;3160
yusbigcyrillic;046B
yusbigiotifiedcyrillic;046D
yuslittlecyrillic;0467
yuslittleiotifiedcyrillic;0469
yusmallhiragana;3085
yusmallkatakana;30E5
yusmallkatakanahalfwidth;FF6D
yuyekorean;318B
yuyeokorean;318A
yyabengali;09DF
yyadeva;095F
z;007A
zaarmenian;0566
zacute;017A
zadeva;095B
zagurmukhi;0A5B
zaharabic;0638
zahfinalarabic;FEC6
zahinitialarabic;FEC7
zahiragana;3056
zahmedialarabic;FEC8
zainarabic;0632
zainfinalarabic;FEB0
zakatakana;30B6
zaqefgadolhebrew;0595
zaqefqatanhebrew;0594
zarqahebrew;0598
zayin;05D6
zayindagesh;FB36
zayindageshhebrew;FB36
zayinhebrew;05D6
zbopomofo;3117
zcaron;017E
zcircle;24E9
zcircumflex;1E91
zcurl;0291
zdot;017C
zdotaccent;017C
zdotbelow;1E93
zecyrillic;0437
zedescendercyrillic;0499
zedieresiscyrillic;04DF
zehiragana;305C
zekatakana;30BC
zero;0030
zeroarabic;0660
zerobengali;09E6
zerodeva;0966
zerogujarati;0AE6
zerogurmukhi;0A66
zerohackarabic;0660
zeroinferior;2080
zeromonospace;FF10
zerooldstyle;F730
zeropersian;06F0
zerosuperior;2070
zerothai;0E50
zerowidthjoiner;FEFF
zerowidthnonjoiner;200C
zerowidthspace;200B
zeta;03B6
zhbopomofo;3113
zhearmenian;056A
zhebrevecyrillic;04C2
zhecyrillic;0436
zhedescendercyrillic;0497
zhedieresiscyrillic;04DD
zihiragana;3058
zikatakana;30B8
zinorhebrew;05AE
zlinebelow;1E95
zmonospace;FF5A
zohiragana;305E
zokatakana;30BE
zparen;24B5
zretroflexhook;0290
zstroke;01B6
zuhiragana;305A
zukatakana;30BA
a100;275E
a101;2761
a102;2762
a103;2763
a104;2764
a105;2710
a106;2765
a107;2766
a108;2767
a109;2660
a10;2721
a110;2665
a111;2666
a112;2663
a117;2709
a118;2708
a119;2707
a11;261B
a120;2460
a121;2461
a122;2462
a123;2463
a124;2464
a125;2465
a126;2466
a127;2467
a128;2468
a129;2469
a12;261E
a130;2776
a131;2777
a132;2778
a133;2779
a134;277A
a135;277B
a136;277C
a137;277D
a138;277E
a139;277F
a13;270C
a140;2780
a141;2781
a142;2782
a143;2783
a144;2784
a145;2785
a146;2786
a147;2787
a148;2788
a149;2789
a14;270D
a150;278A
a151;278B
a152;278C
a153;278D
a154;278E
a155;278F
a156;2790
a157;2791
a158;2792
a159;2793
a15;270E
a160;2794
a161;2192
a162;27A3
a163;2194
a164;2195
a165;2799
a166;279B
a167;279C
a168;279D
a169;279E
a16;270F
a170;279F
a171;27A0
a172;27A1
a173;27A2
a174;27A4
a175;27A5
a176;27A6
a177;27A7
a178;27A8
a179;27A9
a17;2711
a180;27AB
a181;27AD
a182;27AF
a183;27B2
a184;27B3
a185;27B5
a186;27B8
a187;27BA
a188;27BB
a189;27BC
a18;2712
a190;27BD
a191;27BE
a192;279A
a193;27AA
a194;27B6
a195;27B9
a196;2798
a197;27B4
a198;27B7
a199;27AC
a19;2713
a1;2701
a200;27AE
a201;27B1
a202;2703
a203;2750
a204;2752
a205;276E
a206;2770
a20;2714
a21;2715
a22;2716
a23;2717
a24;2718
a25;2719
a26;271A
a27;271B
a28;271C
a29;2722
a2;2702
a30;2723
a31;2724
a32;2725
a33;2726
a34;2727
a35;2605
a36;2729
a37;272A
a38;272B
a39;272C
a3;2704
a40;272D
a41;272E
a42;272F
a43;2730
a44;2731
a45;2732
a46;2733
a47;2734
a48;2735
a49;2736
a4;260E
a50;2737
a51;2738
a52;2739
a53;273A
a54;273B
a55;273C
a56;273D
a57;273E
a58;273F
a59;2740
a5;2706
a60;2741
a61;2742
a62;2743
a63;2744
a64;2745
a65;2746
a66;2747
a67;2748
a68;2749
a69;274A
a6;271D
a70;274B
a71;25CF
a72;274D
a73;25A0
a74;274F
a75;2751
a76;25B2
a77;25BC
a78;25C6
a79;2756
a7;271E
a81;25D7
a82;2758
a83;2759
a84;275A
a85;276F
a86;2771
a87;2772
a88;2773
a89;2768
a8;271F
a90;2769
a91;276C
a92;276D
a93;276A
a94;276B
a95;2774
a96;2775
a97;275B
a98;275C
a99;275D
a9;2720
"""
# string table management
#
class StringTable:
def __init__( self, name_list, master_table_name ):
self.names = name_list
self.master_table = master_table_name
self.indices = {}
index = 0
for name in name_list:
self.indices[name] = index
index += len( name ) + 1
self.total = index
def dump( self, file ):
write = file.write
write( "#ifndef DEFINE_PS_TABLES\n" )
write( "#ifdef __cplusplus\n" )
write( ' extern "C"\n' )
write( "#else\n" )
write( " extern\n" )
write( "#endif\n" )
write( "#endif\n" )
write( " const char " + self.master_table +
"[" + repr( self.total ) + "]\n" )
write( "#ifdef DEFINE_PS_TABLES\n" )
write( " =\n" )
write( " {\n" )
line = ""
for name in self.names:
line += " '"
line += string.join( ( re.findall( ".", name ) ), "','" )
line += "', 0,\n"
write( line )
write( " }\n" )
write( "#endif /* DEFINE_PS_TABLES */\n" )
write( " ;\n\n\n" )
def dump_sublist( self, file, table_name, macro_name, sublist ):
write = file.write
write( "#define " + macro_name + " " + repr( len( sublist ) ) + "\n\n" )
write( " /* Values are offsets into the `" +
self.master_table + "' table */\n\n" )
write( "#ifndef DEFINE_PS_TABLES\n" )
write( "#ifdef __cplusplus\n" )
write( ' extern "C"\n' )
write( "#else\n" )
write( " extern\n" )
write( "#endif\n" )
write( "#endif\n" )
write( " const short " + table_name +
"[" + macro_name + "]\n" )
write( "#ifdef DEFINE_PS_TABLES\n" )
write( " =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for name in sublist:
line += comma
line += "%4d" % self.indices[name]
col += 1
comma = ","
if col == 14:
col = 0
comma = ",\n "
write( line )
write( "\n" )
write( " }\n" )
write( "#endif /* DEFINE_PS_TABLES */\n" )
write( " ;\n\n\n" )
# We now store the Adobe Glyph List in compressed form. The list is put
# into a data structure called `trie' (because it has a tree-like
# appearance). Consider, for example, that you want to store the
# following name mapping:
#
# A => 1
# Aacute => 6
# Abalon => 2
# Abstract => 4
#
# It is possible to store the entries as follows.
#
# A => 1
# |
# +-acute => 6
# |
# +-b
# |
# +-alon => 2
# |
# +-stract => 4
#
# We see that each node in the trie has:
#
# - one or more `letters'
# - an optional value
# - zero or more child nodes
#
# The first step is to call
#
# root = StringNode( "", 0 )
# for word in map.values():
# root.add( word, map[word] )
#
# which creates a large trie where each node has only one children.
#
# Executing
#
# root = root.optimize()
#
# optimizes the trie by merging the letters of successive nodes whenever
# possible.
#
# Each node of the trie is stored as follows.
#
# - First the node's letter, according to the following scheme. We
# use the fact that in the AGL no name contains character codes > 127.
#
# name bitsize description
# ----------------------------------------------------------------
# notlast 1 Set to 1 if this is not the last letter
# in the word.
# ascii 7 The letter's ASCII value.
#
# - The letter is followed by a children count and the value of the
# current key (if any). Again we can do some optimization because all
# AGL entries are from the BMP; this means that 16 bits are sufficient
# to store its Unicode values. Additionally, no node has more than
# 127 children.
#
# name bitsize description
# -----------------------------------------
# hasvalue 1 Set to 1 if a 16-bit Unicode value follows.
# num_children 7 Number of children. Can be 0 only if
# `hasvalue' is set to 1.
# value 16 Optional Unicode value.
#
# - A node is finished by a list of 16bit absolute offsets to the
# children, which must be sorted in increasing order of their first
# letter.
#
# For simplicity, all 16bit quantities are stored in big-endian order.
#
# The root node has first letter = 0, and no value.
#
class StringNode:
def __init__( self, letter, value ):
self.letter = letter
self.value = value
self.children = {}
def __cmp__( self, other ):
return ord( self.letter[0] ) - ord( other.letter[0] )
def add( self, word, value ):
if len( word ) == 0:
self.value = value
return
letter = word[0]
word = word[1:]
if self.children.has_key( letter ):
child = self.children[letter]
else:
child = StringNode( letter, 0 )
self.children[letter] = child
child.add( word, value )
def optimize( self ):
# optimize all children first
children = self.children.values()
self.children = {}
for child in children:
self.children[child.letter[0]] = child.optimize()
# don't optimize if there's a value,
# if we don't have any child or if we
# have more than one child
if ( self.value != 0 ) or ( not children ) or len( children ) > 1:
return self
child = children[0]
self.letter += child.letter
self.value = child.value
self.children = child.children
return self
def dump_debug( self, write, margin ):
# this is used during debugging
line = margin + "+-"
if len( self.letter ) == 0:
line += "<NOLETTER>"
else:
line += self.letter
if self.value:
line += " => " + repr( self.value )
write( line + "\n" )
if self.children:
margin += "| "
for child in self.children.values():
child.dump_debug( write, margin )
def locate( self, index ):
self.index = index
if len( self.letter ) > 0:
index += len( self.letter ) + 1
else:
index += 2
if self.value != 0:
index += 2
children = self.children.values()
children.sort()
index += 2 * len( children )
for child in children:
index = child.locate( index )
return index
def store( self, storage ):
# write the letters
l = len( self.letter )
if l == 0:
storage += struct.pack( "B", 0 )
else:
for n in range( l ):
val = ord( self.letter[n] )
if n < l - 1:
val += 128
storage += struct.pack( "B", val )
# write the count
children = self.children.values()
children.sort()
count = len( children )
if self.value != 0:
storage += struct.pack( "!BH", count + 128, self.value )
else:
storage += struct.pack( "B", count )
for child in children:
storage += struct.pack( "!H", child.index )
for child in children:
storage = child.store( storage )
return storage
def adobe_glyph_values():
"""return the list of glyph names and their unicode values"""
lines = string.split( adobe_glyph_list, '\n' )
glyphs = []
values = []
for line in lines:
if line:
fields = string.split( line, ';' )
# print fields[1] + ' - ' + fields[0]
subfields = string.split( fields[1], ' ' )
if len( subfields ) == 1:
glyphs.append( fields[0] )
values.append( fields[1] )
return glyphs, values
def filter_glyph_names( alist, filter ):
"""filter `alist' by taking _out_ all glyph names that are in `filter'"""
count = 0
extras = []
for name in alist:
try:
filtered_index = filter.index( name )
except:
extras.append( name )
return extras
def dump_encoding( file, encoding_name, encoding_list ):
"""dump a given encoding"""
write = file.write
write( " /* the following are indices into the SID name table */\n" )
write( "#ifndef DEFINE_PS_TABLES\n" )
write( "#ifdef __cplusplus\n" )
write( ' extern "C"\n' )
write( "#else\n" )
write( " extern\n" )
write( "#endif\n" )
write( "#endif\n" )
write( " const unsigned short " + encoding_name +
"[" + repr( len( encoding_list ) ) + "]\n" )
write( "#ifdef DEFINE_PS_TABLES\n" )
write( " =\n" )
write( " {\n" )
line = " "
comma = ""
col = 0
for value in encoding_list:
line += comma
line += "%3d" % value
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
write( line )
write( "\n" )
write( " }\n" )
write( "#endif /* DEFINE_PS_TABLES */\n" )
write( " ;\n\n\n" )
def dump_array( the_array, write, array_name ):
"""dumps a given encoding"""
write( "#ifndef DEFINE_PS_TABLES\n" )
write( "#ifdef __cplusplus\n" )
write( ' extern "C"\n' )
write( "#else\n" )
write( " extern\n" )
write( "#endif\n" )
write( "#endif\n" )
write( " const unsigned char " + array_name +
"[" + repr( len( the_array ) ) + "L]\n" )
write( "#ifdef DEFINE_PS_TABLES\n" )
write( " =\n" )
write( " {\n" )
line = ""
comma = " "
col = 0
for value in the_array:
line += comma
line += "%3d" % ord( value )
comma = ","
col += 1
if col == 16:
col = 0
comma = ",\n "
if len( line ) > 1024:
write( line )
line = ""
write( line )
write( "\n" )
write( " }\n" )
write( "#endif /* DEFINE_PS_TABLES */\n" )
write( " ;\n\n\n" )
def main():
"""main program body"""
if len( sys.argv ) != 2:
print __doc__ % sys.argv[0]
sys.exit( 1 )
file = open( sys.argv[1], "w\n" )
write = file.write
count_sid = len( sid_standard_names )
# `mac_extras' contains the list of glyph names in the Macintosh standard
# encoding which are not in the SID Standard Names.
#
mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names )
# `base_list' contains the names of our final glyph names table.
# It consists of the `mac_extras' glyph names, followed by the SID
# standard names.
#
mac_extras_count = len( mac_extras )
base_list = mac_extras + sid_standard_names
write( "/***************************************************************************/\n" )
write( "/* */\n" )
write( "/* %-71s*/\n" % os.path.basename( sys.argv[1] ) )
write( "/* */\n" )
write( "/* PostScript glyph names. */\n" )
write( "/* */\n" )
write( "/* Copyright 2005-2017 by */\n" )
write( "/* David Turner, Robert Wilhelm, and Werner Lemberg. */\n" )
write( "/* */\n" )
write( "/* This file is part of the FreeType project, and may only be used, */\n" )
write( "/* modified, and distributed under the terms of the FreeType project */\n" )
write( "/* license, LICENSE.TXT. By continuing to use, modify, or distribute */\n" )
write( "/* this file you indicate that you have read the license and */\n" )
write( "/* understand and accept it fully. */\n" )
write( "/* */\n" )
write( "/***************************************************************************/\n" )
write( "\n" )
write( "\n" )
write( " /* This file has been generated automatically -- do not edit! */\n" )
write( "\n" )
write( "\n" )
# dump final glyph list (mac extras + sid standard names)
#
st = StringTable( base_list, "ft_standard_glyph_names" )
st.dump( file )
st.dump_sublist( file, "ft_mac_names",
"FT_NUM_MAC_NAMES", mac_standard_names )
st.dump_sublist( file, "ft_sid_names",
"FT_NUM_SID_NAMES", sid_standard_names )
dump_encoding( file, "t1_standard_encoding", t1_standard_encoding )
dump_encoding( file, "t1_expert_encoding", t1_expert_encoding )
# dump the AGL in its compressed form
#
agl_glyphs, agl_values = adobe_glyph_values()
dict = StringNode( "", 0 )
for g in range( len( agl_glyphs ) ):
dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) )
dict = dict.optimize()
dict_len = dict.locate( 0 )
dict_array = dict.store( "" )
write( """\
/*
* This table is a compressed version of the Adobe Glyph List (AGL),
* optimized for efficient searching. It has been generated by the
* `glnames.py' python script located in the `src/tools' directory.
*
* The lookup function to get the Unicode value for a given string
* is defined below the table.
*/
#ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST
""" )
dump_array( dict_array, write, "ft_adobe_glyph_list" )
# write the lookup routine now
#
write( """\
#ifdef DEFINE_PS_TABLES
/*
* This function searches the compressed table efficiently.
*/
static unsigned long
ft_get_adobe_glyph_index( const char* name,
const char* limit )
{
int c = 0;
int count, min, max;
const unsigned char* p = ft_adobe_glyph_list;
if ( name == 0 || name >= limit )
goto NotFound;
c = *name++;
count = p[1];
p += 2;
min = 0;
max = count;
while ( min < max )
{
int mid = ( min + max ) >> 1;
const unsigned char* q = p + mid * 2;
int c2;
q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] );
c2 = q[0] & 127;
if ( c2 == c )
{
p = q;
goto Found;
}
if ( c2 < c )
min = mid + 1;
else
max = mid;
}
goto NotFound;
Found:
for (;;)
{
/* assert (*p & 127) == c */
if ( name >= limit )
{
if ( (p[0] & 128) == 0 &&
(p[1] & 128) != 0 )
return (unsigned long)( ( (int)p[2] << 8 ) | p[3] );
goto NotFound;
}
c = *name++;
if ( p[0] & 128 )
{
p++;
if ( c != (p[0] & 127) )
goto NotFound;
continue;
}
p++;
count = p[0] & 127;
if ( p[0] & 128 )
p += 2;
p++;
for ( ; count > 0; count--, p += 2 )
{
int offset = ( (int)p[0] << 8 ) | p[1];
const unsigned char* q = ft_adobe_glyph_list + offset;
if ( c == ( q[0] & 127 ) )
{
p = q;
goto NextIter;
}
}
goto NotFound;
NextIter:
;
}
NotFound:
return 0;
}
#endif /* DEFINE_PS_TABLES */
#endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */
""" )
if 0: # generate unit test, or don't
#
# now write the unit test to check that everything works OK
#
write( "#ifdef TEST\n\n" )
write( "static const char* const the_names[] = {\n" )
for name in agl_glyphs:
write( ' "' + name + '",\n' )
write( " 0\n};\n" )
write( "static const unsigned long the_values[] = {\n" )
for val in agl_values:
write( ' 0x' + val + ',\n' )
write( " 0\n};\n" )
write( """
#include <stdlib.h>
#include <stdio.h>
int
main( void )
{
int result = 0;
const char* const* names = the_names;
const unsigned long* values = the_values;
for ( ; *names; names++, values++ )
{
const char* name = *names;
unsigned long reference = *values;
unsigned long value;
value = ft_get_adobe_glyph_index( name, name + strlen( name ) );
if ( value != reference )
{
result = 1;
fprintf( stderr, "name '%s' => %04x instead of %04x\\n",
name, value, reference );
}
}
return result;
}
""" )
write( "#endif /* TEST */\n" )
write("\n/* END */\n")
# Now run the main routine
#
main()
# END
| gpl-3.0 | -6,469,612,608,725,052,000 | 18.251625 | 92 | 0.750156 | false |
bbfamily/abu | abupy/WidgetBu/ABuWGBase.py | 1 | 8919 | # -*- encoding:utf-8 -*-
"""股票基本信息图形可视化"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import logging
import ipywidgets as widgets
from abc import ABCMeta, abstractmethod
from IPython.display import display
from ..CoreBu.ABuFixes import six, partial
from ..UtilBu.ABuStrUtil import to_unicode
from ..UtilBu.ABuOsUtil import show_msg
from ..MarketBu.ABuSymbol import search_to_symbol_dict
__author__ = '阿布'
__weixin__ = 'abu_quant'
show_msg_func = logging.info
"""基于不同系统的提示框使用partial包装title以及显示log"""
show_msg_toast_func = partial(show_msg, u'提示', log=True)
def accordion_shut(accordion):
"""由于版本兼容ipython widgets问题,所以需要对折叠内容做不同处理,且需要捕获异常"""
try:
accordion.selected_index = -1
except:
try:
accordion.selected_index = None
except:
pass
# noinspection PyUnresolvedReferences,PyProtectedMember
class WidgetBase(object):
"""界面组件基类,限定最终widget为self.widget"""
def __call__(self):
return self.widget
def display(self):
"""显示使用统一display"""
display(self.widget)
class WidgetFactorBase(six.with_metaclass(ABCMeta, WidgetBase)):
"""策略可视化基础类"""
def __init__(self, wg_manager):
self.wg_manager = wg_manager
self.widget = None
self.label_layout = widgets.Layout(width='300px', align_items='stretch')
self.description_layout = widgets.Layout(height='150px')
self.widget_layout = widgets.Layout(align_items='stretch', justify_content='space-between')
@abstractmethod
def _init_widget(self):
"""子类因子界面设置初始化"""
pass
@abstractmethod
def delegate_class(self):
"""子类因子所委托的具体因子类"""
pass
class WidgetFactorManagerBase(six.with_metaclass(ABCMeta, WidgetBase)):
"""策略管理可视化基础类"""
def __init__(self, show_add_buy=True, add_button_style='default'):
self.factor_dict = {}
self.factor_wg_array = []
# 策略候选池可x轴左右滚动
self.factor_layout = widgets.Layout(overflow_x='scroll',
# flex_direction='row',
display='flex')
self.selected_factors = widgets.SelectMultiple(
options=[],
description=u'已添加策略:',
disabled=False,
layout=widgets.Layout(width='100%', align_items='stretch')
)
# 已添加的全局策略可点击删除
self.selected_factors.observe(self.remove_factor, names='value')
# 全局策略改变通知接收序列
self.selected_factors_obs = set()
self.factor_box = None
# 默认不启动可滚动因子界面,因为对外的widget版本以及os操作系统不统一
self.scroll_factor_box = False
self._sub_children_group_cnt = 3
self.show_add_buy = show_add_buy
self.add_button_style = add_button_style
# 构建具体子类的界面构建
self._init_widget()
if self.factor_box is None:
raise RuntimeError('_init_widget must build factor_box!')
self.widget = widgets.VBox([self.factor_box, self.selected_factors])
def _sub_children(self, children, n_split):
"""将children每n_split个为一组,组装子children_group序列"""
sub_children_cnt = int(len(children) / n_split)
if sub_children_cnt == 0:
sub_children_cnt = 1
group_adjacent = lambda a, k: zip(*([iter(a)] * k))
children_group = list(group_adjacent(children, sub_children_cnt))
residue_ind = -(len(children) % sub_children_cnt) if sub_children_cnt > 0 else 0
if residue_ind < 0:
children_group.append(children[residue_ind:])
return children_group
def register_subscriber(self, observe):
"""注册已选策略池更新通知与BFSubscriberMixin共同作用"""
self.selected_factors_obs.add(observe)
def unregister_subscriber(self, observe):
"""解除注册已选策略池更新通知与BFSubscriberMixin共同作用"""
self.selected_factors_obs.remove(observe)
def notify_subscriber(self):
"""通知已选策略池发生改变的observe"""
for observe in self.selected_factors_obs:
if hasattr(observe, 'notify_subscriber'):
observe.notify_subscriber()
@abstractmethod
def _init_widget(self):
"""子类因子界面设置初始化, 内部需要构建self.factor_box"""
pass
def refresh_factor(self):
"""已选策略池刷新,通知其它更新"""
self.selected_factors.options = list(self.factor_dict.keys())
self.notify_subscriber()
def remove_factor(self, select):
"""点击从策略池中删除已选择的策略"""
for st_key in list(select['new']):
self.factor_dict.pop(st_key)
self.selected_factors.options = list(self.factor_dict.keys())
# 通知其它需要一起更新的界面进行更新
self.notify_subscriber()
def add_factor(self, factor_dict, factor_desc_key, only_one=False):
"""根据具体策略提供的策略字典对象和策略描述构建上层策略序列"""
if factor_desc_key in self.factor_dict:
msg = u'{} 策略已经添加过,重复添加!'.format(to_unicode(factor_desc_key))
show_msg_toast_func(msg)
return
if only_one:
"""
非重复容器类型策略,如一个买入策略只能对应一个仓位管理策略
大多数为可复容器类型策略,如可以有多个买入因子,多个卖出,
多个选股因子
"""
# 对基础类型不要使用clear等函数,py2低版本不支持
# self.factor_dict.clear()
self.factor_dict = {}
self.factor_dict[factor_desc_key] = factor_dict
self.selected_factors.options = list(self.factor_dict.keys())
# 通知其它需要一起更新的界面进行更新
self.notify_subscriber()
msg = u'{}策略已添加成功!'.format(to_unicode(factor_desc_key))
show_msg_toast_func(msg)
class WidgetSearchBox(WidgetBase):
"""搜索框ui界面"""
# noinspection PyProtectedMember
def __init__(self, search_result_callable):
"""构建股票池选股ui界面"""
if not callable(search_result_callable):
raise TypeError('search_result_select_func must callable!')
# symbol搜索框构建
self.search_bt = widgets.Button(description=u'搜索:', layout=widgets.Layout(height='10%', width='7%'))
self.search_input = widgets.Text(
value='',
placeholder=u'交易代码/公司名称/拼音首字母',
description='',
disabled=False
)
self.search_input.observe(self._search_input_change, names='value')
# symbol搜索结果框
self.search_result = widgets.SelectMultiple(
options=[],
description=u'搜索结果:',
disabled=False,
layout=widgets.Layout(width='300px', align_items='stretch', justify_content='space-between')
)
self.search_result.observe(search_result_callable, names='value')
self.search_bt.on_click(self._do_search)
# 搜索框 + 按钮 + 结果框 box拼接
sc_hb = widgets.HBox([self.search_bt, self.search_input])
self.widget = widgets.VBox([sc_hb, self.search_result])
# noinspection PyUnusedLocal
def _do_search(self, bt):
"""搜索框搜索执行函数"""
result_dict = search_to_symbol_dict(self.search_input.value)
result_options = [u'{}:{}'.format(to_unicode(result_dict[symbol]), to_unicode(symbol))
for symbol in result_dict]
self.search_result.options = result_options
def _search_input_change(self, change):
"""当搜索输入框文字大于1个进行自动搜索"""
search_word = change['new']
if len(search_word) > 1:
# 和_do_search不同这里使用fast_mode
result_dict = search_to_symbol_dict(self.search_input.value, fast_mode=True)
result_options = [u'{}:{}'.format(to_unicode(result_dict[symbol]), to_unicode(symbol))
for symbol in result_dict]
self.search_result.options = result_options
# noinspection PyUnusedLocal
def permission_denied(*arg, **kwargs):
"""执行权限不足的用户提示"""
show_msg_toast_func(u'所执行的操作权限不足!')
| gpl-3.0 | 5,627,444,927,889,660,000 | 33.44 | 108 | 0.61324 | false |
zhaochao/fuel-web | nailgun/nailgun/test/integration/test_notification.py | 1 | 5261 | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, 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.
import uuid
from oslo.serialization import jsonutils
from nailgun.db.sqlalchemy.models import Notification
from nailgun.db.sqlalchemy.models import Task
from nailgun.errors import errors
from nailgun import notifier
from nailgun.rpc import receiver as rcvr
from nailgun.test.base import BaseIntegrationTest
from nailgun.test.base import reverse
class TestNotification(BaseIntegrationTest):
def test_notification_deploy_done(self):
cluster = self.env.create_cluster(api=False)
receiver = rcvr.NailgunReceiver()
task = Task(
uuid=str(uuid.uuid4()),
name="super",
cluster_id=cluster.id
)
self.db.add(task)
self.db.commit()
kwargs = {
'task_uuid': task.uuid,
'status': 'ready',
}
receiver.deploy_resp(**kwargs)
notifications = self.db.query(Notification).filter_by(
cluster_id=cluster.id
).all()
self.assertEqual(len(notifications), 1)
self.assertEqual(notifications[0].status, "unread")
self.assertEqual(notifications[0].topic, "done")
def test_notification_discover_no_node_fails(self):
self.assertRaises(
errors.CannotFindNodeIDForDiscovering,
notifier.notify,
"discover",
"discover message")
def test_notification_deploy_error(self):
cluster = self.env.create_cluster(api=False)
receiver = rcvr.NailgunReceiver()
task = Task(
uuid=str(uuid.uuid4()),
name="super",
cluster_id=cluster.id
)
self.db.add(task)
self.db.commit()
kwargs = {
'task_uuid': task.uuid,
'status': 'error',
}
receiver.deploy_resp(**kwargs)
notifications = self.db.query(Notification).filter_by(
cluster_id=cluster.id
).all()
self.assertEqual(len(notifications), 1)
self.assertEqual(notifications[0].status, "unread")
self.assertEqual(notifications[0].topic, "error")
def test_notification_node_discover(self):
resp = self.app.post(
reverse('NodeCollectionHandler'),
jsonutils.dumps({'mac': self.env.generate_random_mac(),
'meta': self.env.default_metadata(),
'status': 'discover'}),
headers=self.default_headers)
self.assertEqual(resp.status_code, 201)
notifications = self.db.query(Notification).all()
self.assertEqual(len(notifications), 1)
self.assertEqual(notifications[0].status, "unread")
self.assertEqual(notifications[0].topic, "discover")
def test_notification_delete_cluster_done(self):
cluster = self.env.create_cluster(api=False)
cluster_name = cluster.name
receiver = rcvr.NailgunReceiver()
task = Task(
uuid=str(uuid.uuid4()),
name="cluster_deletion",
cluster_id=cluster.id
)
self.db.add(task)
self.db.commit()
kwargs = {
'task_uuid': task.uuid,
'status': 'ready',
}
receiver.remove_cluster_resp(**kwargs)
notifications = self.db.query(Notification).all()
self.assertEqual(len(notifications), 1)
self.assertEqual(notifications[0].status, "unread")
self.assertEqual(notifications[0].topic, "done")
self.assertEqual(
notifications[0].message,
"Environment '%s' and all its nodes "
"are deleted" % cluster_name
)
def test_notification_delete_cluster_failed(self):
cluster = self.env.create_cluster(api=False)
receiver = rcvr.NailgunReceiver()
task = Task(
uuid=str(uuid.uuid4()),
name="cluster_deletion",
cluster_id=cluster.id
)
self.db.add(task)
self.db.commit()
kwargs = {
'task_uuid': task.uuid,
'status': 'error',
'error': 'Cluster deletion fake error'
}
receiver.remove_cluster_resp(**kwargs)
notifications = self.db.query(Notification).filter_by(
cluster_id=cluster.id
).all()
self.assertEqual(len(notifications), 1)
self.assertEqual(notifications[0].status, "unread")
self.assertEqual(notifications[0].topic, "error")
self.assertEqual(notifications[0].cluster_id, cluster.id)
self.assertEqual(
notifications[0].message,
"Cluster deletion fake error"
)
| apache-2.0 | 1,266,336,503,726,043,400 | 30.692771 | 78 | 0.602737 | false |
michellab/Sire | wrapper/Tools/DCDFile.py | 1 | 10606 |
import struct, time, array, os
from math import pi
from Sire.Maths import Vector
from Sire.Mol import *
from Sire.IO import *
#
# Adapted from Peter Eastman's code in OpenMM python API to write a DCD file
#
class DCDFile(object):
"""DCDFile provides methods for creating DCD files.
DCD is a file format for storing simulation trajectories. It is supported by many programs, such
as CHARMM, NAMD, and X-PLOR. Note, however, that different programs produce subtly different
versions of the format. This class generates the CHARMM version. Also note that there is no
standard byte ordering (big-endian or little-endian) for this format. This class always generates
files with little-endian ordering.
To use this class, create a DCDFile object, then call writeModel() once for each model in the file."""
def __init__(self, strfile, group, space, dt, firstStep=0, interval=1):
"""Create a DCD file and write out the header.
Parameters:
- file (file) A file to write to
- topology (Topology) The Topology defining the molecular system being written
- dt (time) The time step used in the trajectory
- firstStep (int=0) The index of the first step in the trajectory
- interval (int=1) The frequency (measured in time steps) at which states are written to the trajectory
"""
file = open(strfile,'wb')
#PDB().write(group, "%s.pdb" % strfile)
self._file = file
self._group = group
self._space = space
self._firstStep = firstStep
self._interval = interval
self._modelCount = 0
#if is_quantity(dt):
# dt = dt.value_in_unit(picoseconds)
#dt /= 0.04888821
dt = dt.value()
natoms = 0
molecules = group.molecules()
molnums = molecules.molNums()
for molnum in molnums:
mol = molecules.molecule(molnum)[0].molecule()
nat = mol.nAtoms()
natoms += nat
print("There are %s atoms in the group " % natoms)
#sys.exit(-1)
boxFlag = 0
if space.isPeriodic():
boxFlag = 1
header = struct.pack(b'<i4c9if', 84, b'C', b'O', b'R', b'D', 0, firstStep, interval, 0, 0, 0, 0, 0, 0, dt)
header += struct.pack(b'<13i', boxFlag, 0, 0, 0, 0, 0, 0, 0, 0, 24, 84, 164, 2)
header += struct.pack(b'<80s', b'Created by OpenMM')
header += struct.pack(b'<80s', bytes('Created '+time.asctime(time.localtime(time.time())),"utf-8"))
header += struct.pack(b'<4i', 164, 4, natoms, 4)
file.write( header )
def writeModel(self, group, space):
"""Write out a model to the DCD file.
Parameters:
- positions (list) The list of atomic positions to write
"""
#if len(list(self._topology.atoms())) != len(positions):
# raise ValueError('The number of positions must match the number of atoms')
#if is_quantity(positions):
# positions = positions.value_in_unit(nanometers)
file = self._file
# Update the header.
self._modelCount += 1
file.seek(8, os.SEEK_SET)
file.write(struct.pack('<i', self._modelCount))
file.seek(20, os.SEEK_SET)
file.write(struct.pack('<i', self._firstStep+self._modelCount*self._interval))
# Write the data.
file.seek(0, os.SEEK_END)
if space.isPeriodic():
# PeriodicBox.
try:
boxSize = space.dimensions()
file.write(struct.pack('<i6di', 48, boxSize[0], 0, boxSize[1], 0, 0, boxSize[2], 48))
# TriclinicBox.
except:
v0 = space.vector0()
v1 = space.vector1()
v2 = space.vector2()
rad2deg = 180 / pi
alpha = Vector.angle(v1, v2).value() * rad2deg
beta = Vector.angle(v0, v2).value() * rad2deg
gamma = Vector.angle(v1, v0).value() * rad2deg
file.write(struct.pack('<i6di', 48, v0.magnitude(), gamma, v1.magnitude(), beta, alpha, v2.magnitude(), 48))
natoms = 0
for i in range(0,group.nMolecules()):
mol = group[MolIdx(i)][0].molecule()
nat = mol.nAtoms()
natoms += nat
length = struct.pack('<i', 4*natoms)
# To get the positions...
# Loop over that group
nmols = group.nMolecules()
coords = []
#spacedims = space.dimensions()
#wrapmolcoordinates = False
#wrapatomcoordinates = False
# JM 10/14 bugfix change of behavior of QSet in QT5
molnums = group.molNums()
molnums.sort()
for i in range(0,group.nMolecules()):
#mol = group[MolIdx(i)].molecule()
mol = group[molnums[i]][0].molecule()
#print (mol)
molcoords = mol.property("coordinates")
#if wrapmolcoordinates:
# molcog = CenterOfGeometry(mol).point()
#
# wrapdelta = Vector( int( math.floor( molcog.x() / spacedims.x() ) ) ,\
# int( math.floor( molcog.y() / spacedims.y() ) ) ,\
# int( math.floor( molcog.z() / spacedims.z() ) ) )
#
# if ( wrapdelta[0] != 0 or wrapdelta[1] != 0 or wrapdelta[2] != 0):
# print("Mol %s wrapdelta %s %s %s " % (molnum.toString(), wrapdelta[0], wrapdelta[1], wrapdelta[2]))
# print(spacedims)
# print(molcoords.toVector())
# wrap = Vector( - wrapdelta[0] * spacedims.x() , - wrapdelta[1] * spacedims.y(), -wrapdelta[2] * spacedims.z() )
# molcoords.translate(wrap)
# print(molcoords.toVector())
#molcoords.translate(wrapdelta)
#coords += molcoords
coords += molcoords.toVector()
#if wrapatomcoordinates:
# molvec = molcoords.toVector()
# for atvec in molvec:
# wrapdelta = Vector( int( math.floor( atvec.x() / spacedims.x() ) ) ,\
# int( math.floor( atvec.y() / spacedims.y() ) ) ,\
# int( math.floor( atvec.z() / spacedims.z() ) ) )
# if ( wrapdelta[0] != 0 or wrapdelta[1] != 0 or wrapdelta[2] != 0):
# wrap = Vector( - wrapdelta[0] * spacedims.x() , - wrapdelta[1] * spacedims.y(), -wrapdelta[2] * spacedims.z() )
# atvec = atvec + wrap
# coords += atvec
#print coords
#print len(coords)
# Have to study that bit...
for i in range(3):
file.write(length)
data = array.array('f', (x[i] for x in coords))
data.tofile(file)
file.write(length)
def writeBufferedModels(self, group, dimensions):
"""Write out a collection of snapshots to the DCD file.
Parameters:
- positions (list) The list of atomic positions to write
"""
#if len(list(self._topology.atoms())) != len(positions):
# raise ValueError('The number of positions must match the number of atoms')
#if is_quantity(positions):
# positions = positions.value_in_unit(nanometers)
file = self._file
# Find the number of buffered frames we have by inspecting the first molecule in the group
# assuming all molecules have same number of buffered coordinates...
mol = group.first()[0].molecule()
molprops = mol.propertyKeys()
nbuf = 0
for molprop in molprops:
if molprop.startswith("buffered_coord"):
nbuf += 1
if nbuf <= 0:
print("Could not find any buffered coordinates in the passed group ! ")
return
#
# Should be more efficient to loop over all mols once
#
for x in range(0,nbuf):
# Update the header
self._modelCount += 1
file.seek(8, os.SEEK_SET)
file.write(struct.pack('<i', self._modelCount))
file.seek(20, os.SEEK_SET)
file.write(struct.pack('<i', self._firstStep+self._modelCount*self._interval))
# Write the data.
file.seek(0, os.SEEK_END)
# Get buffered space...
boxSize = None
if ("buffered_space_%s" % x) in dimensions:
# PeriodicBox.
try:
boxSize = dimensions["buffered_space_%s" % x].dimensions()
#print "buffered_space_%s" % x, boxSize
if boxSize is not None:
file.write(struct.pack('<i6di', 48, boxSize[0], 0, boxSize[1], 0, 0, boxSize[2], 48))
# TriclinicBox.
except:
v0 = dimensions["buffered_space_%s" % x].vector0()
v1 = dimensions["buffered_space_%s" % x].vector1()
v2 = dimensions["buffered_space_%s" % x].vector2()
rad2deg = 180 / pi
alpha = Vector.angle(v1, v2).value() * rad2deg
beta = Vector.angle(v0, v2).value() * rad2deg
gamma = Vector.angle(v1, v0).value() * rad2deg
file.write(struct.pack('<i6di', 48, v0.magnitude(), gamma, v1.magnitude(), beta, alpha, v2.magnitude(), 48))
natoms = 0
for i in range(0,group.nMolecules()):
mol = group[MolIdx(i)][0].molecule()
nat = mol.nAtoms()
natoms += nat
length = struct.pack('<i', 4*natoms)
# To get the positions...
# Loop over that group
nmols = group.nMolecules()
coords = []
# JM 10/14 bugfix change of behavior of QSet in QT5
molnums = group.molNums()
molnums.sort()
for i in range(0,group.nMolecules()):
#mol = group[MolIdx(i)].molecule()
mol = group[molnums[i]][0]
molcoords = mol.property("buffered_coord_%s" % x)
coords += molcoords.toVector()
# Have to study that bit...
for i in range(3):
file.write(length)
data = array.array('f', (x[i] for x in coords))
data.tofile(file)
file.write(length)
#rewind
file.seek(0, os.SEEK_SET)
| gpl-2.0 | 6,188,089,025,012,289,000 | 37.427536 | 136 | 0.528569 | false |
amit0701/rally | tests/unit/common/objects/test_task.py | 1 | 12985 | # Copyright 2013: Mirantis Inc.
# 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.
"""Tests for db.task layer."""
import datetime as dt
import json
import ddt
import jsonschema
import mock
from rally.common import objects
from rally import consts
from rally import exceptions
from tests.unit import test
@ddt.ddt
class TaskTestCase(test.TestCase):
def setUp(self):
super(TaskTestCase, self).setUp()
self.task = {
"uuid": "00ef46a2-c5b8-4aea-a5ca-0f54a10cbca1",
"status": consts.TaskStatus.INIT,
"verification_log": "",
}
@mock.patch("rally.common.objects.task.db.task_create")
def test_init_with_create(self, mock_task_create):
mock_task_create.return_value = self.task
task = objects.Task(status=consts.TaskStatus.FAILED)
mock_task_create.assert_called_once_with({
"status": consts.TaskStatus.FAILED})
self.assertEqual(task["uuid"], self.task["uuid"])
@mock.patch("rally.common.objects.task.db.task_create")
def test_init_without_create(self, mock_task_create):
task = objects.Task(task=self.task)
self.assertFalse(mock_task_create.called)
self.assertEqual(task["uuid"], self.task["uuid"])
@mock.patch("rally.common.objects.task.uuid.uuid4",
return_value="some_uuid")
@mock.patch("rally.common.objects.task.db.task_create")
def test_init_with_fake_true(self, mock_task_create, mock_uuid4):
task = objects.Task(temporary=True)
self.assertFalse(mock_task_create.called)
self.assertTrue(mock_uuid4.called)
self.assertEqual(task["uuid"], mock_uuid4.return_value)
@mock.patch("rally.common.objects.task.db.task_get")
def test_get(self, mock_task_get):
mock_task_get.return_value = self.task
task = objects.Task.get(self.task["uuid"])
mock_task_get.assert_called_once_with(self.task["uuid"])
self.assertEqual(task["uuid"], self.task["uuid"])
@mock.patch("rally.common.objects.task.db.task_get_status")
def test_get_status(self, mock_task_get_status):
task = objects.Task(task=self.task)
status = task.get_status(task["uuid"])
self.assertEqual(status, mock_task_get_status.return_value)
@mock.patch("rally.common.objects.task.db.task_delete")
@mock.patch("rally.common.objects.task.db.task_create")
def test_create_and_delete(self, mock_task_create, mock_task_delete):
mock_task_create.return_value = self.task
task = objects.Task()
task.delete()
mock_task_delete.assert_called_once_with(
self.task["uuid"], status=None)
@mock.patch("rally.common.objects.task.db.task_delete")
@mock.patch("rally.common.objects.task.db.task_create")
def test_create_and_delete_status(self, mock_task_create,
mock_task_delete):
mock_task_create.return_value = self.task
task = objects.Task()
task.delete(status=consts.TaskStatus.FINISHED)
mock_task_delete.assert_called_once_with(
self.task["uuid"], status=consts.TaskStatus.FINISHED)
@mock.patch("rally.common.objects.task.db.task_delete")
def test_delete_by_uuid(self, mock_task_delete):
objects.Task.delete_by_uuid(self.task["uuid"])
mock_task_delete.assert_called_once_with(
self.task["uuid"], status=None)
@mock.patch("rally.common.objects.task.db.task_delete")
def test_delete_by_uuid_status(self, mock_task_delete):
objects.Task.delete_by_uuid(self.task["uuid"],
consts.TaskStatus.FINISHED)
mock_task_delete.assert_called_once_with(
self.task["uuid"], status=consts.TaskStatus.FINISHED)
@mock.patch("rally.common.objects.task.db.task_list",
return_value=[{"uuid": "a",
"created_at": "b",
"status": consts.TaskStatus.FAILED,
"tag": "d",
"deployment_name": "some_name"}])
def list(self, mock_db_task_list):
tasks = objects.Task.list(status="somestatus")
mock_db_task_list.assert_called_once_with("somestatus", None)
self.assertIs(type(tasks), list)
self.assertIsInstance(tasks[0], objects.Task)
self.assertEqual(mock_db_task_list.return_value["uuis"],
tasks[0]["uuid"])
@mock.patch("rally.common.objects.deploy.db.task_update")
@mock.patch("rally.common.objects.task.db.task_create")
def test_update(self, mock_task_create, mock_task_update):
mock_task_create.return_value = self.task
mock_task_update.return_value = {"opt": "val2"}
deploy = objects.Task(opt="val1")
deploy._update({"opt": "val2"})
mock_task_update.assert_called_once_with(
self.task["uuid"], {"opt": "val2"})
self.assertEqual(deploy["opt"], "val2")
@ddt.data(
{
"status": "some_status", "allowed_statuses": ("s_1", "s_2")
},
{
"status": "some_status", "allowed_statuses": None
}
)
@ddt.unpack
@mock.patch("rally.common.objects.task.db.task_update_status")
@mock.patch("rally.common.objects.task.db.task_update")
def test_update_status(self, mock_task_update, mock_task_update_status,
status, allowed_statuses):
task = objects.Task(task=self.task)
task.update_status(consts.TaskStatus.FINISHED, allowed_statuses)
if allowed_statuses:
self.assertFalse(mock_task_update.called)
mock_task_update_status.assert_called_once_with(
self.task["uuid"],
consts.TaskStatus.FINISHED,
allowed_statuses
)
else:
self.assertFalse(mock_task_update_status.called)
mock_task_update.assert_called_once_with(
self.task["uuid"],
{"status": consts.TaskStatus.FINISHED},
)
@mock.patch("rally.common.objects.task.db.task_update")
def test_update_verification_log(self, mock_task_update):
mock_task_update.return_value = self.task
task = objects.Task(task=self.task)
task.update_verification_log({"a": "fake"})
mock_task_update.assert_called_once_with(
self.task["uuid"],
{"verification_log": json.dumps({"a": "fake"})}
)
def test_extend_results(self):
self.assertRaises(TypeError, objects.Task.extend_results)
now = dt.datetime.now()
iterations = [
{"timestamp": i + 2, "duration": i + 5,
"scenario_output": {"errors": "", "data": {}},
"error": [], "idle_duration": i,
"atomic_actions": {
"keystone.create_user": i + 10}} for i in range(10)]
obsolete = [
{"task_uuid": "foo_uuid", "created_at": now, "updated_at": None,
"id": 11, "key": {"kw": {"foo": 42},
"name": "Foo.bar", "pos": 0},
"data": {"raw": iterations, "sla": [],
"full_duration": 40, "load_duration": 32}}]
expected = [
{"iterations": "foo_iterations", "sla": [],
"key": {"kw": {"foo": 42}, "name": "Foo.bar", "pos": 0},
"info": {
"atomic": {"keystone.create_user": {"max_duration": 19,
"min_duration": 10}},
"iterations_count": 10, "iterations_failed": 0,
"max_duration": 14, "min_duration": 5,
"tstamp_start": 2, "full_duration": 40, "load_duration": 32}}]
# serializable is default
results = objects.Task.extend_results(obsolete)
self.assertIsInstance(results[0]["iterations"], type(iter([])))
self.assertEqual(list(results[0]["iterations"]), iterations)
results[0]["iterations"] = "foo_iterations"
self.assertEqual(results, expected)
# serializable is False
results = objects.Task.extend_results(obsolete, serializable=False)
self.assertIsInstance(results[0]["iterations"], type(iter([])))
self.assertEqual(list(results[0]["iterations"]), iterations)
results[0]["iterations"] = "foo_iterations"
self.assertEqual(results, expected)
# serializable is True
results = objects.Task.extend_results(obsolete, serializable=True)
self.assertEqual(list(results[0]["iterations"]), iterations)
expected[0]["created_at"] = now.strftime("%Y-%d-%mT%H:%M:%S")
expected[0]["updated_at"] = None
jsonschema.validate(results[0],
objects.task.TASK_EXTENDED_RESULT_SCHEMA)
results[0]["iterations"] = "foo_iterations"
self.assertEqual(results, expected)
@mock.patch("rally.common.objects.task.db.task_result_get_all_by_uuid",
return_value="foo_results")
def test_get_results(self, mock_task_result_get_all_by_uuid):
task = objects.Task(task=self.task)
results = task.get_results()
mock_task_result_get_all_by_uuid.assert_called_once_with(
self.task["uuid"])
self.assertEqual(results, "foo_results")
@mock.patch("rally.common.objects.task.db.task_result_create")
def test_append_results(self, mock_task_result_create):
task = objects.Task(task=self.task)
task.append_results("opt", "val")
mock_task_result_create.assert_called_once_with(
self.task["uuid"], "opt", "val")
@mock.patch("rally.common.objects.task.db.task_update")
def test_set_failed(self, mock_task_update):
mock_task_update.return_value = self.task
task = objects.Task(task=self.task)
task.set_failed()
mock_task_update.assert_called_once_with(
self.task["uuid"],
{"status": consts.TaskStatus.FAILED, "verification_log": "\"\""},
)
@ddt.data(
{
"soft": True, "status": consts.TaskStatus.INIT
},
{
"soft": True, "status": consts.TaskStatus.VERIFYING
},
{
"soft": False, "status": consts.TaskStatus.INIT
},
{
"soft": False, "status": consts.TaskStatus.VERIFYING
}
)
@ddt.unpack
def test_abort_with_init_and_verifying_states(self, soft, status):
task = objects.Task(mock.MagicMock(), fake=True)
task.get_status = mock.MagicMock(
side_effect=(status, status, "running"))
task._update_status_in_abort = mock.MagicMock()
self.assertRaises(exceptions.RallyException, task.abort, soft)
self.assertEqual(1, task.get_status.call_count)
self.assertFalse(task._update_status_in_abort.called)
@ddt.data(
{
"soft": True, "status": consts.TaskStatus.ABORTED
},
{
"soft": True, "status": consts.TaskStatus.FINISHED
},
{
"soft": True, "status": consts.TaskStatus.FAILED
},
{
"soft": False, "status": consts.TaskStatus.ABORTED
},
{
"soft": False, "status": consts.TaskStatus.FINISHED
},
{
"soft": False, "status": consts.TaskStatus.FAILED
}
)
@ddt.unpack
def test_abort_with_finished_states(self, soft, status):
task = objects.Task(mock.MagicMock(), fake=True)
task.get_status = mock.MagicMock(return_value=status)
task.update_status = mock.MagicMock()
self.assertRaises(exceptions.RallyException, task.abort, soft)
self.assertEqual(1, task.get_status.call_count)
self.assertFalse(task.update_status.called)
@ddt.data(True, False)
def test_abort_with_running_state(self, soft):
task = objects.Task(mock.MagicMock(), fake=True)
task.get_status = mock.MagicMock(return_value="running")
task.update_status = mock.MagicMock()
task.abort(soft)
if soft:
status = consts.TaskStatus.SOFT_ABORTING
else:
status = consts.TaskStatus.ABORTING
task.update_status.assert_called_once_with(
status,
allowed_statuses=(consts.TaskStatus.RUNNING,
consts.TaskStatus.SOFT_ABORTING)
)
| apache-2.0 | -7,038,468,983,800,166,000 | 39.451713 | 78 | 0.595302 | false |
lc525/cmake-project | docs/ext/breathe-1.0.0/breathe/renderer/rst/doxygen/compound.py | 1 | 26721 |
from breathe.renderer.rst.doxygen.base import Renderer
class DoxygenTypeSubRenderer(Renderer):
def render(self):
compound_renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.compounddef)
nodelist = compound_renderer.render()
return [self.node_factory.block_quote("", *nodelist)]
class CompoundDefTypeSubRenderer(Renderer):
section_titles = [
"user-defined",
"public-type",
"public-func",
"public-attrib",
"public-slot",
"signal",
"dcop-func",
"property",
"event",
"public-static-func",
"public-static-attrib",
"protected-type",
"protected-func",
"protected-attrib",
"protected-slot",
"protected-static-func",
"protected-static-attrib",
"package-type",
"package-attrib",
"package-static-func",
"package-static-attrib",
"private-type",
"private-func",
"private-attrib",
"private-slot",
"private-static-func",
"private-static-attrib",
"friend",
"related",
"define",
"prototype",
"typedef",
"enum",
"func",
"var"
]
def render(self):
nodelist = []
if self.data_object.briefdescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.briefdescription)
nodelist.append(self.node_factory.paragraph("", "", *renderer.render()))
if self.data_object.detaileddescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.detaileddescription)
nodelist.append(self.node_factory.paragraph("", "", *renderer.render()))
section_nodelists = {}
# Get all sub sections
for sectiondef in self.data_object.sectiondef:
kind = sectiondef.kind
renderer = self.renderer_factory.create_renderer(self.data_object, sectiondef)
subnodes = renderer.render()
try:
# As "user-defined" can repeat
section_nodelists[kind] += subnodes
except KeyError:
section_nodelists[kind] = subnodes
# Order the results in an appropriate manner
for kind in self.section_titles:
nodelist.extend(section_nodelists.get(kind, []))
# Take care of innerclasses
for innerclass in self.data_object.innerclass:
renderer = self.renderer_factory.create_renderer(self.data_object, innerclass)
class_nodes = renderer.render()
if class_nodes:
nodelist.append(self.node_factory.paragraph("", "", *class_nodes))
for innernamespace in self.data_object.innernamespace:
renderer = self.renderer_factory.create_renderer(self.data_object, innernamespace)
namespace_nodes = renderer.render()
if namespace_nodes:
nodelist.append(self.node_factory.paragraph("", "", *namespace_nodes))
return nodelist
class SectionDefTypeSubRenderer(Renderer):
section_titles = {
"user-defined": "User Defined",
"public-type": "Public Type",
"public-func": "Public Functions",
"public-attrib": "Public Members",
"public-slot": "Public Slot",
"signal": "Signal",
"dcop-func": "DCOP Function",
"property": "Property",
"event": "Event",
"public-static-func": "Public Static Functions",
"public-static-attrib": "Public Static Attributes",
"protected-type": "Protected Types",
"protected-func": "Protected Functions",
"protected-attrib": "Protected Attributes",
"protected-slot": "Protected Slots",
"protected-static-func": "Protected Static Functions",
"protected-static-attrib": "Protected Static Attributes",
"package-type": "Package Types",
"package-attrib": "Package Attributes",
"package-static-func": "Package Static Functions",
"package-static-attrib": "Package Static Attributes",
"private-type": "Private Types",
"private-func": "Private Functions",
"private-attrib": "Private Members",
"private-slot": "Private Slots",
"private-static-func": "Private Static Functions",
"private-static-attrib": "Private Static Attributes",
"friend": "Friends",
"related": "Related",
"define": "Defines",
"prototype": "Prototypes",
"typedef": "Typedefs",
"enum": "Enums",
"func": "Functions",
"var": "Variables",
}
def render(self):
node_list = []
if self.data_object.description:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.description)
node_list.append(self.node_factory.paragraph( "", "", *renderer.render()))
# Get all the memberdef info
for memberdef in self.data_object.memberdef:
renderer = self.renderer_factory.create_renderer(self.data_object, memberdef)
node_list.extend(renderer.render())
if node_list:
text = self.section_titles[self.data_object.kind]
# Override default name for user-defined sections. Use "Unnamed
# Group" if the user didn't name the section
# This is different to Doxygen which will track the groups and name
# them Group1, Group2, Group3, etc.
if self.data_object.kind == "user-defined":
if self.data_object.header:
text = self.data_object.header
else:
text = "Unnamed Group"
title = self.node_factory.emphasis(text=text)
return [title, self.node_factory.block_quote("", *node_list)]
return []
class MemberDefTypeSubRenderer(Renderer):
def create_target(self, refid):
return self.target_handler.create_target(refid)
def create_domain_id(self):
return ""
def title(self):
kind = []
# Variable type or function return type
if self.data_object.type_:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.type_)
kind = renderer.render()
name = self.node_factory.strong(text=self.data_object.name)
args = []
args.extend(kind)
args.extend([self.node_factory.Text(" "), name])
return args
def description(self):
description_nodes = []
if self.data_object.briefdescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.briefdescription)
description_nodes.append(self.node_factory.paragraph("", "", *renderer.render()))
if self.data_object.detaileddescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.detaileddescription)
description_nodes.append(self.node_factory.paragraph( "", "", *renderer.render()))
return description_nodes
def render(self):
refid = "%s%s" % (self.project_info.name(), self.data_object.id)
domain_id = self.create_domain_id()
title = self.title()
target = self.create_target(refid)
target.extend(title)
term = self.node_factory.paragraph("", "", ids=[domain_id,refid], *target )
definition = self.node_factory.paragraph("", "", *self.description())
return [term, self.node_factory.block_quote("", definition)]
class FuncMemberDefTypeSubRenderer(MemberDefTypeSubRenderer):
def create_target(self, refid):
self.domain_handler.create_function_target(self.data_object)
return MemberDefTypeSubRenderer.create_target(self, refid)
def create_domain_id(self):
return self.domain_handler.create_function_id(self.data_object)
def title(self):
lines = []
# Handle any template information
if self.data_object.templateparamlist:
renderer = self.renderer_factory.create_renderer(
self.data_object,
self.data_object.templateparamlist
)
template = [
self.node_factory.Text("template < ")
]
template.extend(renderer.render())
template.append(self.node_factory.Text(" >"))
# Add blank string at the start otherwise for some reason it renders
# the emphasis tags around the kind in plain text (same below)
lines.append(
self.node_factory.line(
"",
self.node_factory.Text(""),
*template
)
)
# Get the function type and name
args = MemberDefTypeSubRenderer.title(self)
# Get the function arguments
args.append(self.node_factory.Text("("))
for i, parameter in enumerate(self.data_object.param):
if i: args.append(self.node_factory.Text(", "))
renderer = self.renderer_factory.create_renderer(self.data_object, parameter)
args.extend(renderer.render())
args.append(self.node_factory.Text(")"))
lines.append(
self.node_factory.line(
"",
self.node_factory.Text(""),
*args
)
)
# Setup the line block with gathered informationo
block = self.node_factory.line_block(
"",
*lines
)
return [block]
class DefineMemberDefTypeSubRenderer(MemberDefTypeSubRenderer):
def title(self):
title = []
title.append(self.node_factory.strong(text=self.data_object.name))
if self.data_object.param:
title.append(self.node_factory.Text("("))
for i, parameter in enumerate(self.data_object.param):
if i: title.append(self.node_factory.Text(", "))
renderer = self.renderer_factory.create_renderer(self.data_object, parameter)
title.extend(renderer.render())
title.append(self.node_factory.Text(")"))
return title
def description(self):
return MemberDefTypeSubRenderer.description(self)
class EnumMemberDefTypeSubRenderer(MemberDefTypeSubRenderer):
def title(self):
if self.data_object.name.startswith("@"):
# Assume anonymous enum
return [self.node_factory.strong(text="Anonymous enum")]
name = self.node_factory.strong(text="%s enum" % self.data_object.name)
return [name]
def description(self):
description_nodes = MemberDefTypeSubRenderer.description(self)
name = self.node_factory.emphasis("", self.node_factory.Text("Values:"))
title = self.node_factory.paragraph("", "", name)
description_nodes.append(title)
enums = []
for item in self.data_object.enumvalue:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
enums.extend(renderer.render())
description_nodes.append(self.node_factory.bullet_list("", classes=["breatheenumvalues"], *enums))
return description_nodes
class TypedefMemberDefTypeSubRenderer(MemberDefTypeSubRenderer):
def title(self):
args = [self.node_factory.Text("typedef ")]
args.extend(MemberDefTypeSubRenderer.title(self))
if self.data_object.argsstring:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.argsstring)
args.extend(renderer.render())
return args
class VariableMemberDefTypeSubRenderer(MemberDefTypeSubRenderer):
def title(self):
args = MemberDefTypeSubRenderer.title(self)
if self.data_object.argsstring:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.argsstring)
args.extend(renderer.render())
return args
class EnumvalueTypeSubRenderer(Renderer):
def render(self):
name = self.node_factory.literal(text=self.data_object.name)
description_nodes = [name]
if self.data_object.initializer:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.initializer)
nodelist = [self.node_factory.Text(" = ")]
nodelist.extend(renderer.render())
description_nodes.append(self.node_factory.literal("", "", *nodelist))
separator = self.node_factory.Text(" - ")
description_nodes.append(separator)
if self.data_object.briefdescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.briefdescription)
description_nodes.extend(renderer.render())
if self.data_object.detaileddescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.detaileddescription)
description_nodes.extend(renderer.render())
# Build the list item
return [self.node_factory.list_item("", *description_nodes)]
class DescriptionTypeSubRenderer(Renderer):
def render(self):
nodelist = []
# Get description in rst_nodes if possible
for item in self.data_object.content_:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
return nodelist
class LinkedTextTypeSubRenderer(Renderer):
def render(self):
nodelist = []
# Recursively process where possible
for i, entry in enumerate(self.data_object.content_):
if i:
nodelist.append(self.node_factory.Text(" "))
renderer = self.renderer_factory.create_renderer(self.data_object, entry)
nodelist.extend(renderer.render())
return nodelist
class ParamTypeSubRenderer(Renderer):
def __init__(
self,
output_defname,
*args
):
Renderer.__init__( self, *args )
self.output_defname = output_defname
def render(self):
nodelist = []
# Parameter type
if self.data_object.type_:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.type_)
nodelist.extend(renderer.render())
# Parameter name
if self.data_object.declname:
if nodelist: nodelist.append(self.node_factory.Text(" "))
nodelist.append(self.node_factory.Text(self.data_object.declname))
if self.output_defname and self.data_object.defname:
if nodelist: nodelist.append(self.node_factory.Text(" "))
nodelist.append(self.node_factory.Text(self.data_object.defname))
# Default value
if self.data_object.defval:
nodelist.append(self.node_factory.Text(" = "))
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.defval)
nodelist.extend(renderer.render())
return nodelist
class DocRefTextTypeSubRenderer(Renderer):
def render(self):
nodelist = []
for item in self.data_object.content_:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
for item in self.data_object.para:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
refid = "%s%s" % (self.project_info.name(), self.data_object.refid)
nodelist = [
self.node_factory.pending_xref(
"",
reftype="ref",
refdomain="std",
refexplicit=True,
refid=refid,
reftarget=refid,
*nodelist
)
]
return nodelist
class DocParaTypeSubRenderer(Renderer):
def render(self):
nodelist = []
for item in self.data_object.content: # Description
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
definition_nodes = []
for item in self.data_object.simplesects: # Returns, user par's, etc
renderer = self.renderer_factory.create_renderer(self.data_object, item)
definition_nodes.extend(renderer.render())
for entry in self.data_object.parameterlist: # Parameters/Exceptions
renderer = self.renderer_factory.create_renderer(self.data_object, entry)
definition_nodes.extend(renderer.render())
if definition_nodes:
definition_list = self.node_factory.definition_list("", *definition_nodes)
nodelist.append(definition_list)
return [self.node_factory.paragraph("", "", *nodelist)]
class DocMarkupTypeSubRenderer(Renderer):
def __init__(
self,
creator,
*args
):
Renderer.__init__( self, *args )
self.creator = creator
def render(self):
nodelist = []
for item in self.data_object.content_:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
return [self.creator("", "", *nodelist)]
class DocParamListTypeSubRenderer(Renderer):
""" Parameter/Exectpion documentation """
lookup = {
"param" : "Parameters",
"exception" : "Exceptions",
"templateparam" : "Templates",
"retval" : "Return Value",
}
def render(self):
nodelist = []
for entry in self.data_object.parameteritem:
renderer = self.renderer_factory.create_renderer(self.data_object, entry)
nodelist.extend(renderer.render())
# Fild list entry
nodelist_list = self.node_factory.bullet_list("", classes=["breatheparameterlist"], *nodelist)
term_text = self.lookup[self.data_object.kind]
term = self.node_factory.term("", "", self.node_factory.strong( "", term_text ) )
definition = self.node_factory.definition('', nodelist_list)
return [self.node_factory.definition_list_item('', term, definition)]
class DocParamListItemSubRenderer(Renderer):
""" Paramter Description Renderer """
def render(self):
nodelist = []
for entry in self.data_object.parameternamelist:
renderer = self.renderer_factory.create_renderer(self.data_object, entry)
nodelist.extend(renderer.render())
term = self.node_factory.literal("","", *nodelist)
separator = self.node_factory.Text(" - ")
nodelist = []
if self.data_object.parameterdescription:
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.parameterdescription)
nodelist.extend(renderer.render())
return [self.node_factory.list_item("", term, separator, *nodelist)]
class DocParamNameListSubRenderer(Renderer):
""" Parameter Name Renderer """
def render(self):
nodelist = []
for entry in self.data_object.parametername:
renderer = self.renderer_factory.create_renderer(self.data_object, entry)
nodelist.extend(renderer.render())
return nodelist
class DocParamNameSubRenderer(Renderer):
def render(self):
nodelist = []
for item in self.data_object.content_:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
return nodelist
class DocSect1TypeSubRenderer(Renderer):
def render(self):
return []
class DocSimpleSectTypeSubRenderer(Renderer):
"Other Type documentation such as Warning, Note, Returns, etc"
def title(self):
text = self.node_factory.Text(self.data_object.kind.capitalize())
return [self.node_factory.strong( "", text )]
def render(self):
nodelist = []
for item in self.data_object.para:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.append(self.node_factory.paragraph("", "", *renderer.render()))
term = self.node_factory.term("", "", *self.title())
definition = self.node_factory.definition("", *nodelist)
return [self.node_factory.definition_list_item("", term, definition)]
class ParDocSimpleSectTypeSubRenderer(DocSimpleSectTypeSubRenderer):
def title(self):
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.title)
return [self.node_factory.strong( "", *renderer.render() )]
class DocTitleTypeSubRenderer(Renderer):
def render(self):
nodelist = []
for item in self.data_object.content_:
renderer = self.renderer_factory.create_renderer(self.data_object, item)
nodelist.extend(renderer.render())
return nodelist
class DocForumlaTypeSubRenderer(Renderer):
def render(self):
nodelist = []
for item in self.data_object.content_:
latex = item.getValue()
# Somewhat hacky if statements to strip out the doxygen markup that slips through
node = None
# Either inline
if latex.startswith("$") and latex.endswith("$"):
latex = latex[1:-1]
# If we're inline create a math node like the :math: role
node = self.node_factory.math()
else:
# Else we're multiline
node = self.node_factory.displaymath()
# Or multiline
if latex.startswith("\[") and latex.endswith("\]"):
latex = latex[2:-2:]
# Here we steal the core of the mathbase "math" directive handling code from:
# sphinx.ext.mathbase
node["latex"] = latex
# Required parameters which we don't have values for
node["label"] = None
node["nowrap"] = False
node["docname"] = self.state.document.settings.env.docname
nodelist.append(node)
return nodelist
class TemplateParamListRenderer(Renderer):
def render(self):
nodelist = []
for i, param in enumerate(self.data_object.param):
if i:
nodelist.append(self.node_factory.Text(", "))
renderer = self.renderer_factory.create_renderer(self.data_object, param)
nodelist.extend(renderer.render())
return nodelist
class IncTypeSubRenderer(Renderer):
def render(self):
if self.data_object.local == u"yes":
text = '#include "%s"' % self.data_object.content_[0].getValue()
else:
text = '#include <%s>' % self.data_object.content_[0].getValue()
return [self.node_factory.emphasis(text=text)]
class RefTypeSubRenderer(Renderer):
ref_types = {
"innerclass" : "class",
"innernamespace" : "namespace",
}
def __init__(self, compound_parser, *args):
Renderer.__init__(self, *args)
self.compound_parser = compound_parser
def render(self):
# Read in the corresponding xml file and process
file_data = self.compound_parser.parse(self.data_object.refid)
data_renderer = self.renderer_factory.create_renderer(self.data_object, file_data)
child_nodes = data_renderer.render()
# Only render the header with refs if we've definitely got content to
# put underneath it. Otherwise return an empty list
if child_nodes:
refid = "%s%s" % (self.project_info.name(), self.data_object.refid)
nodelist = self.target_handler.create_target(refid)
# Set up the title and a reference for it (refid)
type_ = self.ref_types[self.data_object.node_name]
kind = self.node_factory.emphasis(text=type_)
name_text = self.data_object.content_[0].getValue()
name_text = name_text.rsplit("::", 1)[-1]
name = self.node_factory.strong(text=name_text)
nodelist = []
nodelist.append(
self.node_factory.paragraph(
"",
"",
kind,
self.node_factory.Text(" "),
name,
ids=[refid]
)
)
nodelist.extend(child_nodes)
return nodelist
return []
class VerbatimTypeSubRenderer(Renderer):
def __init__(self, content_creator, *args):
Renderer.__init__(self, *args)
self.content_creator = content_creator
def render(self):
if not self.data_object.text.strip().startswith("embed:rst"):
# Remove trailing new lines. Purely subjective call from viewing results
text = self.data_object.text.rstrip()
# Handle has a preformatted text
return [self.node_factory.literal_block(text, text)]
rst = self.content_creator(self.data_object.text)
# Parent node for the generated node subtree
node = self.node_factory.paragraph()
node.document = self.state.document
# Generate node subtree
self.state.nested_parse(rst, 0, node)
return node
class MixedContainerRenderer(Renderer):
def render(self):
renderer = self.renderer_factory.create_renderer(self.data_object, self.data_object.getValue())
return renderer.render()
| bsd-2-clause | -5,708,813,989,462,306,000 | 31.116587 | 117 | 0.587066 | false |
fastcoinproject/fastcoin | contrib/bitrpc/bitrpc.py | 1 | 9669 | from jsonrpc import ServiceProxy
import sys
import string
import getpass
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:9332")
else:
access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:9332")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destination path/filename: ")
print access.backupwallet(path)
except:
print "\n---An error occurred---\n"
elif cmd == "encryptwallet":
try:
pwd = getpass.getpass(prompt="Enter passphrase: ")
pwd2 = getpass.getpass(prompt="Repeat passphrase: ")
if pwd == pwd2:
access.encryptwallet(pwd)
print "\n---Wallet encrypted. Server stopping, restart to run with encrypted wallet---\n"
else:
print "\n---Passphrases do not match---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "getaccount":
try:
addr = raw_input("Enter a Bitcoin address: ")
print access.getaccount(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccountaddress":
try:
acct = raw_input("Enter an account name: ")
print access.getaccountaddress(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
print access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
except:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print access.getconnectioncount()
except:
print "\n---An error occurred---\n"
elif cmd == "getdifficulty":
try:
print access.getdifficulty()
except:
print "\n---An error occurred---\n"
elif cmd == "getgenerate":
try:
print access.getgenerate()
except:
print "\n---An error occurred---\n"
elif cmd == "gethashespersec":
try:
print access.gethashespersec()
except:
print "\n---An error occurred---\n"
elif cmd == "getinfo":
try:
print access.getinfo()
except:
print "\n---An error occurred---\n"
elif cmd == "getnewaddress":
try:
acct = raw_input("Enter an account name: ")
try:
print access.getnewaddress(acct)
except:
print access.getnewaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaccount":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaccount(acct, mc)
except:
print access.getreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a Bitcoin address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaddress(addr, mc)
except:
print access.getreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except:
print "\n---An error occurred---\n"
elif cmd == "getwork":
try:
data = raw_input("Data (optional): ")
try:
print access.gettransaction(data)
except:
print access.gettransaction()
except:
print "\n---An error occurred---\n"
elif cmd == "help":
try:
cmd = raw_input("Command (optional): ")
try:
print access.help(cmd)
except:
print access.help()
except:
print "\n---An error occurred---\n"
elif cmd == "listaccounts":
try:
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.listaccounts(mc)
except:
print access.listaccounts()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaccount":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
print access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print access.listreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "listtransactions":
try:
acct = raw_input("Account (optional): ")
count = raw_input("Number of transactions (optional): ")
frm = raw_input("Skip (optional):")
try:
print access.listtransactions(acct, count, frm)
except:
print access.listtransactions()
except:
print "\n---An error occurred---\n"
elif cmd == "move":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.move(frm, to, amt, mc, comment)
except:
print access.move(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendfrom":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendfrom(frm, to, amt, mc, comment, commentto)
except:
print access.sendfrom(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendmany":
try:
frm = raw_input("From: ")
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.sendmany(frm,to,mc,comment)
except:
print access.sendmany(frm,to)
except:
print "\n---An error occurred---\n"
elif cmd == "sendtoaddress":
try:
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
amt = raw_input("Amount:")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendtoaddress(to,amt,comment,commentto)
except:
print access.sendtoaddress(to,amt)
except:
print "\n---An error occurred---\n"
elif cmd == "setaccount":
try:
addr = raw_input("Address: ")
acct = raw_input("Account:")
print access.setaccount(addr,acct)
except:
print "\n---An error occurred---\n"
elif cmd == "setgenerate":
try:
gen= raw_input("Generate? (true/false): ")
cpus = raw_input("Max processors/cores (-1 for unlimited, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
print access.stop()
except:
print "\n---An error occurred---\n"
elif cmd == "validateaddress":
try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrase":
try:
pwd = getpass.getpass(prompt="Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = getpass.getpass(prompt="Enter old wallet passphrase: ")
pwd2 = getpass.getpass(prompt="Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported"
| mit | -1,961,335,208,077,969,200 | 27.522124 | 101 | 0.568104 | false |
insomnia-lab/calibre | src/calibre/ebooks/docx/char_styles.py | 1 | 8194 | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
from collections import OrderedDict
from calibre.ebooks.docx.block_styles import ( # noqa
inherit, simple_color, LINE_STYLES, simple_float, binary_property, read_shd)
from calibre.ebooks.docx.names import XPath, get
# Read from XML {{{
def read_text_border(parent, dest):
border_color = border_style = border_width = padding = inherit
elems = XPath('./w:bdr')(parent)
if elems:
border_color = simple_color('auto')
border_style = 'solid'
border_width = 1
for elem in elems:
color = get(elem, 'w:color')
if color is not None:
border_color = simple_color(color)
style = get(elem, 'w:val')
if style is not None:
border_style = LINE_STYLES.get(style, 'solid')
space = get(elem, 'w:space')
if space is not None:
try:
padding = float(space)
except (ValueError, TypeError):
pass
sz = get(elem, 'w:sz')
if sz is not None:
# we dont care about art borders (they are only used for page borders)
try:
# A border of less than 1pt is not rendered by WebKit
border_width = min(96, max(8, float(sz))) / 8
except (ValueError, TypeError):
pass
setattr(dest, 'border_color', border_color)
setattr(dest, 'border_style', border_style)
setattr(dest, 'border_width', border_width)
setattr(dest, 'padding', padding)
def read_color(parent, dest):
ans = inherit
for col in XPath('./w:color[@w:val]')(parent):
val = get(col, 'w:val')
if not val:
continue
ans = simple_color(val)
setattr(dest, 'color', ans)
def read_highlight(parent, dest):
ans = inherit
for col in XPath('./w:highlight[@w:val]')(parent):
val = get(col, 'w:val')
if not val:
continue
if not val or val == 'none':
val = 'transparent'
ans = val
setattr(dest, 'highlight', ans)
def read_lang(parent, dest):
ans = inherit
for col in XPath('./w:lang[@w:val]')(parent):
val = get(col, 'w:val')
if not val:
continue
try:
code = int(val, 16)
except (ValueError, TypeError):
ans = val
else:
from calibre.ebooks.docx.lcid import lcid
val = lcid.get(code, None)
if val:
ans = val
setattr(dest, 'lang', ans)
def read_letter_spacing(parent, dest):
ans = inherit
for col in XPath('./w:spacing[@w:val]')(parent):
val = simple_float(get(col, 'w:val'), 0.05)
if val is not None:
ans = val
setattr(dest, 'letter_spacing', ans)
def read_sz(parent, dest):
ans = inherit
for col in XPath('./w:sz[@w:val]')(parent):
val = simple_float(get(col, 'w:val'), 0.5)
if val is not None:
ans = val
setattr(dest, 'font_size', ans)
def read_underline(parent, dest):
ans = inherit
for col in XPath('./w:u[@w:val]')(parent):
val = get(col, 'w:val')
if val:
ans = val if val == 'none' else 'underline'
setattr(dest, 'text_decoration', ans)
def read_vert_align(parent, dest):
ans = inherit
for col in XPath('./w:vertAlign[@w:val]')(parent):
val = get(col, 'w:val')
if val and val in {'baseline', 'subscript', 'superscript'}:
ans = val
setattr(dest, 'vert_align', ans)
def read_font_family(parent, dest):
ans = inherit
for col in XPath('./w:rFonts')(parent):
val = get(col, 'w:asciiTheme')
if val:
val = '|%s|' % val
else:
val = get(col, 'w:ascii')
if val:
ans = val
setattr(dest, 'font_family', ans)
# }}}
class RunStyle(object):
all_properties = {
'b', 'bCs', 'caps', 'cs', 'dstrike', 'emboss', 'i', 'iCs', 'imprint',
'rtl', 'shadow', 'smallCaps', 'strike', 'vanish', 'webHidden',
'border_color', 'border_style', 'border_width', 'padding', 'color', 'highlight', 'background_color',
'letter_spacing', 'font_size', 'text_decoration', 'vert_align', 'lang', 'font_family',
}
toggle_properties = {
'b', 'bCs', 'caps', 'emboss', 'i', 'iCs', 'imprint', 'shadow', 'smallCaps', 'strike', 'dstrike', 'vanish',
}
def __init__(self, rPr=None):
self.linked_style = None
if rPr is None:
for p in self.all_properties:
setattr(self, p, inherit)
else:
for p in (
'b', 'bCs', 'caps', 'cs', 'dstrike', 'emboss', 'i', 'iCs', 'imprint', 'rtl', 'shadow',
'smallCaps', 'strike', 'vanish', 'webHidden',
):
setattr(self, p, binary_property(rPr, p))
for x in ('text_border', 'color', 'highlight', 'shd', 'letter_spacing', 'sz', 'underline', 'vert_align', 'lang', 'font_family'):
f = globals()['read_%s' % x]
f(rPr, self)
for s in XPath('./w:rStyle[@w:val]')(rPr):
self.linked_style = get(s, 'w:val')
self._css = None
def update(self, other):
for prop in self.all_properties:
nval = getattr(other, prop)
if nval is not inherit:
setattr(self, prop, nval)
if other.linked_style is not None:
self.linked_style = other.linked_style
def resolve_based_on(self, parent):
for p in self.all_properties:
val = getattr(self, p)
if val is inherit:
setattr(self, p, getattr(parent, p))
def get_border_css(self, ans):
for x in ('color', 'style', 'width'):
val = getattr(self, 'border_'+x)
if x == 'width' and val is not inherit:
val = '%.3gpt' % val
if val is not inherit:
ans['border-%s' % x] = val
def clear_border_css(self):
for x in ('color', 'style', 'width'):
setattr(self, 'border_'+x, inherit)
@property
def css(self):
if self._css is None:
c = self._css = OrderedDict()
td = set()
if self.text_decoration is not inherit:
td.add(self.text_decoration)
if self.strike and self.strike is not inherit:
td.add('line-through')
if self.dstrike and self.dstrike is not inherit:
td.add('line-through')
if td:
c['text-decoration'] = ' '.join(td)
if self.caps is True:
c['text-transform'] = 'uppercase'
if self.i is True:
c['font-style'] = 'italic'
if self.shadow and self.shadow is not inherit:
c['text-shadow'] = '2px 2px'
if self.smallCaps is True:
c['font-variant'] = 'small-caps'
if self.vanish is True or self.webHidden is True:
c['display'] = 'none'
self.get_border_css(c)
if self.padding is not inherit:
c['padding'] = '%.3gpt' % self.padding
for x in ('color', 'background_color'):
val = getattr(self, x)
if val is not inherit:
c[x.replace('_', '-')] = val
for x in ('letter_spacing', 'font_size'):
val = getattr(self, x)
if val is not inherit:
c[x.replace('_', '-')] = '%.3gpt' % val
if self.highlight is not inherit and self.highlight != 'transparent':
c['background-color'] = self.highlight
if self.b:
c['font-weight'] = 'bold'
if self.font_family is not inherit:
c['font-family'] = self.font_family
return self._css
def same_border(self, other):
return self.get_border_css({}) == other.get_border_css({})
| gpl-3.0 | 1,767,311,756,068,505,300 | 32.720165 | 140 | 0.520625 | false |
mementum/backtrader | backtrader/__init__.py | 1 | 2578 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 Daniel Rodriguez
#
# 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 <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .version import __version__, __btversion__
from .errors import *
from . import errors as errors
from .utils import num2date, date2num, time2num, num2time
from .linebuffer import *
from .functions import *
from .order import *
from .comminfo import *
from .trade import *
from .position import *
from .store import Store
from . import broker as broker
from .broker import *
from .lineseries import *
from .dataseries import *
from .feed import *
from .resamplerfilter import *
from .lineiterator import *
from .indicator import *
from .analyzer import *
from .observer import *
from .sizer import *
from .sizers import SizerFix # old sizer for compatibility
from .strategy import *
from .writer import *
from .signal import *
from .cerebro import *
from .timer import *
from .flt import *
from . import utils as utils
from . import feeds as feeds
from . import indicators as indicators
from . import indicators as ind
from . import studies as studies
from . import strategies as strategies
from . import strategies as strats
from . import observers as observers
from . import observers as obs
from . import analyzers as analyzers
from . import commissions as commissions
from . import commissions as comms
from . import filters as filters
from . import signals as signals
from . import sizers as sizers
from . import stores as stores
from . import brokers as brokers
from . import timer as timer
from . import talib as talib
# Load contributed indicators and studies
import backtrader.indicators.contrib
import backtrader.studies.contrib
| gpl-3.0 | 5,644,990,882,186,810,000 | 27.644444 | 79 | 0.707913 | false |
nCoda/macOS | .eggs/py2app-0.14-py2.7.egg/py2app/recipes/PIL/prescript.py | 1 | 1297 | def _recipes_pil_prescript(plugins):
try:
import Image
have_PIL = False
except ImportError:
from PIL import Image
have_PIL = True
import sys
def init():
if Image._initialized >= 2:
return
if have_PIL:
try:
import PIL.JpegPresets
sys.modules['JpegPresets'] = PIL.JpegPresets
except ImportError:
pass
for plugin in plugins:
try:
if have_PIL:
try:
# First try absolute import through PIL (for
# Pillow support) only then try relative imports
m = __import__(
'PIL.' + plugin, globals(), locals(), [])
m = getattr(m, plugin)
sys.modules[plugin] = m
continue
except ImportError:
pass
__import__(plugin, globals(), locals(), [])
except ImportError:
if Image.DEBUG:
print('Image: failed to import')
if Image.OPEN or Image.SAVE:
Image._initialized = 2
return 1
Image.init = init
| gpl-3.0 | 5,566,119,026,648,664,000 | 27.822222 | 72 | 0.43485 | false |
Caoimhinmg/PmagPy | programs/lowrie.py | 1 | 4077 | #!/usr/bin/env python
from __future__ import division
from __future__ import print_function
from builtins import input
from builtins import range
from past.utils import old_div
import sys
import matplotlib
if matplotlib.get_backend() != "TKAgg":
matplotlib.use("TKAgg")
import pmagpy.pmag as pmag
import pmagpy.pmagplotlib as pmagplotlib
def main():
"""
NAME
lowrie.py
DESCRIPTION
plots intensity decay curves for Lowrie experiments
SYNTAX
lowrie -h [command line options]
INPUT
takes SIO formatted input files
OPTIONS
-h prints help message and quits
-f FILE: specify input file
-N do not normalize by maximum magnetization
-fmt [svg, pdf, eps, png] specify fmt, default is svg
-sav save plots and quit
"""
fmt,plot='svg',0
FIG={} # plot dictionary
FIG['lowrie']=1 # demag is figure 1
pmagplotlib.plot_init(FIG['lowrie'],6,6)
norm=1 # default is to normalize by maximum axis
if len(sys.argv)>1:
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
if '-N' in sys.argv: norm=0 # don't normalize
if '-sav' in sys.argv: plot=1 # don't normalize
if '-fmt' in sys.argv: # sets input filename
ind=sys.argv.index("-fmt")
fmt=sys.argv[ind+1]
if '-f' in sys.argv: # sets input filename
ind=sys.argv.index("-f")
in_file=sys.argv[ind+1]
else:
print(main.__doc__)
print('you must supply a file name')
sys.exit()
else:
print(main.__doc__)
print('you must supply a file name')
sys.exit()
data=open(in_file).readlines() # open the SIO format file
PmagRecs=[] # set up a list for the results
keys=['specimen','treatment','csd','M','dec','inc']
for line in data:
PmagRec={}
rec=line.replace('\n','').split()
for k in range(len(keys)):
PmagRec[keys[k]]=rec[k]
PmagRecs.append(PmagRec)
specs=pmag.get_dictkey(PmagRecs,'specimen','')
sids=[]
for spec in specs:
if spec not in sids:sids.append(spec) # get list of unique specimen names
for spc in sids: # step through the specimen names
print(spc)
specdata=pmag.get_dictitem(PmagRecs,'specimen',spc,'T') # get all this one's data
DIMs,Temps=[],[]
for dat in specdata: # step through the data
DIMs.append([float(dat['dec']),float(dat['inc']),float(dat['M'])*1e-3])
Temps.append(float(dat['treatment']))
carts=pmag.dir2cart(DIMs).transpose()
#if norm==1: # want to normalize
# nrm=max(max(abs(carts[0])),max(abs(carts[1])),max(abs(carts[2]))) # by maximum of x,y,z values
# ylab="M/M_max"
if norm==1: # want to normalize
nrm=(DIMs[0][2]) # normalize by NRM
ylab="M/M_o"
else:
nrm=1. # don't normalize
ylab="Magnetic moment (Am^2)"
xlab="Temperature (C)"
pmagplotlib.plotXY(FIG['lowrie'],Temps,old_div(abs(carts[0]),nrm),sym='r-')
pmagplotlib.plotXY(FIG['lowrie'],Temps,old_div(abs(carts[0]),nrm),sym='ro') # X direction
pmagplotlib.plotXY(FIG['lowrie'],Temps,old_div(abs(carts[1]),nrm),sym='c-')
pmagplotlib.plotXY(FIG['lowrie'],Temps,old_div(abs(carts[1]),nrm),sym='cs') # Y direction
pmagplotlib.plotXY(FIG['lowrie'],Temps,old_div(abs(carts[2]),nrm),sym='k-')
pmagplotlib.plotXY(FIG['lowrie'],Temps,old_div(abs(carts[2]),nrm),sym='k^',title=spc,xlab=xlab,ylab=ylab) # Z direction
files={'lowrie':'lowrie:_'+spc+'_.'+fmt}
if plot==0:
pmagplotlib.drawFIGS(FIG)
ans=input('S[a]ve figure? [q]uit, <return> to continue ')
if ans=='a':
pmagplotlib.saveP(FIG,files)
elif ans=='q':
sys.exit()
else:
pmagplotlib.saveP(FIG,files)
pmagplotlib.clearFIG(FIG['lowrie'])
if __name__ == "__main__":
main()
| bsd-3-clause | 519,150,418,447,072,960 | 35.72973 | 127 | 0.575914 | false |
chetbox/easyedit | easyedit.py | 1 | 32834 | """A simple text editor for s60
Copyright Chetan Padia ([email protected])
Released under GPLv3 (See COPYING.txt)
"""
# This file is part of EasyEdit.
#
# EasyEdit 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.
#
# EasyEdit 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 <http://www.gnu.org/licenses/>.
# Settings
VERSION=(2, 0, 0)
DEBUG = 0
CONFFILE='C:\\SYSTEM\\Data\\EasyEdit\\settings.conf'
BUSY_MESSAGE = u'[busy]'
from appuifw import *
from key_codes import EKeyLeftArrow, EKeyRightArrow, EKeyBackspace, EKey1, EKey2, EKeyEdit, EKeyYes
from e32 import Ao_lock, ao_yield, ao_sleep, s60_version_info, drive_list
from os import rename, mkdir, makedirs, remove, rmdir, listdir
from os.path import exists, isfile, isdir, join, basename, dirname, normpath
from sys import getdefaultencoding, exc_info
from encodings import aliases
from graphics import FONT_ANTIALIAS
import re
# main configuration keys
CONF_VERSION = 'version'
CONF_SCREEN = 'screen size'
CONF_ORIENTATION = 'screen orentation'
CONF_FONT = 'font'
CONF_FONT_SIZE = 'font size'
CONF_FONT_COLOUR = 'font colour'
CONF_FONT_ANTIALIAS = 'font anti-aliasing'
CONF_ENCODING = 'encoding'
CONF_HISTORY = 'history'
CONF_HISTORY_SIZE = 'history size'
CONF_LAST_DIR = 'last dir'
CONF_NEW_LINES = 'new lines'
CONF_LINE_NUMBERS = 'line numbers'
# search settings keys
CONF_FIND_CASE_SENSITIVE = 'case-sensitive search'
CONF_FIND_TEXT = 'search text'
CONF_FIND_DIRECTION = 'search direction'
CONF_FIND_REGEXP = 'regular expression'
CONF_REPLACE_TEXT = 'replace text'
CONF_REGEXP_MULTILINE = 'multi line'
CONF_REGEXP_DOTALL = 'dot all'
# config groups keys
CONF_GROUP_MAIN = 'main'
CONF_GROUP_FIND = 'find'
CONF_GROUP_FIND_DIRECTION = 'find direction'
CONF_GROUP_REPLACE = 'replace'
CONF_GROUP_REGEXP = 'regular expressions'
CONF_DB = [
# id group description default min. s60_version options (None => no dialog) (a,'b') => a.b = option
(CONF_VERSION, CONF_GROUP_MAIN, 'Version', VERSION, 1, None, None ),
(CONF_ENCODING, CONF_GROUP_MAIN, 'File encoding', getdefaultencoding(), 1, [unicode(enc) for enc in aliases.aliases], None ),
(CONF_NEW_LINES, CONF_GROUP_MAIN, 'New lines', 'unix', 1, ['unix', 'windows'], None ),
(CONF_FONT, CONF_GROUP_MAIN, 'Font', Text().font[0], 1, available_fonts(), None ),
(CONF_FONT_SIZE, CONF_GROUP_MAIN, 'Font size', 15, 2, int, None ),
(CONF_FONT_COLOUR, CONF_GROUP_MAIN, 'Font colour', (0,0,0), 1, None, None ),
(CONF_FONT_ANTIALIAS, CONF_GROUP_MAIN, 'Font anti-aliasing', 'no', 2, ['yes', 'no'], None ),
(CONF_LINE_NUMBERS, CONF_GROUP_MAIN, 'Display line number', 'yes', 1, ['yes', 'no'], None ),
(CONF_LAST_DIR, CONF_GROUP_MAIN, 'Last used directory', '\\', 1, None, None ),
(CONF_HISTORY, CONF_GROUP_MAIN, 'History', [], 1, None, None ),
(CONF_HISTORY_SIZE, CONF_GROUP_MAIN, 'Max history size', 8, 1, int, None ),
(CONF_SCREEN, CONF_GROUP_MAIN, 'Screen Size', 'normal', 1, ['normal', 'large', 'full'], (app, 'screen') ),
(CONF_ORIENTATION, CONF_GROUP_MAIN, 'Screen orientation', 'automatic', 3, ['automatic', 'portrait', 'landscape'], (app, 'orientation') ),
(CONF_FIND_TEXT, CONF_GROUP_FIND, 'Search text', '', 1, unicode, None ),
(CONF_REPLACE_TEXT, CONF_GROUP_REPLACE, 'Replace text', '', 1, unicode, None ),
(CONF_FIND_DIRECTION, CONF_GROUP_FIND_DIRECTION, 'Search direction', 'all', 1, ['all', 'next', 'previous'], None ),
(CONF_FIND_CASE_SENSITIVE, CONF_GROUP_FIND, 'Case sensitive find', 'no', 1, ['yes', 'no'], None ),
(CONF_FIND_REGEXP, CONF_GROUP_FIND, 'Regular expression', 'no', 1, ['yes', 'no'], None ),
(CONF_REGEXP_MULTILINE, CONF_GROUP_REGEXP, '^ and $ match lines', 'no', 1, ['yes', 'no'], None ),
(CONF_REGEXP_DOTALL, CONF_GROUP_REGEXP, '. matches all', 'no', 1, ['yes', 'no'], None ),
]
class Titlebar (object):
"""A class to manage the S60 Titlebar"""
# create a wrapper around the titlebar text which ignores prepended text
def __setTitle(self, value):
self.__title = app.title = value
ao_yield()
def __getTitle(self):
return self.__title
title = property(fget = __getTitle, fset = __setTitle)
__oldtitle = [] # (id, message) elements
def __init__(self, id='default', default=app.title):
self.__title = unicode(default)
self.current_id = id
def temporary(self, message):
"""set title but do not remember it when changed"""
app.title = unicode(message)
ao_yield()
def refresh(self):
"""set the titlebar to the current stored value"""
app.title = self.title
ao_yield()
def _begin(self, override, id, message, separator=u' > '):
oldtitle = (self.current_id, self.title)
self.__oldtitle.append(oldtitle)
self.current_id = id
if override:
self.title = unicode(message)
else:
self.title = oldtitle[1] + separator + unicode(message)
ao_yield()
def _end(self):
if len(self.__oldtitle) > 0:
(self.current_id, self.title) = self.__oldtitle.pop()
ao_yield()
def __run(self, override, id, message, function, separator=u' > '):
"""Execute a function while displaying/appending a message on the Titlebar"""
self._begin(override, id, message, separator)
retval = function()
self._end()
return retval
def run(self, id, message, function, separator=u' > '):
"""Execute a function while appending a message to the Titlebar"""
return self.__run(0, id, message, function)
def run_no_path(self, id, message, function, separator=u' > '):
"""Execute a function while displaying a message on the Titlebar"""
return self.__run(1, id, message, function)
def prepend(self, id, message):
"""temporarily prepends a string to the current titlebat text"""
if self.current_id == id:
app.title = unicode(message) + self.title
ao_yield()
class Settings (dict):
"""Settings manager"""
saveRequired = 0
keep_config = 0
db = None
path = None
exit = Ao_lock()
titlebar = None
def __setitem__(self, key, value):
"""equivalent to dict.__setitem__ but flags saveRequired"""
self.saveRequired = 1
dict.__setitem__(self, key, value)
def __init__(self, db, path, titlebar=Titlebar('settings')):
dict.__init__(self)
self.titlebar = titlebar
self.path = path
self.db = db
# create a new configuration in memory if one does not exist
existing_conf = isfile(self.path)
if existing_conf:
try:
# read the config file from disk
f = open(self.path, 'r')
conf_string = f.read()
f.close()
self.update(eval(conf_string))
# check if a new version has been installed
existing_conf = (self[CONF_VERSION] == VERSION)
except:
if DEBUG:
print("Cannot read config file " + self.path)
note(u'Error reading settings', 'error')
self.keep_config = not(query(u'Reset settings?', 'query'))
existing_conf = 0
if not(existing_conf):
note(u"Creating new configuration", 'info')
# set current settings to these defaults
self.update(dict([(id, default) for (id,group,description,default,s60,options,action) in self.db]))
# create the folder containing config if it does not exist
conf_folder = dirname(self.path)
if not(exists(conf_folder)):
makedirs(conf_folder)
self.saveRequired = 1
self.save()
def save(self):
"""Save current config to disk"""
if DEBUG:
print("Saving settings to " + self.path)
if self.saveRequired and not(self.keep_config):
try:
f = open(self.path, 'w')
f.write(repr(self))
f.close()
self.saveRequired = 0
self.keep_config = 0
except:
note(u'Error saving config', 'error')
elif DEBUG:
print("Config not saved")
def __currentSettingsList(self, group_filter=(lambda group: 0)):
return [(id,group,description,default,s60,options,action)
for (id,group,description,default,s60,options,action) in self.db
if s60_version_info[0] >= s60
and options != None # filter out items with no user options
and group_filter(group) # filter by group_filter function
]
def refresh_ui(self, settingsList=None):
"""Update the Settings panel with the settings passed into settingsList"""
if self.settings_list: # make sure the UI control exists
# get a list of all settings if one has not been provided
if settingsList == None:
settingsList = self.__currentSettingsList()
slist = [(unicode(description), unicode(self[id]))
for (id,group,description,default,s60,options,action)
in settingsList
]
self.settings_list.set_list(slist, self.settings_list.current())
ao_yield()
elif DEBUG:
print("Settings: update: No list to update!")
def show_ui(self, group_filter=(lambda group: 0), callback=None, titlebar=u'Settings', menu_items=[]):
"""Create and show a settings editor"""
def show():
def modify(selected):
"""edit a setting"""
(id, description, options, action, supported_s60_version) = [(id, description, options, action, s60)
for (id,group,description,default,s60,options,action)
in self.__currentSettingsList(group_filter)
][selected]
# display options
selection = None
if options.__class__ == type:
if options == int:
selection = query(unicode(description), 'number', self[id])
elif options == str or options == unicode:
selection = query(unicode(description), 'text', unicode(self[id]))
if selection != None:
self[id] = selection
elif options.__class__ == list:
n_options = len(options)
if n_options == 1:
selection == 0
elif n_options == 2: # if there are only 2 options
selection = (options.index(self[id]) + 1) % 2 # select the other option
elif n_options > 2 and n_options <= 4:
selection = popup_menu([unicode(option).capitalize() for option in options], unicode(description))
else:
options = [unicode(option) for option in options]
options.sort()
selection = self.titlebar.run(str(description), unicode(description), lambda: selection_list(choices=options, search_field=1))
if selection != None:
self[id] = options[selection]
elif DEBUG:
print("Settings : Unsupported type " + str(options.__class__))
self.refresh_ui(self.__currentSettingsList(group_filter))
self.saveRequired = 1
# run any immediate action if one has been defined
if action != None and s60_version_info[0] >= supported_s60_version:
try:
setattr(action[0], action[1], self[id])
except:
note(u'Error setting ' + unicode(description), 'error')
self.settings_list = Listbox([(u'dummy',u'item')], lambda: modify(self.settings_list.current()))
self.refresh_ui(self.__currentSettingsList(group_filter))
# save previous application state
previous_body = app.body
previous_menu = app.menu
previous_exit_key_handler = app.exit_key_handler
# show the settings editor
app.body = self.settings_list
app.menu = menu_items + [
(u'Modify', lambda: modify(self.settings_list.current())),
(u'Close', self.exit.signal),
]
self.settings_list.bind(EKeyEdit, lambda: modify(self.settings_list.current()))
self.settings_list.bind(EKeyYes, app.menu[0][1]) # set call key to do first action in menu
app.exit_key_handler = self.exit.signal
# wait for a signal to exit the settings editor
self.exit.wait()
# sve any changes
self.save()
# exit the editor
app.body = previous_body
app.menu = previous_menu
app.exit_key_handler = previous_exit_key_handler
del(self.settings_list) # destroy list UI to save memory
retval = None
if self.titlebar != None:
retval = self.titlebar.run('settings', titlebar, show)
else:
retval = show()
if callback != None:
callback()
return retval
from dir_iter import Directory_iter
class Filebrowser (Directory_iter):
def __init__(self, initial_dir='\\', titlebar=Titlebar('filebrowser')):
self.drive_list = drive_list()
Directory_iter.__init__(self, self.drive_list)
# set initial directory if one has been specified
if initial_dir != '\\':
if isdir(initial_dir):
self.path = initial_dir
self.at_root = 0
# go up a directory if directory current is empty - listbox cannot display empty lists!
if len(self.list_repr()) == 0:
self.pop()
elif DEBUG:
print("Filebrowser : Directory does not exist " + str(initial_dir))
self.lock = Ao_lock()
self.titlebar = titlebar
self.listbox = None
def __getSelection(self):
if self.at_root:
return str(self.drive_list[self.listbox.current()])
else:
return join(self.path, str(self.entry(self.listbox.current())))
abs_path = property(fget=__getSelection)
def refresh_ui(self, current=0):
"""refresh the current file list
current sets the current selection"""
dir_listing = self.list_repr()
# if passed a folder name, find its index
if current.__class__ == str:
try:
current = [file for (file, stats) in dir_listing].index(u'[' + unicode(current) + u']')
except:
# if not found, move focus to beginning of list
current = 0
if len(dir_listing) > 0:
self.titlebar.temporary(self.path)
self.listbox.set_list(dir_listing, current)
ao_yield()
else:
note(u'Empty directory', 'info')
self.pop()
self.refresh_ui(self.listbox.current())
def show_ui(self, allow_directory=0):
"""show the file browser - returns the path selected
allow_directory = 1 allows a directory to be selected"""
def show_ui():
self.return_path = None
def descend():
"""open the currently selected directory"""
selection = self.listbox.current()
path = self.entry(selection)
if self.at_root or isdir(path):
self.add(selection)
self.refresh_ui()
def ascend():
"""go up the directory hierarchy"""
if self.path != '\\':
current_folder = basename(self.path)
self.pop()
self.refresh_ui(current_folder)
def select():
"""select the current file or open the directory"""
if allow_directory or isfile(self.abs_path):
self.return_path = self.abs_path
self.lock.signal()
else:
descend()
def rename_file():
"""Rename the currently selected file"""
path = self.entry(self.listbox.current())
filename = basename(path)
new_name = query(u'Rename ' + filename, 'text', unicode(filename))
if new_name != None:
try:
new_path = dirname(path) + str(new_name)
rename(path, new_path)
note(u'File renamed', 'info')
except:
note(u'Error renaming file', 'error')
self.refresh_ui(self.listbox.current())
def create_directory():
"""create a new directory at the current location"""
if self.at_root:
note(u'Cannot create directory here', 'info')
else:
dir_name = query(u'New dir: ' + unicode(self.path) + u'\\', 'text', u'New directory')
if dir_name != None:
try:
mkdir(join(self.path, str(dir_name)))
except:
note(u'Error creating directory', 'error')
self.refresh_ui()
def delete_file():
path = self.entry(self.listbox.current())
if query(u'Delete ' + unicode(basename(path)) + u'?', 'query'):
change_made = 0
if isfile(path):
try:
remove(path)
change_made = 1
except:
note(u'Error delecting file', 'error')
elif isdir(path):
if len(listdir(path)) == 0:
try:
rmdir(normpath(path))
change_made = 1
except:
note(u'Error deleting directory', 'error')
else:
note(u'Not deleted: Directory is not empty', 'info')
if change_made:
self.refresh_ui()
def os_open():
"""open the currently selected file with the default application specified by the OS"""
if isfile(self.entry(self.listbox.current())):
try:
Content_handler().open_standalone(self.entry(self.listbox.current()))
except:
note(u'Error opening file', 'error')
# save ui state
body_previous = app.body
menu_previous = app.menu
exit_previous = app.exit_key_handler
# show file browser
app.menu = [
(u' [] Select', select),
(u' <- Parent directory', ascend),
(u' -> Enter directory', descend),
(u' 1 New directory', create_directory),
(u' 2 Open with OS', os_open),
(u'ABC Rename', rename_file),
(u' C Delete', delete_file),
]
self.listbox = Listbox([(u'dummy', u'item')], select)
self.listbox.bind(EKeyLeftArrow, ascend)
self.listbox.bind(EKeyRightArrow, descend)
self.listbox.bind(EKey1, create_directory)
self.listbox.bind(EKey2, os_open)
self.listbox.bind(EKeyEdit, rename_file)
self.listbox.bind(EKeyBackspace, delete_file)
self.refresh_ui()
app.body = self.listbox
app.exit_key_handler = self.lock.signal
ao_yield()
self.lock.wait()
self.listbox = None # let the listbox be garbage collected
# restore ui state
app.body = body_previous
app.menu = menu_previous
app.exit_key_handler = exit_previous
return self.return_path
return self.titlebar.run_no_path('filebrowser', unicode(self.path), show_ui)
class Editor:
"""chetbox[at]gmail[dot]com - EasyEdit is Released under GPLv2 (See bundled COPYING.txt)"""
titlebar = None
config = None
hasFocus = 0
filebrowser = None
text = None
running = 0
path = None
def __newline_fix(self, text):
"""Used to replace S60 UI newline characters with normal \n"""
return text.replace(u'\u2029',u'\n')
def __open_document(self, path, read_from_disk=1):
"""Open a document by reading from disk, and showing "busy" status."""
oldpath = self.path
self.path = path
error = 0
self.titlebar._end()
if path != None:
self.titlebar._begin(0, 'document', unicode(basename(path)))
self.__save_last_dir(path)
# add to recent list
if normpath(path) in self.config[CONF_HISTORY]:
self.config[CONF_HISTORY].remove(path)
self.config[CONF_HISTORY] = ([normpath(path)] + self.config[CONF_HISTORY])[:self.config[CONF_HISTORY_SIZE]]
self.config.save()
# show filename in titlebar until a different file is opened
if read_from_disk:
# show "busy" message
self.titlebar.prepend('document', BUSY_MESSAGE + u' ')
try:
# read file from disk
f = open(path)
text = f.read()
f.close()
text = self.decode(text)
# show file in editor
self.text.clear()
self.refresh()
self.text.set(text)
self.text.set_pos(0)
except:
note(u'Error opening file', 'error')
# ask user if they wish to remove it from the recent document list
if query(u'Remove from Recent Documents?', 'query'):
self.config[CONF_HISTORY].remove(path)
self.config.save()
# fallback to the previous document if there was an error
self.__open_document(oldpath, read_from_disk=0)
error = 1
def run(self):
"""Start EasyEdit"""
def exitHandler():
"""Stop EasyEdit"""
self.running = 0
focusLock = Ao_lock()
externalFocusHandler = app.focus
def focusHandler(f):
if f and not(self.hasFocus): # if we have just got focus
self.hasFocus = 1
focusLock.signal()
if not(f) and self.hasFocus: # if we just lost focus
self.hasFocus = 0
if externalFocusHandler:
externalFocusHandler(f)
app.focus = focusHandler
def save_query():
"""check if file needs saving and prompt user if necessary - returns user reponse"""
save = 0
save_required = 1
current_text = self.__newline_fix(self.text.get())
if self.exists():
# read file and compare to current
f = open(self.path, 'r')
saved_text = f.read()
f.close()
if saved_text == self.encode(current_text):
save_required = 0
elif len(current_text) == 0:
save_required = 0
if save_required:
if DEBUG:
print("Save required")
save = popup_menu([u'Yes', u'No'], u'Save file?')
if save != None:
save = not(save) # because 0 => 'yes' option, 1 => 'no' option
if save == 1:
f_save()
return save
def f_new(force=0):
"""start a new, blank document"""
if force or save_query() != None:
self.text.clear()
self.refresh()
self.__open_document(None)
def f_open():
"""open an existing document"""
# show file selector
path = None
if self.filebrowser == None:
self.filebrowser = Filebrowser(self.config[CONF_LAST_DIR], self.titlebar)
path = self.filebrowser.show_ui()
# check if file needs saving, do not open document if file not saved
if path != None:
if save_query() != None:
self.__open_document(path)
def f_open_recent():
"""select a file to open from the recent document list"""
lock = Ao_lock()
listbox = None
def select():
lock.signal()
# check if file needs saving, do not open document if file not saved
if save_query() != None:
self.__open_document(self.config[CONF_HISTORY][listbox.current()])
def current_list():
return [(basename((unicode(file))), dirname(unicode(file))) for file in self.config[CONF_HISTORY]]
def remove_recent():
if query(u'Remove from recent documents?', 'query'):
self.config[CONF_HISTORY].remove(self.config[CONF_HISTORY][listbox.current()])
self.config.save()
new_list = current_list()
if len(new_list) > 0:
listbox.set_list(current_list())
else:
note(u'No more recent documents', 'info')
lock.signal()
list = current_list()
if len(list) > 0:
# save previous application state
previous_body = app.body
previous_menu = app.menu
previous_exit_key_handler = app.exit_key_handler
listbox = Listbox(list, select)
app.body = listbox
app.menu = [
(u'Open', select),
(u'Remove from list', remove_recent),
]
app.exit_key_handler = lock.signal
listbox.bind(EKeyBackspace, remove_recent)
lock.wait()
# exit the editor
app.body = previous_body
app.menu = previous_menu
app.exit_key_handler = previous_exit_key_handler
else:
note(u'No recent documents', 'info')
def f_save(force=0):
"""save the current file - force argument skips exist check"""
if force or self.path != None:
# show "busy" message
self.titlebar.prepend('document', BUSY_MESSAGE + u' ')
try:
text = self.encode(self.text.get())
f=open(self.path, 'w')
f.write(text)
f.close()
note(u'File saved','conf')
except:
note(u'Error saving file.','error')
# clear "busy" message
self.titlebar.refresh()
else:
f_save_as()
def f_save_as():
"""save current file at a new location"""
# show file selector
path = None
if self.filebrowser == None:
self.filebrowser = Filebrowser(self.config[CONF_LAST_DIR], self.titlebar)
path = self.filebrowser.show_ui(allow_directory=1)
if path != None:
# assume a directory has been selected - suggest a filename in the current directory
new_file_location = dirname(path)
containing_dir = basename(path)
# <hack reason="top-level paths (drives) need to have a \ appended because join will not add it">
if len(new_file_location) == 2: # if new_file_location is just a drive letter (top-level)
new_file_location += '\\' # append a \
# </hack>
suggested_filename = join(containing_dir, 'untitled.txt')
# if a file is selected update the suggested name with its name
if isfile(path):
current_filename = containing_dir # if a dir was not selected containing_dir is the filename
containing_dir = basename(new_file_location)
new_file_location = dirname(new_file_location)
suggested_filename = join(containing_dir, current_filename)
new_filename = query(unicode(new_file_location), 'text', unicode(suggested_filename))
if new_filename != None:
new_path = join(new_file_location, new_filename)
# check if file already exists and ask if it should be replaced
save_possible = 0
if isfile(new_path):
save_possible = query(u'Overwite file?', 'query')
elif isdir(new_path):
note(u'Not saved: A directory exists with that name', 'info')
else:
save_possible = 1
if save_possible:
self.__open_document(new_path, read_from_disk=0)
f_save(force=1) # force prevents another call to f_save_as
def s_go_to_line():
"""move cursor to beginning of specified line number"""
text = self.__newline_fix(self.text.get())
total_lines = text.count(u'\n') + 1
line_no = query(u'Line number (1 - ' + unicode(total_lines) + ')', 'number', 1)
if line_no != None:
if line_no > 0 and line_no <= total_lines:
# find the position in the text of the beginning of the line required
last_newline = -1
for line in range(line_no - 1):
last_newline = text.index('\n', (last_newline + 1))
self.text.set_pos(last_newline + 1)
else:
note(u'Invalid line number', 'error')
def s_find():
"""find a string in the document"""
def find():
def findindex(text, searchstring, searchall=(self.config[CONF_FIND_DIRECTION] == 'all'), reverse=(self.config[CONF_FIND_DIRECTION] == 'previous'), ignore_case=(self.config[CONF_FIND_CASE_SENSITIVE] == 'no'), regexp=(self.config[CONF_FIND_REGEXP] == 'yes'), multiline=(self.config[CONF_REGEXP_MULTILINE] == 'yes'), dotall=(self.config[CONF_REGEXP_DOTALL] == 'yes')):
"""Behaves like string.replace(), but does can so in a case-insensitive fashion or with regular expressions"""
current_position = self.text.get_pos()
start_position = 0
# TODO : searching backwards/previous not implemented
if not(searchall):
start_position = current_position
if not(regexp):
searchstring = re.escape(searchstring)
try:
pattern = re.compile(searchstring, re.UNICODE | (ignore_case and re.IGNORECASE) | (multiline and re.MULTILINE) | (dotall and re.DOTALL))
except:
note(u'Invalid expression', 'error')
return None
match = pattern.search(text, start_position)
if match == None:
note(u'Search text not found', 'info')
return current_position
return match.start()
self.config.save()
text = self.__newline_fix(self.text.get())
search_text = self.config[CONF_FIND_TEXT]
new_pos = findindex(text, search_text)
if new_pos != None:
self.text.set_pos(new_pos)
self.config.exit.signal()
self.config.show_ui(group_filter=(lambda group: group in [CONF_GROUP_FIND, CONF_GROUP_FIND_DIRECTION] or (group == CONF_GROUP_REGEXP and self.config[CONF_FIND_REGEXP] == 'yes')), titlebar=u'Find', menu_items=[(u'Search',find)])
def s_replace():
"""replace all matching strings in the document"""
def replace():
def strreplace(text, old, new, count=0, ignore_case=(self.config[CONF_FIND_CASE_SENSITIVE] == 'no'), regexp=(self.config[CONF_FIND_REGEXP] == 'yes'), multiline=(self.config[CONF_REGEXP_MULTILINE] == 'yes'), dotall=(self.config[CONF_REGEXP_DOTALL] == 'yes')):
"""Behaves like string.replace(), but does can so in a case-insensitive fashion or with regular expressions"""
if not(regexp):
old = re.escape(old)
try:
pattern = re.compile(old, re.UNICODE | (ignore_case and re.IGNORECASE) | (multiline and re.MULTILINE) | (dotall and re.DOTALL))
except:
note(u'Invalid expression', 'error')
return None
(new_text, subs) = pattern.subn(new, text, count)
note(unicode(subs) + " matches replaced", 'info')
return new_text
self.config.save()
cursor_position = self.text.get_pos()
current_text = self.__newline_fix(self.text.get())
find_text = self.config[CONF_FIND_TEXT]
replace_text = self.config[CONF_REPLACE_TEXT]
self.titlebar.prepend('settings', BUSY_MESSAGE)
new_text = strreplace(current_text, find_text, replace_text)
if new_text != None:
self.text.set(new_text)
cursor_position = cursor_position + current_text[0:cursor_position].count(find_text) * (len(replace_text) - len(find_text))
self.text.set_pos(cursor_position)
self.config.exit.signal()
self.titlebar.refresh()
self.config.show_ui(group_filter=(lambda group: group in [CONF_GROUP_FIND, CONF_GROUP_REPLACE] or (group == CONF_GROUP_REGEXP and self.config[CONF_FIND_REGEXP] == 'yes')), titlebar=u'Replace', menu_items=[(u'Replace all', replace)])
# read settings
self.titlebar = Titlebar('document', u'EasyEdit')
self.config = Settings(CONF_DB, CONFFILE, Titlebar('settings', u'EasyEdit'))
self.hasFocus = 1
# save current state
old_title = app.title
old_screen = app.screen
old_orientation = app.orientation
old_exit_key_handler = app.exit_key_handler
old_body = app.body
old_menu = app.menu
old_focus_handler = app.focus
# set up environment from settings
app.screen = self.config[CONF_SCREEN]
app.orientation = self.config[CONF_ORIENTATION]
# create editor environment
self.text = Text()
self.path = None
# set up menu
app.menu=[
(u'File', (
(u'New', f_new),
(u'Open', f_open),
(u'Open recent', f_open_recent),
(u'Save', f_save),
(u'Save As', f_save_as),
)),
(u'Search', (
(u'Find', s_find),
(u'Replace', s_replace),
(u'Go to line', s_go_to_line),
)),
(u'Settings', lambda : self.config.show_ui(group_filter=(lambda group: group == CONF_GROUP_MAIN), callback=self.refresh, menu_items=[(u'Return to editor', self.config.exit.signal)])), # show all CONF_GROUP_MAIN settings
(u'Help', (
# (u'README', self.h_readme),
(u'About EasyEdit', lambda : query(unicode(self.__doc__), 'query')),
)),
(u'Exit', exitHandler),
]
# display editor
app.body = self.text
app.exit_key_handler = exitHandler
# set the 'dial' key to save document
self.text.bind(EKeyYes, f_save)
# start editing a new document
f_new()
ao_yield()
quit_app = None
while quit_app == None:
self.running = 1
while self.running:
# display line numbers if enabled
if self.hasFocus:
if self.config[CONF_LINE_NUMBERS] == 'yes':
n = self.__newline_fix(self.text.get()[:self.text.get_pos()]).count(u'\n')
self.titlebar.prepend('document', u'[' + unicode(n + 1) + '] ')
ao_yield()
ao_sleep(0.2) # refresh rate of line numbers (seconds)
else:
# lock to stop busy waiting when app is not in focus
focusLock.wait()
# intent to close application has now been expressed
quit_app = save_query()
# application should now be closing
# restore original state
app.title = old_title
app.screen = old_screen
app.orientation = old_orientation
app.exit_key_handler = old_exit_key_handler
app.body = old_body
app.menu = old_menu
app.focus = old_focus_handler
def encode(self, text):
"""encode text accoridng to settings"""
# ensure all new-lines are represented as '\n'
encoded_text = self.__newline_fix(text)
# convert to windows format if required
if self.config[CONF_NEW_LINES] == 'windows':
encoded_text = encoded_text.replace(u'\n', u'\r\n')
# convert text
encoded_text = encoded_text.encode(self.config[CONF_ENCODING])
return encoded_text
def decode(self, text):
"""decode text according to settings"""
# decode text
decoded_text = unicode(text.decode(self.config[CONF_ENCODING]))
# replace windows new lines if necessary
if self.config[CONF_NEW_LINES] == 'windows':
decoded_text = decoded_text.replace(u'\r\n', u'\n')
return decoded_text
def exists(self):
"""handy function that checks if the open document exists on disk (may have different contents)"""
return (self.path != None) and (len(self.path) > 0) and isfile(self.path)
def refresh(self):
"""refresh the editor view"""
def refresh():
cursor_position = self.text.get_pos()
text = self.text.get()
self.text.font = (
unicode(self.config[CONF_FONT]),
self.config[CONF_FONT_SIZE],
(self.config[CONF_FONT_ANTIALIAS] == 'yes') and FONT_ANTIALIAS
)
self.text.color = self.config[CONF_FONT_COLOUR]
self.text.set(text)
self.text.set_pos(cursor_position)
self.titlebar.run_no_path('refresh', BUSY_MESSAGE, refresh)
def __save_last_dir(self, path):
"""save the location of the last viewed directory in self.config"""
if isdir(path):
self.config[CONF_LAST_DIR] = normpath(path)
else:
self.config[CONF_LAST_DIR] = dirname(normpath(path))
self.config.save()
# run the editor!
if __name__ == '__main__':
Editor().run()
| gpl-3.0 | -936,847,161,768,324,200 | 36.100565 | 369 | 0.655662 | false |
lsaffre/blog | docs/blog/2017/2.py | 1 | 3105 | import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QPushButton,
QMessageBox, QDesktopWidget, QMainWindow,
QAction, qApp, QTextEdit, QHBoxLayout,
QVBoxLayout)
# from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QIcon
class DetailForm(QWidget):
def __init__(self, title="Detail Form"):
super().__init__()
self.setWindowTitle(title)
self.initUI()
def initUI(self):
okButton = QPushButton("OK")
cancelButton = QPushButton("Cancel")
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 150)
# self.show()
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
textEdit = QTextEdit()
self.setCentralWidget(textEdit)
self.setGeometry(300, 300, 300, 220)
self.center()
self.setWindowTitle('2.py')
self.setWindowIcon(QIcon('../../.static/logo.png'))
self.setToolTip('This is a <b>QWidget</b> widget')
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
exitAction = QAction(QIcon('exit.png'), '&Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
fileMenu.addAction(exitAction)
a = QAction(QIcon('detail.png'), '&Detail', self)
a.triggered.connect(self.show_detail)
fileMenu.addAction(a)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
# btn = QPushButton('Quit', self)
# btn.clicked.connect(QCoreApplication.instance().quit)
# btn.setToolTip('This is a <b>QPushButton</b> widget')
# btn.resize(btn.sizeHint())
# btn.move(50, 50)
self.show()
self.statusBar().showMessage('Ready')
def show_detail(self, event):
self.detail_form = DetailForm()
self.detail_form.show()
def closeEvent(self, event):
reply = QMessageBox.question(self, 'MessageBox',
"This will close the window! Are you sure?",
QMessageBox.Yes |
QMessageBox.No, QMessageBox.Yes)
if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
| gpl-3.0 | 2,632,101,182,666,969,000 | 27.75 | 70 | 0.544605 | false |
stphivos/django-mock-queries | examples/users/users/settings.py | 1 | 3188 | """
Django settings for users project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import django
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3sy3!6p&s&g2@t922(%@4z+(np+yc#amz0id80vyk03$x8&38$'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'analytics',
)
if django.VERSION[0] == 1:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
else:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'users.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'users.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| mit | 4,385,639,867,455,560,700 | 26.721739 | 73 | 0.686324 | false |
crichardson17/emgtemp | Metals_Sims/Dusty_sims/z_0.5_2.0/z_0.5_2.0_metal_sim_plots.py | 1 | 18682 | import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
import urllib
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.cm as cm
Low_Temp_Color = 'k'
Mid_Temp_Color = 'g'
High_Temp_Color = 'r'
#Temp_Color = 0.5
Cloudy_Sim_Color = 'cyan'
markersize = 20
SDSS_File = '/Users/Sam/Documents/emgtemp/data/4363_gr_5_0_err_dered.csv'
SDSS_Data = np.genfromtxt(SDSS_File,skip_header=1, delimiter = ',',dtype=float,unpack=True,names=True)
NII_6584 = SDSS_Data['Flux_NII_6583']
Ha_6562 = SDSS_Data['Flux_Ha_6562']
OI_6300 = SDSS_Data['Flux_OI_6300']
OIII_5006 = SDSS_Data['Flux_OIII_5006']
Hb_4861 = SDSS_Data['Flux_Hb_4861']
OIII_4363 = SDSS_Data['Flux_OIII_4363']
SII_6716 = SDSS_Data['Flux_SII_6716']
SII_6731 = SDSS_Data['Flux_SII_6730']
OII_3727 = SDSS_Data['Flux_OII_3726'] + SDSS_Data['Flux_OII_3728']
OIII_Hb = np.log10(OIII_5006/Hb_4861)
NII_Ha = np.log10(NII_6584/Ha_6562)
Temp_Ratio = np.log10(OIII_5006/OIII_4363)
S_Ratio = np.log10(SII_6716/SII_6731)
NO_Ratio = np.log10(NII_6584/OII_3727)
OI_Ratio = np.log10(OI_6300/Ha_6562)
O_Ratio = np.log10(OIII_5006/OII_3727)
S_Ha_Ratio = np.log10((SII_6716+SII_6731)/Ha_6562)
Cloudy_File = '/Users/Sam/Documents/emgtemp/Metals_Sims/Dusty_sims/z_0.5_2.0/z_0.5_2.0_sims.pun'
Cloudy_Data = np.genfromtxt(Cloudy_File, delimiter = '\t',dtype=float,unpack=True,names=True)
Cloudy_NII_6584 = Cloudy_Data['N__2__6584A']
Cloudy_Ha_6562 = Cloudy_Data['H__1__6563A']
Cloudy_OIII_5006 = Cloudy_Data['O__3__5007A']
Cloudy_Hb_4861 = Cloudy_Data['TOTL__4861A']
Cloudy_OIII_4363 = Cloudy_Data['TOTL__4363A']
Cloudy_SII_6716 = Cloudy_Data['S_II__6716A']
Cloudy_SII_6731 = Cloudy_Data['S_II__6731A']
Cloudy_OII_3727 = Cloudy_Data['TOTL__3727A']
Cloudy_OI_6300 = Cloudy_Data['O__1__6300A']
Cloudy_OIII_Hb = np.log10(Cloudy_OIII_5006/Cloudy_Hb_4861)
Cloudy_NII_Ha = np.log10(Cloudy_NII_6584/Cloudy_Ha_6562)
Cloudy_Temp_Ratio = np.log10(Cloudy_OIII_5006/Cloudy_OIII_4363)
Cloudy_S_Ratio = np.log10(Cloudy_SII_6716/Cloudy_SII_6731)
Cloudy_NO_Ratio = np.log10(Cloudy_NII_6584/Cloudy_OII_3727)
Cloudy_OI_Ratio = np.log10(Cloudy_OI_6300/Cloudy_Ha_6562)
Cloudy_O_Ratio = np.log10(Cloudy_OIII_5006/Cloudy_OII_3727)
Cloudy_S_Ha_Ratio = np.log10((Cloudy_SII_6716+Cloudy_SII_6731)/Cloudy_Ha_6562)
Grid_File = '/Users/Sam/Documents/emgtemp/Metals_Sims/Dusty_sims/z_0.6_2.0/z_0.6_2.0_sims.grd'
Grid_Data = np.genfromtxt(Grid_File,skip_header=1,delimiter = '\t',dtype=float,unpack=True)
Cloudy_Metals = Grid_Data[8,:]
Cloudy_Den = Grid_Data[6,:]
Cloudy_NII_Ha_array = np.reshape(Cloudy_NII_Ha,(6,-1))
Cloudy_OI_Ratio_array = np.reshape(Cloudy_OI_Ratio,(6,-1))
Cloudy_OIII_Hb_array = np.reshape(Cloudy_OIII_Hb,(6,-1))
Cloudy_Temp_Ratio_array = np.reshape(Cloudy_Temp_Ratio,(6,-1))
Cloudy_S_Ratio_array = np.reshape(Cloudy_S_Ratio,(6,-1))
Cloudy_NO_Ratio_array = np.reshape(Cloudy_NO_Ratio,(6,-1))
Cloudy_O_Ratio_array = np.reshape(Cloudy_O_Ratio,(6,-1))
Cloudy_S_Ha_Ratio_array = np.reshape(Cloudy_S_Ha_Ratio,(6,-1))
Cloudy_NII_Ha_transpose = np.transpose(Cloudy_NII_Ha_array)
Cloudy_OI_Ratio_transpose = np.transpose(Cloudy_OI_Ratio_array)
Cloudy_OIII_Hb_transpose = np.transpose(Cloudy_OIII_Hb_array)
Cloudy_Temp_Ratio_transpose = np.transpose(Cloudy_Temp_Ratio_array)
Cloudy_S_Ratio_transpose = np.transpose(Cloudy_S_Ratio_array)
Cloudy_NO_Ratio_transpose = np.transpose(Cloudy_NO_Ratio_array)
Cloudy_O_Ratio_transpose = np.transpose(Cloudy_O_Ratio_array)
Cloudy_S_Ha_Ratio_transpose = np.transpose(Cloudy_S_Ha_Ratio_array)
#cold_data_colors = [plt.cm.Blues(i) for i in np.linspace(0,1,len(SDSS_Data['z']))]
#mid_data_colors = [plt.cm.Greens(i) for i in np.linspace(0,1,len(SDSS_Data['z']))]
#hot_data_colors = [plt.cm.Reds(i) for i in np.linspace(0,1,len(SDSS_Data['z']))]
u_colors = [plt.cm.Purples(i) for i in np.linspace(0.5,1,7)]
metal_colors = [plt.cm.Blues(i) for i in np.linspace(0.25,1,6)]
def truncate_colormap(cmap, minval=0.15, maxval=1.0, n=100):
new_cmap = colors.LinearSegmentedColormap.from_list(
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
cmap(np.linspace(minval, maxval, n)))
return new_cmap
u_colors_map = truncate_colormap(cm.Purples)
metal_colors_map = truncate_colormap(cm.Blues)
#This is bad^ 3 and 7 are the number of densities and ionization parameters used, but ideally this wouldn't be hardcoded.
#sf_count = 0.0
#comp_count = 0.0
#agn_count = 0.0
#liner_count = 0.0
#amb_count = 0.0
shape = ['v']
#####################################################################################################
def getShape(NII_Ha, OIII_Hb, S_Ha_Ratio, OI_Ratio):
# Star forming
if OIII_Hb < 0.61/(NII_Ha-0.05)+1.3 and \
OIII_Hb < 0.72/(S_Ha_Ratio-0.32)+1.30 and \
OIII_Hb < 0.73/(OI_Ratio+0.59)+1.33:
shape = 'x'
#sf_count = sf_count+1
# Composite
elif 0.61/(NII_Ha-0.05)+1.3 < OIII_Hb and \
0.61/(NII_Ha-0.47)+1.19 > OIII_Hb:
shape = '+'
#comp_count = comp_count+1
# AGN
elif 0.61/(NII_Ha-0.47)+1.19 < OIII_Hb and \
0.72/(S_Ha_Ratio-0.32)+1.30 < OIII_Hb and \
0.73/(OI_Ratio+0.59)+1.33 < OIII_Hb and \
(1.89*S_Ha_Ratio)+0.76 < OIII_Hb and \
(1.18*OI_Ratio)+1.30 < OIII_Hb:
shape = 'D'
#agn_count = agn_count+1
# LINERs
elif 0.61/(NII_Ha-0.47)+1.19 < OIII_Hb and \
0.72/(S_Ha_Ratio-0.32)+1.30 < OIII_Hb and \
OIII_Hb < (1.89*S_Ha_Ratio)+0.76 and \
0.73/(OI_Ratio+0.59)+1.33 < OIII_Hb and \
OIII_Hb < (1.18*OI_Ratio)+1.30:
shape = 's'
#liner_count = liner_count+1
else:
# Ambiguous
shape = '*'
#amb_count = amb_count+1
return shape
#####################################################################################################
#####################################################################################################
def getColor(OIII_5006, OIII_4363):
Temp_Color = 'k'
if OIII_5006/OIII_4363<50:
#Temp_Color = '0.25'
Temp_Color = plt.cm.gray(0.2)
#red = red + 1
elif OIII_5006/OIII_4363>50 and OIII_5006/OIII_4363<100:
#Temp_Color = '0.5'
Temp_Color = plt.cm.gray(0.5)
#green = green + 1
elif OIII_5006/OIII_4363>100:
#Temp_Color = '0.75'
Temp_Color = plt.cm.gray(0.75)
#black = black + 1
else:
print ("error")
return Temp_Color
#####################################################################################################
fig = plt.figure(21)
fig.subplots_adjust(wspace=0.8,hspace=0.4)
sp1 = plt.subplot(231)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
#print(Temp_Color)
plt.scatter(NII_Ha[i],OIII_Hb[i],s = markersize, marker = shape, color = Temp_Color, edgecolor = 'none')
#print (Temp_Color)
#print(sf_count)
#print(comp_count)
#print(agn_count)
#print(liner_count)
#print(amb_count)
#print(red)
#print(green)
#print(black)
#print(counter)
plt.xlim(-1.5,0.5)
plt.ylim(0,1.3)
plt.ylabel(r"log([OIII] $\lambda$5007/H$\beta$)")
plt.xlabel(r"log ([NII] $\lambda$6584/H$\alpha$)")
#plt.title("BPT Diagram")
#plt.scatter(Cloudy_NII_Ha,Cloudy_OIII_Hb,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp1.set_color_cycle(u_colors)
plt.plot(Cloudy_NII_Ha_array,Cloudy_OIII_Hb_array,linestyle = '--')
sp1.set_color_cycle(metal_colors)
plt.plot(Cloudy_NII_Ha_transpose,Cloudy_OIII_Hb_transpose, lw = '1.5')
x=np.linspace(-1.5,0.3,50)
y=((.61/(x-.47))+1.19)
plt.plot(x,y,color=Low_Temp_Color)
x3=np.linspace(-1,-0.2,50)
y3=((.61/(x3-.05)+1.3))
plt.plot(x3,y3,linestyle='--',color='k')
plt.xticks(np.arange(min(x), max(x)+1,1.0))
#plt.legend([plt.scatter([],[],color='.75', s = markersize, marker = 'x', edgecolor = 'none'),plt.scatter([],[],color='0.75', s = markersize, marker = '+', edgecolor = 'none'), plt.scatter([],[],color='.75', s = markersize, marker = 'D', edgecolor = 'none'), plt.scatter([],[],color='.75', s = markersize, marker = 's', edgecolor = 'none'), plt.scatter([],[],color='.75', s = markersize, marker = '*', edgecolor = 'none')], ("Star-Forming","Composite","AGN","LINER","Ambiguous"),scatterpoints = 1, loc = 'lower left',fontsize =8)
#counter=0
sm = plt.cm.ScalarMappable(norm=colors.Normalize(vmin=0.5, vmax=2.0),cmap=metal_colors_map)
sm._A = []
smaxes = inset_axes(sp1, width=0.06, height=0.4, loc=3, bbox_to_anchor=(0.14, 0.1), bbox_transform=sp1.figure.transFigure)
#smaxes = inset_axes(sp1, width="3%", height="20%", loc=3, bbox_to_anchor=(0.1, 0.1), bbox_transform=ax.figure.transFigure)
cbar = plt.colorbar(sm,cax=smaxes)
cbar.ax.set_title('Z',fontsize=8)
cbar.set_ticks([0.5,2.0])
cbar.set_ticklabels([0.5,2.0])
cbar.ax.tick_params(labelsize=8)
sp2 = plt.subplot(232)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(NII_Ha[i],Temp_Ratio[i], s = markersize, marker = shape, color = Temp_Color, edgecolor = 'none')
#print(counter)
plt.ylabel(r"log([OIII] $\lambda$5007/4363)")
plt.xlabel(r"log ([NII] $\lambda$6584/H$\alpha$)")
#plt.title("Temperature")
plt.ylim(1,2.5)
plt.xlim(-1.5,0.5)
#plt.scatter(Cloudy_NII_Ha,Cloudy_Temp_Ratio,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp2.set_color_cycle(u_colors)
plt.plot(Cloudy_NII_Ha_array,Cloudy_Temp_Ratio_array,linestyle = '--')
sp2.set_color_cycle(metal_colors)
plt.plot(Cloudy_NII_Ha_transpose,Cloudy_Temp_Ratio_transpose, lw = '1.5')
plt.xticks(np.arange(min(x), max(x)+1,1.0))
#plt.legend([plt.scatter([],[],color='0.75', s = markersize), plt.scatter([],[],color='0.5', s = markersize), plt.scatter([],[],color='0.25', s = markersize)], (r"T$_e$<1.17*10$^4$",r"1.17*10$^4$<T$_e$<1.54*10$^4$",r"T$_e$>1.54*10$^4$"),scatterpoints = 1, loc = 'lower left',fontsize =8)
sm = plt.cm.ScalarMappable(norm=colors.Normalize(vmin=-3.5, vmax=-0.5),cmap=u_colors_map)
sm._A = []
smaxes = inset_axes(sp2, width=0.06, height=0.4, loc=3, bbox_to_anchor=(0.3, .1), bbox_transform=sp2.figure.transFigure)
cbar = plt.colorbar(sm,cax=smaxes)
cbar.ax.set_title('U',fontsize=8)
cbar.set_ticks([-3.5,-0.5])
cbar.set_ticklabels([-3.5,-0.5])
cbar.ax.tick_params(labelsize=8)
sp3 = plt.subplot(234)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(NII_Ha[i],S_Ratio[i], s = markersize, marker = shape, c = Temp_Color, edgecolor = 'none')
plt.ylabel(r"log([SII] $\lambda$6717/6731)")
plt.xlabel(r"log ([NII] $\lambda$6584/H$\alpha$)")
plt.ylim(-0.3,0.3)
plt.xlim(-1.5,0.5)
#plt.title("Density")
#plt.scatter(Cloudy_NII_Ha,Cloudy_S_Ratio,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp3.set_color_cycle(u_colors)
plt.plot(Cloudy_NII_Ha_array,Cloudy_S_Ratio_array,linestyle = '--')
sp3.set_color_cycle(metal_colors)
plt.plot(Cloudy_NII_Ha_transpose,Cloudy_S_Ratio_transpose, lw = '1.5')
plt.xticks(np.arange(min(x), max(x)+1,1.0))
#plt.legend([plt.scatter([],[],color=Low_Temp_Color, s = markersize), plt.scatter([],[],color=Mid_Temp_Color, s = markersize), plt.scatter([],[],color=High_Temp_Color, s = markersize),plt.scatter([],[],c=Cloudy_Sim_Color, s = markersize, edgecolor = 'none')], (r"$\frac{OIII[5007]}{OIII[4363]}$<50.0",r"$50.0<\frac{OIII[5007]}{OIII[4363]}<100.0$",r"$\frac{OIII[5007]}{OIII[4363]}$>100.0","Cloudy Simulation"),scatterpoints = 1, loc = 'lower left',fontsize =8)
sp4 = plt.subplot(233)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(NII_Ha[i],NO_Ratio[i], s = markersize, marker = shape, c = Temp_Color, edgecolor = 'none')
plt.ylabel(r"log([NII] $\lambda$6584/[OII] $\lambda$3727)")
plt.xlabel(r"log ([NII] $\lambda$6584/H$\alpha$)")
#plt.title("Metallicity")
plt.xlim(-1.5,0.5)
plt.ylim(-1,0.5)
#plt.scatter(Cloudy_NII_Ha,Cloudy_NO_Ratio,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp4.set_color_cycle(u_colors)
plt.plot(Cloudy_NII_Ha_array,Cloudy_NO_Ratio_array,linestyle = '--')
sp4.set_color_cycle(metal_colors)
plt.plot(Cloudy_NII_Ha_transpose,Cloudy_NO_Ratio_transpose, lw = '1.5')
plt.xticks(np.arange(min(x), max(x)+1,1.0))
#plt.legend([plt.scatter([],[],color=Low_Temp_Color, s = markersize), plt.scatter([],[],color=Mid_Temp_Color, s = markersize), plt.scatter([],[],color=High_Temp_Color, s = markersize),plt.scatter([],[],c=Cloudy_Sim_Color, s = markersize, edgecolor = 'none')], (r"$\frac{OIII[5007]}{OIII[4363]}$<50.0",r"$50.0<\frac{OIII[5007]}{OIII[4363]}<100.0$",r"$\frac{OIII[5007]}{OIII[4363]}$>100.0","Cloudy Simulation"),scatterpoints = 1, loc = 'lower left',fontsize =8)
plt.suptitle('n$_H$ = 3.5, -0.5 < U < -3.5, 0.5 < Z < 2.0')
plt.savefig("Z_0.5_2.0_Sims_Plots.pdf", dpi = 600)
plt.show()
fig2 = plt.figure(22)
sp5 = plt.subplot(221)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(NII_Ha[i],OI_Ratio[i], s = markersize, marker = shape, c = Temp_Color, edgecolor = 'none')
plt.ylabel(r"log([OI] $\lambda$6300/H$\alpha$)")
plt.xlabel(r"log ([NII] $\lambda$6584/H$\alpha$)")
plt.title("OI_6300")
plt.xlim(-2.5,0.5)
plt.ylim(-2.5,0)
#plt.scatter(Cloudy_NII_Ha,Cloudy_OI_Ratio,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp5.set_color_cycle(u_colors)
plt.plot(Cloudy_NII_Ha_array,Cloudy_OI_Ratio_array,linestyle = '--', lw = '2')
sp5.set_color_cycle(metal_colors)
plt.plot(Cloudy_NII_Ha_transpose,Cloudy_OI_Ratio_transpose, lw = '2')
plt.legend([plt.scatter([],[],color='.75', s = markersize, marker = 'x', edgecolor = 'none'),plt.scatter([],[],color='0.75', s = markersize, marker = '+', edgecolor = 'none'), plt.scatter([],[],color='.75', s = markersize, marker = 'D', edgecolor = 'none'), plt.scatter([],[],color='.75', s = markersize, marker = 's', edgecolor = 'none'), plt.scatter([],[],color='.75', s = markersize, marker = '*', edgecolor = 'none')], ("Star-Forming","Composite","AGN","LINER","Ambiguous"),scatterpoints = 1, loc = 'lower left',fontsize =8)
sp6 = plt.subplot(222)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(OI_Ratio[i],OIII_Hb[i], s = markersize, marker = shape, c = Temp_Color, edgecolor = 'none')
plt.ylabel(r"log([OIII] $\lambda$5007/H$\beta$)")
plt.xlabel(r"log ([OI] $\lambda$6300/H$\alpha$)")
plt.title("OI_6300 vs. OIII_5007")
#plt.scatter(Cloudy_OI_Ratio,Cloudy_OIII_Hb,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp6.set_color_cycle(u_colors)
plt.plot(Cloudy_OI_Ratio_array,Cloudy_OIII_Hb_array,linestyle = '--', lw = '2')
sp6.set_color_cycle(metal_colors)
plt.plot(Cloudy_OI_Ratio_transpose,Cloudy_OIII_Hb_transpose, lw = '2')
x6 = np.linspace(-2.5,-0.6,50)
y6 = ((.73/(x6+0.59))+1.33)
plt.plot(x6,y6,color = 'k')
x7 = np.linspace(-1.125,0.25,50)
y7 = (1.18*x7) + 1.30
plt.plot(x7,y7, color = 'b')
plt.ylim(-1,1.5)
plt.xlim(-2.5,0.5)
#plt.legend([plt.scatter([],[],color=Low_Temp_Color, s = markersize), plt.scatter([],[],color=Mid_Temp_Color, s = markersize), plt.scatter([],[],color=High_Temp_Color, s = markersize),plt.scatter([],[],c=Cloudy_Sim_Color, s = markersize, edgecolor = 'none')], (r"$\frac{OIII[5007]}{OIII[4363]}$<50.0",r"$50.0<\frac{OIII[5007]}{OIII[4363]}<100.0$",r"$\frac{OIII[5007]}{OIII[4363]}$>100.0","Cloudy Simulation"),scatterpoints = 1, loc = 'lower left',fontsize =8)
sp7 = plt.subplot(223)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(OI_Ratio[i],O_Ratio[i], s = markersize, marker = shape, c = Temp_Color, edgecolor = 'none')
plt.ylabel(r"log([OIII] $\lambda$5007/[OII]$\lambda$3727)")
plt.xlabel(r"log ([OI] $\lambda$6300/H$\alpha$)")
plt.title("Groves Diagram")
#plt.scatter(Cloudy_OI_Ratio,Cloudy_O_Ratio,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp7.set_color_cycle(u_colors)
plt.plot(Cloudy_OI_Ratio_array,Cloudy_O_Ratio_array,linestyle = '--', lw = '2')
sp7.set_color_cycle(metal_colors)
plt.plot(Cloudy_OI_Ratio_transpose,Cloudy_O_Ratio_transpose, lw = '2')
x1 = np.linspace(-2.0,-.25,50)
y1 = ((-1.701*x1)-2.163)
x2 = np.linspace(-1.05998,0,50)
y2 = x2 + 0.7
plt.plot(x2,y2, color = 'k')
plt.plot(x1,y1, color = 'k')
plt.xlim(-2.5,0)
plt.ylim(-1.5,1)
#plt.legend([plt.scatter([],[],color=Low_Temp_Color, s = markersize), plt.scatter([],[],color=Mid_Temp_Color, s = markersize), plt.scatter([],[],color=High_Temp_Color, s = markersize),plt.scatter([],[],c=Cloudy_Sim_Color, s = markersize, edgecolor = 'none')], (r"$\frac{OIII[5007]}{OIII[4363]}$<50.0",r"$50.0<\frac{OIII[5007]}{OIII[4363]}<100.0$",r"$\frac{OIII[5007]}{OIII[4363]}$>100.0","Cloudy Simulation"),scatterpoints = 1, loc = 'lower left',fontsize =8)
sp8 = plt.subplot(224)
for i in range(0,len(SDSS_Data['z'])):
shape = getShape(NII_Ha[i], OIII_Hb[i], S_Ha_Ratio[i], OI_Ratio[i])
Temp_Color = getColor(OIII_5006[i], OIII_4363[i])
plt.scatter(S_Ha_Ratio[i],OIII_Hb[i], s = markersize, marker = shape, c = Temp_Color, edgecolor = 'none')
plt.ylabel(r"log([OIII] $\lambda$5007/H$\beta$)")
plt.xlabel(r"log ([SII]/H$\alpha$)")
plt.title("OIII_5007 vs. SII")
plt.ylim(-1,1.5)
x4 = np.linspace(-0.32,0.25,50)
y4 = ((1.89*x4)+0.76)
x5 = np.linspace(-1.5,0.25,50)
y5 = ((0.72/(x - 0.32))+1.3)
plt.plot(x5,y5,color = 'k')
plt.plot(x4,y4,color = 'b')
#plt.scatter(Cloudy_S_Ha_Ratio,Cloudy_OIII_Hb,c=Cloudy_Sim_Color, s = markersize, edgecolor ='none')
sp8.set_color_cycle(u_colors)
plt.plot(Cloudy_S_Ha_Ratio_array,Cloudy_OIII_Hb_array,linestyle = '--', lw = '2')
sp8.set_color_cycle(metal_colors)
plt.plot(Cloudy_S_Ha_Ratio_transpose,Cloudy_OIII_Hb_transpose, lw = '2')
plt.suptitle('n$_H$ = 3.5, -0.5 < U < -3.5, 0.5 < Z < 2.0')
#plt.legend([plt.scatter([],[],color=Low_Temp_Color, s = markersize), plt.scatter([],[],color=Mid_Temp_Color, s = markersize), plt.scatter([],[],color=High_Temp_Color, s = markersize),plt.scatter([],[],c=Cloudy_Sim_Color, s = markersize, edgecolor = 'none')], (r"$\frac{OIII[5007]}{OIII[4363]}$<50.0",r"$50.0<\frac{OIII[5007]}{OIII[4363]}<100.0$",r"$\frac{OIII[5007]}{OIII[4363]}$>100.0","Cloudy Simulation"),scatterpoints = 1, loc = 'lower left',fontsize =8)
#plt.savefig("Metallicity Sim Plots1.pdf")
#plt.show() | mit | 2,493,449,929,102,906,400 | 49.631436 | 529 | 0.640938 | false |
lucianopuccio/golem | tests/report/test_report_test.py | 1 | 6386 | import json
import os
from golem.core import utils
from golem.test_runner import test_runner
from golem.report.execution_report import create_execution_directory
from golem.report.execution_report import create_execution_dir_single_test
from golem.report import test_report
from golem.report.test_report import get_test_case_data
from golem.report.test_report import get_test_debug_log
from golem.report.test_report import create_report_directory
from golem.report.test_report import generate_report
class TestGetTestCaseData:
def test_get_test_case_data(self, project_class, test_utils):
_, project = project_class.activate()
exc = test_utils.execute_random_suite(project)
test_name = exc['exec_data']['tests'][0]['name']
test_set = exc['exec_data']['tests'][0]['test_set']
test_data = get_test_case_data(project, test_name, exc['suite_name'],
exc['timestamp'], test_set)
assert test_data['name'] == exc['tests'][0]
assert isinstance(test_data['debug_log'], list) and len(test_data['debug_log'])
assert isinstance(test_data['info_log'], list) and len(test_data['info_log'])
assert test_data['has_finished'] is True
class TestTestReportDirectory:
def test_test_report_directory(self, project_session):
testdir, project = project_session.activate()
suite = 'suite1'
timestamp = '1.2.3.4'
test = 'test1'
test_set = 'test_set1'
path = test_report.test_report_directory(project, suite, timestamp, test, test_set)
expected = os.path.join(testdir, 'projects', project, 'reports', suite, timestamp,
test, test_set)
assert path == expected
class TestTestReportDirectorySingleTest:
def test_test_report_directory_single_test(self, project_session):
testdir, project = project_session.activate()
timestamp = '1.2.3.4'
test = 'test1'
test_set = 'test_set1'
path = test_report.test_report_directory_single_test(project, test, timestamp, test_set)
expected = os.path.join(testdir, 'projects', project, 'reports', 'single_tests',
test, timestamp, test_set)
assert path == expected
class TestGetTestLog:
def test_get_test_x_log(self, project_class, test_utils):
_, project = project_class.activate()
exc = test_utils.execute_random_suite(project)
test_name = exc['exec_data']['tests'][0]['name']
test_set = exc['exec_data']['tests'][0]['test_set']
log = get_test_debug_log(project, exc['timestamp'], test_name, test_set,
suite=exc['suite_name'])
assert 'root DEBUG test does not have setup function' in log
# inexistent test set
log = get_test_debug_log(project, exc['timestamp'], test_name,
'inexistent_test_set', suite=exc['suite_name'])
assert log is None
# inexistent test
log = get_test_debug_log(project, exc['timestamp'], 'inexistent_test_name',
test_set, suite=exc['suite_name'])
assert log is None
class TestCreateReportDirectory:
def test_create_report_directory_test(self, project_session):
testdir, project = project_session.activate()
timestamp = utils.get_timestamp()
test_name = 'testing_report_001'
exec_dir = create_execution_dir_single_test(project, test_name, timestamp)
directory = create_report_directory(exec_dir, test_name, is_suite=False)
assert os.path.isdir(directory)
def test_create_report_directory_suite(self, project_session):
testdir, project = project_session.activate()
timestamp = utils.get_timestamp()
suite_name = 'suite_foo_002'
test_name = 'testing_report_002'
exec_dir = create_execution_directory(project, suite_name, timestamp)
directory = create_report_directory(exec_dir, test_name, is_suite=True)
assert os.path.isdir(directory)
class TestGenerateReport:
def test_generate_report_with_env(self, project_session):
_, project = project_session.activate()
timestamp = utils.get_timestamp()
test_name = 'testing_report_003'
suite_name = 'suite_foo_003'
exec_dir = create_execution_directory(project, suite_name, timestamp)
report_dir = create_report_directory(exec_dir, test_name, is_suite=True)
test_data = {
'env': {
'name': 'env01',
'url': '1.1.1.1'
},
'var2': 'value2'
}
test_data = test_runner.Data(test_data)
result = {
'result': 'success',
'errors': [],
'description': 'description of the test',
'steps': [
{'message': 'step1', 'screenshot': None, 'error': None},
{'message': 'step2', 'screenshot': None, 'error': None}
],
'test_elapsed_time': 22.22,
'test_timestamp': '2018.02.04.02.16.42.729',
'browser': 'chrome',
'browser_full_name': '',
'set_name': 'set_001',
}
generate_report(report_dir, test_name, test_data, result)
path = os.path.join(report_dir, 'report.json')
with open(path) as report_file:
actual = json.load(report_file)
assert len(actual.items()) == 11
assert actual['test_case'] == test_name
assert actual['result'] == 'success'
assert actual['steps'][0]['message'] == 'step1'
assert actual['steps'][1]['message'] == 'step2'
assert actual['description'] == 'description of the test'
assert actual['errors'] == []
assert actual['test_elapsed_time'] == 22.22
assert actual['test_timestamp'] == '2018.02.04.02.16.42.729'
assert actual['browser'] == 'chrome'
assert actual['environment'] == 'env01'
assert actual['set_name'] == 'set_001'
test_data_a = "{'url': '1.1.1.1', 'name': 'env01'}"
test_data_b = "{'name': 'env01', 'url': '1.1.1.1'}"
assert actual['test_data']['env'] in [test_data_a, test_data_b]
assert actual['test_data']['var2'] == "'value2'"
| mit | -3,508,836,499,478,213,000 | 40.467532 | 96 | 0.593173 | false |
cjaniake/ionicweb | webapp/area/views.py | 1 | 10040 | from django.shortcuts import render
from django.views.generic.base import TemplateView
from area.forms import AreaForm, LocationForm, BuildingForm
from area.models import Area, Location, Building
from django.http import HttpResponseRedirect
import logging
# GET /areas
class ListAreaView(TemplateView):
template_name = "area/area_list.html"
def get_context_data(self, **kwargs):
logger = logging.getLogger('webapp')
logger.info('run get_context_data run')
context = super(ListAreaView, self).get_context_data(**kwargs)
context['object_list'] = list(Area.objects.all())
new = Area()
new.name = "new"
context['object_list'].append(new)
return context
# GET/POST /area
def handle_area(request):
logger = logging.getLogger('webapp')
logger.info('run handle_area run')
if request.method == 'POST':
form = AreaForm(request.POST, request.FILES)
if form.is_valid():
a = Area()
a.adminEmail = form.cleaned_data['adminEmail']
a.areaStatus = form.cleaned_data['areaStatus']
a.createdDate = form.cleaned_data['createdDate']
a.folderName = form.cleaned_data['folderName']
a.language = form.cleaned_data['language']
a.logoFile = form.cleaned_data['logoFile']
a.name = form.cleaned_data['name']
a.paymentIntegration = form.cleaned_data['paymentIntegration']
a.paymentId = form.cleaned_data['paymentId']
a.plan = form.cleaned_data['plan']
a.save()
return HttpResponseRedirect('/areas/')
else:
form = AreaForm()
return render(request, 'area/area_detail.html', {'form': form, 'action':'/area/', 'http_method':'POST'})
# GET/POST /area/<areacode>
def edit_area(request, areacode=None):
logger = logging.getLogger('webapp')
logger.info('run edit_area run')
if(areacode):
a = Area.objects.get(id=int(areacode))
if request.method == 'POST':
#update record with submitted values
logger.info('run submit_edit run')
form = AreaForm(request.POST, request.FILES, instance=a)
if form.is_valid():
logger.info('updating area')
logger.info(form.cleaned_data)
a.adminEmail = form.cleaned_data['adminEmail']
a.areaStatus = form.cleaned_data['areaStatus']
a.createdDate = form.cleaned_data['createdDate']
a.folderName = form.cleaned_data['folderName']
a.language = form.cleaned_data['language']
a.logoFile = form.cleaned_data['logoFile']
a.name = form.cleaned_data['name']
a.paymentIntegration = form.cleaned_data['paymentIntegration']
a.paymentId = form.cleaned_data['paymentId']
a.plan = form.cleaned_data['plan']
a.save()
return HttpResponseRedirect('/areas/')
return render(request, 'area/area_detail.html', {'form': form, 'action':'/area/' + areacode + '/', 'http_method':'POST'})
else:
#load record to allow edition
form = AreaForm(instance=a)
return render(request, 'area/area_detail.html', {'form': form, 'action':'/area/' + areacode + '/', 'http_method':'POST'})
else:
return HttpResponseRedirect('/areas/')
# GET /area/<areacode>/locations
class ListLocationView(TemplateView):
template_name = "area/location_list.html"
def get_context_data(self, **kwargs):
logger = logging.getLogger('webapp')
areacode = kwargs['areacode']
#logger.info('get locations', areacode)
context = super(ListLocationView, self).get_context_data(**kwargs)
area = Area.objects.get(id=int(areacode))
context['area'] = area
locationArray = area.location_set.values
context['object_list'] = locationArray
return context
# GET/POST /area/<areacode>/location
def handle_location(request, areacode=None):
logger = logging.getLogger('webapp')
logger.info('run handle_location run')
area = Area.objects.get(id=int(areacode))
if request.method == 'POST':
form = LocationForm(request.POST)
if form.is_valid():
l = Location()
l.name = form.cleaned_data['name']
l.city = form.cleaned_data['city']
l.state = form.cleaned_data['state']
l.adminEmail = form.cleaned_data['adminEmail']
area = Area.objects.get(id=int(areacode))
area.location_set.add(l)
return HttpResponseRedirect('/area/' + areacode + '/locations')
else:
form = LocationForm()
return render(request, 'area/location_detail.html', {'form': form, 'action':'/area/' + areacode + '/location/', 'http_method':'POST', 'area': area})
# GET/POST /area/<areacode>/location/<locationid>
def edit_location(request, areacode=None, locationid=None):
logger = logging.getLogger('webapp')
logger.info('run edit_location run')
if(areacode and locationid):
area = Area.objects.get(id=int(areacode))
l = Location.objects.get(id=int(locationid))
if request.method == 'POST':
#update record with submitted values
form = LocationForm(request.POST, instance=l)
if form.is_valid():
l.name = form.cleaned_data['name']
l.city = form.cleaned_data['city']
l.state = form.cleaned_data['state']
l.adminEmail = form.cleaned_data['adminEmail']
l.save()
return HttpResponseRedirect('/area/' + areacode + '/locations')
return render(request, 'area/location_detail.html', {'form': form, 'action':'/area/' + areacode + '/location/' + locationid + '/', 'http_method':'POST', 'area': area})
else:
#load record to allow edition
form = LocationForm(instance=l)
return render(request, 'area/location_detail.html', {'form': form, 'action':'/area/' + areacode + '/location/' + locationid + '/', 'http_method':'POST', 'area': area})
else:
return HttpResponseRedirect('/area/' + areacode + '/locations') if areacode else HttpResponseRedirect('/areas/')
# GET /area/<areacode>/location/<locationid>/buildings
class ListBuildingView(TemplateView):
template_name = "area/building_list.html"
def get_context_data(self, **kwargs):
logger = logging.getLogger('webapp')
areacode = kwargs['areacode']
locationid = kwargs['locationid']
#logger.info('get buildings', areacode, locationid)
context = super(ListBuildingView, self).get_context_data(**kwargs)
area = Area.objects.get(id=int(areacode))
context['area'] = area
location = Location.objects.get(id=int(locationid))
context['location'] = location
buildingArray = location.building_set.values
context['object_list'] = buildingArray
return context
# GET/POST /area/<areacode>/location/<locationid>/building
def handle_building(request, areacode=None, locationid=None):
logger = logging.getLogger('webapp')
logger.info('run handle_building run')
area = Area.objects.get(id=int(areacode))
if request.method == 'POST':
form = BuildingForm(request.POST)
if form.is_valid():
b = Building()
b.name = form.cleaned_data['name']
b.address = form.cleaned_data['address']
b.zipcode = form.cleaned_data['zipcode']
b.phone = form.cleaned_data['phone']
b.cellphone = form.cleaned_data['cellphone']
b.adminEmail = form.cleaned_data['adminEmail']
location = Location.objects.get(id=int(locationid))
location.building_set.add(b)
return HttpResponseRedirect('/area/' + areacode + '/location/' + locationid + '/buildings')
else:
form = BuildingForm()
return render(request, 'area/building_detail.html', {'form': form, 'action':'/area/' + areacode + '/location/' + locationid + '/building/', 'http_method':'POST', 'area': area})
# GET/POST /area/<areacode>/location/<locationid>/building/<buildingid>
def edit_building(request, areacode=None, locationid=None, buildingid=None):
logger = logging.getLogger('webapp')
logger.info('run edit_building run')
if(areacode and locationid and buildingid):
area = Area.objects.get(id=int(areacode))
l = Location.objects.get(id=int(locationid))
b = Building.objects.get(id=int(buildingid))
if request.method == 'POST':
#update record with submitted values
form = BuildingForm(request.POST, instance=b)
if form.is_valid():
b.name = form.cleaned_data['name']
b.address = form.cleaned_data['address']
b.zipcode = form.cleaned_data['zipcode']
b.phone = form.cleaned_data['phone']
b.cellphone = form.cleaned_data['cellphone']
b.adminEmail = form.cleaned_data['adminEmail']
b.save()
return HttpResponseRedirect('/area/' + areacode + '/location/' + locationid + '/buildings')
return render(request, 'area/building_detail.html', {'form': form, 'action':'/area/' + areacode + '/location/' + locationid + '/building/' + buildingid + '/', 'http_method':'POST', 'area': area, 'location': l})
else:
#load record to allow edition
form = BuildingForm(instance=b)
return render(request, 'area/building_detail.html', {'form': form, 'action':'/area/' + areacode + '/location/' + locationid + '/building/' + buildingid + '/', 'http_method':'POST', 'area': area, 'location': l})
else:
return HttpResponseRedirect('/area/' + areacode + '/location/' + locationid + '/buildings') if areacode and locationid else HttpResponseRedirect('/areas/')
| gpl-2.0 | 3,064,346,551,269,282,300 | 40.147541 | 222 | 0.609263 | false |
loggerhead/Easy-Karabiner | easy_karabiner/basexml.py | 1 | 3477 | # -*- coding: utf-8 -*-
from __future__ import print_function
import lxml.etree as etree
import xml.dom.minidom as minidom
import xml.sax.saxutils as saxutils
from . import exception
from .fucking_string import ensure_utf8
class BaseXML(object):
xml_parser = etree.XMLParser(strip_cdata=False)
@classmethod
def unescape(cls, s):
return saxutils.unescape(s, {
""": '"',
"'": "'",
})
@classmethod
def parse(cls, filepath):
return etree.parse(filepath).getroot()
@classmethod
def parse_string(cls, xml_str):
return etree.fromstring(xml_str, cls.xml_parser)
@classmethod
def get_class_name(cls):
return cls.__name__
@classmethod
def is_cdata_text(cls, text):
return text.startswith('<![CDATA[') and text.endswith(']]>')
@classmethod
def remove_cdata_mark(cls, text):
return text[len('<![CDATA['):-len(']]>')]
@classmethod
def create_cdata_text(cls, text):
# do NOT use `etree.CDATA`
return '<![CDATA[%s]]>' % text
@classmethod
def assign_text_attribute(cls, etree_element, text):
if text is not None:
etree_element.text = ensure_utf8(text)
else:
etree_element.text = text
@classmethod
def create_tag(cls, name, text=None, **kwargs):
et = etree.Element(name, **kwargs)
cls.assign_text_attribute(et, text)
return et
@classmethod
def pretty_text(cls, elem, indent=" ", level=0):
"""WARNING: This method would change the construct of XML tree"""
i = "\n" + level * indent
if len(elem) == 0:
if elem.text is not None:
lines = elem.text.split('\n')
if len(lines) > 1:
if not lines[0].startswith(' '):
lines[0] = (i + indent) + lines[0]
if lines[-1].strip() == '':
lines.pop()
elem.text = (i + indent).join(lines) + i
else:
for subelem in elem:
BaseXML.pretty_text(subelem, indent, level + 1)
return elem
@classmethod
def to_format_str(cls, xml_tree, pretty_text=True):
indent = " "
if pretty_text:
BaseXML.pretty_text(xml_tree, indent=indent)
xml_string = etree.tostring(xml_tree)
xml_string = minidom.parseString(xml_string).toprettyxml(indent=indent)
xml_string = cls.unescape(xml_string)
return xml_string
def to_xml(self):
"""NOTICE: This method must be a REENTRANT function, which means
it should NOT change status or modify any member of `self` object.
Because other methods may change the construct of the XML tree.
"""
raise exception.NeedOverrideError()
def to_str(self, pretty_text=True, remove_first_line=False):
xml_str = self.to_format_str(self.to_xml(), pretty_text=pretty_text)
if remove_first_line:
lines = xml_str.split('\n')
if len(lines[-1].strip()) == 0:
# remove last blank line
lines = lines[1:-1]
else:
lines = lines[1:]
xml_str = '\n'.join(lines)
return xml_str
def __str__(self):
# `remove_first_line=True` is used to remove version tag in the first line
return self.to_str(remove_first_line=True)
| mit | 7,036,706,235,977,799,000 | 30.324324 | 82 | 0.561979 | false |
jfterpstra/bluebottle | bluebottle/test/factory_models/accounting.py | 1 | 2678 | import factory
from datetime import date, timedelta
from decimal import Decimal
from bluebottle.accounting.models import (BankTransaction, BankTransactionCategory,
RemoteDocdataPayout, RemoteDocdataPayment)
from bluebottle.test.factory_models.payouts import ProjectPayoutFactory
from .payments import PaymentFactory
DEFAULT_CURRENCY = 'EUR'
TODAY = date.today()
class RemoteDocdataPayoutFactory(factory.DjangoModelFactory):
class Meta(object):
model = RemoteDocdataPayout
payout_reference = factory.Sequence(lambda n: 'Reference_{0}'.format(n))
payout_date = TODAY
start_date = TODAY - timedelta(days=10)
end_date = TODAY + timedelta(days=10)
collected_amount = Decimal('10')
payout_amount = Decimal('10')
class RemoteDocdataPaymentFactory(factory.DjangoModelFactory):
class Meta(object):
model = RemoteDocdataPayment
merchant_reference = 'merchant reference'
triple_deal_reference = 'triple deal reference'
payment_type = 1
amount_collected = Decimal('10')
currency_amount_collected = DEFAULT_CURRENCY
docdata_fee = Decimal('0.25')
currency_docdata_fee = DEFAULT_CURRENCY
local_payment = factory.SubFactory(PaymentFactory)
remote_payout = factory.SubFactory(RemoteDocdataPayoutFactory)
status = 'valid' # or 'missing' or 'mismatch' as in RemoteDocdataPayment.IntegretyStatus
# status_remarks, tpcd, currency_tpcd, tpci, currency_tpci
class BankTransactionCategoryFactory(factory.DjangoModelFactory):
class Meta(object):
model = BankTransactionCategory
django_get_or_create = ('name',)
name = factory.Sequence(lambda n: 'Category_{0}'.format(n))
class BankTransactionFactory(factory.DjangoModelFactory):
class Meta(object):
model = BankTransaction
category = factory.SubFactory(BankTransactionCategoryFactory)
# only one of these three make sense, so set 2 on None when using this factory
payout = factory.SubFactory(ProjectPayoutFactory)
remote_payout = factory.SubFactory(RemoteDocdataPayoutFactory)
remote_payment = factory.SubFactory(RemoteDocdataPaymentFactory)
sender_account = 'NL24RABO0133443493'
currency = DEFAULT_CURRENCY
interest_date = TODAY + timedelta(days=30)
credit_debit = 'C' # or 'D'
amount = Decimal('100')
counter_account = 'NL91ABNA0417164300'
counter_name = 'Counter name'
book_date = TODAY
book_code = 'bg'
status = 'valid' # or 'unknown', 'mismatch' # BankTransaction.IntegrityStatus.choices
# description1 (t/m description6), end_to_end_id, id_recipient, mandate_id, status_remarks, filler
| bsd-3-clause | -7,912,064,976,835,343,000 | 32.898734 | 102 | 0.724048 | false |
automl/SpySMAC | cave/analyzer/parameter_importance/fanova.py | 1 | 5790 | import operator
import os
from collections import OrderedDict
from pandas import DataFrame
from cave.analyzer.parameter_importance.base_parameter_importance import BaseParameterImportance
class Fanova(BaseParameterImportance):
"""
fANOVA (functional analysis of variance) computes the fraction of the variance in the cost space explained by
changing a parameter by marginalizing over all other parameters, for each parameter (or for pairs of
parameters). Parameters with high importance scores will have a large impact on the performance. To this end, a
random forest is trained as an empirical performance model on the available empirical data from the available
runhistories.
"""
def __init__(self,
runscontainer,
marginal_threshold=0.05):
"""Wrapper for parameter_importance to save the importance-object/ extract the results. We want to show the
top X most important parameter-fanova-plots.
Parameters
----------
runscontainer: RunsContainer
contains all important information about the configurator runs
marginal_threshold: float
parameter/s must be at least this important to be mentioned
"""
super().__init__(runscontainer)
self.marginal_threshold = marginal_threshold
self.parameter_importance("fanova")
def get_name(self):
return 'fANOVA'
def postprocess(self, pimp, output_dir):
result = OrderedDict()
def parse_pairwise(p):
"""parse pimp's way of having pairwise parameters as key as str and return list of individuals"""
res = [tmp.strip('\' ') for tmp in p.strip('[]').split(',')]
return res
parameter_imp = {k: v * 100 for k, v in pimp.evaluator.evaluated_parameter_importance.items()}
param_imp_std = {}
if hasattr(pimp.evaluator, 'evaluated_parameter_importance_uncertainty'):
param_imp_std = {k: v * 100 for k, v in pimp.evaluator.evaluated_parameter_importance_uncertainty.items()}
for k in parameter_imp.keys():
self.logger.debug("fanova-importance for %s: mean (over trees): %f, std: %s", k, parameter_imp[k],
str(param_imp_std[k]) if param_imp_std else 'N/A')
# Split single and pairwise (pairwise are string: "['p1','p2']")
single_imp = {k: v for k, v in parameter_imp.items() if not k.startswith('[') and v > self.marginal_threshold}
pairwise_imp = {k: v for k, v in parameter_imp.items() if k.startswith('[') and v > self.marginal_threshold}
# Set internal parameter importance for further analysis (such as parallel coordinates)
self.fanova_single_importance = single_imp
self.fanova_pairwise_importance = single_imp
# Dicts to lists of tuples, sorted descending after importance
single_imp = OrderedDict(sorted(single_imp.items(), key=operator.itemgetter(1), reverse=True))
pairwise_imp = OrderedDict(sorted(pairwise_imp.items(), key=operator.itemgetter(1), reverse=True))
# Create table
table = []
if len(single_imp) > 0:
table.extend([(20*"-"+" Single importance: "+20*"-", 20*"-")])
for k, v in single_imp.items():
value = str(round(v, 4))
if param_imp_std:
value += " +/- " + str(round(param_imp_std[k], 4))
table.append((k, value))
if len(pairwise_imp) > 0:
table.extend([(20*"-"+" Pairwise importance: "+20*"-", 20*"-")])
for k, v in pairwise_imp.items():
name = ' & '.join(parse_pairwise(k))
value = str(round(v, 4))
if param_imp_std:
value += " +/- " + str(round(param_imp_std[k], 4))
table.append((name, value))
keys, fanova_table = [k[0] for k in table], [k[1:] for k in table]
df = DataFrame(data=fanova_table, index=keys)
result['Importance'] = {'table': df.to_html(escape=False, header=False, index=True, justify='left')}
# Get plot-paths
result['Marginals'] = {p: {'figure': os.path.join(output_dir, "fanova", p + '.png')} for p in single_imp.keys()}
# Right now no way to access paths of the plots -> file issue
pairwise_plots = {" & ".join(parse_pairwise(p)):
os.path.join(output_dir, 'fanova', '_'.join(parse_pairwise(p)) + '.png')
for p in pairwise_imp.keys()}
result['Pairwise Marginals'] = {p: {'figure': path}
for p, path in pairwise_plots.items() if os.path.exists(path)}
return result
def get_jupyter(self):
from IPython.core.display import HTML, Image, display
for b, result in self.result.items():
error = self.result[b]['else'] if 'else' in self.result[b] else None
if error:
display(HTML(error))
else:
# Show table
display(HTML(self.result[b]["Importance"]["table"]))
# Show plots
display(*list([Image(filename=d["figure"]) for d in self.result[b]['Marginals'].values()]))
display(*list([Image(filename=d["figure"]) for d in self.result[b]['Pairwise Marginals'].values()]))
# While working for a prettier solution, this might be an option:
# display(HTML(figure_to_html([d["figure"] for d in self.result[b]['Marginals'].values()] +
# [d["figure"] for d in self.result[b]['Pairwise Marginals'].values()],
# max_in_a_row=3, true_break_between_rows=True)))
| bsd-3-clause | 8,205,455,852,385,124,000 | 48.487179 | 120 | 0.589465 | false |
rfriedlein/zenoss | ZenPacks/ZenPacks.Coredial.Baytech/ZenPacks/Coredial/Baytech/BaytechPduBank.py | 1 | 3595 | ##########################################################################
# Author: rfriedlein, [email protected]
# Date: February 4th, 2011
# Revised:
#
# BaytechPduBank object class
#
# This program can be used under the GNU General Public License version 2
# You can find full information here: http://www.zenoss.com/oss
#
##########################################################################
__doc__="""BaytechPduBank
BaytechPduBank is a component of a BaytechPduDevice Device
$Id: $"""
__version__ = "$Revision: $"[11:-2]
from Globals import DTMLFile
from Globals import InitializeClass
from Products.ZenRelations.RelSchema import *
from Products.ZenModel.ZenossSecurity import ZEN_VIEW, ZEN_CHANGE_SETTINGS
from Products.ZenModel.DeviceComponent import DeviceComponent
from Products.ZenModel.ManagedEntity import ManagedEntity
import logging
log = logging.getLogger('BaytechPduBank')
class BaytechPduBank(DeviceComponent, ManagedEntity):
"""Baytech PDU Bank object"""
portal_type = meta_type = 'BaytechPduBank'
#**************Custom data Variables here from modeling************************
bankNumber = 0
bankState = 0
bankStateText = ''
#**************END CUSTOM VARIABLES *****************************
#************* Those should match this list below *******************
_properties = (
{'id':'bankNumber', 'type':'int', 'mode':''},
{'id':'bankState', 'type':'int', 'mode':''},
{'id':'bankStateText', 'type':'string', 'mode':''},
)
#****************
_relations = (
("BaytechPduDevBan", ToOne(ToManyCont,
"ZenPacks.ZenSystems.Baytech.BaytechPduDevice", "BaytechPduBan")),
)
factory_type_information = (
{
'id' : 'BaytechPduBank',
'meta_type' : 'BaytechPduBank',
'description' : """Baytech PDU Bank info""",
'product' : 'BaytechPdu',
'immediate_view' : 'viewBaytechPduBank',
'actions' :
(
{ 'id' : 'status'
, 'name' : 'Baytech PDU Bank Graphs'
, 'action' : 'viewBaytechPduBank'
, 'permissions' : (ZEN_VIEW, )
},
{ 'id' : 'perfConf'
, 'name' : 'Baytech PDU Bank Template'
, 'action' : 'objTemplates'
, 'permissions' : (ZEN_CHANGE_SETTINGS, )
},
{ 'id' : 'viewHistory'
, 'name' : 'Modifications'
, 'action' : 'viewHistory'
, 'permissions' : (ZEN_VIEW, )
},
)
},
)
isUserCreatedFlag = True
def isUserCreated(self):
"""
Returns the value of isUserCreated. True adds SAVE & CANCEL buttons to Details menu
"""
return self.isUserCreatedFlag
def viewName(self):
"""Pretty version human readable version of this object"""
# return str( self.bankNumber )
return self.id
# use viewName as titleOrId because that method is used to display a human
# readable version of the object in the breadcrumbs
titleOrId = name = viewName
def device(self):
return self.BaytechPduDevBan()
def monitored(self):
"""
Dummy
"""
return True
InitializeClass(BaytechPduBank)
| gpl-3.0 | 5,278,256,024,859,762,000 | 29.991379 | 91 | 0.502921 | false |
alexisrolland/data-quality | scripts/init/validity.py | 1 | 3496 | """Manage class and methods for data validity indicators."""
import logging
import pandas
from indicator import Indicator
from session import update_session_status
# Load logging configuration
log = logging.getLogger(__name__)
class Validity(Indicator):
"""Class used to compute indicators of type validity."""
def __init__(self):
pass
def execute(self, session: dict):
"""Execute indicator of type validity."""
# Update session status to running
session_id = session['id']
indicator_id = session['indicatorId']
log.info('Start execution of session Id %i for indicator Id %i.', session_id, indicator_id)
log.debug('Update session status to Running.')
update_session_status(session_id, 'Running')
# Verify if the list of indicator parameters is valid
indicator_type_id = session['indicatorByIndicatorId']['indicatorTypeId']
parameters = session['indicatorByIndicatorId']['parametersByIndicatorId']['nodes']
parameters = super().verify_indicator_parameters(indicator_type_id, parameters)
# Get target data
dimensions = parameters[4]
measures = parameters[5]
target = parameters[8]
target_request = parameters[9]
target_data = super().get_data_frame(target, target_request, dimensions, measures)
# Evaluate completeness
alert_operator = parameters[1] # Alert operator
alert_threshold = parameters[2] # Alert threshold
log.info('Evaluate validity of target data source.')
result_data = self.evaluate_validity(
target_data, measures, alert_operator, alert_threshold)
# Compute session result
nb_records_alert = super().compute_session_result(
session_id, alert_operator, alert_threshold, result_data)
# Send e-mail alert
if nb_records_alert != 0:
indicator_name = session['indicatorByIndicatorId']['name']
distribution_list = parameters[3] # Distribution list
super().send_alert(indicator_id, indicator_name, session_id, distribution_list,
alert_operator, alert_threshold, nb_records_alert, result_data)
# Update session status to succeeded
log.debug('Update session status to Succeeded.')
update_session_status(session_id, 'Succeeded')
log.info('Session Id %i for indicator Id %i completed successfully.', session_id, indicator_id)
def evaluate_validity(self, target_data: pandas.DataFrame, measures: str, alert_operator: str, alert_threshold: str):
"""Compute specificities of validity indicator and return results in a data frame."""
# No tranformation needed for this data frame
result_data = target_data
result_data = result_data.fillna(value=0) # Replace NaN values per 0
# Formatting data to improve readability
for measure in measures:
result_data[measure] = round(result_data[measure], 2).astype(float)
# For each record and measure in data frame test if alert must be sent and update alert column
result_data['Alert'] = False
for measure in measures:
for row_num in result_data.index:
measure_value = result_data.loc[row_num, measure]
if self.is_alert(measure_value, alert_operator, alert_threshold):
result_data.loc[row_num, 'Alert'] = True
return result_data
| apache-2.0 | 4,305,772,009,656,806,400 | 43.253165 | 121 | 0.657609 | false |
lidavidm/mathics-heroku | venv/lib/python2.7/site-packages/sympy/polys/polytools.py | 1 | 163118 | """User-friendly public interface to polynomial functions. """
from sympy.core import (
S, Basic, Expr, I, Integer, Add, Mul, Dummy, Tuple, Rational
)
from sympy.core.mul import _keep_coeff
from sympy.core.basic import preorder_traversal
from sympy.core.sympify import (
sympify, SympifyError,
)
from sympy.core.decorators import (
_sympifyit,
)
from sympy.polys.polyclasses import DMP
from sympy.polys.polyutils import (
basic_from_dict,
_sort_gens,
_unify_gens,
_dict_reorder,
_dict_from_expr,
_parallel_dict_from_expr,
)
from sympy.polys.rationaltools import (
together,
)
from sympy.polys.rootisolation import (
dup_isolate_real_roots_list,
)
from sympy.polys.groebnertools import groebner as _groebner
from sympy.polys.fglmtools import matrix_fglm
from sympy.polys.monomialtools import (
Monomial, monomial_key,
)
from sympy.polys.polyerrors import (
OperationNotSupported, DomainError,
CoercionFailed, UnificationFailed,
GeneratorsNeeded, PolynomialError,
MultivariatePolynomialError,
ExactQuotientFailed,
PolificationFailed,
ComputationFailed,
GeneratorsError,
)
from sympy.utilities import group
import sympy.polys
import sympy.mpmath
from sympy.polys.domains import FF, QQ
from sympy.polys.constructor import construct_domain
from sympy.polys import polyoptions as options
from sympy.core.compatibility import iterable
class Poly(Expr):
"""Generic class for representing polynomial expressions. """
__slots__ = ['rep', 'gens']
is_commutative = True
is_Poly = True
def __new__(cls, rep, *gens, **args):
"""Create a new polynomial instance out of something useful. """
opt = options.build_options(gens, args)
if 'order' in opt:
raise NotImplementedError("'order' keyword is not implemented yet")
if iterable(rep, exclude=str):
if isinstance(rep, dict):
return cls._from_dict(rep, opt)
else:
return cls._from_list(list(rep), opt)
else:
rep = sympify(rep)
if rep.is_Poly:
return cls._from_poly(rep, opt)
else:
return cls._from_expr(rep, opt)
@classmethod
def new(cls, rep, *gens):
"""Construct :class:`Poly` instance from raw representation. """
if not isinstance(rep, DMP):
raise PolynomialError(
"invalid polynomial representation: %s" % rep)
elif rep.lev != len(gens) - 1:
raise PolynomialError("invalid arguments: %s, %s" % (rep, gens))
obj = Basic.__new__(cls)
obj.rep = rep
obj.gens = gens
return obj
@classmethod
def from_dict(cls, rep, *gens, **args):
"""Construct a polynomial from a ``dict``. """
opt = options.build_options(gens, args)
return cls._from_dict(rep, opt)
@classmethod
def from_list(cls, rep, *gens, **args):
"""Construct a polynomial from a ``list``. """
opt = options.build_options(gens, args)
return cls._from_list(rep, opt)
@classmethod
def from_poly(cls, rep, *gens, **args):
"""Construct a polynomial from a polynomial. """
opt = options.build_options(gens, args)
return cls._from_poly(rep, opt)
@classmethod
def from_expr(cls, rep, *gens, **args):
"""Construct a polynomial from an expression. """
opt = options.build_options(gens, args)
return cls._from_expr(rep, opt)
@classmethod
def _from_dict(cls, rep, opt):
"""Construct a polynomial from a ``dict``. """
gens = opt.gens
if not gens:
raise GeneratorsNeeded(
"can't initialize from 'dict' without generators")
level = len(gens) - 1
domain = opt.domain
if domain is None:
domain, rep = construct_domain(rep, opt=opt)
else:
for monom, coeff in rep.iteritems():
rep[monom] = domain.convert(coeff)
return cls.new(DMP.from_dict(rep, level, domain), *gens)
@classmethod
def _from_list(cls, rep, opt):
"""Construct a polynomial from a ``list``. """
gens = opt.gens
if not gens:
raise GeneratorsNeeded(
"can't initialize from 'list' without generators")
elif len(gens) != 1:
raise MultivariatePolynomialError(
"'list' representation not supported")
level = len(gens) - 1
domain = opt.domain
if domain is None:
domain, rep = construct_domain(rep, opt=opt)
else:
rep = map(domain.convert, rep)
return cls.new(DMP.from_list(rep, level, domain), *gens)
@classmethod
def _from_poly(cls, rep, opt):
"""Construct a polynomial from a polynomial. """
if cls != rep.__class__:
rep = cls.new(rep.rep, *rep.gens)
gens = opt.gens
field = opt.field
domain = opt.domain
if gens and rep.gens != gens:
if set(rep.gens) != set(gens):
return cls._from_expr(rep.as_expr(), opt)
else:
rep = rep.reorder(*gens)
if 'domain' in opt and domain:
rep = rep.set_domain(domain)
elif field is True:
rep = rep.to_field()
return rep
@classmethod
def _from_expr(cls, rep, opt):
"""Construct a polynomial from an expression. """
rep, opt = _dict_from_expr(rep, opt)
return cls._from_dict(rep, opt)
def _hashable_content(self):
"""Allow SymPy to hash Poly instances. """
return (self.rep, self.gens)
def __hash__(self):
return super(Poly, self).__hash__()
@property
def free_symbols(self):
"""
Free symbols of a polynomial expression.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1).free_symbols
set([x])
>>> Poly(x**2 + y).free_symbols
set([x, y])
>>> Poly(x**2 + y, x).free_symbols
set([x, y])
"""
symbols = set([])
for gen in self.gens:
symbols |= gen.free_symbols
return symbols | self.free_symbols_in_domain
@property
def free_symbols_in_domain(self):
"""
Free symbols of the domain of ``self``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1).free_symbols_in_domain
set()
>>> Poly(x**2 + y).free_symbols_in_domain
set()
>>> Poly(x**2 + y, x).free_symbols_in_domain
set([y])
"""
domain, symbols = self.rep.dom, set()
if domain.is_Composite:
for gen in domain.gens:
symbols |= gen.free_symbols
elif domain.is_EX:
for coeff in self.coeffs():
symbols |= coeff.free_symbols
return symbols
@property
def args(self):
"""
Don't mess up with the core.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).args
(x**2 + 1,)
"""
return (self.as_expr(),)
@property
def gen(self):
"""
Return the principal generator.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).gen
x
"""
return self.gens[0]
@property
def domain(self):
"""Get the ground domain of ``self``. """
return self.get_domain()
@property
def zero(self):
"""Return zero polynomial with ``self``'s properties. """
return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens)
@property
def one(self):
"""Return one polynomial with ``self``'s properties. """
return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens)
@property
def unit(self):
"""Return unit polynomial with ``self``'s properties. """
return self.new(self.rep.unit(self.rep.lev, self.rep.dom), *self.gens)
def unify(f, g):
"""
Make ``f`` and ``g`` belong to the same domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f, g = Poly(x/2 + 1), Poly(2*x + 1)
>>> f
Poly(1/2*x + 1, x, domain='QQ')
>>> g
Poly(2*x + 1, x, domain='ZZ')
>>> F, G = f.unify(g)
>>> F
Poly(1/2*x + 1, x, domain='QQ')
>>> G
Poly(2*x + 1, x, domain='QQ')
"""
_, per, F, G = f._unify(g)
return per(F), per(G)
def _unify(f, g):
g = sympify(g)
if not g.is_Poly:
try:
return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g))
except CoercionFailed:
raise UnificationFailed("can't unify %s with %s" % (f, g))
if isinstance(f.rep, DMP) and isinstance(g.rep, DMP):
gens = _unify_gens(f.gens, g.gens)
dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1
if f.gens != gens:
f_monoms, f_coeffs = _dict_reorder(
f.rep.to_dict(), f.gens, gens)
if f.rep.dom != dom:
f_coeffs = [ dom.convert(c, f.rep.dom) for c in f_coeffs ]
F = DMP(dict(zip(f_monoms, f_coeffs)), dom, lev)
else:
F = f.rep.convert(dom)
if g.gens != gens:
g_monoms, g_coeffs = _dict_reorder(
g.rep.to_dict(), g.gens, gens)
if g.rep.dom != dom:
g_coeffs = [ dom.convert(c, g.rep.dom) for c in g_coeffs ]
G = DMP(dict(zip(g_monoms, g_coeffs)), dom, lev)
else:
G = g.rep.convert(dom)
else:
raise UnificationFailed("can't unify %s with %s" % (f, g))
cls = f.__class__
def per(rep, dom=dom, gens=gens, remove=None):
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return dom.to_sympy(rep)
return cls.new(rep, *gens)
return dom, per, F, G
def per(f, rep, gens=None, remove=None):
"""
Create a Poly out of the given representation.
Examples
========
>>> from sympy import Poly, ZZ
>>> from sympy.abc import x, y
>>> from sympy.polys.polyclasses import DMP
>>> a = Poly(x**2 + 1)
>>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y])
Poly(y + 1, y, domain='ZZ')
"""
if gens is None:
gens = f.gens
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return f.rep.dom.to_sympy(rep)
return f.__class__.new(rep, *gens)
def set_domain(f, domain):
"""Set the ground domain of ``f``. """
opt = options.build_options(f.gens, {'domain': domain})
return f.per(f.rep.convert(opt.domain))
def get_domain(f):
"""Get the ground domain of ``f``. """
return f.rep.dom
def set_modulus(f, modulus):
"""
Set the modulus of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2)
Poly(x**2 + 1, x, modulus=2)
"""
modulus = options.Modulus.preprocess(modulus)
return f.set_domain(FF(modulus))
def get_modulus(f):
"""
Get the modulus of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, modulus=2).get_modulus()
2
"""
domain = f.get_domain()
if domain.is_FiniteField:
return Integer(domain.characteristic())
else:
raise PolynomialError("not a polynomial over a Galois field")
def _eval_subs(f, old, new):
"""Internal implementation of :func:`subs`. """
if old in f.gens:
if new.is_number:
return f.eval(old, new)
else:
try:
return f.replace(old, new)
except PolynomialError:
pass
return f.as_expr().subs(old, new)
def exclude(f):
"""
Remove unnecessary generators from ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import a, b, c, d, x
>>> Poly(a + x, a, b, c, d, x).exclude()
Poly(a + x, a, x, domain='ZZ')
"""
J, new = f.rep.exclude()
gens = []
for j in range(len(f.gens)):
if j not in J:
gens.append(f.gens[j])
return f.per(new, gens=gens)
def replace(f, x, y=None):
"""
Replace ``x`` with ``y`` in generators list.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 1, x).replace(x, y)
Poly(y**2 + 1, y, domain='ZZ')
"""
if y is None:
if f.is_univariate:
x, y = f.gen, x
else:
raise PolynomialError(
"syntax supported only in univariate case")
if x == y:
return f
if x in f.gens and y not in f.gens:
dom = f.get_domain()
if not dom.is_Composite or y not in dom.gens:
gens = list(f.gens)
gens[gens.index(x)] = y
return f.per(f.rep, gens=gens)
raise PolynomialError("can't replace %s with %s in %s" % (x, y, f))
def reorder(f, *gens, **args):
"""
Efficiently apply new order of generators.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x*y**2, x, y).reorder(y, x)
Poly(y**2*x + x**2, y, x, domain='ZZ')
"""
opt = options.Options((), args)
if not gens:
gens = _sort_gens(f.gens, opt=opt)
elif set(f.gens) != set(gens):
raise PolynomialError(
"generators list can differ only up to order of elements")
rep = dict(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens)))
return f.per(DMP(rep, f.rep.dom, len(gens) - 1), gens=gens)
def ltrim(f, gen):
"""
Remove dummy generators from the "left" of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(y**2 + y*z**2, x, y, z).ltrim(y)
Poly(y**2 + y*z**2, y, z, domain='ZZ')
"""
rep = f.as_dict(native=True)
j = f._gen_to_level(gen)
terms = {}
for monom, coeff in rep.iteritems():
monom = monom[j:]
if monom not in terms:
terms[monom] = coeff
else:
raise PolynomialError("can't left trim %s" % f)
gens = f.gens[j:]
return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens)
def has_only_gens(f, *gens):
"""
Return ``True`` if ``Poly(f, *gens)`` retains ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x*y + 1, x, y, z).has_only_gens(x, y)
True
>>> Poly(x*y + z, x, y, z).has_only_gens(x, y)
False
"""
f_gens = list(f.gens)
indices = set([])
for gen in gens:
try:
index = f_gens.index(gen)
except ValueError:
raise GeneratorsError(
"%s doesn't have %s as generator" % (f, gen))
else:
indices.add(index)
for monom in f.monoms():
for i, elt in enumerate(monom):
if i not in indices and elt:
return False
return True
def to_ring(f):
"""
Make the ground domain a ring.
Examples
========
>>> from sympy import Poly, QQ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, domain=QQ).to_ring()
Poly(x**2 + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'to_ring'):
result = f.rep.to_ring()
else: # pragma: no cover
raise OperationNotSupported(f, 'to_ring')
return f.per(result)
def to_field(f):
"""
Make the ground domain a field.
Examples
========
>>> from sympy import Poly, ZZ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x, domain=ZZ).to_field()
Poly(x**2 + 1, x, domain='QQ')
"""
if hasattr(f.rep, 'to_field'):
result = f.rep.to_field()
else: # pragma: no cover
raise OperationNotSupported(f, 'to_field')
return f.per(result)
def to_exact(f):
"""
Make the ground domain exact.
Examples
========
>>> from sympy import Poly, RR
>>> from sympy.abc import x
>>> Poly(x**2 + 1.0, x, domain=RR).to_exact()
Poly(x**2 + 1, x, domain='QQ')
"""
if hasattr(f.rep, 'to_exact'):
result = f.rep.to_exact()
else: # pragma: no cover
raise OperationNotSupported(f, 'to_exact')
return f.per(result)
def retract(f, field=None):
"""
Recalculate the ground domain of a polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2 + 1, x, domain='QQ[y]')
>>> f
Poly(x**2 + 1, x, domain='QQ[y]')
>>> f.retract()
Poly(x**2 + 1, x, domain='ZZ')
>>> f.retract(field=True)
Poly(x**2 + 1, x, domain='QQ')
"""
dom, rep = construct_domain(f.as_dict(zero=True), field=field)
return f.from_dict(rep, f.gens, domain=dom)
def slice(f, x, m, n=None):
"""Take a continuous subsequence of terms of ``f``. """
if n is None:
j, m, n = 0, x, m
else:
j = f._gen_to_level(x)
m, n = int(m), int(n)
if hasattr(f.rep, 'slice'):
result = f.rep.slice(m, n, j)
else: # pragma: no cover
raise OperationNotSupported(f, 'slice')
return f.per(result)
def coeffs(f, order=None):
"""
Returns all non-zero coefficients from ``f`` in lex order.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x + 3, x).coeffs()
[1, 2, 3]
See Also
========
all_coeffs
coeff_monomial
nth
"""
return [ f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order) ]
def monoms(f, order=None):
"""
Returns all non-zero monomials from ``f`` in lex order.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms()
[(2, 0), (1, 2), (1, 1), (0, 1)]
See Also
========
all_monoms
"""
return f.rep.monoms(order=order)
def terms(f, order=None):
"""
Returns all non-zero terms from ``f`` in lex order.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms()
[((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)]
See Also
========
all_terms
"""
return [ (m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order) ]
def all_coeffs(f):
"""
Returns all coefficients from a univariate polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_coeffs()
[1, 0, 2, -1]
"""
return [ f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs() ]
def all_monoms(f):
"""
Returns all monomials from a univariate polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_monoms()
[(3,), (2,), (1,), (0,)]
See Also
========
all_terms
"""
return f.rep.all_monoms()
def all_terms(f):
"""
Returns all terms from a univariate polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x - 1, x).all_terms()
[((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)]
"""
return [ (m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms() ]
def termwise(f, func, *gens, **args):
"""
Apply a function to all terms of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> def func((k,), coeff):
... return coeff//10**(2-k)
>>> Poly(x**2 + 20*x + 400).termwise(func)
Poly(x**2 + 2*x + 4, x, domain='ZZ')
"""
terms = {}
for monom, coeff in f.terms():
result = func(monom, coeff)
if isinstance(result, tuple):
monom, coeff = result
else:
coeff = result
if coeff:
if monom not in terms:
terms[monom] = coeff
else:
raise PolynomialError(
"%s monomial was generated twice" % monom)
return f.from_dict(terms, *(gens or f.gens), **args)
def length(f):
"""
Returns the number of non-zero terms in ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 2*x - 1).length()
3
"""
return len(f.as_dict())
def as_dict(f, native=False, zero=False):
"""
Switch to a ``dict`` representation.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict()
{(0, 1): -1, (1, 2): 2, (2, 0): 1}
"""
if native:
return f.rep.to_dict(zero=zero)
else:
return f.rep.to_sympy_dict(zero=zero)
def as_list(f, native=False):
"""Switch to a ``list`` representation. """
if native:
return f.rep.to_list()
else:
return f.rep.to_sympy_list()
def as_expr(f, *gens):
"""
Convert a Poly instance to an Expr instance.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2 + 2*x*y**2 - y, x, y)
>>> f.as_expr()
x**2 + 2*x*y**2 - y
>>> f.as_expr({x: 5})
10*y**2 - y + 25
>>> f.as_expr(5, 6)
379
"""
if not gens:
gens = f.gens
elif len(gens) == 1 and isinstance(gens[0], dict):
mapping = gens[0]
gens = list(f.gens)
for gen, value in mapping.iteritems():
try:
index = gens.index(gen)
except ValueError:
raise GeneratorsError(
"%s doesn't have %s as generator" % (f, gen))
else:
gens[index] = value
return basic_from_dict(f.rep.to_sympy_dict(), *gens)
def lift(f):
"""
Convert algebraic coefficients to rationals.
Examples
========
>>> from sympy import Poly, I
>>> from sympy.abc import x
>>> Poly(x**2 + I*x + 1, x, extension=I).lift()
Poly(x**4 + 3*x**2 + 1, x, domain='QQ')
"""
if hasattr(f.rep, 'lift'):
result = f.rep.lift()
else: # pragma: no cover
raise OperationNotSupported(f, 'lift')
return f.per(result)
def deflate(f):
"""
Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate()
((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ'))
"""
if hasattr(f.rep, 'deflate'):
J, result = f.rep.deflate()
else: # pragma: no cover
raise OperationNotSupported(f, 'deflate')
return J, f.per(result)
def inject(f, front=False):
"""
Inject ground domain generators into ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2*y + x*y**3 + x*y + 1, x)
>>> f.inject()
Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ')
>>> f.inject(front=True)
Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ')
"""
dom = f.rep.dom
if dom.is_Numerical:
return f
elif not dom.is_Poly:
raise DomainError("can't inject generators over %s" % dom)
if hasattr(f.rep, 'inject'):
result = f.rep.inject(front=front)
else: # pragma: no cover
raise OperationNotSupported(f, 'inject')
if front:
gens = dom.gens + f.gens
else:
gens = f.gens + dom.gens
return f.new(result, *gens)
def eject(f, *gens):
"""
Eject selected generators into the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y)
>>> f.eject(x)
Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
>>> f.eject(y)
Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
"""
dom = f.rep.dom
if not dom.is_Numerical:
raise DomainError("can't eject generators over %s" % dom)
n, k = len(f.gens), len(gens)
if f.gens[:k] == gens:
_gens, front = f.gens[k:], True
elif f.gens[-k:] == gens:
_gens, front = f.gens[:-k], False
else:
raise NotImplementedError(
"can only eject front or back generators")
dom = dom.inject(*gens)
if hasattr(f.rep, 'eject'):
result = f.rep.eject(dom, front=front)
else: # pragma: no cover
raise OperationNotSupported(f, 'eject')
return f.new(result, *_gens)
def terms_gcd(f):
"""
Remove GCD of terms from the polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd()
((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ'))
"""
if hasattr(f.rep, 'terms_gcd'):
J, result = f.rep.terms_gcd()
else: # pragma: no cover
raise OperationNotSupported(f, 'terms_gcd')
return J, f.per(result)
def add_ground(f, coeff):
"""
Add an element of the ground domain to ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).add_ground(2)
Poly(x + 3, x, domain='ZZ')
"""
if hasattr(f.rep, 'add_ground'):
result = f.rep.add_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'add_ground')
return f.per(result)
def sub_ground(f, coeff):
"""
Subtract an element of the ground domain from ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).sub_ground(2)
Poly(x - 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'sub_ground'):
result = f.rep.sub_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'sub_ground')
return f.per(result)
def mul_ground(f, coeff):
"""
Multiply ``f`` by a an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 1).mul_ground(2)
Poly(2*x + 2, x, domain='ZZ')
"""
if hasattr(f.rep, 'mul_ground'):
result = f.rep.mul_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'mul_ground')
return f.per(result)
def quo_ground(f, coeff):
"""
Quotient of ``f`` by a an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x + 4).quo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> Poly(2*x + 3).quo_ground(2)
Poly(x + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'quo_ground'):
result = f.rep.quo_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'quo_ground')
return f.per(result)
def exquo_ground(f, coeff):
"""
Exact quotient of ``f`` by a an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x + 4).exquo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> Poly(2*x + 3).exquo_ground(2)
Traceback (most recent call last):
...
ExactQuotientFailed: 2 does not divide 3 in ZZ
"""
if hasattr(f.rep, 'exquo_ground'):
result = f.rep.exquo_ground(coeff)
else: # pragma: no cover
raise OperationNotSupported(f, 'exquo_ground')
return f.per(result)
def abs(f):
"""
Make all coefficients in ``f`` positive.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).abs()
Poly(x**2 + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'abs'):
result = f.rep.abs()
else: # pragma: no cover
raise OperationNotSupported(f, 'abs')
return f.per(result)
def neg(f):
"""
Negate all coefficients in ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).neg()
Poly(-x**2 + 1, x, domain='ZZ')
>>> -Poly(x**2 - 1, x)
Poly(-x**2 + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'neg'):
result = f.rep.neg()
else: # pragma: no cover
raise OperationNotSupported(f, 'neg')
return f.per(result)
def add(f, g):
"""
Add two polynomials ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).add(Poly(x - 2, x))
Poly(x**2 + x - 1, x, domain='ZZ')
>>> Poly(x**2 + 1, x) + Poly(x - 2, x)
Poly(x**2 + x - 1, x, domain='ZZ')
"""
g = sympify(g)
if not g.is_Poly:
return f.add_ground(g)
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'add'):
result = F.add(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'add')
return per(result)
def sub(f, g):
"""
Subtract two polynomials ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).sub(Poly(x - 2, x))
Poly(x**2 - x + 3, x, domain='ZZ')
>>> Poly(x**2 + 1, x) - Poly(x - 2, x)
Poly(x**2 - x + 3, x, domain='ZZ')
"""
g = sympify(g)
if not g.is_Poly:
return f.sub_ground(g)
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'sub'):
result = F.sub(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'sub')
return per(result)
def mul(f, g):
"""
Multiply two polynomials ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).mul(Poly(x - 2, x))
Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')
>>> Poly(x**2 + 1, x)*Poly(x - 2, x)
Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ')
"""
g = sympify(g)
if not g.is_Poly:
return f.mul_ground(g)
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'mul'):
result = F.mul(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'mul')
return per(result)
def sqr(f):
"""
Square a polynomial ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x - 2, x).sqr()
Poly(x**2 - 4*x + 4, x, domain='ZZ')
>>> Poly(x - 2, x)**2
Poly(x**2 - 4*x + 4, x, domain='ZZ')
"""
if hasattr(f.rep, 'sqr'):
result = f.rep.sqr()
else: # pragma: no cover
raise OperationNotSupported(f, 'sqr')
return f.per(result)
def pow(f, n):
"""
Raise ``f`` to a non-negative power ``n``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x - 2, x).pow(3)
Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')
>>> Poly(x - 2, x)**3
Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ')
"""
n = int(n)
if hasattr(f.rep, 'pow'):
result = f.rep.pow(n)
else: # pragma: no cover
raise OperationNotSupported(f, 'pow')
return f.per(result)
def pdiv(f, g):
"""
Polynomial pseudo-division of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x))
(Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ'))
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pdiv'):
q, r = F.pdiv(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'pdiv')
return per(q), per(r)
def prem(f, g):
"""
Polynomial pseudo-remainder of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x))
Poly(20, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'prem'):
result = F.prem(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'prem')
return per(result)
def pquo(f, g):
"""
Polynomial pseudo-quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x))
Poly(2*x + 4, x, domain='ZZ')
>>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x))
Poly(2*x + 2, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pquo'):
result = F.pquo(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'pquo')
return per(result)
def pexquo(f, g):
"""
Polynomial exact pseudo-quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x))
Poly(2*x + 2, x, domain='ZZ')
>>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x))
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'pexquo'):
try:
result = F.pexquo(G)
except ExactQuotientFailed, exc:
raise exc.new(f.as_expr(), g.as_expr())
else: # pragma: no cover
raise OperationNotSupported(f, 'pexquo')
return per(result)
def div(f, g, auto=True):
"""
Polynomial division with remainder of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x))
(Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ'))
>>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False)
(Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ'))
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.has_Ring and not dom.has_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'div'):
q, r = F.div(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'div')
if retract:
try:
Q, R = q.to_ring(), r.to_ring()
except CoercionFailed:
pass
else:
q, r = Q, R
return per(q), per(r)
def rem(f, g, auto=True):
"""
Computes the polynomial remainder of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly, ZZ, QQ
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x))
Poly(5, x, domain='ZZ')
>>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False)
Poly(x**2 + 1, x, domain='ZZ')
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.has_Ring and not dom.has_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'rem'):
r = F.rem(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'rem')
if retract:
try:
r = r.to_ring()
except CoercionFailed:
pass
return per(r)
def quo(f, g, auto=True):
"""
Computes polynomial quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x))
Poly(1/2*x + 1, x, domain='QQ')
>>> Poly(x**2 - 1, x).quo(Poly(x - 1, x))
Poly(x + 1, x, domain='ZZ')
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.has_Ring and not dom.has_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'quo'):
q = F.quo(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'quo')
if retract:
try:
q = q.to_ring()
except CoercionFailed:
pass
return per(q)
def exquo(f, g, auto=True):
"""
Computes polynomial exact quotient of ``f`` by ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x))
Poly(x + 1, x, domain='ZZ')
>>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x))
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
dom, per, F, G = f._unify(g)
retract = False
if auto and dom.has_Ring and not dom.has_Field:
F, G = F.to_field(), G.to_field()
retract = True
if hasattr(f.rep, 'exquo'):
try:
q = F.exquo(G)
except ExactQuotientFailed, exc:
raise exc.new(f.as_expr(), g.as_expr())
else: # pragma: no cover
raise OperationNotSupported(f, 'exquo')
if retract:
try:
q = q.to_ring()
except CoercionFailed:
pass
return per(q)
def _gen_to_level(f, gen):
"""Returns level associated with the given generator. """
if isinstance(gen, int):
length = len(f.gens)
if -length <= gen < length:
if gen < 0:
return length + gen
else:
return gen
else:
raise PolynomialError("-%s <= gen < %s expected, got %s" %
(length, length, gen))
else:
try:
return list(f.gens).index(sympify(gen))
except ValueError:
raise PolynomialError(
"a valid generator expected, got %s" % gen)
def degree(f, gen=0):
"""
Returns degree of ``f`` in ``x_j``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).degree()
2
>>> Poly(x**2 + y*x + y, x, y).degree(y)
1
"""
j = f._gen_to_level(gen)
if hasattr(f.rep, 'degree'):
return f.rep.degree(j)
else: # pragma: no cover
raise OperationNotSupported(f, 'degree')
def degree_list(f):
"""
Returns a list of degrees of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).degree_list()
(2, 1)
"""
if hasattr(f.rep, 'degree_list'):
return f.rep.degree_list()
else: # pragma: no cover
raise OperationNotSupported(f, 'degree_list')
def total_degree(f):
"""
Returns the total degree of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + y*x + 1, x, y).total_degree()
2
>>> Poly(x + y**5, x, y).total_degree()
5
"""
if hasattr(f.rep, 'total_degree'):
return f.rep.total_degree()
else: # pragma: no cover
raise OperationNotSupported(f, 'total_degree')
def homogeneous_order(f):
"""
Returns the homogeneous order of ``f``.
A homogeneous polynomial is a polynomial whose all monomials with
non-zero coefficients have the same total degree. This degree is
the homogeneous order of ``f``. If you only want to check if a
polynomial is homogeneous, then use :func:`Poly.is_homogeneous`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4)
>>> f.homogeneous_order()
5
"""
if hasattr(f.rep, 'homogeneous_order'):
return f.rep.homogeneous_order()
else: # pragma: no cover
raise OperationNotSupported(f, 'homogeneous_order')
def LC(f, order=None):
"""
Returns the leading coefficient of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC()
4
"""
if order is not None:
return f.coeffs(order)[0]
if hasattr(f.rep, 'LC'):
result = f.rep.LC()
else: # pragma: no cover
raise OperationNotSupported(f, 'LC')
return f.rep.dom.to_sympy(result)
def TC(f):
"""
Returns the trailing coefficient of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x**2 + 3*x, x).TC()
0
"""
if hasattr(f.rep, 'TC'):
result = f.rep.TC()
else: # pragma: no cover
raise OperationNotSupported(f, 'TC')
return f.rep.dom.to_sympy(result)
def EC(f, order=None):
"""
Returns the last non-zero coefficient of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 + 2*x**2 + 3*x, x).EC()
3
"""
if hasattr(f.rep, 'coeffs'):
return f.coeffs(order)[-1]
else: # pragma: no cover
raise OperationNotSupported(f, 'EC')
def coeff_monomial(f, monom):
"""
Returns the coefficient of ``monom`` in ``f`` if there, else None.
Examples
========
>>> from sympy import Poly, exp
>>> from sympy.abc import x, y
>>> p = Poly(24*x*y*exp(8) + 23*x, x, y)
>>> p.coeff_monomial(x)
23
>>> p.coeff_monomial(y)
0
>>> p.coeff_monomial(x*y)
24*exp(8)
Note that ``Expr.coeff()`` behaves differently, collecting terms
if possible; the Poly must be converted to an Expr to use that
method, however:
>>> p.as_expr().coeff(x)
24*y*exp(8) + 23
>>> p.as_expr().coeff(y)
24*x*exp(8)
>>> p.as_expr().coeff(x*y)
24*exp(8)
See Also
========
nth: more efficient query using exponents of the monomial's generators
"""
return f.nth(*Monomial(monom, f.gens).exponents)
def nth(f, *N):
"""
Returns the ``n``-th coefficient of ``f`` where ``N`` are the
exponents of the generators in the term of interest.
Examples
========
>>> from sympy import Poly, sqrt
>>> from sympy.abc import x, y
>>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2)
2
>>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2)
2
>>> Poly(4*sqrt(x)*y)
Poly(4*y*sqrt(x), y, sqrt(x), domain='ZZ')
>>> _.nth(1, 1)
4
See Also
========
coeff_monomial
"""
if hasattr(f.rep, 'nth'):
result = f.rep.nth(*map(int, N))
else: # pragma: no cover
raise OperationNotSupported(f, 'nth')
return f.rep.dom.to_sympy(result)
def coeff(f, x, n=1, right=False):
# the semantics of coeff_monomial and Expr.coeff are different;
# if someone is working with a Poly, they should be aware of the
# differences and chose the method best suited for the query.
# Alternatively, a pure-polys method could be written here but
# at this time the ``right`` keyword would be ignored because Poly
# doesn't work with non-commutatives.
raise NotImplementedError(
'Either convert to Expr with `as_expr` method '
'to use Expr\'s coeff method or else use the '
'`coeff_monomial` method of Polys.')
def LM(f, order=None):
"""
Returns the leading monomial of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM()
x**2*y**0
"""
return Monomial(f.monoms(order)[0], f.gens)
def EM(f, order=None):
"""
Returns the last non-zero monomial of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM()
x**0*y**1
"""
return Monomial(f.monoms(order)[-1], f.gens)
def LT(f, order=None):
"""
Returns the leading term of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT()
(x**2*y**0, 4)
"""
monom, coeff = f.terms(order)[0]
return Monomial(monom, f.gens), coeff
def ET(f, order=None):
"""
Returns the last non-zero term of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET()
(x**0*y**1, 3)
"""
monom, coeff = f.terms(order)[-1]
return Monomial(monom, f.gens), coeff
def max_norm(f):
"""
Returns maximum norm of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(-x**2 + 2*x - 3, x).max_norm()
3
"""
if hasattr(f.rep, 'max_norm'):
result = f.rep.max_norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'max_norm')
return f.rep.dom.to_sympy(result)
def l1_norm(f):
"""
Returns l1 norm of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(-x**2 + 2*x - 3, x).l1_norm()
6
"""
if hasattr(f.rep, 'l1_norm'):
result = f.rep.l1_norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'l1_norm')
return f.rep.dom.to_sympy(result)
def clear_denoms(f, convert=False):
"""
Clear denominators, but keep the ground domain.
Examples
========
>>> from sympy import Poly, S, QQ
>>> from sympy.abc import x
>>> f = Poly(x/2 + S(1)/3, x, domain=QQ)
>>> f.clear_denoms()
(6, Poly(3*x + 2, x, domain='QQ'))
>>> f.clear_denoms(convert=True)
(6, Poly(3*x + 2, x, domain='ZZ'))
"""
if not f.rep.dom.has_Field:
return S.One, f
dom = f.get_domain()
if dom.has_assoc_Ring:
dom = f.rep.dom.get_ring()
if hasattr(f.rep, 'clear_denoms'):
coeff, result = f.rep.clear_denoms()
else: # pragma: no cover
raise OperationNotSupported(f, 'clear_denoms')
coeff, f = dom.to_sympy(coeff), f.per(result)
if not convert:
return coeff, f
else:
return coeff, f.to_ring()
def rat_clear_denoms(f, g):
"""
Clear denominators in a rational function ``f/g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = Poly(x**2/y + 1, x)
>>> g = Poly(x**3 + y, x)
>>> p, q = f.rat_clear_denoms(g)
>>> p
Poly(x**2 + y, x, domain='ZZ[y]')
>>> q
Poly(y*x**3 + y**2, x, domain='ZZ[y]')
"""
dom, per, f, g = f._unify(g)
f = per(f)
g = per(g)
if not (dom.has_Field and dom.has_assoc_Ring):
return f, g
a, f = f.clear_denoms(convert=True)
b, g = g.clear_denoms(convert=True)
f = f.mul_ground(b)
g = g.mul_ground(a)
return f, g
def integrate(f, *specs, **args):
"""
Computes indefinite integral of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x + 1, x).integrate()
Poly(1/3*x**3 + x**2 + x, x, domain='QQ')
>>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0))
Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ')
"""
if args.get('auto', True) and f.rep.dom.has_Ring:
f = f.to_field()
if hasattr(f.rep, 'integrate'):
if not specs:
return f.per(f.rep.integrate(m=1))
rep = f.rep
for spec in specs:
if type(spec) is tuple:
gen, m = spec
else:
gen, m = spec, 1
rep = rep.integrate(int(m), f._gen_to_level(gen))
return f.per(rep)
else: # pragma: no cover
raise OperationNotSupported(f, 'integrate')
def diff(f, *specs):
"""
Computes partial derivative of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + 2*x + 1, x).diff()
Poly(2*x + 2, x, domain='ZZ')
>>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1))
Poly(2*x*y, x, y, domain='ZZ')
"""
if hasattr(f.rep, 'diff'):
if not specs:
return f.per(f.rep.diff(m=1))
rep = f.rep
for spec in specs:
if type(spec) is tuple:
gen, m = spec
else:
gen, m = spec, 1
rep = rep.diff(int(m), f._gen_to_level(gen))
return f.per(rep)
else: # pragma: no cover
raise OperationNotSupported(f, 'diff')
def eval(f, x, a=None, auto=True):
"""
Evaluate ``f`` at ``a`` in the given variable.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> Poly(x**2 + 2*x + 3, x).eval(2)
11
>>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2)
Poly(5*y + 8, y, domain='ZZ')
>>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)
>>> f.eval({x: 2})
Poly(5*y + 2*z + 6, y, z, domain='ZZ')
>>> f.eval({x: 2, y: 5})
Poly(2*z + 31, z, domain='ZZ')
>>> f.eval({x: 2, y: 5, z: 7})
45
>>> f.eval((2, 5))
Poly(2*z + 31, z, domain='ZZ')
>>> f(2, 5)
Poly(2*z + 31, z, domain='ZZ')
"""
if a is None:
if isinstance(x, dict):
mapping = x
for gen, value in mapping.iteritems():
f = f.eval(gen, value)
return f
elif isinstance(x, (tuple, list)):
values = x
if len(values) > len(f.gens):
raise ValueError("too many values provided")
for gen, value in zip(f.gens, values):
f = f.eval(gen, value)
return f
else:
j, a = 0, x
else:
j = f._gen_to_level(x)
if not hasattr(f.rep, 'eval'): # pragma: no cover
raise OperationNotSupported(f, 'eval')
try:
result = f.rep.eval(a, j)
except CoercionFailed:
if not auto:
raise DomainError("can't evaluate at %s in %s" % (a, f.rep.dom))
else:
a_domain, [a] = construct_domain([a])
new_domain = f.get_domain().unify(a_domain, gens=f.gens)
f = f.set_domain(new_domain)
a = new_domain.convert(a, a_domain)
result = f.rep.eval(a, j)
return f.per(result, remove=j)
def __call__(f, *values):
"""
Evaluate ``f`` at the give values.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y, z
>>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z)
>>> f(2)
Poly(5*y + 2*z + 6, y, z, domain='ZZ')
>>> f(2, 5)
Poly(2*z + 31, z, domain='ZZ')
>>> f(2, 5, 7)
45
"""
return f.eval(values)
def half_gcdex(f, g, auto=True):
"""
Half extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
>>> g = x**3 + x**2 - 4*x - 4
>>> Poly(f).half_gcdex(Poly(g))
(Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ'))
"""
dom, per, F, G = f._unify(g)
if auto and dom.has_Ring:
F, G = F.to_field(), G.to_field()
if hasattr(f.rep, 'half_gcdex'):
s, h = F.half_gcdex(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'half_gcdex')
return per(s), per(h)
def gcdex(f, g, auto=True):
"""
Extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15
>>> g = x**3 + x**2 - 4*x - 4
>>> Poly(f).gcdex(Poly(g))
(Poly(-1/5*x + 3/5, x, domain='QQ'),
Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'),
Poly(x + 1, x, domain='QQ'))
"""
dom, per, F, G = f._unify(g)
if auto and dom.has_Ring:
F, G = F.to_field(), G.to_field()
if hasattr(f.rep, 'gcdex'):
s, t, h = F.gcdex(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'gcdex')
return per(s), per(t), per(h)
def invert(f, g, auto=True):
"""
Invert ``f`` modulo ``g`` when possible.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x))
Poly(-4/3, x, domain='QQ')
>>> Poly(x**2 - 1, x).invert(Poly(x - 1, x))
Traceback (most recent call last):
...
NotInvertible: zero divisor
"""
dom, per, F, G = f._unify(g)
if auto and dom.has_Ring:
F, G = F.to_field(), G.to_field()
if hasattr(f.rep, 'invert'):
result = F.invert(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'invert')
return per(result)
def revert(f, n):
"""Compute ``f**(-1)`` mod ``x**n``. """
if hasattr(f.rep, 'revert'):
result = f.rep.revert(int(n))
else: # pragma: no cover
raise OperationNotSupported(f, 'revert')
return f.per(result)
def subresultants(f, g):
"""
Computes the subresultant PRS of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x))
[Poly(x**2 + 1, x, domain='ZZ'),
Poly(x**2 - 1, x, domain='ZZ'),
Poly(-2, x, domain='ZZ')]
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'subresultants'):
result = F.subresultants(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'subresultants')
return map(per, result)
def resultant(f, g, includePRS=False):
"""
Computes the resultant of ``f`` and ``g`` via PRS.
If includePRS=True, it includes the subresultant PRS in the result.
Because the PRS is used to calculate the resultant, this is more
efficient than calling :func:`subresultants` separately.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**2 + 1, x)
>>> f.resultant(Poly(x**2 - 1, x))
4
>>> f.resultant(Poly(x**2 - 1, x), includePRS=True)
(4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'),
Poly(-2, x, domain='ZZ')])
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'resultant'):
if includePRS:
result, R = F.resultant(G, includePRS=includePRS)
else:
result = F.resultant(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'resultant')
if includePRS:
return (per(result, remove=0), map(per, R))
return per(result, remove=0)
def discriminant(f):
"""
Computes the discriminant of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + 2*x + 3, x).discriminant()
-8
"""
if hasattr(f.rep, 'discriminant'):
result = f.rep.discriminant()
else: # pragma: no cover
raise OperationNotSupported(f, 'discriminant')
return f.per(result, remove=0)
def cofactors(f, g):
"""
Returns the GCD of ``f`` and ``g`` and their cofactors.
Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and
``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors
of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x))
(Poly(x - 1, x, domain='ZZ'),
Poly(x + 1, x, domain='ZZ'),
Poly(x - 2, x, domain='ZZ'))
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'cofactors'):
h, cff, cfg = F.cofactors(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'cofactors')
return per(h), per(cff), per(cfg)
def gcd(f, g):
"""
Returns the polynomial GCD of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x))
Poly(x - 1, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'gcd'):
result = F.gcd(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'gcd')
return per(result)
def lcm(f, g):
"""
Returns polynomial LCM of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x))
Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'lcm'):
result = F.lcm(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'lcm')
return per(result)
def trunc(f, p):
"""
Reduce ``f`` modulo a constant ``p``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3)
Poly(-x**3 - x + 1, x, domain='ZZ')
"""
p = f.rep.dom.convert(p)
if hasattr(f.rep, 'trunc'):
result = f.rep.trunc(p)
else: # pragma: no cover
raise OperationNotSupported(f, 'trunc')
return f.per(result)
def monic(f, auto=True):
"""
Divides all coefficients by ``LC(f)``.
Examples
========
>>> from sympy import Poly, ZZ
>>> from sympy.abc import x
>>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic()
Poly(x**2 + 2*x + 3, x, domain='QQ')
>>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic()
Poly(x**2 + 4/3*x + 2/3, x, domain='QQ')
"""
if auto and f.rep.dom.has_Ring:
f = f.to_field()
if hasattr(f.rep, 'monic'):
result = f.rep.monic()
else: # pragma: no cover
raise OperationNotSupported(f, 'monic')
return f.per(result)
def content(f):
"""
Returns the GCD of polynomial coefficients.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(6*x**2 + 8*x + 12, x).content()
2
"""
if hasattr(f.rep, 'content'):
result = f.rep.content()
else: # pragma: no cover
raise OperationNotSupported(f, 'content')
return f.rep.dom.to_sympy(result)
def primitive(f):
"""
Returns the content and a primitive form of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 + 8*x + 12, x).primitive()
(2, Poly(x**2 + 4*x + 6, x, domain='ZZ'))
"""
if hasattr(f.rep, 'primitive'):
cont, result = f.rep.primitive()
else: # pragma: no cover
raise OperationNotSupported(f, 'primitive')
return f.rep.dom.to_sympy(cont), f.per(result)
def compose(f, g):
"""
Computes the functional composition of ``f`` and ``g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + x, x).compose(Poly(x - 1, x))
Poly(x**2 - x, x, domain='ZZ')
"""
_, per, F, G = f._unify(g)
if hasattr(f.rep, 'compose'):
result = F.compose(G)
else: # pragma: no cover
raise OperationNotSupported(f, 'compose')
return per(result)
def decompose(f):
"""
Computes a functional decomposition of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose()
[Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')]
"""
if hasattr(f.rep, 'decompose'):
result = f.rep.decompose()
else: # pragma: no cover
raise OperationNotSupported(f, 'decompose')
return map(f.per, result)
def shift(f, a):
"""
Efficiently compute Taylor shift ``f(x + a)``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).shift(2)
Poly(x**2 + 2*x + 1, x, domain='ZZ')
"""
if hasattr(f.rep, 'shift'):
result = f.rep.shift(a)
else: # pragma: no cover
raise OperationNotSupported(f, 'shift')
return f.per(result)
def sturm(f, auto=True):
"""
Computes the Sturm sequence of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 - 2*x**2 + x - 3, x).sturm()
[Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'),
Poly(3*x**2 - 4*x + 1, x, domain='QQ'),
Poly(2/9*x + 25/9, x, domain='QQ'),
Poly(-2079/4, x, domain='QQ')]
"""
if auto and f.rep.dom.has_Ring:
f = f.to_field()
if hasattr(f.rep, 'sturm'):
result = f.rep.sturm()
else: # pragma: no cover
raise OperationNotSupported(f, 'sturm')
return map(f.per, result)
def gff_list(f):
"""
Computes greatest factorial factorization of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**5 + 2*x**4 - x**3 - 2*x**2
>>> Poly(f).gff_list()
[(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)]
"""
if hasattr(f.rep, 'gff_list'):
result = f.rep.gff_list()
else: # pragma: no cover
raise OperationNotSupported(f, 'gff_list')
return [ (f.per(g), k) for g, k in result ]
def sqf_norm(f):
"""
Computes square-free norm of ``f``.
Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and
``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``,
where ``a`` is the algebraic extension of the ground domain.
Examples
========
>>> from sympy import Poly, sqrt
>>> from sympy.abc import x
>>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm()
>>> s
1
>>> f
Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>')
>>> r
Poly(x**4 - 4*x**2 + 16, x, domain='QQ')
"""
if hasattr(f.rep, 'sqf_norm'):
s, g, r = f.rep.sqf_norm()
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_norm')
return s, f.per(g), f.per(r)
def sqf_part(f):
"""
Computes square-free part of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**3 - 3*x - 2, x).sqf_part()
Poly(x**2 - x - 2, x, domain='ZZ')
"""
if hasattr(f.rep, 'sqf_part'):
result = f.rep.sqf_part()
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_part')
return f.per(result)
def sqf_list(f, all=False):
"""
Returns a list of square-free factors of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16
>>> Poly(f).sqf_list()
(2, [(Poly(x + 1, x, domain='ZZ'), 2),
(Poly(x + 2, x, domain='ZZ'), 3)])
>>> Poly(f).sqf_list(all=True)
(2, [(Poly(1, x, domain='ZZ'), 1),
(Poly(x + 1, x, domain='ZZ'), 2),
(Poly(x + 2, x, domain='ZZ'), 3)])
"""
if hasattr(f.rep, 'sqf_list'):
coeff, factors = f.rep.sqf_list(all)
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_list')
return f.rep.dom.to_sympy(coeff), [ (f.per(g), k) for g, k in factors ]
def sqf_list_include(f, all=False):
"""
Returns a list of square-free factors of ``f``.
Examples
========
>>> from sympy import Poly, expand
>>> from sympy.abc import x
>>> f = expand(2*(x + 1)**3*x**4)
>>> f
2*x**7 + 6*x**6 + 6*x**5 + 2*x**4
>>> Poly(f).sqf_list_include()
[(Poly(2, x, domain='ZZ'), 1),
(Poly(x + 1, x, domain='ZZ'), 3),
(Poly(x, x, domain='ZZ'), 4)]
>>> Poly(f).sqf_list_include(all=True)
[(Poly(2, x, domain='ZZ'), 1),
(Poly(1, x, domain='ZZ'), 2),
(Poly(x + 1, x, domain='ZZ'), 3),
(Poly(x, x, domain='ZZ'), 4)]
"""
if hasattr(f.rep, 'sqf_list_include'):
factors = f.rep.sqf_list_include(all)
else: # pragma: no cover
raise OperationNotSupported(f, 'sqf_list_include')
return [ (f.per(g), k) for g, k in factors ]
def factor_list(f):
"""
Returns a list of irreducible factors of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y
>>> Poly(f).factor_list()
(2, [(Poly(x + y, x, y, domain='ZZ'), 1),
(Poly(x**2 + 1, x, y, domain='ZZ'), 2)])
"""
if hasattr(f.rep, 'factor_list'):
try:
coeff, factors = f.rep.factor_list()
except DomainError:
return S.One, [(f, 1)]
else: # pragma: no cover
raise OperationNotSupported(f, 'factor_list')
return f.rep.dom.to_sympy(coeff), [ (f.per(g), k) for g, k in factors ]
def factor_list_include(f):
"""
Returns a list of irreducible factors of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y
>>> Poly(f).factor_list_include()
[(Poly(2*x + 2*y, x, y, domain='ZZ'), 1),
(Poly(x**2 + 1, x, y, domain='ZZ'), 2)]
"""
if hasattr(f.rep, 'factor_list_include'):
try:
factors = f.rep.factor_list_include()
except DomainError:
return [(f, 1)]
else: # pragma: no cover
raise OperationNotSupported(f, 'factor_list_include')
return [ (f.per(g), k) for g, k in factors ]
def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False):
"""
Compute isolating intervals for roots of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3, x).intervals()
[((-2, -1), 1), ((1, 2), 1)]
>>> Poly(x**2 - 3, x).intervals(eps=1e-2)
[((-26/15, -19/11), 1), ((19/11, 26/15), 1)]
"""
if eps is not None:
eps = QQ.convert(eps)
if eps <= 0:
raise ValueError("'eps' must be a positive rational")
if inf is not None:
inf = QQ.convert(inf)
if sup is not None:
sup = QQ.convert(sup)
if hasattr(f.rep, 'intervals'):
result = f.rep.intervals(
all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf)
else: # pragma: no cover
raise OperationNotSupported(f, 'intervals')
if sqf:
def _real(interval):
s, t = interval
return (QQ.to_sympy(s), QQ.to_sympy(t))
if not all:
return map(_real, result)
def _complex(rectangle):
(u, v), (s, t) = rectangle
return (QQ.to_sympy(u) + I*QQ.to_sympy(v),
QQ.to_sympy(s) + I*QQ.to_sympy(t))
real_part, complex_part = result
return map(_real, real_part), map(_complex, complex_part)
else:
def _real(interval):
(s, t), k = interval
return ((QQ.to_sympy(s), QQ.to_sympy(t)), k)
if not all:
return map(_real, result)
def _complex(rectangle):
((u, v), (s, t)), k = rectangle
return ((QQ.to_sympy(u) + I*QQ.to_sympy(v),
QQ.to_sympy(s) + I*QQ.to_sympy(t)), k)
real_part, complex_part = result
return map(_real, real_part), map(_complex, complex_part)
def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False):
"""
Refine an isolating interval of a root to the given precision.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2)
(19/11, 26/15)
"""
if check_sqf and not f.is_sqf:
raise PolynomialError("only square-free polynomials supported")
s, t = QQ.convert(s), QQ.convert(t)
if eps is not None:
eps = QQ.convert(eps)
if eps <= 0:
raise ValueError("'eps' must be a positive rational")
if steps is not None:
steps = int(steps)
elif eps is None:
steps = 1
if hasattr(f.rep, 'refine_root'):
S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast)
else: # pragma: no cover
raise OperationNotSupported(f, 'refine_root')
return QQ.to_sympy(S), QQ.to_sympy(T)
def count_roots(f, inf=None, sup=None):
"""
Return the number of roots of ``f`` in ``[inf, sup]`` interval.
Examples
========
>>> from sympy import Poly, I
>>> from sympy.abc import x
>>> Poly(x**4 - 4, x).count_roots(-3, 3)
2
>>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I)
1
"""
inf_real, sup_real = True, True
if inf is not None:
inf = sympify(inf)
if inf is S.NegativeInfinity:
inf = None
else:
re, im = inf.as_real_imag()
if not im:
inf = QQ.convert(inf)
else:
inf, inf_real = map(QQ.convert, (re, im)), False
if sup is not None:
sup = sympify(sup)
if sup is S.Infinity:
sup = None
else:
re, im = sup.as_real_imag()
if not im:
sup = QQ.convert(sup)
else:
sup, sup_real = map(QQ.convert, (re, im)), False
if inf_real and sup_real:
if hasattr(f.rep, 'count_real_roots'):
count = f.rep.count_real_roots(inf=inf, sup=sup)
else: # pragma: no cover
raise OperationNotSupported(f, 'count_real_roots')
else:
if inf_real and inf is not None:
inf = (inf, QQ.zero)
if sup_real and sup is not None:
sup = (sup, QQ.zero)
if hasattr(f.rep, 'count_complex_roots'):
count = f.rep.count_complex_roots(inf=inf, sup=sup)
else: # pragma: no cover
raise OperationNotSupported(f, 'count_complex_roots')
return Integer(count)
def root(f, index, radicals=True):
"""
Get an indexed root of a polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4)
>>> f.root(0)
-1/2
>>> f.root(1)
2
>>> f.root(2)
2
>>> f.root(3)
Traceback (most recent call last):
...
IndexError: root index out of [-3, 2] range, got 3
>>> Poly(x**5 + x + 1).root(0)
RootOf(x**3 - x**2 + 1, 0)
"""
return sympy.polys.rootoftools.RootOf(f, index, radicals=radicals)
def real_roots(f, multiple=True, radicals=True):
"""
Return a list of real roots with multiplicities.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots()
[-1/2, 2, 2]
>>> Poly(x**3 + x + 1).real_roots()
[RootOf(x**3 + x + 1, 0)]
"""
reals = sympy.polys.rootoftools.RootOf.real_roots(f, radicals=radicals)
if multiple:
return reals
else:
return group(reals, multiple=False)
def all_roots(f, multiple=True, radicals=True):
"""
Return a list of real and complex roots with multiplicities.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots()
[-1/2, 2, 2]
>>> Poly(x**3 + x + 1).all_roots()
[RootOf(x**3 + x + 1, 0),
RootOf(x**3 + x + 1, 1),
RootOf(x**3 + x + 1, 2)]
"""
roots = sympy.polys.rootoftools.RootOf.all_roots(f, radicals=radicals)
if multiple:
return roots
else:
return group(roots, multiple=False)
def nroots(f, n=15, maxsteps=50, cleanup=True, error=False):
"""
Compute numerical approximations of roots of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 3).nroots(n=15)
[-1.73205080756888, 1.73205080756888]
>>> Poly(x**2 - 3).nroots(n=30)
[-1.73205080756887729352744634151, 1.73205080756887729352744634151]
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"can't compute numerical roots of %s" % f)
if f.degree() <= 0:
return []
coeffs = [ coeff.evalf(n=n).as_real_imag()
for coeff in f.all_coeffs() ]
dps = sympy.mpmath.mp.dps
sympy.mpmath.mp.dps = n
try:
try:
coeffs = [ sympy.mpmath.mpc(*coeff) for coeff in coeffs ]
except TypeError:
raise DomainError(
"numerical domain expected, got %s" % f.rep.dom)
result = sympy.mpmath.polyroots(
coeffs, maxsteps=maxsteps, cleanup=cleanup, error=error)
if error:
roots, error = result
else:
roots, error = result, None
roots = map(sympify, sorted(roots, key=lambda r: (r.real, r.imag)))
finally:
sympy.mpmath.mp.dps = dps
if error is not None:
return roots, sympify(error)
else:
return roots
def ground_roots(f):
"""
Compute roots of ``f`` by factorization in the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots()
{0: 2, 1: 2}
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"can't compute ground roots of %s" % f)
roots = {}
for factor, k in f.factor_list()[1]:
if factor.is_linear:
a, b = factor.all_coeffs()
roots[-b/a] = k
return roots
def nth_power_roots_poly(f, n):
"""
Construct a polynomial with n-th powers of roots of ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = Poly(x**4 - x**2 + 1)
>>> f.nth_power_roots_poly(2)
Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(3)
Poly(x**4 + 2*x**2 + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(4)
Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ')
>>> f.nth_power_roots_poly(12)
Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ')
"""
if f.is_multivariate:
raise MultivariatePolynomialError(
"must be a univariate polynomial")
N = sympify(n)
if N.is_Integer and N >= 1:
n = int(N)
else:
raise ValueError("'n' must an integer and n >= 1, got %s" % n)
x = f.gen
t = Dummy('t')
r = f.resultant(f.__class__.from_expr(x**n - t, x, t))
return r.replace(t, x)
def cancel(f, g, include=False):
"""
Cancel common factors in a rational function ``f/g``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x))
(1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))
>>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True)
(Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ'))
"""
dom, per, F, G = f._unify(g)
if hasattr(F, 'cancel'):
result = F.cancel(G, include=include)
else: # pragma: no cover
raise OperationNotSupported(f, 'cancel')
if not include:
if dom.has_assoc_Ring:
dom = dom.get_ring()
cp, cq, p, q = result
cp = dom.to_sympy(cp)
cq = dom.to_sympy(cq)
return cp/cq, per(p), per(q)
else:
return tuple(map(per, result))
@property
def is_zero(f):
"""
Returns ``True`` if ``f`` is a zero polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(0, x).is_zero
True
>>> Poly(1, x).is_zero
False
"""
return f.rep.is_zero
@property
def is_one(f):
"""
Returns ``True`` if ``f`` is a unit polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(0, x).is_one
False
>>> Poly(1, x).is_one
True
"""
return f.rep.is_one
@property
def is_sqf(f):
"""
Returns ``True`` if ``f`` is a square-free polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 - 2*x + 1, x).is_sqf
False
>>> Poly(x**2 - 1, x).is_sqf
True
"""
return f.rep.is_sqf
@property
def is_monic(f):
"""
Returns ``True`` if the leading coefficient of ``f`` is one.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x + 2, x).is_monic
True
>>> Poly(2*x + 2, x).is_monic
False
"""
return f.rep.is_monic
@property
def is_primitive(f):
"""
Returns ``True`` if GCD of the coefficients of ``f`` is one.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(2*x**2 + 6*x + 12, x).is_primitive
False
>>> Poly(x**2 + 3*x + 6, x).is_primitive
True
"""
return f.rep.is_primitive
@property
def is_ground(f):
"""
Returns ``True`` if ``f`` is an element of the ground domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x, x).is_ground
False
>>> Poly(2, x).is_ground
True
>>> Poly(y, x).is_ground
True
"""
return f.rep.is_ground
@property
def is_linear(f):
"""
Returns ``True`` if ``f`` is linear in all its variables.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x + y + 2, x, y).is_linear
True
>>> Poly(x*y + 2, x, y).is_linear
False
"""
return f.rep.is_linear
@property
def is_quadratic(f):
"""
Returns ``True`` if ``f`` is quadratic in all its variables.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x*y + 2, x, y).is_quadratic
True
>>> Poly(x*y**2 + 2, x, y).is_quadratic
False
"""
return f.rep.is_quadratic
@property
def is_monomial(f):
"""
Returns ``True`` if ``f`` is zero or has only one term.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(3*x**2, x).is_monomial
True
>>> Poly(3*x**2 + 1, x).is_monomial
False
"""
return f.rep.is_monomial
@property
def is_homogeneous(f):
"""
Returns ``True`` if ``f`` is a homogeneous polynomial.
A homogeneous polynomial is a polynomial whose all monomials with
non-zero coefficients have the same total degree. If you want not
only to check if a polynomial is homogeneous but also compute its
homogeneous order, then use :func:`Poly.homogeneous_order`.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x*y, x, y).is_homogeneous
True
>>> Poly(x**3 + x*y, x, y).is_homogeneous
False
"""
return f.rep.is_homogeneous
@property
def is_irreducible(f):
"""
Returns ``True`` if ``f`` has no factors over its domain.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible
True
>>> Poly(x**2 + 1, x, modulus=2).is_irreducible
False
"""
return f.rep.is_irreducible
@property
def is_univariate(f):
"""
Returns ``True`` if ``f`` is a univariate polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x + 1, x).is_univariate
True
>>> Poly(x*y**2 + x*y + 1, x, y).is_univariate
False
>>> Poly(x*y**2 + x*y + 1, x).is_univariate
True
>>> Poly(x**2 + x + 1, x, y).is_univariate
False
"""
return len(f.gens) == 1
@property
def is_multivariate(f):
"""
Returns ``True`` if ``f`` is a multivariate polynomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x, y
>>> Poly(x**2 + x + 1, x).is_multivariate
False
>>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate
True
>>> Poly(x*y**2 + x*y + 1, x).is_multivariate
False
>>> Poly(x**2 + x + 1, x, y).is_multivariate
True
"""
return len(f.gens) != 1
@property
def is_cyclotomic(f):
"""
Returns ``True`` if ``f`` is a cyclotomic polnomial.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import x
>>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1
>>> Poly(f).is_cyclotomic
False
>>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1
>>> Poly(g).is_cyclotomic
True
"""
return f.rep.is_cyclotomic
def __abs__(f):
return f.abs()
def __neg__(f):
return f.neg()
@_sympifyit('g', NotImplemented)
def __add__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, *f.gens)
except PolynomialError:
return f.as_expr() + g
return f.add(g)
@_sympifyit('g', NotImplemented)
def __radd__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, *f.gens)
except PolynomialError:
return g + f.as_expr()
return g.add(f)
@_sympifyit('g', NotImplemented)
def __sub__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, *f.gens)
except PolynomialError:
return f.as_expr() - g
return f.sub(g)
@_sympifyit('g', NotImplemented)
def __rsub__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, *f.gens)
except PolynomialError:
return g - f.as_expr()
return g.sub(f)
@_sympifyit('g', NotImplemented)
def __mul__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, *f.gens)
except PolynomialError:
return f.as_expr()*g
return f.mul(g)
@_sympifyit('g', NotImplemented)
def __rmul__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, *f.gens)
except PolynomialError:
return g*f.as_expr()
return g.mul(f)
@_sympifyit('n', NotImplemented)
def __pow__(f, n):
if n.is_Integer and n >= 0:
return f.pow(n)
else:
return f.as_expr()**n
@_sympifyit('g', NotImplemented)
def __divmod__(f, g):
if not g.is_Poly:
g = f.__class__(g, *f.gens)
return f.div(g)
@_sympifyit('g', NotImplemented)
def __rdivmod__(f, g):
if not g.is_Poly:
g = f.__class__(g, *f.gens)
return g.div(f)
@_sympifyit('g', NotImplemented)
def __mod__(f, g):
if not g.is_Poly:
g = f.__class__(g, *f.gens)
return f.rem(g)
@_sympifyit('g', NotImplemented)
def __rmod__(f, g):
if not g.is_Poly:
g = f.__class__(g, *f.gens)
return g.rem(f)
@_sympifyit('g', NotImplemented)
def __floordiv__(f, g):
if not g.is_Poly:
g = f.__class__(g, *f.gens)
return f.quo(g)
@_sympifyit('g', NotImplemented)
def __rfloordiv__(f, g):
if not g.is_Poly:
g = f.__class__(g, *f.gens)
return g.quo(f)
@_sympifyit('g', NotImplemented)
def __div__(f, g):
return f.as_expr()/g.as_expr()
@_sympifyit('g', NotImplemented)
def __rdiv__(f, g):
return g.as_expr()/f.as_expr()
__truediv__ = __div__
__rtruediv__ = __rdiv__
@_sympifyit('g', NotImplemented)
def __eq__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, f.gens, domain=f.get_domain())
except (PolynomialError, DomainError, CoercionFailed):
return False
if f.gens != g.gens:
return False
if f.rep.dom != g.rep.dom:
try:
dom = f.rep.dom.unify(g.rep.dom, f.gens)
except UnificationFailed:
return False
f = f.set_domain(dom)
g = g.set_domain(dom)
return f.rep == g.rep
@_sympifyit('g', NotImplemented)
def __ne__(f, g):
return not f.__eq__(g)
def __nonzero__(f):
return not f.is_zero
def eq(f, g, strict=False):
if not strict:
return f.__eq__(g)
else:
return f._strict_eq(sympify(g))
def ne(f, g, strict=False):
return not f.eq(g, strict=strict)
def _strict_eq(f, g):
return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True)
class PurePoly(Poly):
"""Class for representing pure polynomials. """
def _hashable_content(self):
"""Allow SymPy to hash Poly instances. """
return (self.rep,)
def __hash__(self):
return super(PurePoly, self).__hash__()
@property
def free_symbols(self):
"""
Free symbols of a polynomial.
Examples
========
>>> from sympy import PurePoly
>>> from sympy.abc import x, y
>>> PurePoly(x**2 + 1).free_symbols
set()
>>> PurePoly(x**2 + y).free_symbols
set()
>>> PurePoly(x**2 + y, x).free_symbols
set([y])
"""
return self.free_symbols_in_domain
@_sympifyit('g', NotImplemented)
def __eq__(f, g):
if not g.is_Poly:
try:
g = f.__class__(g, f.gens, domain=f.get_domain())
except (PolynomialError, DomainError, CoercionFailed):
return False
if len(f.gens) != len(g.gens):
return False
if f.rep.dom != g.rep.dom:
try:
dom = f.rep.dom.unify(g.rep.dom, f.gens)
except UnificationFailed:
return False
f = f.set_domain(dom)
g = g.set_domain(dom)
return f.rep == g.rep
def _strict_eq(f, g):
return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True)
def _unify(f, g):
g = sympify(g)
if not g.is_Poly:
try:
return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g))
except CoercionFailed:
raise UnificationFailed("can't unify %s with %s" % (f, g))
if len(f.gens) != len(g.gens):
raise UnificationFailed("can't unify %s with %s" % (f, g))
if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)):
raise UnificationFailed("can't unify %s with %s" % (f, g))
cls = f.__class__
gens = f.gens
dom = f.rep.dom.unify(g.rep.dom, gens)
F = f.rep.convert(dom)
G = g.rep.convert(dom)
def per(rep, dom=dom, gens=gens, remove=None):
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return dom.to_sympy(rep)
return cls.new(rep, *gens)
return dom, per, F, G
def poly_from_expr(expr, *gens, **args):
"""Construct a polynomial from an expression. """
opt = options.build_options(gens, args)
return _poly_from_expr(expr, opt)
def _poly_from_expr(expr, opt):
"""Construct a polynomial from an expression. """
orig, expr = expr, sympify(expr)
if not isinstance(expr, Basic):
raise PolificationFailed(opt, orig, expr)
elif expr.is_Poly:
poly = expr.__class__._from_poly(expr, opt)
opt['gens'] = poly.gens
opt['domain'] = poly.domain
if opt.polys is None:
opt['polys'] = True
return poly, opt
elif opt.expand:
expr = expr.expand()
try:
rep, opt = _dict_from_expr(expr, opt)
except GeneratorsNeeded:
raise PolificationFailed(opt, orig, expr)
monoms, coeffs = zip(*rep.items())
domain = opt.domain
if domain is None:
domain, coeffs = construct_domain(coeffs, opt=opt)
else:
coeffs = map(domain.from_sympy, coeffs)
level = len(opt.gens) - 1
poly = Poly.new(
DMP.from_monoms_coeffs(monoms, coeffs, level, domain), *opt.gens)
opt['domain'] = domain
if opt.polys is None:
opt['polys'] = False
return poly, opt
def parallel_poly_from_expr(exprs, *gens, **args):
"""Construct polynomials from expressions. """
opt = options.build_options(gens, args)
return _parallel_poly_from_expr(exprs, opt)
def _parallel_poly_from_expr(exprs, opt):
"""Construct polynomials from expressions. """
if len(exprs) == 2:
f, g = exprs
if isinstance(f, Poly) and isinstance(g, Poly):
f = f.__class__._from_poly(f, opt)
g = g.__class__._from_poly(g, opt)
f, g = f.unify(g)
opt['gens'] = f.gens
opt['domain'] = f.domain
if opt.polys is None:
opt['polys'] = True
return [f, g], opt
origs, exprs = list(exprs), []
_exprs, _polys = [], []
failed = False
for i, expr in enumerate(origs):
expr = sympify(expr)
if isinstance(expr, Basic):
if expr.is_Poly:
_polys.append(i)
else:
_exprs.append(i)
if opt.expand:
expr = expr.expand()
else:
failed = True
exprs.append(expr)
if failed:
raise PolificationFailed(opt, origs, exprs, True)
if _polys:
# XXX: this is a temporary solution
for i in _polys:
exprs[i] = exprs[i].as_expr()
try:
reps, opt = _parallel_dict_from_expr(exprs, opt)
except GeneratorsNeeded:
raise PolificationFailed(opt, origs, exprs, True)
coeffs_list, lengths = [], []
all_monoms = []
all_coeffs = []
for rep in reps:
monoms, coeffs = zip(*rep.items())
coeffs_list.extend(coeffs)
all_monoms.append(monoms)
lengths.append(len(coeffs))
domain = opt.domain
if domain is None:
domain, coeffs_list = construct_domain(coeffs_list, opt=opt)
else:
coeffs_list = map(domain.from_sympy, coeffs_list)
for k in lengths:
all_coeffs.append(coeffs_list[:k])
coeffs_list = coeffs_list[k:]
polys, level = [], len(opt.gens) - 1
for monoms, coeffs in zip(all_monoms, all_coeffs):
rep = DMP.from_monoms_coeffs(monoms, coeffs, level, domain)
polys.append(Poly.new(rep, *opt.gens))
opt['domain'] = domain
if opt.polys is None:
opt['polys'] = bool(_polys)
return polys, opt
def _update_args(args, key, value):
"""Add a new ``(key, value)`` pair to arguments ``dict``. """
args = dict(args)
if key not in args:
args[key] = value
return args
def degree(f, *gens, **args):
"""
Return the degree of ``f`` in the given variable.
Examples
========
>>> from sympy import degree
>>> from sympy.abc import x, y
>>> degree(x**2 + y*x + 1, gen=x)
2
>>> degree(x**2 + y*x + 1, gen=y)
1
"""
options.allowed_flags(args, ['gen', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('degree', 1, exc)
return Integer(F.degree(opt.gen))
def degree_list(f, *gens, **args):
"""
Return a list of degrees of ``f`` in all variables.
Examples
========
>>> from sympy import degree_list
>>> from sympy.abc import x, y
>>> degree_list(x**2 + y*x + 1)
(2, 1)
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('degree_list', 1, exc)
degrees = F.degree_list()
return tuple(map(Integer, degrees))
def LC(f, *gens, **args):
"""
Return the leading coefficient of ``f``.
Examples
========
>>> from sympy import LC
>>> from sympy.abc import x, y
>>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y)
4
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('LC', 1, exc)
return F.LC(order=opt.order)
def LM(f, *gens, **args):
"""
Return the leading monomial of ``f``.
Examples
========
>>> from sympy import LM
>>> from sympy.abc import x, y
>>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y)
x**2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('LM', 1, exc)
monom = F.LM(order=opt.order)
return monom.as_expr()
def LT(f, *gens, **args):
"""
Return the leading term of ``f``.
Examples
========
>>> from sympy import LT
>>> from sympy.abc import x, y
>>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y)
4*x**2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('LT', 1, exc)
monom, coeff = F.LT(order=opt.order)
return coeff*monom.as_expr()
def pdiv(f, g, *gens, **args):
"""
Compute polynomial pseudo-division of ``f`` and ``g``.
Examples
========
>>> from sympy import pdiv
>>> from sympy.abc import x
>>> pdiv(x**2 + 1, 2*x - 4)
(2*x + 4, 20)
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('pdiv', 2, exc)
q, r = F.pdiv(G)
if not opt.polys:
return q.as_expr(), r.as_expr()
else:
return q, r
def prem(f, g, *gens, **args):
"""
Compute polynomial pseudo-remainder of ``f`` and ``g``.
Examples
========
>>> from sympy import prem
>>> from sympy.abc import x
>>> prem(x**2 + 1, 2*x - 4)
20
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('prem', 2, exc)
r = F.prem(G)
if not opt.polys:
return r.as_expr()
else:
return r
def pquo(f, g, *gens, **args):
"""
Compute polynomial pseudo-quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import pquo
>>> from sympy.abc import x
>>> pquo(x**2 + 1, 2*x - 4)
2*x + 4
>>> pquo(x**2 - 1, 2*x - 1)
2*x + 1
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('pquo', 2, exc)
try:
q = F.pquo(G)
except ExactQuotientFailed:
raise ExactQuotientFailed(f, g)
if not opt.polys:
return q.as_expr()
else:
return q
def pexquo(f, g, *gens, **args):
"""
Compute polynomial exact pseudo-quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import pexquo
>>> from sympy.abc import x
>>> pexquo(x**2 - 1, 2*x - 2)
2*x + 2
>>> pexquo(x**2 + 1, 2*x - 4)
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('pexquo', 2, exc)
q = F.pexquo(G)
if not opt.polys:
return q.as_expr()
else:
return q
def div(f, g, *gens, **args):
"""
Compute polynomial division of ``f`` and ``g``.
Examples
========
>>> from sympy import div, ZZ, QQ
>>> from sympy.abc import x
>>> div(x**2 + 1, 2*x - 4, domain=ZZ)
(0, x**2 + 1)
>>> div(x**2 + 1, 2*x - 4, domain=QQ)
(x/2 + 1, 5)
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('div', 2, exc)
q, r = F.div(G, auto=opt.auto)
if not opt.polys:
return q.as_expr(), r.as_expr()
else:
return q, r
def rem(f, g, *gens, **args):
"""
Compute polynomial remainder of ``f`` and ``g``.
Examples
========
>>> from sympy import rem, ZZ, QQ
>>> from sympy.abc import x
>>> rem(x**2 + 1, 2*x - 4, domain=ZZ)
x**2 + 1
>>> rem(x**2 + 1, 2*x - 4, domain=QQ)
5
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('rem', 2, exc)
r = F.rem(G, auto=opt.auto)
if not opt.polys:
return r.as_expr()
else:
return r
def quo(f, g, *gens, **args):
"""
Compute polynomial quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import quo
>>> from sympy.abc import x
>>> quo(x**2 + 1, 2*x - 4)
x/2 + 1
>>> quo(x**2 - 1, x - 1)
x + 1
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('quo', 2, exc)
q = F.quo(G, auto=opt.auto)
if not opt.polys:
return q.as_expr()
else:
return q
def exquo(f, g, *gens, **args):
"""
Compute polynomial exact quotient of ``f`` and ``g``.
Examples
========
>>> from sympy import exquo
>>> from sympy.abc import x
>>> exquo(x**2 - 1, x - 1)
x + 1
>>> exquo(x**2 + 1, 2*x - 4)
Traceback (most recent call last):
...
ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('exquo', 2, exc)
q = F.exquo(G, auto=opt.auto)
if not opt.polys:
return q.as_expr()
else:
return q
def half_gcdex(f, g, *gens, **args):
"""
Half extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``.
Examples
========
>>> from sympy import half_gcdex
>>> from sympy.abc import x
>>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
(-x/5 + 3/5, x + 1)
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
s, h = domain.half_gcdex(a, b)
except NotImplementedError:
raise ComputationFailed('half_gcdex', 2, exc)
else:
return domain.to_sympy(s), domain.to_sympy(h)
s, h = F.half_gcdex(G, auto=opt.auto)
if not opt.polys:
return s.as_expr(), h.as_expr()
else:
return s, h
def gcdex(f, g, *gens, **args):
"""
Extended Euclidean algorithm of ``f`` and ``g``.
Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``.
Examples
========
>>> from sympy import gcdex
>>> from sympy.abc import x
>>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4)
(-x/5 + 3/5, x**2/5 - 6*x/5 + 2, x + 1)
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
s, t, h = domain.gcdex(a, b)
except NotImplementedError:
raise ComputationFailed('gcdex', 2, exc)
else:
return domain.to_sympy(s), domain.to_sympy(t), domain.to_sympy(h)
s, t, h = F.gcdex(G, auto=opt.auto)
if not opt.polys:
return s.as_expr(), t.as_expr(), h.as_expr()
else:
return s, t, h
def invert(f, g, *gens, **args):
"""
Invert ``f`` modulo ``g`` when possible.
Examples
========
>>> from sympy import invert
>>> from sympy.abc import x
>>> invert(x**2 - 1, 2*x - 1)
-4/3
>>> invert(x**2 - 1, x - 1)
Traceback (most recent call last):
...
NotInvertible: zero divisor
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
return domain.to_sympy(domain.invert(a, b))
except NotImplementedError:
raise ComputationFailed('invert', 2, exc)
h = F.invert(G, auto=opt.auto)
if not opt.polys:
return h.as_expr()
else:
return h
def subresultants(f, g, *gens, **args):
"""
Compute subresultant PRS of ``f`` and ``g``.
Examples
========
>>> from sympy import subresultants
>>> from sympy.abc import x
>>> subresultants(x**2 + 1, x**2 - 1)
[x**2 + 1, x**2 - 1, -2]
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('subresultants', 2, exc)
result = F.subresultants(G)
if not opt.polys:
return [ r.as_expr() for r in result ]
else:
return result
def resultant(f, g, *gens, **args):
"""
Compute resultant of ``f`` and ``g``.
Examples
========
>>> from sympy import resultant
>>> from sympy.abc import x
>>> resultant(x**2 + 1, x**2 - 1)
4
"""
includePRS = args.pop('includePRS', False)
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('resultant', 2, exc)
if includePRS:
result, R = F.resultant(G, includePRS=includePRS)
else:
result = F.resultant(G)
if not opt.polys:
if includePRS:
return result.as_expr(), [r.as_expr() for r in R]
return result.as_expr()
else:
if includePRS:
return result, R
return result
def discriminant(f, *gens, **args):
"""
Compute discriminant of ``f``.
Examples
========
>>> from sympy import discriminant
>>> from sympy.abc import x
>>> discriminant(x**2 + 2*x + 3)
-8
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('discriminant', 1, exc)
result = F.discriminant()
if not opt.polys:
return result.as_expr()
else:
return result
def cofactors(f, g, *gens, **args):
"""
Compute GCD and cofactors of ``f`` and ``g``.
Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and
``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors
of ``f`` and ``g``.
Examples
========
>>> from sympy import cofactors
>>> from sympy.abc import x
>>> cofactors(x**2 - 1, x**2 - 3*x + 2)
(x - 1, x + 1, x - 2)
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
h, cff, cfg = domain.cofactors(a, b)
except NotImplementedError:
raise ComputationFailed('cofactors', 2, exc)
else:
return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg)
h, cff, cfg = F.cofactors(G)
if not opt.polys:
return h.as_expr(), cff.as_expr(), cfg.as_expr()
else:
return h, cff, cfg
def gcd_list(seq, *gens, **args):
"""
Compute GCD of a list of polynomials.
Examples
========
>>> from sympy import gcd_list
>>> from sympy.abc import x
>>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
x - 1
"""
seq = sympify(seq)
if not gens and not args:
domain, numbers = construct_domain(seq)
if not numbers:
return domain.zero
elif domain.is_Numerical:
result, numbers = numbers[0], numbers[1:]
for number in numbers:
result = domain.gcd(result, number)
if domain.is_one(result):
break
return domain.to_sympy(result)
options.allowed_flags(args, ['polys'])
try:
polys, opt = parallel_poly_from_expr(seq, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('gcd_list', len(seq), exc)
if not polys:
if not opt.polys:
return S.Zero
else:
return Poly(0, opt=opt)
result, polys = polys[0], polys[1:]
for poly in polys:
result = result.gcd(poly)
if result.is_one:
break
if not opt.polys:
return result.as_expr()
else:
return result
def gcd(f, g=None, *gens, **args):
"""
Compute GCD of ``f`` and ``g``.
Examples
========
>>> from sympy import gcd
>>> from sympy.abc import x
>>> gcd(x**2 - 1, x**2 - 3*x + 2)
x - 1
"""
if hasattr(f, '__iter__'):
if g is not None:
gens = (g,) + gens
return gcd_list(f, *gens, **args)
elif g is None:
raise TypeError("gcd() takes 2 arguments or a sequence of arguments")
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
return domain.to_sympy(domain.gcd(a, b))
except NotImplementedError:
raise ComputationFailed('gcd', 2, exc)
result = F.gcd(G)
if not opt.polys:
return result.as_expr()
else:
return result
def lcm_list(seq, *gens, **args):
"""
Compute LCM of a list of polynomials.
Examples
========
>>> from sympy import lcm_list
>>> from sympy.abc import x
>>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2])
x**5 - x**4 - 2*x**3 - x**2 + x + 2
"""
seq = sympify(seq)
if not gens and not args:
domain, numbers = construct_domain(seq)
if not numbers:
return domain.one
elif domain.is_Numerical:
result, numbers = numbers[0], numbers[1:]
for number in numbers:
result = domain.lcm(result, number)
return domain.to_sympy(result)
options.allowed_flags(args, ['polys'])
try:
polys, opt = parallel_poly_from_expr(seq, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('lcm_list', len(seq), exc)
if not polys:
if not opt.polys:
return S.One
else:
return Poly(1, opt=opt)
result, polys = polys[0], polys[1:]
for poly in polys:
result = result.lcm(poly)
if not opt.polys:
return result.as_expr()
else:
return result
def lcm(f, g=None, *gens, **args):
"""
Compute LCM of ``f`` and ``g``.
Examples
========
>>> from sympy import lcm
>>> from sympy.abc import x
>>> lcm(x**2 - 1, x**2 - 3*x + 2)
x**3 - 2*x**2 - x + 2
"""
if hasattr(f, '__iter__'):
if g is not None:
gens = (g,) + gens
return lcm_list(f, *gens, **args)
elif g is None:
raise TypeError("lcm() takes 2 arguments or a sequence of arguments")
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
domain, (a, b) = construct_domain(exc.exprs)
try:
return domain.to_sympy(domain.lcm(a, b))
except NotImplementedError:
raise ComputationFailed('lcm', 2, exc)
result = F.lcm(G)
if not opt.polys:
return result.as_expr()
else:
return result
def terms_gcd(f, *gens, **args):
"""
Remove GCD of terms from ``f``.
If the ``deep`` flag is True, then the arguments of ``f`` will have
terms_gcd applied to them.
If a fraction is factored out of ``f`` and ``f`` is an Add, then
an unevaluated Mul will be returned so that automatic simplification
does not redistribute it. The hint ``clear``, when set to False, can be
used to prevent such factoring when all coefficients are not fractions.
Examples
========
>>> from sympy import terms_gcd, cos, pi
>>> from sympy.abc import x, y
>>> terms_gcd(x**6*y**2 + x**3*y, x, y)
x**3*y*(x**3*y + 1)
The default action of polys routines is to expand the expression
given to them. terms_gcd follows this behavior:
>>> terms_gcd((3+3*x)*(x+x*y))
3*x*(x*y + x + y + 1)
If this is not desired then the hint ``expand`` can be set to False.
In this case the expression will be treated as though it were comprised
of one or more terms:
>>> terms_gcd((3+3*x)*(x+x*y), expand=False)
(3*x + 3)*(x*y + x)
In order to traverse factors of a Mul or the arguments of other
functions, the ``deep`` hint can be used:
>>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True)
3*x*(x + 1)*(y + 1)
>>> terms_gcd(cos(x + x*y), deep=True)
cos(x*(y + 1))
Rationals are factored out by default:
>>> terms_gcd(x + y/2)
(2*x + y)/2
Only the y-term had a coefficient that was a fraction; if one
does not want to factor out the 1/2 in cases like this, the
flag ``clear`` can be set to False:
>>> terms_gcd(x + y/2, clear=False)
x + y/2
>>> terms_gcd(x*y/2 + y**2, clear=False)
y*(x/2 + y)
The ``clear`` flag is ignored if all coefficients are fractions:
>>> terms_gcd(x/3 + y/2, clear=False)
(2*x + 3*y)/6
See Also
========
sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms
"""
if not isinstance(f, Expr) or f.is_Atom:
return sympify(f)
if args.get('deep', False):
new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args])
args.pop('deep')
args['expand'] = False
return terms_gcd(new, *gens, **args)
clear = args.pop('clear', True)
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
return exc.expr
J, f = F.terms_gcd()
if opt.domain.has_Ring:
if opt.domain.has_Field:
denom, f = f.clear_denoms(convert=True)
coeff, f = f.primitive()
if opt.domain.has_Field:
coeff /= denom
else:
coeff = S.One
term = Mul(*[ x**j for x, j in zip(f.gens, J) ])
if clear:
return _keep_coeff(coeff, term*f.as_expr())
# base the clearing on the form of the original expression, not
# the (perhaps) Mul that we have now
coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul()
return _keep_coeff(coeff, term*f, clear=False)
def trunc(f, p, *gens, **args):
"""
Reduce ``f`` modulo a constant ``p``.
Examples
========
>>> from sympy import trunc
>>> from sympy.abc import x
>>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3)
-x**3 - x + 1
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('trunc', 1, exc)
result = F.trunc(sympify(p))
if not opt.polys:
return result.as_expr()
else:
return result
def monic(f, *gens, **args):
"""
Divide all coefficients of ``f`` by ``LC(f)``.
Examples
========
>>> from sympy import monic
>>> from sympy.abc import x
>>> monic(3*x**2 + 4*x + 2)
x**2 + 4*x/3 + 2/3
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('monic', 1, exc)
result = F.monic(auto=opt.auto)
if not opt.polys:
return result.as_expr()
else:
return result
def content(f, *gens, **args):
"""
Compute GCD of coefficients of ``f``.
Examples
========
>>> from sympy import content
>>> from sympy.abc import x
>>> content(6*x**2 + 8*x + 12)
2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('content', 1, exc)
return F.content()
def primitive(f, *gens, **args):
"""
Compute content and the primitive form of ``f``.
Examples
========
>>> from sympy.polys.polytools import primitive
>>> from sympy.abc import x, y
>>> primitive(6*x**2 + 8*x + 12)
(2, 3*x**2 + 4*x + 6)
>>> eq = (2 + 2*x)*x + 2
Expansion is performed by default:
>>> primitive(eq)
(2, x**2 + x + 1)
Set ``expand`` to False to shut this off. Note that the
extraction will not be recursive; use the as_content_primitive method
for recursive, non-destructive Rational extraction.
>>> primitive(eq, expand=False)
(1, x*(2*x + 2) + 2)
>>> eq.as_content_primitive()
(2, x*(x + 1) + 1)
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('primitive', 1, exc)
cont, result = F.primitive()
if not opt.polys:
return cont, result.as_expr()
else:
return cont, result
def compose(f, g, *gens, **args):
"""
Compute functional composition ``f(g)``.
Examples
========
>>> from sympy import compose
>>> from sympy.abc import x
>>> compose(x**2 + x, x - 1)
x**2 - x
"""
options.allowed_flags(args, ['polys'])
try:
(F, G), opt = parallel_poly_from_expr((f, g), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('compose', 2, exc)
result = F.compose(G)
if not opt.polys:
return result.as_expr()
else:
return result
def decompose(f, *gens, **args):
"""
Compute functional decomposition of ``f``.
Examples
========
>>> from sympy import decompose
>>> from sympy.abc import x
>>> decompose(x**4 + 2*x**3 - x - 1)
[x**2 - x - 1, x**2 + x]
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('decompose', 1, exc)
result = F.decompose()
if not opt.polys:
return [ r.as_expr() for r in result ]
else:
return result
def sturm(f, *gens, **args):
"""
Compute Sturm sequence of ``f``.
Examples
========
>>> from sympy import sturm
>>> from sympy.abc import x
>>> sturm(x**3 - 2*x**2 + x - 3)
[x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4]
"""
options.allowed_flags(args, ['auto', 'polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('sturm', 1, exc)
result = F.sturm(auto=opt.auto)
if not opt.polys:
return [ r.as_expr() for r in result ]
else:
return result
def gff_list(f, *gens, **args):
"""
Compute a list of greatest factorial factors of ``f``.
Examples
========
>>> from sympy import gff_list, ff
>>> from sympy.abc import x
>>> f = x**5 + 2*x**4 - x**3 - 2*x**2
>>> gff_list(f)
[(x, 1), (x + 2, 4)]
>>> (ff(x, 1)*ff(x + 2, 4)).expand() == f
True
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('gff_list', 1, exc)
factors = F.gff_list()
if not opt.polys:
return [ (g.as_expr(), k) for g, k in factors ]
else:
return factors
def gff(f, *gens, **args):
"""Compute greatest factorial factorization of ``f``. """
raise NotImplementedError('symbolic falling factorial')
def sqf_norm(f, *gens, **args):
"""
Compute square-free norm of ``f``.
Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and
``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``,
where ``a`` is the algebraic extension of the ground domain.
Examples
========
>>> from sympy import sqf_norm, sqrt
>>> from sympy.abc import x
>>> sqf_norm(x**2 + 1, extension=[sqrt(3)])
(1, x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16)
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('sqf_norm', 1, exc)
s, g, r = F.sqf_norm()
if not opt.polys:
return Integer(s), g.as_expr(), r.as_expr()
else:
return Integer(s), g, r
def sqf_part(f, *gens, **args):
"""
Compute square-free part of ``f``.
Examples
========
>>> from sympy import sqf_part
>>> from sympy.abc import x
>>> sqf_part(x**3 - 3*x - 2)
x**2 - x - 2
"""
options.allowed_flags(args, ['polys'])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('sqf_part', 1, exc)
result = F.sqf_part()
if not opt.polys:
return result.as_expr()
else:
return result
def _sorted_factors(factors, method):
"""Sort a list of ``(expr, exp)`` pairs. """
if method == 'sqf':
def key(obj):
poly, exp = obj
rep = poly.rep.rep
return (exp, len(rep), rep)
else:
def key(obj):
poly, exp = obj
rep = poly.rep.rep
return (len(rep), exp, rep)
return sorted(factors, key=key)
def _factors_product(factors):
"""Multiply a list of ``(expr, exp)`` pairs. """
return Mul(*[ f.as_expr()**k for f, k in factors ])
def _symbolic_factor_list(expr, opt, method):
"""Helper function for :func:`_symbolic_factor`. """
coeff, factors = S.One, []
for arg in Mul.make_args(expr):
if arg.is_Number:
coeff *= arg
continue
elif arg.is_Pow:
base, exp = arg.args
if base.is_Number:
factors.append((base, exp))
continue
else:
base, exp = arg, S.One
try:
poly, _ = _poly_from_expr(base, opt)
except PolificationFailed, exc:
factors.append((exc.expr, exp))
else:
func = getattr(poly, method + '_list')
_coeff, _factors = func()
if _coeff is not S.One:
if exp.is_Integer:
coeff *= _coeff**exp
elif _coeff.is_positive:
factors.append((_coeff, exp))
else:
_factors.append((_coeff, None))
if exp is S.One:
factors.extend(_factors)
elif exp.is_integer or len(_factors) == 1:
factors.extend([ (f, k*exp) for f, k in _factors ])
else:
other = []
for f, k in _factors:
if f.as_expr().is_positive:
factors.append((f, k*exp))
elif k is not None:
other.append((f, k))
else:
other.append((f, S.One))
if len(other) == 1:
f, k = other[0]
factors.append((f, k*exp))
else:
factors.append((_factors_product(other), exp))
return coeff, factors
def _symbolic_factor(expr, opt, method):
"""Helper function for :func:`_factor`. """
if isinstance(expr, Expr) and not expr.is_Relational:
coeff, factors = _symbolic_factor_list(together(expr), opt, method)
return _keep_coeff(coeff, _factors_product(factors))
elif hasattr(expr, 'args'):
return expr.func(*[ _symbolic_factor(arg, opt, method) for arg in expr.args ])
elif hasattr(expr, '__iter__'):
return expr.__class__([ _symbolic_factor(arg, opt, method) for arg in expr ])
else:
return expr
def _generic_factor_list(expr, gens, args, method):
"""Helper function for :func:`sqf_list` and :func:`factor_list`. """
options.allowed_flags(args, ['frac', 'polys'])
opt = options.build_options(gens, args)
expr = sympify(expr)
if isinstance(expr, Expr) and not expr.is_Relational:
numer, denom = together(expr).as_numer_denom()
cp, fp = _symbolic_factor_list(numer, opt, method)
cq, fq = _symbolic_factor_list(denom, opt, method)
if fq and not opt.frac:
raise PolynomialError("a polynomial expected, got %s" % expr)
_opt = opt.clone(dict(expand=True))
for factors in (fp, fq):
for i, (f, k) in enumerate(factors):
if not f.is_Poly:
f, _ = _poly_from_expr(f, _opt)
factors[i] = (f, k)
fp = _sorted_factors(fp, method)
fq = _sorted_factors(fq, method)
if not opt.polys:
fp = [ (f.as_expr(), k) for f, k in fp ]
fq = [ (f.as_expr(), k) for f, k in fq ]
coeff = cp/cq
if not opt.frac:
return coeff, fp
else:
return coeff, fp, fq
else:
raise PolynomialError("a polynomial expected, got %s" % expr)
def _generic_factor(expr, gens, args, method):
"""Helper function for :func:`sqf` and :func:`factor`. """
options.allowed_flags(args, [])
opt = options.build_options(gens, args)
return _symbolic_factor(sympify(expr), opt, method)
def to_rational_coeffs(f):
"""
try to transform a polynomial to have rational coefficients
try to find a transformation ``x = alpha*y``
``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with
rational coefficients, ``lc`` the leading coefficient.
If this fails, try ``x = y + beta``
``f(x) = g(y)``
Returns ``None`` if ``g`` not found;
``(lc, alpha, None, g)`` in case of rescaling
``(None, None, beta, g)`` in case of translation
Notes
=====
Currently it transforms only polynomials without roots larger than 2.
Examples
========
>>> from sympy import sqrt, Poly, simplify, expand
>>> from sympy.polys.polytools import to_rational_coeffs
>>> from sympy.abc import x
>>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX')
>>> lc, r, _, g = to_rational_coeffs(p)
>>> lc, r
(7 + 5*sqrt(2), -2*sqrt(2) + 2)
>>> g
Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ')
>>> r1 = simplify(1/r)
>>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p
True
"""
from sympy.simplify.simplify import simplify
def _try_rescale(f):
"""
try rescaling ``x -> alpha*x`` to convert f to a polynomial
with rational coefficients.
Returns ``alpha, f``; if the rescaling is successful,
``alpha`` is the rescaling factor, and ``f`` is the rescaled
polynomial; else ``alpha`` is ``None``.
"""
from sympy.core.add import Add
if not len(f.gens) == 1 or not (f.gens[0]).is_Atom:
return None, f
n = f.degree()
lc = f.LC()
coeffs = f.monic().all_coeffs()[1:]
coeffs = [simplify(coeffx) for coeffx in coeffs]
if coeffs[-2] and not all(coeffx.is_rational for coeffx in coeffs):
rescale1_x = simplify(coeffs[-2]/coeffs[-1])
coeffs1 = []
for i in range(len(coeffs)):
coeffx = simplify(coeffs[i]*rescale1_x**(i + 1))
if not coeffx.is_rational:
break
coeffs1.append(coeffx)
else:
rescale_x = simplify(1/rescale1_x)
x = f.gens[0]
v = [x**n]
for i in range(1, n + 1):
v.append(coeffs1[i - 1]*x**(n - i))
f = Add(*v)
f = Poly(f)
return lc, rescale_x, f
return None
def _try_translate(f):
"""
try translating ``x -> x + alpha`` to convert f to a polynomial
with rational coefficients.
Returns ``alpha, f``; if the translating is successful,
``alpha`` is the translating factor, and ``f`` is the shifted
polynomial; else ``alpha`` is ``None``.
"""
from sympy.core.add import Add
from sympy.utilities.iterables import sift
if not len(f.gens) == 1 or not (f.gens[0]).is_Atom:
return None, f
n = f.degree()
f1 = f.monic()
coeffs = f1.all_coeffs()[1:]
c = simplify(coeffs[0])
if c and not c.is_rational:
if c.is_Add:
args = c.args
else:
args = [c]
sifted = sift(args, lambda z: z.is_rational)
c1, c2 = sifted[True], sifted[False]
alpha = -Add(*c2)/n
f2 = f1.shift(alpha)
return alpha, f2
return None
def _has_square_roots(p):
"""
Return True if ``f`` is a sum with square roots but no other root
"""
from sympy.core.exprtools import Factors
coeffs = p.coeffs()
has_sq = False
for y in coeffs:
for x in Add.make_args(y):
f = Factors(x).factors
r = [wx.q for wx in f.values() if wx.is_Rational and wx.q >= 2]
if not r:
continue
if min(r) == 2:
has_sq = True
if max(r) > 2:
return False
return has_sq
if f.get_domain().is_EX and _has_square_roots(f):
rescale_x = None
translate_x = None
r = _try_rescale(f)
if r:
return r[0], r[1], None, r[2]
else:
r = _try_translate(f)
if r:
return None, None, r[0], r[1]
return None
def _torational_factor_list(p, x):
"""
helper function to factor polynomial using to_rational_coeffs
Examples
========
>>> from sympy.polys.polytools import _torational_factor_list
>>> from sympy.abc import x
>>> from sympy import sqrt, expand, Mul
>>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}))
>>> factors = _torational_factor_list(p, x); factors
(-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)])
>>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p
True
>>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)}))
>>> factors = _torational_factor_list(p, x); factors
(1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)])
>>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p
True
"""
from sympy.simplify.simplify import simplify
p1 = Poly(p, x, domain='EX')
n = p1.degree()
res = to_rational_coeffs(p1)
if not res:
return None
lc, r, t, g = res
factors = factor_list(g.as_expr())
if lc:
c = simplify(factors[0]*lc*r**n)
r1 = simplify(1/r)
a = []
for z in factors[1:][0]:
a.append((simplify(z[0].subs({x:x*r1})), z[1]))
else:
c = factors[0]
a = []
for z in factors[1:][0]:
a.append((z[0].subs({x:x - t}), z[1]))
return (c, a)
def sqf_list(f, *gens, **args):
"""
Compute a list of square-free factors of ``f``.
Examples
========
>>> from sympy import sqf_list
>>> from sympy.abc import x
>>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
(2, [(x + 1, 2), (x + 2, 3)])
"""
return _generic_factor_list(f, gens, args, method='sqf')
def sqf(f, *gens, **args):
"""
Compute square-free factorization of ``f``.
Examples
========
>>> from sympy import sqf
>>> from sympy.abc import x
>>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
2*(x + 1)**2*(x + 2)**3
"""
return _generic_factor(f, gens, args, method='sqf')
def factor_list(f, *gens, **args):
"""
Compute a list of irreducible factors of ``f``.
Examples
========
>>> from sympy import factor_list
>>> from sympy.abc import x, y
>>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
(2, [(x + y, 1), (x**2 + 1, 2)])
"""
return _generic_factor_list(f, gens, args, method='factor')
def factor(f, *gens, **args):
"""
Compute the factorization of expression, ``f``, into irreducibles. (To
factor an integer into primes, use ``factorint``.)
There two modes implemented: symbolic and formal. If ``f`` is not an
instance of :class:`Poly` and generators are not specified, then the
former mode is used. Otherwise, the formal mode is used.
In symbolic mode, :func:`factor` will traverse the expression tree and
factor its components without any prior expansion, unless an instance
of :class:`Add` is encountered (in this case formal factorization is
used). This way :func:`factor` can handle large or symbolic exponents.
By default, the factorization is computed over the rationals. To factor
over other domain, e.g. an algebraic or finite field, use appropriate
options: ``extension``, ``modulus`` or ``domain``.
Examples
========
>>> from sympy import factor, sqrt
>>> from sympy.abc import x, y
>>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y)
2*(x + y)*(x**2 + 1)**2
>>> factor(x**2 + 1)
x**2 + 1
>>> factor(x**2 + 1, modulus=2)
(x + 1)**2
>>> factor(x**2 + 1, gaussian=True)
(x - I)*(x + I)
>>> factor(x**2 - 2, extension=sqrt(2))
(x - sqrt(2))*(x + sqrt(2))
>>> factor((x**2 - 1)/(x**2 + 4*x + 4))
(x - 1)*(x + 1)/(x + 2)**2
>>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1))
(x + 2)**20000000*(x**2 + 1)
By default, factor deals with an expression as a whole:
>>> eq = 2**(x**2 + 2*x + 1)
>>> factor(eq)
2**(x**2 + 2*x + 1)
If the ``deep`` flag is True then subexpressions will
be factored:
>>> factor(eq, deep=True)
2**((x + 1)**2)
See Also
========
sympy.ntheory.factor_.factorint
"""
f = sympify(f)
if args.pop('deep', False):
partials = {}
muladd = f.atoms(Mul, Add)
for p in muladd:
fac = factor(p, *gens, **args)
if (fac.is_Mul or fac.is_Pow) and fac != p:
partials[p] = fac
return f.xreplace(partials)
try:
return _generic_factor(f, gens, args, method='factor')
except PolynomialError, msg:
if not f.is_commutative:
from sympy.core.exprtools import factor_nc
return factor_nc(f)
else:
raise PolynomialError(msg)
def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False):
"""
Compute isolating intervals for roots of ``f``.
Examples
========
>>> from sympy import intervals
>>> from sympy.abc import x
>>> intervals(x**2 - 3)
[((-2, -1), 1), ((1, 2), 1)]
>>> intervals(x**2 - 3, eps=1e-2)
[((-26/15, -19/11), 1), ((19/11, 26/15), 1)]
"""
if not hasattr(F, '__iter__'):
try:
F = Poly(F)
except GeneratorsNeeded:
return []
return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf)
else:
polys, opt = parallel_poly_from_expr(F, domain='QQ')
if len(opt.gens) > 1:
raise MultivariatePolynomialError
for i, poly in enumerate(polys):
polys[i] = poly.rep.rep
if eps is not None:
eps = opt.domain.convert(eps)
if eps <= 0:
raise ValueError("'eps' must be a positive rational")
if inf is not None:
inf = opt.domain.convert(inf)
if sup is not None:
sup = opt.domain.convert(sup)
intervals = dup_isolate_real_roots_list(polys, opt.domain,
eps=eps, inf=inf, sup=sup, strict=strict, fast=fast)
result = []
for (s, t), indices in intervals:
s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t)
result.append(((s, t), indices))
return result
def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False):
"""
Refine an isolating interval of a root to the given precision.
Examples
========
>>> from sympy import refine_root
>>> from sympy.abc import x
>>> refine_root(x**2 - 3, 1, 2, eps=1e-2)
(19/11, 26/15)
"""
try:
F = Poly(f)
except GeneratorsNeeded:
raise PolynomialError(
"can't refine a root of %s, not a polynomial" % f)
return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf)
def count_roots(f, inf=None, sup=None):
"""
Return the number of roots of ``f`` in ``[inf, sup]`` interval.
If one of ``inf`` or ``sup`` is complex, it will return the number of roots
in the complex rectangle with corners at ``inf`` and ``sup``.
Examples
========
>>> from sympy import count_roots, I
>>> from sympy.abc import x
>>> count_roots(x**4 - 4, -3, 3)
2
>>> count_roots(x**4 - 4, 0, 1 + 3*I)
1
"""
try:
F = Poly(f, greedy=False)
except GeneratorsNeeded:
raise PolynomialError("can't count roots of %s, not a polynomial" % f)
return F.count_roots(inf=inf, sup=sup)
def real_roots(f, multiple=True):
"""
Return a list of real roots with multiplicities of ``f``.
Examples
========
>>> from sympy import real_roots
>>> from sympy.abc import x
>>> real_roots(2*x**3 - 7*x**2 + 4*x + 4)
[-1/2, 2, 2]
"""
try:
F = Poly(f, greedy=False)
except GeneratorsNeeded:
raise PolynomialError(
"can't compute real roots of %s, not a polynomial" % f)
return F.real_roots(multiple=multiple)
def nroots(f, n=15, maxsteps=50, cleanup=True, error=False):
"""
Compute numerical approximations of roots of ``f``.
Examples
========
>>> from sympy import nroots
>>> from sympy.abc import x
>>> nroots(x**2 - 3, n=15)
[-1.73205080756888, 1.73205080756888]
>>> nroots(x**2 - 3, n=30)
[-1.73205080756887729352744634151, 1.73205080756887729352744634151]
"""
try:
F = Poly(f, greedy=False)
except GeneratorsNeeded:
raise PolynomialError(
"can't compute numerical roots of %s, not a polynomial" % f)
return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup, error=error)
def ground_roots(f, *gens, **args):
"""
Compute roots of ``f`` by factorization in the ground domain.
Examples
========
>>> from sympy import ground_roots
>>> from sympy.abc import x
>>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2)
{0: 2, 1: 2}
"""
options.allowed_flags(args, [])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('ground_roots', 1, exc)
return F.ground_roots()
def nth_power_roots_poly(f, n, *gens, **args):
"""
Construct a polynomial with n-th powers of roots of ``f``.
Examples
========
>>> from sympy import nth_power_roots_poly, factor, roots
>>> from sympy.abc import x
>>> f = x**4 - x**2 + 1
>>> g = factor(nth_power_roots_poly(f, 2))
>>> g
(x**2 - x + 1)**2
>>> R_f = [ (r**2).expand() for r in roots(f) ]
>>> R_g = roots(g).keys()
>>> set(R_f) == set(R_g)
True
"""
options.allowed_flags(args, [])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('nth_power_roots_poly', 1, exc)
result = F.nth_power_roots_poly(n)
if not opt.polys:
return result.as_expr()
else:
return result
def cancel(f, *gens, **args):
"""
Cancel common factors in a rational function ``f``.
Examples
========
>>> from sympy import cancel, sqrt, Symbol
>>> from sympy.abc import x
>>> A = Symbol('A', commutative=False)
>>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1))
(2*x + 2)/(x - 1)
>>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A))
sqrt(6)/2
"""
from sympy.core.exprtools import factor_terms
options.allowed_flags(args, ['polys'])
f = sympify(f)
if not isinstance(f, (tuple, Tuple)):
if f.is_Number:
return f
f = factor_terms(f, radical=True)
p, q = f.as_numer_denom()
elif len(f) == 2:
p, q = f
elif isinstance(f, Tuple):
return factor_terms(f)
else:
raise ValueError('unexpected argument: %s' % f)
try:
(F, G), opt = parallel_poly_from_expr((p, q), *gens, **args)
except PolificationFailed:
if not isinstance(f, (tuple, Tuple)):
return f
else:
return S.One, p, q
except PolynomialError, msg:
if f.is_commutative:
raise PolynomialError(msg)
# non-commutative
if f.is_Mul:
c, nc = f.args_cnc(split_1=False)
nc = [cancel(i) for i in nc]
return cancel(Mul._from_args(c))*Mul(*nc)
elif f.is_Add:
c = []
nc = []
for i in f.args:
if i.is_commutative:
c.append(i)
else:
nc.append(cancel(i))
return cancel(Add(*c)) + Add(*nc)
else:
reps = []
pot = preorder_traversal(f)
pot.next()
for e in pot:
if isinstance(e, (tuple, Tuple)):
continue
try:
reps.append((e, cancel(e)))
pot.skip() # this was handled successfully
except NotImplementedError:
pass
return f.xreplace(dict(reps))
c, P, Q = F.cancel(G)
if not isinstance(f, (tuple, Tuple)):
return c*(P.as_expr()/Q.as_expr())
else:
if not opt.polys:
return c, P.as_expr(), Q.as_expr()
else:
return c, P, Q
def reduced(f, G, *gens, **args):
"""
Reduces a polynomial ``f`` modulo a set of polynomials ``G``.
Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r``
is a completely reduced polynomial with respect to ``G``.
Examples
========
>>> from sympy import reduced
>>> from sympy.abc import x, y
>>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y])
([2*x, 1], x**2 + y**2 + y)
"""
options.allowed_flags(args, ['polys', 'auto'])
try:
polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('reduced', 0, exc)
domain = opt.domain
retract = False
if opt.auto and domain.has_Ring and not domain.has_Field:
opt = opt.clone(dict(domain=domain.get_field()))
retract = True
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, opt.order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
Q, r = polys[0].div(polys[1:])
Q = [ Poly._from_dict(dict(q), opt) for q in Q ]
r = Poly._from_dict(dict(r), opt)
if retract:
try:
_Q, _r = [ q.to_ring() for q in Q ], r.to_ring()
except CoercionFailed:
pass
else:
Q, r = _Q, _r
if not opt.polys:
return [ q.as_expr() for q in Q ], r.as_expr()
else:
return Q, r
def groebner(F, *gens, **args):
"""
Computes the reduced Groebner basis for a set of polynomials.
Use the ``order`` argument to set the monomial ordering that will be
used to compute the basis. Allowed orders are ``lex``, ``grlex`` and
``grevlex``. If no order is specified, it defaults to ``lex``.
For more information on Groebner bases, see the references and the docstring
of `solve_poly_system()`.
Examples
========
Example taken from [1].
>>> from sympy import groebner
>>> from sympy.abc import x, y
>>> F = [x*y - 2*y, 2*y**2 - x**2]
>>> groebner(F, x, y, order='lex')
GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y,
domain='ZZ', order='lex')
>>> groebner(F, x, y, order='grlex')
GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
domain='ZZ', order='grlex')
>>> groebner(F, x, y, order='grevlex')
GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y,
domain='ZZ', order='grevlex')
By default, an improved implementation of the Buchberger algorithm is
used. Optionally, an implementation of the F5B algorithm can be used.
The algorithm can be set using ``method`` flag or with the :func:`setup`
function from :mod:`sympy.polys.polyconfig`:
>>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)]
>>> groebner(F, x, y, method='buchberger')
GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')
>>> groebner(F, x, y, method='f5b')
GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex')
References
==========
1. [Buchberger01]_
2. [Cox97]_
"""
return GroebnerBasis(F, *gens, **args)
def is_zero_dimensional(F, *gens, **args):
"""
Checks if the ideal generated by a Groebner basis is zero-dimensional.
The algorithm checks if the set of monomials not divisible by the
leading monomial of any element of ``F`` is bounded.
References
==========
David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and
Algorithms, 3rd edition, p. 230
"""
return GroebnerBasis(F, *gens, **args).is_zero_dimensional
class GroebnerBasis(Basic):
"""Represents a reduced Groebner basis. """
__slots__ = ['_basis', '_options']
def __new__(cls, F, *gens, **args):
"""Compute a reduced Groebner basis for a system of polynomials. """
options.allowed_flags(args, ['polys', 'method'])
try:
polys, opt = parallel_poly_from_expr(F, *gens, **args)
except PolificationFailed, exc:
raise ComputationFailed('groebner', len(F), exc)
domain = opt.domain
if domain.has_assoc_Field:
opt.domain = domain.get_field()
else:
raise DomainError("can't compute a Groebner basis over %s" % opt.domain)
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, opt.order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
G = _groebner(polys, _ring, method=opt.method)
G = [ Poly._from_dict(g, opt) for g in G ]
if not domain.has_Field:
G = [ g.clear_denoms(convert=True)[1] for g in G ]
opt.domain = domain
return cls._new(G, opt)
@classmethod
def _new(cls, basis, options):
obj = Basic.__new__(cls)
obj._basis = tuple(basis)
obj._options = options
return obj
@property
def args(self):
return (Tuple(*self._basis), Tuple(*self._options.gens))
@property
def exprs(self):
return [ poly.as_expr() for poly in self._basis ]
@property
def polys(self):
return list(self._basis)
@property
def gens(self):
return self._options.gens
@property
def domain(self):
return self._options.domain
@property
def order(self):
return self._options.order
def __len__(self):
return len(self._basis)
def __iter__(self):
if self._options.polys:
return iter(self.polys)
else:
return iter(self.exprs)
def __getitem__(self, item):
if self._options.polys:
basis = self.polys
else:
basis = self.exprs
return basis[item]
def __hash__(self):
return hash((self._basis, tuple(self._options.items())))
def __eq__(self, other):
if isinstance(other, self.__class__):
return self._basis == other._basis and self._options == other._options
elif iterable(other):
return self.polys == list(other) or self.exprs == list(other)
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
@property
def is_zero_dimensional(self):
"""
Checks if the ideal generated by a Groebner basis is zero-dimensional.
The algorithm checks if the set of monomials not divisible by the
leading monomial of any element of ``F`` is bounded.
References
==========
David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and
Algorithms, 3rd edition, p. 230
"""
def single_var(monomial):
return sum(map(bool, monomial)) == 1
exponents = Monomial([0]*len(self.gens))
order = self._options.order
for poly in self.polys:
monomial = poly.LM(order=order)
if single_var(monomial):
exponents *= monomial
# If any element of the exponents vector is zero, then there's
# a variable for which there's no degree bound and the ideal
# generated by this Groebner basis isn't zero-dimensional.
return all(exponents)
def fglm(self, order):
"""
Convert a Groebner basis from one ordering to another.
The FGLM algorithm converts reduced Groebner bases of zero-dimensional
ideals from one ordering to another. This method is often used when it
is infeasible to compute a Groebner basis with respect to a particular
ordering directly.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import groebner
>>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1]
>>> G = groebner(F, x, y, order='grlex')
>>> list(G.fglm('lex'))
[2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]
>>> list(groebner(F, x, y, order='lex'))
[2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7]
References
==========
J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient
Computation of Zero-dimensional Groebner Bases by Change of
Ordering
"""
opt = self._options
src_order = opt.order
dst_order = monomial_key(order)
if src_order == dst_order:
return self
if not self.is_zero_dimensional:
raise NotImplementedError("can't convert Groebner bases of ideals with positive dimension")
polys = list(self._basis)
domain = opt.domain
opt = opt.clone(dict(
domain=domain.get_field(),
order=dst_order,
))
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, src_order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
G = matrix_fglm(polys, _ring, dst_order)
G = [ Poly._from_dict(dict(g), opt) for g in G ]
if not domain.has_Field:
G = [ g.clear_denoms(convert=True)[1] for g in G ]
opt.domain = domain
return self._new(G, opt)
def reduce(self, expr, auto=True):
"""
Reduces a polynomial modulo a Groebner basis.
Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``,
computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r``
such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r``
is a completely reduced polynomial with respect to ``G``.
Examples
========
>>> from sympy import groebner, expand
>>> from sympy.abc import x, y
>>> f = 2*x**4 - x**2 + y**3 + y**2
>>> G = groebner([x**3 - x, y**3 - y])
>>> G.reduce(f)
([2*x, 1], x**2 + y**2 + y)
>>> Q, r = _
>>> expand(sum(q*g for q, g in zip(Q, G)) + r)
2*x**4 - x**2 + y**3 + y**2
>>> _ == f
True
"""
poly = Poly._from_expr(expr, self._options)
polys = [poly] + list(self._basis)
opt = self._options
domain = opt.domain
retract = False
if auto and domain.has_Ring and not domain.has_Field:
opt = opt.clone(dict(domain=domain.get_field()))
retract = True
from sympy.polys.rings import xring
_ring, _ = xring(opt.gens, opt.domain, opt.order)
for i, poly in enumerate(polys):
poly = poly.set_domain(opt.domain).rep.to_dict()
polys[i] = _ring.from_dict(poly)
Q, r = polys[0].div(polys[1:])
Q = [ Poly._from_dict(dict(q), opt) for q in Q ]
r = Poly._from_dict(dict(r), opt)
if retract:
try:
_Q, _r = [ q.to_ring() for q in Q ], r.to_ring()
except CoercionFailed:
pass
else:
Q, r = _Q, _r
if not opt.polys:
return [ q.as_expr() for q in Q ], r.as_expr()
else:
return Q, r
def contains(self, poly):
"""
Check if ``poly`` belongs the ideal generated by ``self``.
Examples
========
>>> from sympy import groebner
>>> from sympy.abc import x, y
>>> f = 2*x**3 + y**3 + 3*y
>>> G = groebner([x**2 + y**2 - 1, x*y - 2])
>>> G.contains(f)
True
>>> G.contains(f + 1)
False
"""
return self.reduce(poly)[1] == 0
def poly(expr, *gens, **args):
"""
Efficiently transform an expression into a polynomial.
Examples
========
>>> from sympy import poly
>>> from sympy.abc import x
>>> poly(x*(x**2 + x - 1)**2)
Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ')
"""
options.allowed_flags(args, [])
def _poly(expr, opt):
terms, poly_terms = [], []
for term in Add.make_args(expr):
factors, poly_factors = [], []
for factor in Mul.make_args(term):
if factor.is_Add:
poly_factors.append(_poly(factor, opt))
elif factor.is_Pow and factor.base.is_Add and factor.exp.is_Integer:
poly_factors.append(
_poly(factor.base, opt).pow(factor.exp))
else:
factors.append(factor)
if not poly_factors:
terms.append(term)
else:
product = poly_factors[0]
for factor in poly_factors[1:]:
product = product.mul(factor)
if factors:
factor = Mul(*factors)
if factor.is_Number:
product = product.mul(factor)
else:
product = product.mul(Poly._from_expr(factor, opt))
poly_terms.append(product)
if not poly_terms:
result = Poly._from_expr(expr, opt)
else:
result = poly_terms[0]
for term in poly_terms[1:]:
result = result.add(term)
if terms:
term = Add(*terms)
if term.is_Number:
result = result.add(term)
else:
result = result.add(Poly._from_expr(term, opt))
return result.reorder(*opt.get('gens', ()), **args)
expr = sympify(expr)
if expr.is_Poly:
return Poly(expr, *gens, **args)
if 'expand' not in args:
args['expand'] = False
opt = options.build_options(gens, args)
return _poly(expr, opt)
| gpl-3.0 | 801,035,838,103,991,400 | 24.114396 | 103 | 0.490173 | false |
alex20465/open-scriptorium | scriptorium/tests/test_generic_elements.py | 1 | 2567 | # -*- encoding: utf-8 -*-
from django.test import TestCase
from scriptorium.elementor import GenericElement
class TestAbstractBaseElement(TestCase):
def setUp(self):
self.ele = GenericElement("div")
self.second_ele = GenericElement("div")
def test_add_classes(self):
self.ele.add_cls("test")
self.ele.add_cls("test2")
self.assertIn('class="test test2"', str(self.ele.build()))
def test_remove_classes(self):
self.ele.add_cls("test")
self.assertIn('class="test"', str(self.ele.build()))
self.ele.remove_cls('test')
self.assertNotIn('class="test"', str(self.ele.build()))
def test_has_class(self):
self.assertFalse(self.ele.has_cls("test"))
self.ele.add_cls("test")
self.assertTrue(self.ele.has_cls("test"))
def test_attribute_setter(self):
self.ele.set_attribute('test', '1')
self.assertIn('test="1"', self.ele.render())
def test_multiple_attribute_setter(self):
self.ele.set_attributes({
'test': '1',
'test2': '2'
})
self.assertIn('test="1"', self.ele.render())
self.assertIn('test2="2"', self.ele.render())
def test_class_attribute_handling(self):
self.ele.set_attribute('class', 'test')
self.ele.add_cls('test2')
self.assertIn('class="test test2"', self.ele.render())
def test_attribute_transfer(self):
self.ele.set_attributes({
'test1': '1',
'test2': '2'
})
self.ele.transfer(self.second_ele)
self.assertIn('test1="1"', self.second_ele.render())
def test_content_transfer(self):
self.ele.add_content('fire')
self.ele.transfer(self.second_ele)
self.assertIn('>fire<', self.second_ele.render())
def test_escape_string_content(self):
self.ele.add_content('<script></script>')
self.assertNotIn('<script></script>', self.ele.render())
self.assertIn('<script></script>', self.ele.render())
def test_not_escape_element(self):
self.ele.add_content(self.second_ele)
self.assertIn('<div><div></div></div>', self.ele.render(pretty=False))
class TestTagElement(TestCase):
def setUp(self):
self.ele = GenericElement("custom")
def test_tag_name(self):
self.assertEquals(str(self.ele.build()), "<custom></custom>")
def test_content(self):
self.ele.add_content('fire')
self.ele.add_content('2')
self.assertIn('>fire2<', self.ele.render())
| mit | -8,683,653,076,775,628,000 | 30.304878 | 78 | 0.599922 | false |
Kanabanarama/Skrubba | skrubba/scheduler.py | 1 | 6277 | #!/usr/bin/env python
"""
File scheduler.py
Job scheduler for managing configured events
by Kana [email protected]
"""
import time
import atexit
import logging
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler # pylint: disable=import-error
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR # pylint: disable=import-error
from skrubba.shiftregister import Shiftregister
from skrubba.relay import Relay
from skrubba.display import Display
from skrubba.db import DB
class Scheduler():
"""
Scheduler
"""
SCHEDULER = BackgroundScheduler(standalone=True)
STORE = DB()
VALVES = Shiftregister()
PUMP = Relay()
TFT = Display()
def __init__(self):
logging.basicConfig()
self.TFT.display_image('static/gfx/lcd-skrubba-color.png',
pos_x=67, pos_y=10, clear_screen=True)
def unload_scheduler(self):
"""
Scheduler cleanups
"""
self.SCHEDULER.shutdown()
self.VALVES.disable()
return True
def is_running(self):
return self.SCHEDULER.running
def valve_job(self, valve_setting): #(valve, onDuration)
"""
Open a valve specified with settings
"""
self.TFT.mark_active_job(valve_setting['id'], True)
duration_left = int(valve_setting['on_duration']) + 2
#binaryValveList = map(int, list(format(valve_setting['valve'], '08b')))
self.PUMP.switch_on()
time.sleep(1)
#VALVES = Shiftregister()
#shiftreg.output_list(binaryValveList)
self.VALVES.output_decimal(valve_setting['valve'])
self.VALVES.enable()
while duration_left > 2:
time.sleep(1)
duration_left -= 1
self.PUMP.switch_off()
self.VALVES.disable()
self.VALVES.reset()
time.sleep(1)
self.TFT.mark_active_job(valve_setting['id'], False)
self.STORE.add_log_line(valve_setting, datetime.now())
return True
def start_scheduler(self):
"""
start scheduler if not already running (debug mode has 2 threads, so we
have to make sure it only starts once)
"""
self.SCHEDULER.start()
self.SCHEDULER.add_listener(self.scheduler_job_event_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
atexit.register(self.unload_scheduler)
return True
def scheduler_job_event_listener(self, event):
"""
Event listener for scheduler, do emergency stuff when something goes wrong
"""
if event.exception:
print('The scheduler job crashed.')
#else:
# print('The scheduler job finished successfully.')
def restart_job_manager(self):
"""
Remove all jobs
"""
display_time = time.time()
for job in self.SCHEDULER.get_jobs():
self.SCHEDULER.remove_job(job.id)
self.TFT.clear_job_display()
# Add all jobs that are stored in database
valve_configs = self.STORE.load_valve_configs()
for config in valve_configs:
if config['on_time'] and config['on_duration'] and config['is_active']:
self.TFT.display_job(config)
time_components = [int(x) for x in config['on_time'].split(':')]
if config['interval_type'] == 'daily':
self.SCHEDULER.add_job(self.valve_job,
'cron',
day_of_week='mon-sun',
hour=time_components[0],
minute=time_components[1],
second=time_components[2],
args=[config])
#print('Scheduled daily job [%i:%i]'
# % (time_components[0], time_components[1]))
if config['interval_type'] == 'weekly':
self.SCHEDULER.add_job(self.valve_job,
'cron',
day_of_week='sun',
hour=time_components[0],
minute=time_components[1],
second=time_components[2],
args=[config])
#print('Scheduled weekly job [sun %i:%i]'
# % (time_components[0], time_components[1]))
if config['interval_type'] == 'monthly':
self.SCHEDULER.add_job(self.valve_job,
'cron',
day=1,
hour=time_components[0],
minute=time_components[1],
second=time_components[2],
args=[config])
#print('Scheduled monthly job [1st of the month %i:%i]'
# % (time_components[0], time_components[1]))
# print('JOBS:')
# print(SCHEDULER.get_jobs())
while time.time() - display_time < 5:
time.sleep(1)
self.TFT.clear()
self.TFT.set_background_image('static/gfx/lcd-ui-background.png', pos_x=0, pos_y=0)
self.add_tft_job()
return True
def add_tft_job(self):
"""
Job for updating tft display
"""
def tft_job():
#if(os.getenv('SSH_CLIENT')):
# os.environ.get('SSH_CLIENT')
# os.environ['SSH_CLIENT'] // nothing ?
# TFT.display_text(os.getenv('SSH_CLIENT'),
# 24,
# (205, 30),
# (249, 116, 75),
# (0, 110, 46))
# text, size, pos_x, pos_y, color, bg_color
self.TFT.display_text(time.strftime('%H:%M:%S'), 40, 205, 10, (255, 255, 255), (0, 110, 46))
self.TFT.update_job_display()
self.SCHEDULER.add_job(tft_job, 'interval', seconds=1)
return True
| gpl-2.0 | 6,901,141,346,179,683,000 | 35.494186 | 108 | 0.507249 | false |
Brian-Williams/acceptanceutils | tests/test_surjection.py | 1 | 1832 | from acceptanceutils import surjection
import string
import random
one = ([1], 1)
two = ([1, 2], 2)
three = ([1, 2, 3], 3)
three_none = (three[0], None)
three_item_group = (one, two, three, three_none)
ten_item_group = ([0]*10, 1)
so = surjection.surjective_options
class TestSurjectiveOptions(object):
three_lis = list(so(*three_item_group))
def test_number_of_lists_returned(self):
assert len(type(self).three_lis) == 3
def test_default(self):
alphabet = (list(string.ascii_lowercase), None)
alphabet_plus_one = (list(string.ascii_lowercase + 'a'), None)
lis = list(so(alphabet, alphabet_plus_one))
final_list = lis[len(alphabet_plus_one[0])-1]
alphabet_default = alphabet[1]
assert final_list[0] == alphabet_default
def test_defaults(self):
for _ in range(10):
# get a new list every iteration so can't use class attributes
lis = list(so(*three_item_group))
for li in lis[1:]:
assert li[0] == one[1]
for li in lis[2:]:
assert li[1] == two[1]
def test_static_item_location(self):
true_first = ((True, False), True)
false_first = ((False, True), True)
lis = list(so(true_first, false_first, shuffle=True))
for i, li in enumerate(lis):
assert li[0] == true_first[0][i]
assert li[1] == false_first[0][i]
def test_partial_shuffling(self):
size = 1000
big_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(size))
shuffle_list = (list(big_string), None)
no_shuffle_tuple = (tuple(big_string), None)
assert so(shuffle_list, shuffle=True) != so(no_shuffle_tuple, shuffle=True)
def test_no_input(self):
list(so())
| mit | 1,493,371,034,271,605,000 | 30.050847 | 102 | 0.590611 | false |
cmattoon/today-i-learned | arduino-ekg/replay.py | 1 | 1929 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy
import sys, struct
from scipy.fftpack import fft, fftfreq, fftshift
def getlines(filename):
with open(filename) as fd:
return [line.strip() for line in fd.readlines()]
def replay_packets(filename):
for line in getlines(filename):
yield tuple(int(i) for i in line[1:-1].split(','))
def replay_bytes(filename):
"""Reconstructs binary packets based on reading in
17-element tuples each representing a packet.
"""
for packet in replay_packets(filename):
yield struct.pack('BBBBBBBBBBBBBBBBB', *packet)
ch1 = []
ch2 = []
ch3 = []
ch4 = []
ch5 = []
ch6 = []
def do_fft(ch):
samples = len(ch)
spacing = 1.0 / len(ch)
x = numpy.linspace(0.0, samples * spacing, samples)
y = [c for c in ch]
xf = numpy.linspace(0.0, 1.0/(2.0*spacing), samples/2)
yf = fft(ch)
print x
print y
print("-----------")
print xf
print yf
plt.plot(xf, 2.0/samples * numpy.abs(yf[0:samples/2]))
plt.grid()
plt.show()
last = -1
for pkt in replay_packets(sys.argv[1]):
seq = int(pkt[3])
if seq > last:
ch1.append(pkt[5])
ch2.append(pkt[7])
ch3.append(pkt[9])
ch4.append(pkt[11])
ch5.append(pkt[13])
ch6.append(pkt[15])
"""
group[seq] = {
'CH1': { 'low': pkt[4], 'high': pkt[5] },
'CH2': { 'low': pkt[6], 'high': pkt[7] },
'CH3': { 'low': pkt[8], 'high': pkt[9] },
'CH4': { 'low': pkt[10], 'high': pkt[11] },
'CH5': { 'low': pkt[12], 'high': pkt[13] },
'CH6': { 'low': pkt[14], 'high': pkt[15] }
}
"""
last = int(seq)
else:
print ch1
last = -1
do_fft(ch1)
do_fft(ch2)
ch1 = []
ch2 = []
ch3 = []
ch4 = []
ch5 = []
ch6 = []
| mit | 3,888,901,447,269,513,700 | 22.814815 | 58 | 0.505962 | false |
douglaskastle/AcraNetwork | examples/benchmark_pcap.py | 1 | 4560 | # -------------------------------------------------------------------------------
# Name: benchmark_pcap
# Purpose: Benchmark the creation and parsing of a biug pcap file
#
# Author:
#
# Created:
#
# Copyright 2014 Diarmuid Collins
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import sys
sys.path.append("..")
import time
import struct
import AcraNetwork.IENA as iena
import AcraNetwork.iNetX as inetx
import AcraNetwork.Pcap as pcap
import AcraNetwork.SimpleEthernet as SimpleEthernet
import argparse
parser = argparse.ArgumentParser(description='Benchmark the creation of pcap files containing packets')
parser.add_argument('--type', required=True, type=str,choices=["udp","iena","inetx"], help='The type of payload, udp iena or inetx')
parser.add_argument('--ignoretime',required=False, action='store_true', default=False)
args = parser.parse_args()
# constants
PCAP_FNAME = "output_test.pcap"
PACKETS_TO_WRITE = 50000
PAYLOAD_SIZE = 1300 # size of the payload in bytes
HEADER_SIZE = {'udp' : 58 , 'inetx' :86 ,'iena':74}
# Write out a pcapfile with each inetx and iena packet generated
mypcap = pcap.Pcap(PCAP_FNAME,forreading=False)
mypcap.writeGlobalHeader()
ethernet_packet = SimpleEthernet.Ethernet()
ethernet_packet.srcmac = 0x001122334455
ethernet_packet.dstmac = 0x554433221100
ethernet_packet.type = SimpleEthernet.Ethernet.TYPE_IP
ip_packet = SimpleEthernet.IP()
ip_packet.dstip = "235.0.0.2"
ip_packet.srcip = "127.0.0.1"
udp_packet = SimpleEthernet.UDP()
udp_packet.dstport = 4422
# Fixed payload for both
payload = (struct.pack(">B",5) * PAYLOAD_SIZE)
if args.type == "inetx":
# Create an inetx packet
avionics_packet = inetx.iNetX()
avionics_packet.inetxcontrol = inetx.iNetX.DEF_CONTROL_WORD
avionics_packet.pif = 0
avionics_packet.streamid = 0xdc
avionics_packet.sequence = 0
avionics_packet.payload = payload
elif args.type == "iena":
# Create an iena packet
avionics_packet = iena.IENA()
avionics_packet.key = 0xdc
avionics_packet.keystatus = 0
avionics_packet.endfield = 0xbeef
avionics_packet.sequence = 0
avionics_packet.payload = payload
avionics_packet.status = 0
packets_written = 0
start_time = time.time()
while packets_written < PACKETS_TO_WRITE:
if args.type == "udp":
udp_packet.srcport = 4999
udp_packet.payload = payload
else:
if args.ignoretime:
currenttime = 0
else:
currenttime = int(time.time())
if args.type == "iena":
avionics_packet.sequence = (avionics_packet.sequence +1) % 65536
udp_packet.srcport = 5000
else:
avionics_packet.sequence = (avionics_packet.sequence +1) % 0x100000000
udp_packet.srcport = 5001
avionics_packet.setPacketTime(currenttime)
udp_packet.payload = avionics_packet.pack()
ip_packet.payload = udp_packet.pack()
ethernet_packet.payload = ip_packet.pack()
record = pcap.PcapRecord()
if args.ignoretime:
record.usec = 0
record.sec = 0
else:
record.setCurrentTime()
record.packet = ethernet_packet.pack()
mypcap.writeARecord(record)
packets_written += 1
mypcap.close()
end_time = time.time()
print("INFO: Wrote {} packets of type {} with payload of {} bytes in {} seconds".format(PACKETS_TO_WRITE,args.type,PAYLOAD_SIZE,end_time-start_time))
print("INFO: Wrote {} bytes in {}".format((HEADER_SIZE[args.type]+PAYLOAD_SIZE)*PACKETS_TO_WRITE,end_time-start_time))
print("INFO: Wrote {} packets per second".format(PACKETS_TO_WRITE/(end_time-start_time)))
print("INFO: Wrote {:.2f} Mbps".format((HEADER_SIZE[args.type]+PAYLOAD_SIZE)*PACKETS_TO_WRITE*8/((end_time-start_time)*1024*1024)))
| gpl-2.0 | -101,800,711,013,690,860 | 33.905512 | 149 | 0.669956 | false |
unitedstack/rock | rock/rules/rule_parser.py | 1 | 10238 | # -*- coding: utf-8 -*-
# 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 copy
import json
import datetime
import uuid
from oslo_log import log as logging
from oslo_utils import importutils
from oslo_utils import timeutils
from rock.db import api as db_api
from rock.rules import rule_utils
from rock.tasks.manager import run_flow
LOG = logging.getLogger(__name__)
def data_get_by_obj_time(obj_name, delta):
model_name = 'model_' + obj_name
model = importutils.import_class(
'rock.db.sqlalchemy.%s.%s' %
(model_name, rule_utils.underline_to_camel(model_name)))
timedelta = datetime.timedelta(seconds=delta)
return db_api.get_period_records(model,
timeutils.utcnow()-timedelta,
end_time=timeutils.utcnow(),
sort_key='created_at')
class RuleParser(object):
def __init__(self, rule):
if isinstance(rule, basestring):
self.rule = json.loads(rule)
else:
self.rule = rule
self.raw_data = {}
self.target_data = {}
self.l1_data = {}
self.l2_data = {}
self.all_data = {}
def calculate(self):
LOG.info("Starting collect data.")
self._collect_data()
LOG.info("Got target data %s", self.target_data)
l2_result = self._rule_mapping_per_target()
LOG.info("Got l1 data %s", self.l1_data)
LOG.info("Got l2 result %s", l2_result)
if l2_result:
self._action()
def _collect_data(self):
funcs = self.Functions()
splited_raw_data = {}
# raw_data organized by data_model.
# {"data_model": [list_of_all_target_resources]}
for key, value in self.rule["collect_data"].items():
rule = copy.deepcopy(value['data'])
self.raw_data[key] = self._calculate(rule, funcs)
splited_raw_data[key] = {}
# splited_raw_data organized by data_model first, then target.
# {"data_model": {"target": [list_of_single_target_resources]}}
for key, value in self.raw_data.items():
for item in value:
if not splited_raw_data[key].get(item['target']):
splited_raw_data[key][item['target']] = [item]
else:
splited_raw_data[key][item['target']].append(item)
# target_data organized by target first, then data_model, and each
# data_model show calc_result.
# {'target': {'data_model': {'last_piece','judge_result'}
for key, value in self.rule["collect_data"].items():
for target, target_data in splited_raw_data[key].items():
if not self.target_data.get(target):
self.target_data[target] = {}
self.target_data[target][key] = {}
judge_rule = value["judge"] + [target_data]
self.target_data[target][key]['judge_result'] = \
self._calculate(judge_rule, funcs)
self.target_data[target][key].update(target_data[0])
target_required_len = len(self.rule["collect_data"])
for key, value in self.target_data.items():
if len(self.target_data[key]) != target_required_len:
self.target_data.pop(key)
LOG.warning("Find host %s do not match.", key)
def _rule_mapping_per_target(self):
def _replace_variate(target, rule):
for posi, value in enumerate(rule):
if isinstance(value, unicode) and value.startswith('$'):
dict_args = value[1:].split('.')
rule[posi] = self.target_data[target][dict_args[0]]
dict_args.pop(0)
while dict_args:
rule[posi] = rule[posi][dict_args[0]]
dict_args.pop(0)
elif isinstance(value, list):
_replace_variate(target, value)
funcs = self.Functions()
for target, data in self.target_data.items():
l1_rule = copy.deepcopy(self.rule['l1_rule'])
_replace_variate(target, l1_rule)
self.l1_data[target] = \
{'l1_result': self._calculate(l1_rule, funcs)}
l2_rule = copy.deepcopy(self.rule['l2_rule'])
l2_rule = self._replace_rule_parameter(l2_rule)
return self._calculate(l2_rule, funcs)
def _action(self):
funcs = self.Functions()
actions = self.rule['action']['tasks']
for target in self.l1_data:
if not self.l1_data[target]['l1_result']:
filter_flag = False
for each_filter in self.rule['action']['filters']:
rule = copy.deepcopy(each_filter)
rule = self._replace_rule_parameter(
rule, self.target_data[target])
if not self._calculate(rule, funcs):
filter_flag = True
LOG.info('Skipped target %s due to filter %s.',
target, each_filter)
if filter_flag:
continue
LOG.info("Triggered action on %s.", target)
tasks = []
task_uuid = str(uuid.uuid4())
store_spec = {'taskflow_uuid': task_uuid,
'target': target}
for task in actions:
tasks.append(task[0])
for input_params in task[1:]:
input_kv = input_params.split(':')
store_spec[input_kv[0]] = input_kv[1]
run_flow(task_uuid, store_spec, tasks)
def _calculate(self, rule, funcs):
def _recurse_calc(arg):
if isinstance(arg, list) and isinstance(arg[0], unicode) \
and arg[0].startswith('%') and arg[0] != '%map':
return self._calculate(arg, funcs)
elif isinstance(arg, list)and arg[0] == '%map':
ret = {}
for k, v in arg[1].items():
map_rule = self._replace_map_para(arg[2], arg[1], k)
ret[k] = {}
ret[k]['map_result'] = self._calculate(map_rule, funcs)
return ret
else:
return arg
r = map(_recurse_calc, rule)
r[0] = self.Functions.ALIAS.get(r[0]) or r[0]
func = getattr(funcs, r[0])
return func(*r[1:])
def _replace_rule_parameter(self, rule, input=None):
if not isinstance(rule, list):
return
def _recurse_replace(arg):
if isinstance(arg, list) and isinstance(arg[0], unicode) \
and arg[0].startswith('%'):
return self._replace_rule_parameter(arg, input)
elif isinstance(arg, unicode) and arg.startswith('$'):
args = arg[1:].split('.')
if not input:
ret = getattr(self, args[0])
else:
ret = input[args[0]]
args.pop(0)
while args:
ret = ret[args[0]]
args.pop(0)
return ret
else:
return arg
r = map(_recurse_replace, rule)
return r
def _replace_map_para(self, map_rule, para_dict, target):
def _recurse_replace(arg):
if isinstance(arg, list) and isinstance(arg[0], unicode) \
and arg[0].startswith('%'):
return self._replace_map_para(arg, para_dict, target)
elif isinstance(arg, unicode) and arg.startswith('map.'):
map_para_list = arg.split('.')
map_para_list.pop(0)
ret = para_dict[target][map_para_list[0]]
map_para_list.pop(0)
while map_para_list:
ret = ret[map_para_list[0]]
map_para_list.pop(0)
return ret
else:
return arg
r = map(_recurse_replace, map_rule)
return r
class Functions(object):
ALIAS = {
'%==': 'eq',
'%<=': 'lt_or_eq',
'%and': '_and',
'%or': '_or',
'%not': '_not',
'%get_by_time': 'get_data_by_time',
'%false_end_count_lt': 'false_end_count_lt',
'%count': 'count',
'%map': '_map'
}
def eq(self, *args):
return args[0] == args[1]
def lt_or_eq(self, *args):
return args[0] <= args[1]
def _and(self, *args):
return all(args)
def _or(self, *args):
return any(args)
def _not(self, *args):
return not args[0]
def get_data_by_time(self, *args):
return data_get_by_obj_time(args[0], args[1])
def false_end_count_lt(self, *args):
boundary = int(args[0])
count = 0
for item in args[1]:
if item['result'] in [False, 'false', 'False']:
count += 1
else:
break
return count < boundary
def count(self, *args):
if args[2] in [False, 'false', 'False']:
count_type = False
elif args[2] in [True, 'true', 'True']:
count_type = True
else:
return len(args[1])
count = 0
for k, v in args[0].items():
if v.get(args[1]) == count_type:
count += 1
return count
| apache-2.0 | -6,026,574,041,103,912,000 | 35.695341 | 75 | 0.504298 | false |
rushiprasad/stwitto | stwitto/twitt.py | 1 | 1227 | import tweepy
import argparse
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('/etc/stwitto/config.ini')
consumer_key = config.get('twitter_auth_config', 'consumer_key')
consumer_secret = config.get('twitter_auth_config', 'consumer_secret')
access_token = config.get('twitter_auth_config', 'access_token')
access_token_secret = config.get('twitter_auth_config', 'access_token_secret')
def get_api():
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
return tweepy.API(auth)
def main():
parser = argparse.ArgumentParser(description='Automatic Twitter Tweets through CLI')
parser.add_argument('--tweet', nargs='+', help='your tweet goes here')
parser.add_argument('--image', help='your tweet image goes here')
args = parser.parse_args()
api = get_api()
if args.tweet and args.image:
tweet = ' '.join(args.tweet)
status = api.update_with_media(args.image, tweet)
elif args.tweet:
tweet = ' '.join(args.tweet)
status = api.update_status(status=tweet)
else:
print('Expected an Argument')
parser.print_help()
if __name__ == "__main__":
main()
| gpl-2.0 | -6,080,710,177,383,759,000 | 32.162162 | 88 | 0.679707 | false |
hyc/HyperDex | test/doc-extract.py | 1 | 2556 | # Copyright (c) 2013, Cornell University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of HyperDex nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
PREAMBLE = {
'python':
'''# File generated from {code} blocks in "{infile}"
>>> import sys
>>> HOST = sys.argv[2]
>>> PORT = int(sys.argv[3])
'''}
def transform(code, infile, outfile):
fin = open(infile, 'r')
fout = open(outfile, 'w')
begin = '\\begin{%scode}\n' % code
end = '\\end{%scode}\n' % code
fout.write(PREAMBLE[code].format(code=code, infile=infile))
output = False
for line in fin:
if line == begin:
assert not output
output = True
elif line == end:
output = False
elif output:
if line == ">>> a = hyperdex.admin.Admin('127.0.0.1', 1982)\n":
fout.write(">>> a = hyperdex.admin.Admin(HOST, PORT)\n")
elif line == ">>> c = hyperdex.client.Client('127.0.0.1', 1982)\n":
fout.write(">>> c = hyperdex.client.Client(HOST, PORT)\n")
else:
fout.write(line)
transform(sys.argv[1], sys.argv[2], sys.argv[3])
| bsd-3-clause | 4,422,403,885,164,071,400 | 43.068966 | 80 | 0.678013 | false |
unho/translate | translate/convert/test_po2ts.py | 1 | 4424 | # -*- coding: utf-8 -*-
from io import BytesIO
from translate.convert import po2ts, test_convert
from translate.storage import po
class TestPO2TS:
def po2ts(self, posource):
"""helper that converts po source to ts source without requiring files"""
inputfile = BytesIO(posource.encode())
inputpo = po.pofile(inputfile)
convertor = po2ts.po2ts()
output = BytesIO()
convertor.convertstore(inputpo, output)
return output.getvalue().decode('utf-8')
def singleelement(self, storage):
"""checks that the pofile contains a single non-header element, and returns it"""
assert len(storage.units) == 1
return storage.units[0]
def test_simpleunit(self):
"""checks that a simple po entry definition converts properly to a ts entry"""
minipo = r'''#: term.cpp
msgid "Term"
msgstr "asdf"'''
tsfile = self.po2ts(minipo)
print(tsfile)
assert "<name>term.cpp</name>" in tsfile
assert "<source>Term</source>" in tsfile
assert "<translation>asdf</translation>" in tsfile
assert "<comment>" not in tsfile
def test_simple_unicode_unit(self):
"""checks that a simple unit with unicode strings"""
minipo = r'''#: unicode.cpp
msgid "ßource"
msgstr "†arget"'''
tsfile = self.po2ts(minipo)
print(tsfile)
print(type(tsfile))
assert u"<name>unicode.cpp</name>" in tsfile
assert u"<source>ßource</source>" in tsfile
assert u"<translation>†arget</translation>" in tsfile
def test_fullunit(self):
"""check that an entry with various settings is converted correctly"""
posource = '''# Translator comment
#. Automatic comment
#: location.cpp:100
msgid "Source"
msgstr "Target"
'''
tsfile = self.po2ts(posource)
print(tsfile)
# The other section are a duplicate of test_simplentry
# FIXME need to think about auto vs trans comments maybe in TS v1.1
assert "<comment>Translator comment</comment>" in tsfile
def test_fuzzyunit(self):
"""check that we handle fuzzy units correctly"""
posource = '''#: term.cpp
#, fuzzy
msgid "Source"
msgstr "Target"'''
tsfile = self.po2ts(posource)
print(tsfile)
assert '''<translation type="unfinished">Target</translation>''' in tsfile
def test_obsolete(self):
"""test that we can take back obsolete messages"""
posource = '''#. (obsolete)
#: term.cpp
msgid "Source"
msgstr "Target"'''
tsfile = self.po2ts(posource)
print(tsfile)
assert '''<translation type="obsolete">Target</translation>''' in tsfile
def test_duplicates(self):
"""test that we can handle duplicates in the same context block"""
posource = '''#: @@@#1
msgid "English"
msgstr "a"
#: @@@#3
msgid "English"
msgstr "b"
'''
tsfile = self.po2ts(posource)
print(tsfile)
assert tsfile.find("English") != tsfile.rfind("English")
def test_linebreak(self):
"""test that we can handle linebreaks"""
minipo = r'''#: linebreak.cpp
msgid "Line 1\n"
"Line 2"
msgstr "Linea 1\n"
"Linea 2"'''
tsfile = self.po2ts(minipo)
print(tsfile)
print(type(tsfile))
assert u"<name>linebreak.cpp</name>" in tsfile
assert r'''<source>Line 1
Line 2</source>''' in tsfile
assert r'''<translation>Linea 1
Linea 2</translation>''' in tsfile
def test_linebreak_consecutive(self):
"""test that we can handle consecutive linebreaks"""
minipo = r'''#: linebreak.cpp
msgid "Line 1\n"
"\n"
"Line 3"
msgstr "Linea 1\n"
"\n"
"Linea 3"'''
tsfile = self.po2ts(minipo)
print(tsfile)
print(type(tsfile))
assert u"<name>linebreak.cpp</name>" in tsfile
assert r'''<source>Line 1
Line 3</source>''' in tsfile
assert r'''<translation>Linea 1
Linea 3</translation>''' in tsfile
class TestPO2TSCommand(test_convert.TestConvertCommand, TestPO2TS):
"""Tests running actual po2ts commands on files"""
convertmodule = po2ts
def test_help(self, capsys):
"""tests getting help"""
options = test_convert.TestConvertCommand.test_help(self, capsys)
options = self.help_check(options, "-c CONTEXT, --context=CONTEXT")
options = self.help_check(options, "-t TEMPLATE, --template=TEMPLATE", last=True)
| gpl-2.0 | -6,105,735,019,182,657,000 | 30.333333 | 89 | 0.62947 | false |
ksons/gltf-blender-importer | addons/io_scene_gltf_ksons/animation/material.py | 1 | 2432 | import bpy
from . import quote
from .curve import Curve
def add_material_animation(op, anim_info, material_id):
anim_id = anim_info.anim_id
data = anim_info.material[material_id]
animation = op.gltf['animations'][anim_id]
material = op.get('material', material_id)
name = '%s@%s (Material)' % (
animation.get('name', 'animations[%d]' % anim_id),
material.name,
)
action = bpy.data.actions.new(name)
anim_info.material_actions[material_id] = action
fcurves = []
for prop, sampler in data.get('properties', {}).items():
curve = Curve.for_sampler(op, sampler)
data_path = op.material_infos[material_id].paths.get(prop)
if not data_path:
print('no place to put animated property %s in material node tree' % prop)
continue
fcurves += curve.make_fcurves(op, action, data_path)
if fcurves:
group = action.groups.new('Material Property')
for fcurve in fcurves:
fcurve.group = group
for texture_type, samplers in data.get('texture_transform', {}).items():
base_path = op.material_infos[material_id].paths[texture_type + '-transform']
fcurves = []
if 'offset' in samplers:
curve = Curve.for_sampler(op, samplers['offset'])
data_path = base_path + '.translation'
fcurves += curve.make_fcurves(op, action, data_path)
if 'rotation' in samplers:
curve = Curve.for_sampler(op, samplers['rotation'])
data_path = [(base_path + '.rotation', 2)] # animate rotation around Z-axis
fcurves += curve.make_fcurves(op, action, data_path, transform=lambda theta:-theta)
if 'scale' in samplers:
curve = Curve.for_sampler(op, samplers['scale'])
data_path = base_path + '.scale'
fcurves += curve.make_fcurves(op, action, data_path)
group_name = {
'normalTexture': 'Normal',
'occlusionTexture': 'Occlusion',
'emissiveTexture': 'Emissive',
'baseColorTexture': 'Base Color',
'metallicRoughnessTexture': 'Metallic-Roughness',
'diffuseTexture': 'Diffuse',
'specularGlossinessTexture': 'Specular-Glossiness',
}[texture_type] + ' Texture Transform'
group = action.groups.new(group_name)
for fcurve in fcurves:
fcurve.group = group
| mit | -374,302,995,571,520,960 | 36.415385 | 95 | 0.598684 | false |
EsqWiggles/SLA-bot | SLA_bot/module/alertfeed.py | 1 | 2516 | """Collect hourly event announcements for PSO2
Take announcement data from a third party source, convert it into a string,
and store it for later reads. Update at least once before reading.
"""
# The current source is already translated into English. In the event that the
# flyergo source is discontinued, this module must adapt to a new source. If no
# other alternatives can be found, then this will fall back to using twitter
# bot at https://twitter.com/pso2_emg_hour and translating it.
import aiohttp
import asyncio
import json
import re
import SLA_bot.util as ut
cache = ''
source_url = 'http://pso2emq.flyergo.eu/api/v2/'
async def update():
"""Download and store the announcement data."""
try:
async with aiohttp.ClientSession() as session:
async with session.get(source_url) as response:
global cache
data = await response.json(content_type=None)
cache = data[0]['text']
except ut.GetErrors as e:
ut.note('Failed to GET: ' + source_url)
except (json.decoder.JSONDecodeError, IndexError, KeyError) as e:
ut.note('Unexpected data format from: ' + source_url)
def read():
"""Return the string of the most recent announcement."""
if not cache:
return '[ ?? JST Emergency Quest Notice ]\nNot found.'
if is_unscheduled():
return align_shiplabels(cache) + '\n** **'
return cache + '\n** **'
def is_unscheduled():
"""Return whether the last announcement looks like an unscheduled event."""
# Checks if 50% or more of the lines (-1 from the header) start with what
# looks like a ship label.
# Unscheduled Ship label = ##:Event Name
# Scheduled Time = ##:## Event Name
# The regex matches if there are 2 numbers and a semicolon at the start of
# the line but not if 2 more numbers and a space follows it. In case an
# event name is added that starts with 2 digits and a space in the future,
# exclude the common minute times of 00 and 30 instead.
if not cache:
return True
ship_labels = re.findall('^\d\d:(?!\d\d\s)', cache, flags=re.MULTILINE)
return len(ship_labels) / cache.count('\n') >= 0.50
def align_shiplabels(text):
"""Return the announcement with the ship labels aligned."""
# See comment in is_unscheduled() for a description of the regex,
def monospace(matched):
return '`{}`'.format(matched.group(0))
return re.sub('^\d\d:(?!\d\d\s)', monospace, text, flags=re.MULTILINE)
| mit | -8,873,405,941,662,445,000 | 37.707692 | 79 | 0.667329 | false |
simudream/dask | dask/context.py | 4 | 1129 | """
Control global computation context
"""
from contextlib import contextmanager
from collections import defaultdict
_globals = defaultdict(lambda: None)
class set_options(object):
""" Set global state within controled context
This lets you specify various global settings in a tightly controlled with
block
Valid keyword arguments currently include:
get - the scheduler to use
pool - a thread or process pool
cache - Cache to use for intermediate results
func_loads/func_dumps - loads/dumps functions for serialization of data
likely to contain functions. Defaults to dill.loads/dill.dumps
rerun_exceptions_locally - rerun failed tasks in master process
Example
-------
>>> with set_options(get=dask.get): # doctest: +SKIP
... x = np.array(x) # uses dask.get internally
"""
def __init__(self, **kwargs):
self.old = _globals.copy()
_globals.update(kwargs)
def __enter__(self):
return
def __exit__(self, type, value, traceback):
_globals.clear()
_globals.update(self.old)
| bsd-3-clause | 1,848,362,725,765,397,800 | 26.536585 | 79 | 0.65279 | false |
CognitionGuidedSurgery/msml-gui | src/msmlgui/text/mainframe.py | 1 | 5476 | __author__ = 'weigl'
from path import path
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import msmlgui.rcc
from .flycheck import build_overview
from .editor_ui import Ui_MainWindow
from ..help import *
icon = lambda x: QIcon(r':/icons/tango/16x16/%s.png' % x)
class MainFrame(Ui_MainWindow, QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self._setupActions()
self.setupToolBar()
self.readSettings()
self.textEditor.firePositionStackUpdate.connect(self.breadcrump.positionStackUpdate)
self.textEditor.firePositionStackUpdate.connect(self.openHelp)
self.textEditor.problemsChanged.connect(self.updateProblems)
self.textEditor.contentChanged.connect(self.updateOverview)
self.open("/org/share/home/weigl/workspace/msml/examples/BunnyExample/bunnyCGAL.msml.xml")
self.oldHelp = None
def _setupActions(self):
self.actionNew = QAction(icon("document-new"), "New", self)
self.actionNew.setShortcut(QKeySequence.New)
self.actionOpen = QAction(icon("document-open"), "Open", self)
self.actionOpen.setShortcut(QKeySequence.Open)
self.actionOpen.triggered.connect(self.search_open_file)
self.actionSave = QAction(icon("document-save"), "Save", self)
self.actionSave.setShortcut(QKeySequence.Save)
self.actionSave.triggered.connect(self.save_file)
self.actionSaveAs = QAction(icon("document-save-as"), "Save as...", self)
self.actionSaveAs.setShortcut(QKeySequence.SaveAs)
self.actionSaveAs.triggered.connect(self.save_file_as)
self.actionClose = QAction(icon("document-close"), "Close", self)
self.actionClose.setShortcut(QKeySequence("Alt-F4"))
def setupToolBar(self):
file = [self.actionNew, self.actionOpen, self.actionSave, self.actionSaveAs, self.actionClose]
self.toolBar.addActions(file)
self.menuFile.clear()
self.menuFile.addActions(file)
self.menuWindow.addAction(self.dockHelp.toggleViewAction())
def open_file(self, filename):
pass
def closeEvent(self, event=QCloseEvent()):
settings = QSettings("CoginitionGuidedSurgery", "msml-gui-editor")
settings.setValue("geometry", self.saveGeometry())
settings.setValue("windowState", self.saveState())
QMainWindow.closeEvent(self, event)
def readSettings(self):
settings = QSettings("CoginitionGuidedSurgery", "msml-gui-editor")
self.restoreGeometry(settings.value("geometry").toByteArray())
self.restoreState(settings.value("windowState").toByteArray())
def search_open_file(self):
MSML_FILE_FILTER = "MSML (*.xml *.msml *.msml.xml);; All types (*.*)"
filename, _ = QFileDialog.getOpenFileNameAndFilter(self, "Open MSML file", self.last_path, MSML_FILE_FILTER)
if filename:
filename = path(filename)
self.last_path = filename.dirname()
self.open_file(filename)
def save_file(self):
if self.last_save_path is None:
self.save_file_as()
from msmlgui.helper.writer import to_xml, save_xml
xml = to_xml(self.msml_model)
save_xml(self.last_save_path, xml)
def save_file_as(self):
MSML_FILE_FILTER = "MSML (*.xml *.msml *.msml.xml);; All types (*.*)"
last_dir = ""
if self.last_save_path:
last_dir = self.last_save_path.dirname()
filename = QFileDialog.getSaveFileName(self, "Open MSML file", last_dir, MSML_FILE_FILTER)
if filename:
self.last_save_path = path(filename)
self.save_file()
def openHelp(self, toks):
try:
tok = toks[-1]
c = get_help(tok.value)
if c == self.oldHelp: return
self.oldHelp = c
if c.startswith("http://"):
print "Open Help: %s" % c
self.webView.setUrl(QUrl(c))
else:
self.webView.setHtml(c)
except IndexError: pass
def updateOverview(self, tokens, char2line):
overview = build_overview(tokens)
self.treeOverview.clear()
def appendUnder(name, seq):
item = QTreeWidgetItem(self.treeOverview)
item.setText(0, name)
item.addChildren(seq)
appendUnder("Variables", overview.variables)
appendUnder("Objects", overview.objects)
appendUnder("Tasks", overview.tasks)
appendUnder("Environment", overview.environment)
def updateProblems(self, problems):
print "updateProblems", problems
self.tableProblems.clear()
self.tableProblems.setColumnCount(3)
self.tableProblems.setRowCount(len(problems))
for i, p in enumerate(problems):
c2 = QTableWidgetItem(p.message)
c3 = QTableWidgetItem(str(p.position))
if p.level == 1:
c2.setForeground(QBrush(Qt.darkRed))
c3.setForeground(QBrush(Qt.darkRed))
else:
c2.setForeground(QBrush(Qt.darkBlue))
c3.setForeground(QBrush(Qt.darkBlue))
self.tableProblems.setItem(i, 0, c2)
self.tableProblems.setItem(i, 1, c3)
def open(self, filename):
with open(filename) as fp:
content = fp.read()
self.textEditor.insertPlainText(content)
| gpl-3.0 | -8,745,189,579,018,515,000 | 30.291429 | 116 | 0.6313 | false |
nkmk/python-snippets | notebook/arithmetic_operator_num.py | 1 | 1336 | print(10 + 3)
# 13
print(10 - 3)
# 7
print(10 * 3)
# 30
print(10 / 3)
# 3.3333333333333335
print(10 // 3)
# 3
print(10 % 3)
# 1
print(10 ** 3)
# 1000
print(2 ** 0.5)
# 1.4142135623730951
print(10 ** -2)
# 0.01
print(0 ** 0)
# 1
# print(10 / 0)
# ZeroDivisionError: integer division or modulo by zero
# print(10 // 0)
# ZeroDivisionError: integer division or modulo by zero
# print(10 % 0)
# ZeroDivisionError: integer division or modulo by zero
# print(0 ** -1)
# ZeroDivisionError: 0.0 cannot be raised to a negative power
a = 10
b = 3
c = a + b
print('a:', a)
print('b:', b)
print('c:', c)
# a: 10
# b: 3
# c: 13
a = 10
b = 3
a += b
print('a:', a)
print('b:', b)
# a: 13
# b: 3
a = 10
b = 3
a %= b
print('a:', a)
print('b:', b)
# a: 1
# b: 3
a = 10
b = 3
a **= b
print('a:', a)
print('b:', b)
# a: 1000
# b: 3
print(2 + 3.0)
print(type(2 + 3.0))
# 5.0
# <class 'float'>
print(10 / 2)
print(type(10 / 2))
# 5.0
# <class 'float'>
print(2 ** 3)
print(type(2 ** 3))
# 8
# <class 'int'>
print(2.0 ** 3)
print(type(2.0 ** 3))
# 8.0
# <class 'float'>
print(25 ** 0.5)
print(type(25 ** 0.5))
# 5.0
# <class 'float'>
print(0.01 ** -2)
print(type(0.01 ** -2))
# 10000.0
# <class 'float'>
print(100 / 10 ** 2 + 2 * 3 - 5)
# 2.0
print(100 / (10 ** 2) + (2 * 3) - 5)
# 2.0
print((100 / 10) ** 2 + 2 * (3 - 5))
# 96.0
| mit | 8,110,380,658,963,956,000 | 10.322034 | 61 | 0.528443 | false |
grimoirelab/arthur | arthur/server.py | 1 | 4264 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Bitergia
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors:
# Santiago Dueñas <[email protected]>
# Alvaro del Castillo San Felix <[email protected]>
#
import logging
import threading
import time
import cherrypy
from grimoirelab_toolkit.datetime import str_to_datetime
from .arthur import Arthur
from .utils import JSONEncoder
logger = logging.getLogger(__name__)
def json_encoder(*args, **kwargs):
"""Custom JSON encoder handler"""
obj = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
for chunk in JSONEncoder().iterencode(obj):
yield chunk.encode('utf-8')
class ArthurServer(Arthur):
"""Arthur REST server"""
def __init__(self, *args, **kwargs):
if 'writer' in kwargs:
writer = kwargs.pop('writer')
super().__init__(*args, **kwargs)
if writer:
self.writer_th = threading.Thread(target=self.write_items,
args=(writer, self.items))
else:
self.writer_th = None
cherrypy.engine.subscribe('start', self.start, 100)
def start(self):
"""Start the server and the writer"""
super().start()
if self.writer_th:
self.writer_th.start()
@classmethod
def write_items(cls, writer, items_generator):
"""Write items to the queue
:param writer: the writer object
:param items_generator: items to be written in the queue
"""
while True:
items = items_generator()
writer.write(items)
time.sleep(1)
@cherrypy.expose
@cherrypy.tools.json_in()
def add(self):
"""Add tasks"""
payload = cherrypy.request.json
logger.debug("Reading tasks...")
for task_data in payload['tasks']:
try:
category = task_data['category']
backend_args = task_data['backend_args']
archive_args = task_data.get('archive', None)
sched_args = task_data.get('scheduler', None)
except KeyError as ex:
logger.error("Task badly formed")
raise ex
from_date = backend_args.get('from_date', None)
if from_date:
backend_args['from_date'] = str_to_datetime(from_date)
super().add_task(task_data['task_id'],
task_data['backend'],
category,
backend_args,
archive_args=archive_args,
sched_args=sched_args)
logger.debug("Done. Ready to work!")
return "Tasks added"
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out(handler=json_encoder)
def remove(self):
"""Remove tasks"""
payload = cherrypy.request.json
logger.debug("Reading tasks to remove...")
task_ids = {}
for task_data in payload['tasks']:
task_id = task_data['task_id']
removed = super().remove_task(task_id)
task_ids[task_id] = removed
result = {'tasks': task_ids}
return result
@cherrypy.expose
@cherrypy.tools.json_out(handler=json_encoder)
def tasks(self):
"""List tasks"""
logger.debug("API 'tasks' method called")
result = [task.to_dict() for task in self._tasks.tasks]
result = {'tasks': result}
logger.debug("Tasks registry read")
return result
| gpl-3.0 | -4,247,991,870,050,024,000 | 27.610738 | 76 | 0.588318 | false |
albertz/music-player | mac/pyobjc-framework-Quartz/PyObjCTest/test_cgimagesource.py | 1 | 2486 | from PyObjCTools.TestSupport import *
import Quartz
try:
unicode
except NameError:
unicode = str
try:
long
except NameError:
long = int
class TestCGImageSource (TestCase):
def testConstants(self):
self.assertEqual(Quartz.kCGImageStatusUnexpectedEOF, -5)
self.assertEqual(Quartz.kCGImageStatusInvalidData, -4)
self.assertEqual(Quartz.kCGImageStatusUnknownType, -3)
self.assertEqual(Quartz.kCGImageStatusReadingHeader, -2)
self.assertEqual(Quartz.kCGImageStatusIncomplete, -1)
self.assertEqual(Quartz.kCGImageStatusComplete, 0)
self.assertIsInstance(Quartz.kCGImageSourceTypeIdentifierHint, unicode)
self.assertIsInstance(Quartz.kCGImageSourceShouldCache, unicode)
self.assertIsInstance(Quartz.kCGImageSourceShouldAllowFloat, unicode)
self.assertIsInstance(Quartz.kCGImageSourceCreateThumbnailFromImageIfAbsent, unicode)
self.assertIsInstance(Quartz.kCGImageSourceThumbnailMaxPixelSize, unicode)
self.assertIsInstance(Quartz.kCGImageSourceCreateThumbnailWithTransform, unicode)
def testTypes(self):
self.assertIsCFType(Quartz.CGImageSourceRef)
def testFunctions(self):
self.assertIsInstance(Quartz.CGImageSourceGetTypeID(), (int, long))
self.assertResultIsCFRetained(Quartz.CGImageSourceCopyTypeIdentifiers)
self.assertResultIsCFRetained(Quartz.CGImageSourceCreateWithDataProvider)
self.assertResultIsCFRetained(Quartz.CGImageSourceCreateWithData)
self.assertResultIsCFRetained(Quartz.CGImageSourceCreateWithURL)
Quartz.CGImageSourceGetType
Quartz.CGImageSourceGetCount
self.assertResultIsCFRetained(Quartz.CGImageSourceCopyProperties)
self.assertResultIsCFRetained(Quartz.CGImageSourceCopyPropertiesAtIndex)
self.assertResultIsCFRetained(Quartz.CGImageSourceCreateImageAtIndex)
self.assertResultIsCFRetained(Quartz.CGImageSourceCreateThumbnailAtIndex)
self.assertResultIsCFRetained(Quartz.CGImageSourceCreateIncremental)
self.assertArgHasType(Quartz.CGImageSourceUpdateData, 2, objc._C_BOOL)
self.assertArgHasType(Quartz.CGImageSourceUpdateDataProvider, 2, objc._C_BOOL)
Quartz.CGImageSourceGetStatus
Quartz.CGImageSourceGetStatusAtIndex
@min_os_level('10.8')
def testFunctions10_8(self):
self.assertResultIsCFRetained(Quartz.CGImageSourceCopyMetadataAtIndex)
if __name__ == "__main__":
main()
| bsd-2-clause | -6,229,102,326,952,175,000 | 39.754098 | 93 | 0.772325 | false |
sein-tao/trash-cli | trashcli/trash.py | 1 | 25907 | # Copyright (C) 2007-2011 Andrea Francia Trivolzio(PV) Italy
from __future__ import absolute_import
version='0.12.10.3~'
import os
import logging
from .fstab import Fstab
logger=logging.getLogger('trashcli.trash')
logger.setLevel(logging.WARNING)
logger.addHandler(logging.StreamHandler())
# Error codes (from os on *nix, hard coded for Windows):
EX_OK = getattr(os, 'EX_OK' , 0)
EX_USAGE = getattr(os, 'EX_USAGE', 64)
EX_IOERR = getattr(os, 'EX_IOERR', 74)
from .fs import list_files_in_dir
import os
from .fs import remove_file
from .fs import move, mkdirs
class TrashDirectory:
def __init__(self, path, volume):
self.path = os.path.normpath(path)
self.volume = volume
self.logger = logger
self.info_dir = os.path.join(self.path, 'info')
self.files_dir = os.path.join(self.path, 'files')
def warn_non_trashinfo():
self.logger.warning("Non .trashinfo file in info dir")
self.on_non_trashinfo_found = warn_non_trashinfo
def trashed_files(self) :
# Only used by trash-restore
for info_file in self.all_info_files():
try:
yield self._create_trashed_file_from_info_file(info_file)
except ValueError:
self.logger.warning("Non parsable trashinfo file: %s" % info_file)
except IOError as e:
self.logger.warning(str(e))
def all_info_files(self) :
'Returns a generator of "Path"s'
try :
for info_file in list_files_in_dir(self.info_dir):
if not os.path.basename(info_file).endswith('.trashinfo') :
self.on_non_trashinfo_found()
else :
yield info_file
except OSError: # when directory does not exist
pass
def _create_trashed_file_from_info_file(self, trashinfo_file_path):
trash_info2 = LazyTrashInfoParser(
lambda:contents_of(trashinfo_file_path), self.volume)
original_location = trash_info2.original_location()
deletion_date = trash_info2.deletion_date()
backup_file_path = backup_file_path_from(trashinfo_file_path)
return TrashedFile(original_location, deletion_date,
trashinfo_file_path, backup_file_path, self)
def backup_file_path_from(trashinfo_file_path):
trashinfo_basename = os.path.basename(trashinfo_file_path)
backupfile_basename = trashinfo_basename[:-len('.trashinfo')]
info_dir = os.path.dirname(trashinfo_file_path)
trash_dir = os.path.dirname(info_dir)
files_dir = os.path.join(trash_dir, 'files')
return os.path.join(files_dir, backupfile_basename)
class HomeTrashCan:
def __init__(self, environ):
self.environ = environ
def path_to(self, out):
if 'XDG_DATA_HOME' in self.environ:
out('%(XDG_DATA_HOME)s/Trash' % self.environ)
elif 'HOME' in self.environ:
out('%(HOME)s/.local/share/Trash' % self.environ)
class TrashDirectories:
def __init__(self, volume_of, getuid, mount_points, environ):
self.home_trashcan = HomeTrashCan(environ)
self.volume_of = volume_of
self.getuid = getuid
self.mount_points = mount_points
def all_trashed_files(self):
for trash_dir in self.all_trash_directories():
for trashedfile in trash_dir.trashed_files():
yield trashedfile
def all_trash_directories(self):
collected = []
def add_trash_dir(path, volume):
collected.append(TrashDirectory(path, volume))
self.home_trash_dir(add_trash_dir)
for volume in self.mount_points:
self.volume_trash_dir1(volume, add_trash_dir)
self.volume_trash_dir2(volume, add_trash_dir)
return collected
def home_trash_dir(self, out) :
self.home_trashcan.path_to(lambda path:
out(path, self.volume_of(path)))
def volume_trash_dir1(self, volume, out):
out(
path = os.path.join(volume, '.Trash/%s' % self.getuid()),
volume = volume)
def volume_trash_dir2(self, volume, out):
out(
path = os.path.join(volume, ".Trash-%s" % self.getuid()),
volume = volume)
class TrashedFile:
"""
Represent a trashed file.
Each trashed file is persisted in two files:
- $trash_dir/info/$id.trashinfo
- $trash_dir/files/$id
Properties:
- path : the original path from where the file has been trashed
- deletion_date : the time when the file has been trashed (instance of
datetime)
- info_file : the file that contains information (instance of Path)
- actual_path : the path where the trashed file has been placed after the
trash opeartion (instance of Path)
- trash_directory :
"""
def __init__(self, path, deletion_date, info_file, actual_path,
trash_directory):
self.path = path
self.deletion_date = deletion_date
self.info_file = info_file
self.actual_path = actual_path
self.trash_directory = trash_directory
self.original_file = actual_path
def restore(self, dest=None) :
if dest is not None:
raise NotImplementedError("not yet supported")
if os.path.exists(self.path):
raise IOError('Refusing to overwrite existing file "%s".' % os.path.basename(self.path))
else:
parent = os.path.dirname(self.path)
mkdirs(parent)
move(self.original_file, self.path)
remove_file(self.info_file)
def getcwd_as_realpath(): return os.path.realpath(os.curdir)
import sys
class RestoreCmd:
def __init__(self, stdout, stderr, environ, exit, input,
curdir = getcwd_as_realpath, version = version):
self.out = stdout
self.err = stderr
self.exit = exit
self.input = input
fstab = Fstab()
self.trashcan = TrashDirectories(
volume_of = fstab.volume_of,
getuid = os.getuid,
mount_points = fstab.mount_points(),
environ = environ)
self.curdir = curdir
self.version = version
def run(self, args = sys.argv):
if '--version' in args[1:]:
command = os.path.basename(args[0])
self.println('%s %s' %(command, self.version))
return
trashed_files = []
self.for_all_trashed_file_in_dir(trashed_files.append, self.curdir())
if not trashed_files:
self.report_no_files_found()
else :
for i, trashedfile in enumerate(trashed_files):
self.println("%4d %s %s" % (i, trashedfile.deletion_date, trashedfile.path))
index=self.input("What file to restore [0..%d]: " % (len(trashed_files)-1))
if index == "" :
self.println("Exiting")
else :
#index = int(index)
files = (trashed_files[int(i)] for i in index.split())
for file in files:
try:
file.restore()
except IOError as e:
self.printerr(e)
self.exit(1)
def for_all_trashed_file_in_dir(self, action, dir):
def is_trashed_from_curdir(trashedfile):
return trashedfile.path.startswith(dir + os.path.sep)
for trashedfile in filter(is_trashed_from_curdir,
self.trashcan.all_trashed_files()) :
action(trashedfile)
def report_no_files_found(self):
self.println("No files trashed from current dir ('%s')" % self.curdir())
def println(self, line):
self.out.write(line + '\n')
def printerr(self, msg):
self.err.write('%s\n' % msg)
from .fs import FileSystemReader, contents_of, FileRemover
class ListCmd:
def __init__(self, out, err, environ, list_volumes, getuid,
file_reader = FileSystemReader(),
version = version):
self.output = self.Output(out, err)
self.err = self.output.err
self.contents_of = file_reader.contents_of
self.version = version
top_trashdir_rules = TopTrashDirRules(file_reader)
self.trashdirs = TrashDirs(environ, getuid,
list_volumes = list_volumes,
top_trashdir_rules=top_trashdir_rules)
self.harvester = Harvester(file_reader)
def run(self, *argv):
parse=Parser()
parse.on_help(PrintHelp(self.description, self.output.println))
parse.on_version(PrintVersion(self.output.println, self.version))
parse.as_default(self.list_trash)
parse(argv)
def list_trash(self):
self.harvester.on_volume = self.output.set_volume_path
self.harvester.on_trashinfo_found = self._print_trashinfo
self.trashdirs.on_trashdir_skipped_because_parent_not_sticky = self.output.top_trashdir_skipped_because_parent_not_sticky
self.trashdirs.on_trashdir_skipped_because_parent_is_symlink = self.output.top_trashdir_skipped_because_parent_is_symlink
self.trashdirs.on_trash_dir_found = self.harvester._analize_trash_directory
self.trashdirs.list_trashdirs()
def _print_trashinfo(self, path):
try:
contents = self.contents_of(path)
except IOError as e :
self.output.print_read_error(e)
else:
deletion_date = parse_deletion_date(contents) or unknown_date()
try:
path = parse_path(contents)
except ParseError:
self.output.print_parse_path_error(path)
else:
self.output.print_entry(deletion_date, path)
def description(self, program_name, printer):
printer.usage('Usage: %s [OPTIONS...]' % program_name)
printer.summary('List trashed files')
printer.options(
" --version show program's version number and exit",
" -h, --help show this help message and exit")
printer.bug_reporting()
class Output:
def __init__(self, out, err):
self.out = out
self.err = err
def println(self, line):
self.out.write(line+'\n')
def error(self, line):
self.err.write(line+'\n')
def print_read_error(self, error):
self.error(str(error))
def print_parse_path_error(self, offending_file):
self.error("Parse Error: %s: Unable to parse Path." % (offending_file))
def top_trashdir_skipped_because_parent_not_sticky(self, trashdir):
self.error("TrashDir skipped because parent not sticky: %s"
% trashdir)
def top_trashdir_skipped_because_parent_is_symlink(self, trashdir):
self.error("TrashDir skipped because parent is symlink: %s"
% trashdir)
def set_volume_path(self, volume_path):
self.volume_path = volume_path
def print_entry(self, maybe_deletion_date, relative_location):
import os
original_location = os.path.join(self.volume_path, relative_location)
self.println("%s %s" %(maybe_deletion_date, original_location))
def do_nothing(*argv, **argvk): pass
class Parser:
def __init__(self):
self.default_action = do_nothing
self.argument_action = do_nothing
self.short_options = ''
self.long_options = []
self.actions = dict()
self._on_invalid_option = do_nothing
def __call__(self, argv):
program_name = argv[0]
from getopt import getopt, GetoptError
try:
options, arguments = getopt(argv[1:],
self.short_options,
self.long_options)
except GetoptError, e:
invalid_option = e.opt
self._on_invalid_option(program_name, invalid_option)
else:
for option, value in options:
if option in self.actions:
self.actions[option](program_name)
return
for argument in arguments:
self.argument_action(argument)
self.default_action()
def on_invalid_option(self, action):
self._on_invalid_option = action
def on_help(self, action):
self.add_option('help', action, 'h')
def on_version(self, action):
self.add_option('version', action)
def add_option(self, long_option, action, short_aliases=''):
self.long_options.append(long_option)
self.actions['--' + long_option] = action
for short_alias in short_aliases:
self.add_short_option(short_alias, action)
def add_short_option(self, short_option, action):
self.short_options += short_option
self.actions['-' + short_option] = action
def on_argument(self, argument_action):
self.argument_action = argument_action
def as_default(self, default_action):
self.default_action = default_action
class CleanableTrashcan:
def __init__(self, file_remover):
self._file_remover = file_remover
def delete_orphan(self, path_to_backup_copy):
self._file_remover.remove_file(path_to_backup_copy)
def delete_trashinfo_and_backup_copy(self, trashinfo_path):
backup_copy = self._path_of_backup_copy(trashinfo_path)
self._file_remover.remove_file_if_exists(backup_copy)
self._file_remover.remove_file(trashinfo_path)
def _path_of_backup_copy(self, path_to_trashinfo):
from os.path import dirname as parent_of, join, basename
trash_dir = parent_of(parent_of(path_to_trashinfo))
return join(trash_dir, 'files', basename(path_to_trashinfo)[:-len('.trashinfo')])
class ExpiryDate:
def __init__(self, contents_of, now, trashcan):
self._contents_of = contents_of
self._now = now
self._maybe_delete = self._delete_unconditionally
self._trashcan = trashcan
def set_max_age_in_days(self, arg):
self.max_age_in_days = int(arg)
self._maybe_delete = self._delete_according_date
def delete_if_expired(self, trashinfo_path):
self._maybe_delete(trashinfo_path)
def _delete_according_date(self, trashinfo_path):
contents = self._contents_of(trashinfo_path)
ParseTrashInfo(
on_deletion_date=IfDate(
OlderThan(self.max_age_in_days, self._now),
lambda: self._delete_unconditionally(trashinfo_path)
),
)(contents)
def _delete_unconditionally(self, trashinfo_path):
self._trashcan.delete_trashinfo_and_backup_copy(trashinfo_path)
class TrashDirs:
def __init__(self, environ, getuid, list_volumes, top_trashdir_rules):
self.getuid = getuid
self.mount_points = list_volumes
self.top_trashdir_rules = top_trashdir_rules
self.home_trashcan = HomeTrashCan(environ)
# events
self.on_trash_dir_found = lambda trashdir, volume: None
self.on_trashdir_skipped_because_parent_not_sticky = lambda trashdir: None
self.on_trashdir_skipped_because_parent_is_symlink = lambda trashdir: None
def list_trashdirs(self):
self.emit_home_trashcan()
self._for_each_volume_trashcan()
def emit_home_trashcan(self):
def return_result_with_volume(trashcan_path):
self.on_trash_dir_found(trashcan_path, '/')
self.home_trashcan.path_to(return_result_with_volume)
def _for_each_volume_trashcan(self):
for volume in self.mount_points():
self.emit_trashcans_for(volume)
def emit_trashcans_for(self, volume):
self.emit_trashcan_1_for(volume)
self.emit_trashcan_2_for(volume)
def emit_trashcan_1_for(self,volume):
top_trashdir_path = os.path.join(volume, '.Trash/%s' % self.getuid())
class IsValidOutput:
def not_valid_parent_should_not_be_a_symlink(_):
self.on_trashdir_skipped_because_parent_is_symlink(top_trashdir_path)
def not_valid_parent_should_be_sticky(_):
self.on_trashdir_skipped_because_parent_not_sticky(top_trashdir_path)
def is_valid(_):
self.on_trash_dir_found(top_trashdir_path, volume)
self.top_trashdir_rules.valid_to_be_read(top_trashdir_path, IsValidOutput())
def emit_trashcan_2_for(self, volume):
alt_top_trashdir = os.path.join(volume, '.Trash-%s' % self.getuid())
self.on_trash_dir_found(alt_top_trashdir, volume)
from datetime import datetime
class EmptyCmd:
def __init__(self, out, err, environ, list_volumes,
now = datetime.now,
file_reader = FileSystemReader(),
getuid = os.getuid,
file_remover = FileRemover(),
version = version):
self.out = out
self.err = err
self.file_reader = file_reader
top_trashdir_rules = TopTrashDirRules(file_reader)
self.trashdirs = TrashDirs(environ, getuid,
list_volumes = list_volumes,
top_trashdir_rules = top_trashdir_rules)
self.harvester = Harvester(file_reader)
self.version = version
self._cleaning = CleanableTrashcan(file_remover)
self._expiry_date = ExpiryDate(file_reader.contents_of, now,
self._cleaning)
def run(self, *argv):
self.exit_code = EX_OK
parse = Parser()
parse.on_help(PrintHelp(self.description, self.println))
parse.on_version(PrintVersion(self.println, self.version))
parse.on_argument(self._expiry_date.set_max_age_in_days)
parse.as_default(self._empty_all_trashdirs)
parse.on_invalid_option(self.report_invalid_option_usage)
parse(argv)
return self.exit_code
def report_invalid_option_usage(self, program_name, option):
self.err.write(
"{program_name}: invalid option -- '{option}'\n".format(**locals()))
self.exit_code |= EX_USAGE
def description(self, program_name, printer):
printer.usage('Usage: %s [days]' % program_name)
printer.summary('Purge trashed files.')
printer.options(
" --version show program's version number and exit",
" -h, --help show this help message and exit")
printer.bug_reporting()
def _empty_all_trashdirs(self):
self.harvester.on_trashinfo_found = self._expiry_date.delete_if_expired
self.harvester.on_orphan_found = self._cleaning.delete_orphan
self.trashdirs.on_trash_dir_found = self.harvester._analize_trash_directory
self.trashdirs.list_trashdirs()
def println(self, line):
self.out.write(line + '\n')
class Harvester:
def __init__(self, file_reader):
self.file_reader = file_reader
self.trashdir = TrashDir(self.file_reader)
self.on_orphan_found = do_nothing
self.on_trashinfo_found = do_nothing
self.on_volume = do_nothing
def _analize_trash_directory(self, trash_dir_path, volume_path):
self.on_volume(volume_path)
self.trashdir.open(trash_dir_path, volume_path)
self.trashdir.each_trashinfo(self.on_trashinfo_found)
self.trashdir.each_orphan(self.on_orphan_found)
class IfDate:
def __init__(self, date_criteria, then):
self.date_criteria = date_criteria
self.then = then
def __call__(self, date2):
if self.date_criteria(date2):
self.then()
class OlderThan:
def __init__(self, days_ago, now):
from datetime import timedelta
self.limit_date = now() - timedelta(days=days_ago)
def __call__(self, deletion_date):
return deletion_date < self.limit_date
class PrintHelp:
def __init__(self, description, println):
class Printer:
def __init__(self, println):
self.println = println
def usage(self, usage):
self.println(usage)
self.println('')
def summary(self, summary):
self.println(summary)
self.println('')
def options(self, *line_describing_option):
self.println('Options:')
for line in line_describing_option:
self.println(line)
self.println('')
def bug_reporting(self):
self.println("Report bugs to http://code.google.com/p/trash-cli/issues")
self.description = description
self.printer = Printer(println)
def __call__(self, program_name):
self.description(program_name, self.printer)
class PrintVersion:
def __init__(self, println, version):
self.println = println
self.version = version
def __call__(self, program_name):
self.println("%s %s" % (program_name, self.version))
class TopTrashDirRules:
def __init__(self, fs):
self.fs = fs
def valid_to_be_read(self, path, output):
parent_trashdir = os.path.dirname(path)
if not self.fs.exists(path):
return
if not self.fs.is_sticky_dir(parent_trashdir):
output.not_valid_parent_should_be_sticky()
return
if self.fs.is_symlink(parent_trashdir):
output.not_valid_parent_should_not_be_a_symlink()
return
else:
output.is_valid()
class Dir:
def __init__(self, path, entries_if_dir_exists):
self.path = path
self.entries_if_dir_exists = entries_if_dir_exists
def entries(self):
return self.entries_if_dir_exists(self.path)
def full_path(self, entry):
return os.path.join(self.path, entry)
class TrashDir:
def __init__(self, file_reader):
self.file_reader = file_reader
def open(self, path, volume_path):
self.trash_dir_path = path
self.volume_path = volume_path
self.files_dir = Dir(self._files_dir(),
self.file_reader.entries_if_dir_exists)
def each_orphan(self, action):
for entry in self.files_dir.entries():
trashinfo_path = self._trashinfo_path_from_file(entry)
file_path = self.files_dir.full_path(entry)
if not self.file_reader.exists(trashinfo_path): action(file_path)
def _entries_if_dir_exists(self, path):
return self.file_reader.entries_if_dir_exists(path)
def each_trashinfo(self, action):
for entry in self._trashinfo_entries():
action(os.path.join(self._info_dir(), entry))
def _info_dir(self):
return os.path.join(self.trash_dir_path, 'info')
def _trashinfo_path_from_file(self, file_entry):
return os.path.join(self._info_dir(), file_entry + '.trashinfo')
def _files_dir(self):
return os.path.join(self.trash_dir_path, 'files')
def _trashinfo_entries(self, on_non_trashinfo=do_nothing):
for entry in self._entries_if_dir_exists(self._info_dir()):
if entry.endswith('.trashinfo'):
yield entry
else:
on_non_trashinfo()
class ParseError(ValueError): pass
class LazyTrashInfoParser:
def __init__(self, contents, volume_path):
self.contents = contents
self.volume_path = volume_path
def deletion_date(self):
return parse_deletion_date(self.contents())
def _path(self):
return parse_path(self.contents())
def original_location(self):
return os.path.join(self.volume_path, self._path())
def maybe_parse_deletion_date(contents):
result = Basket(unknown_date())
ParseTrashInfo(
on_deletion_date = lambda date: result.collect(date),
on_invalid_date = lambda: result.collect(unknown_date())
)(contents)
return result.collected
def unknown_date():
return '????-??-?? ??:??:??'
class ParseTrashInfo:
def __init__(self,
on_deletion_date = do_nothing,
on_invalid_date = do_nothing,
on_path = do_nothing):
self.found_deletion_date = on_deletion_date
self.found_invalid_date = on_invalid_date
self.found_path = on_path
def __call__(self, contents):
from datetime import datetime
import urllib
for line in contents.split('\n'):
if line.startswith('DeletionDate='):
try:
date = datetime.strptime(line, "DeletionDate=%Y-%m-%dT%H:%M:%S")
except ValueError:
self.found_invalid_date()
else:
self.found_deletion_date(date)
if line.startswith('Path='):
path=urllib.unquote(line[len('Path='):])
self.found_path(path)
class Basket:
def __init__(self, initial_value = None):
self.collected = initial_value
def collect(self, value):
self.collected = value
def parse_deletion_date(contents):
result = Basket()
ParseTrashInfo(on_deletion_date=result.collect)(contents)
return result.collected
def parse_path(contents):
import urllib
for line in contents.split('\n'):
if line.startswith('Path='):
return urllib.unquote(line[len('Path='):])
raise ParseError('Unable to parse Path')
| gpl-2.0 | 731,896,114,119,365,900 | 38.673813 | 129 | 0.59289 | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.