text
stringlengths 29
850k
|
---|
# Copyright (c) 2016 Intel Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from neutron_lib.objects import common_types
from neutron.db.models import dns as models
from neutron.objects import base
@base.NeutronObjectRegistry.register
class FloatingIPDNS(base.NeutronDbObject):
# Version 1.0: Initial version
VERSION = '1.0'
db_model = models.FloatingIPDNS
primary_keys = ['floatingip_id']
foreign_keys = {'FloatingIP': {'floatingip_id': 'id'}}
fields = {
'floatingip_id': common_types.UUIDField(),
'dns_name': common_types.DomainNameField(),
'dns_domain': common_types.DomainNameField(),
'published_dns_name': common_types.DomainNameField(),
'published_dns_domain': common_types.DomainNameField(),
}
|
We spent two weeks wrapping up the year to see what I thought of everything versus what I thought I’d think back in January. Now we get to my favorite part of the scientific method: analyzing the data.
What I do here is lay everything out and see just how well I did at guessing stuff, and what I thought of everything this year, by rating, by month, by just about any metric I can think of. I’d be lying if I didn’t say I greatly look forward to doing this every year.
So we jus spent twelve days going over everything that came out. Today we go over what didn’t.
At this point I track like 500 movies a year. Not all of them are gonna come out. A lot of stuff is gonna get pushed throughout the year. This is just me reorganizing that so I can be more targeted in a few weeks when I start over and start tracking for 2019. I can see if some movies look any closer to coming out, and decide which ones I want to stop tracking altogether.
So, this is a list of everything that was either pushed or hasn’t come out. I’ll tell you what each one is, look at what the current status is (if any) and decide whether or not it’s gonna be a part of 2019’s Film Release Calendar. Mostly this is record keeping for me, but should you be so interested, it’s all here.
After Thanksgiving, most people get happy because they know Christmas is around the corner. I get happy because I know these articles are around the corner. Even if a year is absolutely atrocious and I get absolutely nothing done on this site (like this one), I know that once December rolls around, I have things to say until March. But before we get into the Oscars, we gotta wrap up the year.
Here’s the skinny for the newbies: every January I preview an ungodly amount of movies. And then, from then through December, I watch an ungodly amount of movies, tracking along the way what I thought of each of them. Then, when we get to this point, I recap everything and see how close I guessed my eventual rating back in January. That part is mostly for me, but along the way you get my thoughts of all the stuff I watched (which will probably give you a bunch of stuff you didn’t even know about). So everybody wins. |
# -*- coding: utf-8 -*-
"""Lark parser to parse the expression."""
__author__ = "Yuan Chang"
__copyright__ = "Copyright (C) 2016-2021"
__license__ = "AGPL"
__email__ = "[email protected]"
from abc import abstractmethod
from typing import (
cast, Tuple, List, Dict, Iterator, Optional, Union, TypeVar, Generic,
)
from dataclasses import dataclass
from lark import Lark, Transformer, LexError
from .expression import get_vlinks, VJoint, VPoint, VLink
from .graph import Graph
_T1 = TypeVar('_T1')
_T2 = TypeVar('_T2')
_Coord = Tuple[float, float]
_JointArgs = List[Union[str, VJoint, float, _Coord, Tuple[str, ...]]]
# Color dictionary
_color_list: Dict[str, Tuple[int, int, int]] = {
'red': (172, 68, 68),
'green': (110, 190, 30),
'blue': (68, 120, 172),
'cyan': (0, 255, 255),
'magenta': (255, 0, 255),
'brick-red': (255, 130, 130),
'yellow': (255, 255, 0),
'gray': (160, 160, 160),
'orange': (225, 165, 0),
'pink': (225, 192, 230),
'black': (0, 0, 0),
'white': (255, 255, 255),
'dark-red': (128, 0, 0),
'dark-green': (0, 128, 0),
'dark-blue': (0, 0, 128),
'dark-cyan': (128, 0, 128),
'dark-magenta': (255, 0, 255),
'dark-yellow': (128, 128, 0),
'dark-gray': (128, 128, 128),
'dark-orange': (225, 140, 0),
'dark-pink': (225, 20, 147),
}
color_names = tuple(sorted(_color_list.keys()))
def color_rgb(name: str) -> Tuple[int, int, int]:
"""Get color by name.
Get RGB color data by name, return `(0, 0, 0)` if it is invalid.
Also support `"(R, G, B)"` string format.
"""
name = name.lower()
if name in _color_list:
return _color_list[name]
else:
try:
# Input RGB as a "(255, 255, 255)" string
rgb = (
name.replace('(', '')
.replace(')', '')
.replace(" ", '')
.split(',', maxsplit=3)
)
color_text = (int(rgb[0]), int(rgb[1]), int(rgb[2]))
except ValueError:
return 0, 0, 0
else:
return color_text
@dataclass(repr=False, eq=False)
class PointArgs:
"""Point table argument."""
links: str
type: str
color: str
x: float
y: float
@dataclass(repr=False, eq=False)
class LinkArgs:
"""Link table argument."""
name: str
color: str
points: str
_GRAMMAR = Lark(r"""
// Number
DIGIT: "0".."9"
INT: DIGIT+
SIGNED_INT: ["+" | "-"] INT
DECIMAL: INT "." INT? | "." INT
_EXP: ("e" | "E") SIGNED_INT
FLOAT: INT _EXP | DECIMAL _EXP?
NUMBER: FLOAT | INT
SIGNED_NUMBER: ["+" | "-"] NUMBER
// Letters
LCASE_LETTER: "a".."z"
UCASE_LETTER: "A".."Z"
LETTER: UCASE_LETTER | LCASE_LETTER | "_"
CNAME: LETTER (LETTER | DIGIT)*
// White space and new line
WS: /\s+/
CR: /\r/
LF: /\n/
NEWLINE: (CR? LF)+
%ignore WS
%ignore NEWLINE
// Comment
LINE_COMMENT: /#[^\n]*/
MULTILINE_COMMENT: /#\[[\s\S]*#\][^\n]*/
%ignore LINE_COMMENT
%ignore MULTILINE_COMMENT
// Custom data type
JOINT_TYPE: "RP" | "R" | "P"
COLOR: """ + "|".join(f'"{color}"i' for color in color_names) + r"""
type: JOINT_TYPE
name: CNAME
number: SIGNED_NUMBER
color_value: INT
// Main grammar
joint: "J[" type ["," angle] ["," color] "," point "," link "]"
link: "L[" [name ("," name)* ","?] "]"
point: "P[" number "," number "]"
angle: "A[" number "]"
color: "color[" (("(" color_value ("," color_value) ~ 2 ")") | COLOR) "]"
mechanism: "M[" [joint ("," joint)* ","?] "]"
?start: mechanism
""", parser='lalr')
class _Transformer(Transformer, Generic[_T1, _T2]):
"""Base transformer implementation."""
@staticmethod
@abstractmethod
def type(n: List[str]) -> _T1:
raise NotImplementedError
@staticmethod
def name(n: List[str]) -> str:
return str(n[0])
@staticmethod
def color(n: List[str]) -> str:
return str(n[0]) if len(n) == 1 else str(tuple(n))
@staticmethod
def color_value(n: List[str]) -> int:
return int(n[0])
@staticmethod
def number(n: List[str]) -> float:
return float(n[0])
angle = number
@staticmethod
def point(c: List[float]) -> _Coord:
return c[0], c[1]
@staticmethod
def link(a: List[str]) -> Tuple[str, ...]:
return tuple(a)
@staticmethod
@abstractmethod
def joint(args: _JointArgs) -> _T2:
raise NotImplementedError
@staticmethod
def mechanism(joints: List[_T2]) -> List[_T2]:
return joints
class _ParamsTrans(_Transformer[str, PointArgs]):
"""Transformer will parse into a list of VPoint data."""
@staticmethod
def type(n: List[str]) -> str:
return str(n[0])
@staticmethod
def joint(args: _JointArgs) -> PointArgs:
"""Sort the argument list.
[0]: type
([1]: angle)
([2]: color)
[-2]: point (coordinate)
[-1]: link
"""
type_str = cast(str, args[0])
x, y = cast(_Coord, args[-2])
links = ','.join(cast(Tuple[str, ...], args[-1]))
if type_str == 'R':
if len(args) == 3:
return PointArgs(links, 'R', 'Green', x, y)
elif len(args) == 4:
color = cast(str, args[-3])
return PointArgs(links, 'R', color, x, y)
else:
angle = cast(float, args[1])
type_angle = f'{type_str}:{angle}'
if len(args) == 4:
return PointArgs(links, type_angle, 'Green', x, y)
elif len(args) == 5:
color = cast(str, args[-3])
return PointArgs(links, type_angle, color, x, y)
raise LexError(f"invalid options: {args}")
class _PositionTrans(_Transformer[str, _Coord]):
"""Transformer will parse into a list of position data."""
@staticmethod
def type(n: List[str]) -> str:
return str(n[0])
@staticmethod
def joint(args: _JointArgs) -> _Coord:
x, y = cast(_Coord, args[-2])
return x, y
class _VPointsTrans(_Transformer[VJoint, VPoint]):
"""Using same grammar return as VPoints."""
@staticmethod
def type(n: List[str]) -> VJoint:
"""Return as int type."""
type_str = str(n[0])
if type_str == 'R':
return VJoint.R
elif type_str == 'P':
return VJoint.P
elif type_str == 'RP':
return VJoint.RP
else:
raise ValueError(f"invalid joint type: {type_str}")
@staticmethod
def joint(args: _JointArgs) -> VPoint:
"""Sort the argument list.
[0]: type
([1]: angle)
([2]: color)
[-2]: point (coordinate)
[-1]: link
"""
type_int = cast(VJoint, args[0])
x, y = cast(_Coord, args[-2])
links = cast(Tuple[str, ...], args[-1])
if type_int == VJoint.R:
if len(args) == 3:
return VPoint.r_joint(links, x, y)
elif len(args) == 4:
color = cast(str, args[-3])
return VPoint(links, VJoint.R, 0., color, x, y, color_rgb)
else:
angle = cast(float, args[1])
if len(args) == 4:
return VPoint.slider_joint(links, type_int, angle, x, y)
elif len(args) == 5:
color = cast(str, args[-3])
return VPoint(links, type_int, angle, color, x, y, color_rgb)
raise LexError(f"invalid options: {args}")
_params_translator = _ParamsTrans()
_pos_translator = _PositionTrans()
_vpoint_translator = _VPointsTrans()
def parse_params(expr: str) -> List[PointArgs]:
"""Parse mechanism expression into VPoint constructor arguments."""
return _params_translator.transform(_GRAMMAR.parse(expr))
def parse_pos(expr: str) -> List[_Coord]:
"""Parse mechanism expression into coordinates."""
return _pos_translator.transform(_GRAMMAR.parse(expr))
def parse_vpoints(expr: str) -> List[VPoint]:
"""Parse mechanism expression into VPoint objects."""
return _vpoint_translator.transform(_GRAMMAR.parse(expr))
def parse_vlinks(expr: str) -> List[VLink]:
"""Parse mechanism expression into VLink objects."""
return get_vlinks(parse_vpoints(expr))
def _sorted_pair(a: int, b: int) -> Tuple[int, int]:
return (a, b) if a < b else (b, a)
def edges_view(graph: Graph) -> Iterator[Tuple[int, Tuple[int, int]]]:
"""The iterator will yield the sorted edges from `graph`."""
yield from enumerate(sorted(_sorted_pair(n1, n2) for n1, n2 in graph.edges))
def graph2vpoints(
graph: Graph,
pos: Dict[int, _Coord],
cus: Optional[Dict[int, int]] = None,
same: Optional[Dict[int, int]] = None,
grounded: Optional[int] = None
) -> List[VPoint]:
"""Transform `graph` into [VPoint] objects. The vertices are mapped to links.
+ `pos`: Position for each vertices.
+ `cus`: Extra points on the specific links.
+ `same`: Multiple joint setting. The joints are according to [`edges_view`](#edges_view).
+ `grounded`: The ground link of vertices.
"""
if cus is None:
cus = {}
if same is None:
same = {}
same_r: Dict[int, List[int]] = {}
for k, v in same.items():
if v in same_r:
same_r[v].append(k)
else:
same_r[v] = [k]
tmp_list = []
ev = dict(edges_view(graph))
for i, edge in ev.items():
if i in same:
# Do not connect to anyone!
continue
edges = set(edge)
if i in same_r:
for j in same_r[i]:
edges.update(set(ev[j]))
x, y = pos[i]
links = [
f"L{link}" if link != grounded else VLink.FRAME for link in edges
]
tmp_list.append(VPoint.r_joint(links, x, y))
for name in sorted(cus):
link = f"L{cus[name]}" if cus[name] != grounded else VLink.FRAME
x, y = pos[name]
tmp_list.append(VPoint.r_joint((link,), x, y))
return tmp_list
|
Buying a used car may involve various hassles. But these hassles can be easily overcome by choosing the best dealer. It is always the best option to make use of the online dealers rather than approaching the dealers in the local market. This is because the online dealers tend to provide more opportunities and facilities for both the buyers and sellers. Hence by utilizing those services at the best one can enjoy several benefits. But all these aspects are possible only with the reputed dealers in the market. The qualities which can be expected from the online used car dealer are revealed in this article. This would be the best guide for the people who are about to hire the used car dealer for the first time.
It is to be noted that the dealer must have the best inventory for their clients. They must have the wide collection of used cars which can put the buyers into great excitement. There are some dealers who don’t have wide range and collection of cars. It is always better to stay out of these dealers as one cannot find the most appropriate car according to their expectation. Hence before trusting any online dealer, one can check their inventories in online. In case if they tend to have huge collections, they can be trusted without any constraint.
The dealers must not just stop with selling the car, but they must also help in financing. They must have the best financial method through which one can buy the used cars easily. Especially this factor should be carefully noted by the people who tend to have poor credits. This is because these people will always need a better financial help for buying the used car. Hence they can make use of this opportunity and can get benefited in all the means. Even though this sounds to be good, one must check whether their credit option is easy and quick.
There are many dealers who tend to concentrate only in promoting the sales. This kind of quality of a dealer will never benefit the buyers to a greater extent. Hence such dealers should always be ignored without any constraint. The dealer who can provide the best customer support in all the possible ways will always be the right choice for both the buyers and the sellers. In order to point out such service, one must make use of the feedbacks provided by the other people who have used this service for their needs. By taking all the above mentioned qualities into consideration one can easily choose the best Used cars Chicago without any kind of compromise.
Find the best personal trainer for you! |
#!/usr/bin/python
"""
BookSearch
Module: main
Author: Wael Al-Sallami
Date: 2/10/2013
"""
import sys, re, cmd, gen, engn, timer
class Prompt(cmd.Cmd):
"""Search query interface"""
engine = None
store = None
line = None
prompt = "\nquery> "
welcome = "\n### Welcome to BookSearch!\n### Enter your query to perform a search.\n### Enter '?' for help and 'exit' to terminate."
def preloop(self):
"""Print intro message and write or load indices"""
print self.welcome
with timer.Timer() as t:
self.store = gen.Store("books")
print '> Request took %.03f sec.' % t.interval
def default(self, line):
"""Handle search query"""
query = self.parse_query(line)
with timer.Timer() as t:
if not self.engine:
self.engine = engn.Engine(self.store)
answers = self.engine.search(query)
self.print_answers(answers)
print '\n> Search took %.06f sec.' % t.interval
def parse_query(self, line):
"""Parse all three kinds of query terms into a dict"""
query = {'bool': [], 'phrase': [], 'wild': []}
self.line = re.sub(r'[_]|[^\w\s"*]', ' ', line.strip().lower())
query = self.parse_wildcard(query)
query = self.parse_phrase(query)
query = self.parse_boolean(query)
return query
def parse_wildcard(self, query):
"""Extract wildcard queries into query{}"""
regex = r"([\w]+)?([\*])([\w]+)?"
query['wild'] = re.findall(regex, self.line)
if query['wild']:
self.line = re.sub(regex, '', self.line)
for i in range(len(query['wild'])):
query['wild'][i] = filter(len, query['wild'][i])
return query
def parse_phrase(self, query):
"""extract phrase query terms into query{}"""
regex = r'\w*"([^"]*)"'
query['phrase'] = re.findall(regex, self.line)
if query['phrase']:
self.line = re.sub(regex, '', self.line)
return query
def parse_boolean(self, query):
"""Consider whatever is left as boolean query terms"""
query['bool'] = self.line.split()
return query
def print_answers(self, answers):
"""Print search results"""
if answers:
print "\n> Found %d search results:" % len(answers),
for doc in answers: print doc,
else:
print "\n> Sorry, your search for: (%s) did not yield any results :(" % line
def emptyline(self):
"""Called when user doesn't enter anything"""
print "\n> Enter your search query or type '?' for help."
def do_exit(slef, line):
"""Type 'exit' to terminate the program"""
return True
def do_EOF(self, line):
print '' # print new line for prettier exits
return True
def main():
Prompt().cmdloop()
if __name__ == '__main__':
main()
|
Hi I need to build a webpage with a integrated booking/shop. The shop is simple where u can buy 3 different kinds of services. I also need the webpage to let customers...u can buy 3 different kinds of services. I also need the webpage to let customers to create a profile with some data about them. I also need google map integrated in the website. |
import copy
import random
import numpy as np
import pandas as pd
from .graph_utils import get_tips, get_root
def get_persistence_barcode(G, dist='radDist'):
if dist == 'radDist':
f = _radial_dist_to_soma
else:
raise NotImplementedError
return _get_persistence_barcode(G, f)
def _get_persistence_barcode(G, f):
"""
Creates the persistence barcode for the graph G. The algorithm is taken from
_Quantifying topological invariants of neuronal morphologies_ from Lida Kanari et al
(https://arxiv.org/abs/1603.08432).
:param G: networkx.DiGraph
:param f: A real-valued function defined over the set of nodes in G.
:return: pandas.DataFrame with entries node_id | type | birth | death . Where birth and death are defined in
distance from soma according to the distance function f.
"""
# Initialization
L = get_tips(G)
R = get_root(G)
D = dict(node_id=[], type=[], birth=[], death=[]) # holds persistence barcode
v = dict() # holds 'aging' function of visited nodes defined by f
# active nodes
A = list(copy.copy(L))
# set the initial value for leaf nodes
for l in L:
v[l] = f(G, l)
while R not in A:
for l in A:
p = G.predecessors(l)[0]
C = G.successors(p)
# if all children are active
if all(c in A for c in C):
# choose randomly from the oldest children
age = np.array([v[c] for c in C])
indices = np.where(age == age[np.argmax(age)])[0]
c_m = C[random.choice(indices)]
A.append(p)
for c_i in C:
A.remove(c_i)
if c_i != c_m:
D['node_id'].append(c_i)
D['type'].append(G.node[c_i]['type'])
D['birth'].append(v[c_i])
D['death'].append(f(G, p))
v[p] = v[c_m]
D['node_id'].append(R)
D['type'].append(1)
D['birth'].append(v[R])
D['death'].append(f(G, R))
return pd.DataFrame(D)
def _radial_dist_to_soma(G, n):
root_pos = G.node[1]['pos']
return np.sqrt(np.dot(G.node[n]['pos'] - root_pos, G.node[n]['pos'] - root_pos))
|
Growing up in the vibrancy of Midtown Manhattan, DJ Dubbz went from block parties, to nightclubs, eventually landing huge stadiums with thousands of fans. New York’s eclectic pulse influenced his open format DJ style which includes; Hip Hop, Latin, Reggae, House, & Top 40’s. His signature high energy presence at every venue and unique combinations of genres, melodies, and scratch techniques made him a favorite among club go-ers and music lovers alike.
During his early years DubbZ had his first official broadcasting position at JOHN JAY COLLEGE RADIO serving as Program Director and Vice President. Soon after, he began headlining numerous events all over NYC and even had guest spots on AMERICAN LATINO TV and THE STYLE NETWORK. Currently he splits his time between his monthly live broadcast on 92.5 Kiss (an iHeart Radio station), mixing live for Showtime Boxing, and his current residency at Hudson Terrace in NYC.
Most recently DJ DubbZ placed 3rd in the 2016 WINTER MUSIC CONFERENCE DJ Spinoff and has opened his own events company, THE HEADLINERS INCORPORATED. From New York to Vegas, Toronto to Spain, there hasn’t been a crowd he couldn’t move. With his schedule filling quickly and numerous recording projects in the works, his eyes are set on FM Radio and touring internationally. Make sure to Keep an eye out for DJ DubbZ, as he is sure to hit a stereo, club, or stadium near you. |
exec(compile(open('CompileOptions.py', 'rb').read(), 'CompileOptions.py', 'exec'))
# matches all symbols
pi = hfst.read_att_string("0 0 @_IDENTITY_SYMBOL_@ @_IDENTITY_SYMBOL_@\n\
0")
# matches all symbols except "|"
pi_house = hfst.read_att_string("0 0 @_IDENTITY_SYMBOL_@ @_IDENTITY_SYMBOL_@\n\
0 1 | |\n\
0")
# The possible values of a house color (spaces are added for better readability)
Color = hfst.fst(["blue ", "green ", "red ", "white ", "yellow "])
# The possible values of nationality
Nationality = hfst.fst(["Dane ", "Englishman ", "German ", "Swede ", "Norwegian "])
# The possible values of a drink
Drink = hfst.fst(["bier ", "coffee ", "milk ", "tea ", "water "])
# The possible values of cigarettes
Cigarette = hfst.fst(["Blend ", "BlueMaster ", "Dunhill ", "PallMall ", "Prince "])
# The possible values of animals
Pet = hfst.fst(["birds ", "cats ", "dogs ", "fish ", "horses "])
Color.write_to_file('Color.py.hfst')
Nationality.write_to_file('Nationality.py.hfst')
Drink.write_to_file('Drink.py.hfst')
Cigarette.write_to_file('Cigarette.py.hfst')
Pet.write_to_file('Pet.py.hfst')
# Convert all strings into transducers
vars={}
for i in ("blue ", "green ", "red ", "white ", "yellow ",
"Dane ", "Englishman ", "German ", "Swede ", "Norwegian ",
"bier ", "coffee ", "milk ", "tea ", "water ",
"Blend ", "BlueMaster ", "Dunhill ", "PallMall ", "Prince ",
"birds ", "cats ", "dogs ", "fish ", "horses "):
tr = hfst.fst(i)
vars[i] = tr
# Separator character (spaces are included for better readability)
HouseSeparator = hfst.fst("| ")
# House contains the consecutive values "ColorNationalityDrinkCigarettePet"
House = hfst.concatenate((Color, Nationality, Drink, Cigarette, Pet))
# Houses is "House| House| House| House| House"
tmp = hfst.concatenate((House, HouseSeparator))
tmp.repeat_n(4)
Houses = hfst.concatenate((tmp, House))
# 1. The Englishman lives in the red house.
# Since color and nationality are adjacent, it is enough to accept all strings that contain "red Englishman"
tmp = hfst.fst("red Englishman")
C1 = hfst.concatenate((pi, tmp, pi)) # .* "red Englishman" .*
# 2. The Swede keeps dogs.
# Now we must match the string between Swede and dog inside the same house.
tmp1 = hfst.fst('Swede')
tmp2 = hfst.fst('dogs')
C2 = hfst.concatenate((pi, tmp1, pi_house, tmp2, pi)) # .* "Swede" .* "dogs" .*
# 3. The Dane drinks tea
C3 = hfst.concatenate((pi, vars['Dane '], vars['tea '], pi))
# 4. The green house is just to the left of the white one
C4 = hfst.concatenate((pi, vars['green '], pi_house, HouseSeparator, vars['white '], pi))
# 5. The owner of the green house drinks coffee
C5 = hfst.concatenate((pi, vars['green '], pi_house, vars['coffee '], pi))
# 6. The Pall Mall smoker keeps birds
C6 = hfst.concatenate((pi, vars['PallMall '], vars['birds '], pi))
# 7. The owner of the yellow house smokes Dunhills
C7 = hfst.concatenate((pi, vars['yellow '], pi_house, vars['Dunhill '], pi))
# 8. The man in the center house drinks milk
C8 = hfst.concatenate((pi_house, HouseSeparator, pi_house, HouseSeparator, pi_house,
vars['milk '], pi_house, HouseSeparator, pi_house, HouseSeparator, pi_house))
# 9. The Norwegian lives in the first house
C9 = hfst.concatenate((pi_house, vars['Norwegian '], pi))
# 10. The Blend smoker has a neighbor who keeps cats
C101 = hfst.concatenate((pi, vars['Blend '], Pet, HouseSeparator, pi_house, vars['cats '], pi))
C102 = hfst.concatenate((pi, vars['cats '], pi_house, HouseSeparator, pi_house, vars['Blend '], pi))
C10 = hfst.disjunct((C101, C102))
C10.minimize()
# 11. The man who keeps horses lives next to the Dunhill smoker
C111 = hfst.concatenate((pi, vars['horses '], HouseSeparator, pi_house, vars['Dunhill '], pi))
C112 = hfst.concatenate((pi, vars['Dunhill '], pi_house, HouseSeparator, pi_house, vars['horses '], pi))
C11 = hfst.disjunct((C111, C112))
C11.minimize()
# 12. The man who smokes Blue Masters drinks bier.
C12 = hfst.concatenate((pi, vars['bier '], vars['BlueMaster '], pi))
# 13. The German smokes Prince
C13 = hfst.concatenate((pi, vars['German '], Drink, vars['Prince '], pi))
# 14. The Norwegian lives next to the blue house
C141 = hfst.concatenate((pi, vars['Norwegian '], pi_house, HouseSeparator, vars['blue '], pi))
C142 = hfst.concatenate((pi, vars['blue '], pi_house, HouseSeparator, Color, vars['Norwegian '], pi))
C14 = hfst.disjunct((C141, C142))
C14.minimize()
# 15. The Blend smoker has a neighbor who drinks water
C151 = hfst.concatenate((pi, vars['Blend '], Pet, HouseSeparator, pi_house, vars['water '], pi))
C152 = hfst.concatenate((pi, vars['water '], pi_house, HouseSeparator, pi_house, vars['Blend '], pi))
C15 = hfst.disjunct((C151, C152))
C15.minimize()
# Let's minimize the constraint transducers to carry out conjunction more efficiently:
Result = Houses
for i in (C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15):
i.minimize()
# Let's conjunct Houses with the constraints one by one:
Result.conjunct(i)
Result.minimize()
Result.write_to_file('Result')
|
You can easily trust Alarm Company Guys to provide the best quality professional services regarding Alarm Companies in Ivor, VA. We have got a team of qualified contractors and the most resourceful technology available to give you just what you might need. Our materials are of the very best quality and we know how to save costs. We intend to assist you to put together decisions for your mission, answer your questions, and organize an appointment with our contractors when you give us a call by dialing 888-353-1299.
You've got a price range to stick to, and you intend to spend less money. Though, conserving money shouldn't ever indicate that you sacrifice superior quality for Alarm Companies in Ivor, VA. Our attempts to help you save money will not compromise the excellent quality of our work. Our goal is to ensure that you enjoy the best quality products and a result which holds up over time. For instance, we take care to keep clear of costly errors, work quickly to conserve time, and be sure you are given the best bargains on materials and labor. Get in touch with Alarm Company Guys if you want the best quality solutions at a minimal cost. You can easily contact us by dialing 888-353-1299 to start.
When you're thinking of Alarm Companies in Ivor, VA, you'll need to be knowledgeable to make the very best decisions. We will make sure you know what can be expected. We take the surprises from the picture by giving accurate and thorough information. You can start by talking about your task with our client service staff when you dial 888-353-1299. We'll address all of your questions and arrange the initial meeting. We work closely with you through the whole project, and our team can show up promptly and prepared.
Lots of reasons can be found to pick Alarm Company Guys for Alarm Companies in Ivor, VA. Our company is the first choice when you need the most beneficial money saving solutions, the top equipment, and the highest rank of client satisfaction. We have got the experience that you need to meet all of your goals. Contact 888-353-1299 to reach Alarm Company Guys and discuss all your expectations about Alarm Companies in Ivor. |
import urllib2
import mechanize
from bs4 import BeautifulSoup
import os
def get_html(url):
header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
request = urllib2.Request(url, headers=header)
try:
br = mechanize.Browser()
response = br.open(request)
return response.get_data()
except urllib2.HTTPError, e:
print e.fp.read()
def get_info(title):
movie = {}
url = "http://www.imdb.com/title/{}".format(title)
site = BeautifulSoup(get_html(url))
top_bar = site.find(id="overview-top")
header = top_bar.find("h1", {"class": "header" })
movie['name'] = header.find("span", {"itemprop": "name"}).string
movie['year'] = header.find("a").string
info_bar = top_bar.find("div", {"class": "infobar"})
try:
movie['content_rating'] = info_bar.find("span", {"itemprop": "contentRating"})['content']
except TypeError as e:
movie['content_rating'] = "N/A"
movie['duration'] = info_bar.find("time").string
index = movie['duration'].find(" min")
movie['duration'] = movie['duration'][:index]
movie['release_date'] = info_bar.find("meta", {"itemprop": "datePublished"})['content']
movie['rating'] = top_bar.find("div", {"class": "star-box"}).find("div", {"class": "star-box-giga-star"}).string
movie['director'] = top_bar.find("div", {"itemprop": "director"}).find("span", {"itemprop": "name"}).string
movie['actors'] = [tag.string for tag in top_bar.find("div", {"itemprop": "actors"}).find_all("span", {"itemprop": "name"})]
movie['genre'] = [tag.string for tag in site.find("div", {"id": "titleStoryLine"}).find("div", {"itemprop": "genre"}).find_all("a")]
details = site.find("div", {"id": "titleDetails"})
movie['country'] = details.find("h4", text="Country:").parent.find("a").text
# Find award wins and nominations.
awards = site.find("div", {"id": "titleAwardsRanks"}).find_all("span", {"itemprop": "awards"})
awards = [award.find("b").text for award in awards if award.find("b") is not None]
oscar_nominations = 0
oscar_wins = 0
for award in awards:
if "Nominated" in award:
start = "for "
end = "Oscar"
oscar_nominations = int(award[award.find(start) + len(start) : award.rfind(end)])
elif "Won" in award:
start = "Won"
end ="Oscar"
oscar_wins = int(award[award.find(start) + len(start) : award.rfind(end)])
movie['oscar_nominations'] = oscar_nominations
movie['oscar_wins'] = oscar_wins
for prop in movie:
if not str(type(movie[prop])) == "<type 'list'>": # :'(
movie[prop] = str(movie[prop]).strip(" \t\n\r")
else:
movie[prop] = str([ele.encode("utf-8").strip(" \t\n\r") for ele in movie[prop]])
return movie
# print get_info(imdb_movie_id)
|
What does it mean if someone’s on a still hunt? This hunting term, for when you’re walking quietly to find prey, has been conscripted by the political world to refer to certain kinds of campaign strategies. This is part of a complete episode.
When I heard this conversation, my mind went immediately toward an image of “Revenooers” searching stealthily through the backwoods in search of illicit stills. They, of course, had to be extremely quiet, the better to surprise their prey. Martha, I’m surprised that a Kentucky girl didn’t see that coming. |
# from JumpScale.core.System import System
from JumpScale import j
import urllib
class TemplateEngine(object):
def __init__(self):
self.replaceDict = {}##dict(string,string)
#System ##System
def add(self, search, replace,variants=False):
if not j.basetype.string.check(search):
raise RuntimeError("only strings can be searched for when using template engine, param search is not a string")
if not j.basetype.string.check(replace):
raise RuntimeError("can only replace with strings when using template engine, param replace is not a string")
self.replaceDict[search] = replace
if variants:
self.replaceDict[search+"s"] =self.makePlural(replace)
self.replaceDict[self.capitalize(search)] =self.capitalize(replace)
self.replaceDict[self.capitalize(search+"s")] =self.makePlural(self.capitalize(replace))
def capitalize(self,txt):
return txt[0].upper()+txt[1:]
def makePlural(self,txt):
if txt[-1]=="y":
txt=txt[:-1]+"ies"
else:
txt=txt+"s"
return txt
def __replace(self,body):
for search in self.replaceDict.keys():
replace = self.replaceDict[search]
body = body.replace("{" + search + "}", replace)
body = body.replace("{:urlencode:" + search + "}", urllib.quote(replace, ''))
return body
def replace(self, body, replaceCount = 3):
for i in range(replaceCount):
body = self.__replace(body)
return body
def replaceInsideFile(self, filePath, replaceCount = 3):
self.__createFileFromTemplate(filePath, filePath, replaceCount)
def writeFileFromTemplate(self,templatePath,targetPath):
self.__createFileFromTemplate(templatePath, targetPath)
def getOutputFromTemplate(self,templatePath):
originalFile = j.system.fs.fileGetContents(templatePath)
modifiedString = self.replace(originalFile, replaceCount=3)
return modifiedString
def __createFileFromTemplate(self, templatePath, targetPath, replaceCount = 3):
originalFile = j.system.fs.fileGetContents(templatePath)
modifiedString = self.replace(originalFile, replaceCount)
j.system.fs.writeFile(targetPath, modifiedString)
def reset(self):
self.replaceDict={}
if __name__ == '__main__':
te=TemplateEngine()
te.add("login", "kristof")
te.add("passwd","root")
text="This is a test file for {login} with a passwd:{passwd}"
print te.replace(text)
|
TONGANI TEA COMPANY LIMITED is a Public Company limited by Shares. It is registered with Registrar of Companies, Kolkata on -.
Current Status of Tongani Tea Company Limited is Active.
It is a Non-govt company with an Authorized Capital of ₹ 1,00,00,000 (One Crore Indian Rupees) and Paid Up Capital of ₹ 18,57,750 (Eighteen Lakh, Fiftyseven Thousand, Seven Hundred And Fifty Indian Rupees).
There are 4 Directors associated with Tongani Tea Company Limited. They are: Manoj Kumar Daga, Ashok Vardhan Bagree, Ravindra Kumar Murarka and Sumana Raychaudhuri.
There are 3 Signatories associated with Tongani Tea Company Limited. They are: Ajay Kumar Agarwala, Sukhpal Singh and Achintya Sekhar Rarhi.
As per the records of Ministry of Corporate Affairs (MCA), Tongani Tea Company Limited's last Annual General Meeting (AGM) was held on Sep 7, 2018, and the date of lastest Balance Sheet is Mar 31, 2018.
Corporate Identification Number (CIN) of Tongani Tea Company Limited is L01132WB1893PLC000742 and its Registration Number is 000742. Its Registered Address and Contact Email are 'OCTAVIUS CENTRE,3RD FLOOR 15B,HEMANTA BASU SARANI KOLKATA WB 700001 IN' and [email protected] respectively.
Are you the owner or authorized representative of 'TONGANI TEA COMPANY LIMITED'?
You may link to "Profile Page" of "TONGANI TEA COMPANY LIMITED" in your websites (or) blogs. |
# -*- coding: utf-8 -*-
"""widgets to be used in a form"""
from bs4 import BeautifulSoup
from django.forms import Media
from floppyforms.widgets import TextInput
from djaloha import settings
class AlohaInput(TextInput):
"""
Text widget with aloha html editor
requires floppyforms to be installed
"""
template_name = 'djaloha/alohainput.html'
def __init__(self, *args, **kwargs):
# for compatibility with previous versions
kwargs.pop('text_color_plugin', None)
self.aloha_plugins = kwargs.pop('aloha_plugins', None)
self.extra_aloha_plugins = kwargs.pop('extra_aloha_plugins', None)
self.aloha_init_url = kwargs.pop('aloha_init_url', None)
super(AlohaInput, self).__init__(*args, **kwargs)
def _get_media(self):
"""
return code for inserting required js and css files
need aloha , plugins and initialization
"""
try:
aloha_init_url = self.aloha_init_url or settings.init_url()
aloha_version = settings.aloha_version()
aloha_plugins = self.aloha_plugins
if not aloha_plugins:
aloha_plugins = settings.plugins()
if self.extra_aloha_plugins:
aloha_plugins = tuple(aloha_plugins) + tuple(self.extra_aloha_plugins)
css = {
'all': (
"{0}/css/aloha.css".format(aloha_version),
)
}
javascripts = []
if not settings.skip_jquery():
javascripts.append(settings.jquery_version())
#if aloha_version.startswith('aloha.0.22.') or aloha_version.startswith('aloha.0.23.'):
javascripts.append("{0}/lib/require.js".format(aloha_version))
javascripts.append(aloha_init_url)
javascripts.append(
u'{0}/lib/aloha.js" data-aloha-plugins="{1}'.format(aloha_version, u",".join(aloha_plugins))
)
javascripts.append('djaloha/js/djaloha-init.js')
return Media(css=css, js=javascripts)
except Exception, msg:
print '## AlohaInput._get_media Error ', msg
media = property(_get_media)
def value_from_datadict(self, data, files, name):
"""return value"""
value = super(AlohaInput, self).value_from_datadict(data, files, name)
return self.clean_value(value)
def clean_value(self, origin_value):
"""This apply several fixes on the html"""
return_value = origin_value
if return_value: # don't manage None values
callbacks = (self._fix_br, self._fix_img, )
for callback in callbacks:
return_value = callback(return_value)
return return_value
def _fix_br(self, content):
"""
This change the <br> tag into <br />
in order to avoid empty lines at the end in HTML4 for example for newsletters
"""
return content.replace('<br>', '<br />')
def _fix_img(self, content):
"""Remove the handlers generated on the image for resizing. It may be not removed by editor in some cases"""
soup = BeautifulSoup(content, 'html.parser')
wrapped_img = soup.select(".ui-wrapper img")
if len(wrapped_img) > 0:
img = wrapped_img[0]
# Remove the ui-resizable class
img_classes = img.get('class', None) or []
img_classes.remove('ui-resizable')
img['class'] = img_classes
# Replace the ui-wrapper by the img
wrapper = soup.select(".ui-wrapper")[0]
wrapper.replace_with(img)
content = unicode(soup)
return content
|
love, love , love it!!!
i really like that you sometimes work on cardboard. it has a great texture that makes for an interesting surface quality. this is an excellent pastel.
most interesting and ardently so.
Very expressive work. I think I know the feeling.
Truly amazing, fantastic work as always! :-D. Phil.
this is an excellent piece. i love your signature elements as you described your cast of characters, especially the hands :-) keep up the fantastic work!!
Great imagination -- very lovely! Bravo!!
.your imagination is always wild!
I like this one very much! The deeper colors have an intensity which the lighter colors( of pastel 2) lack. In my humble view, what makes your art fabulous is that, to my eye at least, it is absorbingly intense but with a touch of whimsy.
Hi Jennifer,i like very much your new pastel series.
The combination of colors is just great.
the darker colors capture the essence of your other works.
raw would be the word, and the cardboard complements your vision.
Talking about wild women...your imagination is always wild!
Good morning, my dear Jennifer!! A lot of strong Feeling this picture invite!!!
And following Thoughts that I will try to pack into Words. Primal is Feeling!!!
Your Colors are Pure and Primal!! Always, but always I Feel Love for Life, does not matter how deep (and You go Deep) go. It s because of Your Big Heart capable to Hug Life. ALL Life. All Its Sides! It is Rare. It is easier to avoid and close the eyes, Heart too.
Open Heart feels more and pains more. It is the Balance issue:-).Here are more levels.
It s about Evil, Fear, Giving Up, Goodness...All tough questions!!
Pureness of Inner us depends of Our Strenght and how we face and fight our Inner Poison that attack from inside, and how we fight with Poison from Outside!!.
How much we will be damaged After, it is the question?!?
how a strong image!!! great!
Love the work Jennifer!! Great going with the pastels! Congratulations on the Sales!!! Well deserved! Hugs; Philip.
powerful stuff, jennifer . . .
This makes me think of when there are too many people chattering around me and I want to yell "leave me alone and shut up".
Remarkable work and exquisite colours, Jennifer. Very nice but I haven't seen much of your work in blues before. This one is distinctive. these subjects look like they may have some things, unpleasant, on their minds. Not only the blues and greys but that snake -- perhaps thru and not behind the lady's head -- is also a hint.
Wonderful. Love your choice of colours.
wonderful, I love the style you paint.
Excellent work Jennifer, here I see a soul searching time when there are bad influences circling our environment but we do not let them in, also we see where any guidance is available from the slightly open hand but there again it may only be limited advice.
Another winner! Hope you are well.
Your work never leaves indifferent, Jennifer...impressive and I like the blue tones.
An outstanding piece of work Jennifer and superb creativity!!
fantastic ... love the colors in this piece!
Jennifer, your work always amazes me!! Wishing you a wonderful weekend, my friend!
A very creative pastel, Jennifer, a fabulous use of lighter pastel colours and rich ones too! A well balanced painting and a very interesting presentation! Such wonderful composition!
one of my favorites that you have posted. great art !!! |
# Copyright 2015 Intel Corp.
#
# 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 mock
from cinder.objects import base
from cinder import rpc
from cinder import test
class FakeAPI(rpc.RPCAPI):
RPC_API_VERSION = '1.5'
TOPIC = 'cinder-scheduler-topic'
BINARY = 'cinder-scheduler'
class RPCAPITestCase(test.TestCase):
"""Tests RPCAPI mixin aggregating stuff related to RPC compatibility."""
def setUp(self):
super(RPCAPITestCase, self).setUp()
# Reset cached version pins
rpc.LAST_RPC_VERSIONS = {}
rpc.LAST_OBJ_VERSIONS = {}
@mock.patch('cinder.objects.Service.get_minimum_rpc_version',
return_value='1.2')
@mock.patch('cinder.objects.Service.get_minimum_obj_version',
return_value='1.4')
@mock.patch('cinder.rpc.get_client')
def test_init(self, get_client, get_min_obj, get_min_rpc):
def fake_get_client(target, version_cap, serializer):
self.assertEqual(FakeAPI.TOPIC, target.topic)
self.assertEqual(FakeAPI.RPC_API_VERSION, target.version)
self.assertEqual('1.2', version_cap)
self.assertEqual('1.4', serializer.version_cap)
get_client.side_effect = fake_get_client
FakeAPI()
@mock.patch('cinder.objects.Service.get_minimum_rpc_version',
return_value='liberty')
@mock.patch('cinder.objects.Service.get_minimum_obj_version',
return_value='liberty')
@mock.patch('cinder.rpc.get_client')
def test_init_liberty_caps(self, get_client, get_min_obj, get_min_rpc):
def fake_get_client(target, version_cap, serializer):
self.assertEqual(FakeAPI.TOPIC, target.topic)
self.assertEqual(FakeAPI.RPC_API_VERSION, target.version)
self.assertEqual(rpc.LIBERTY_RPC_VERSIONS[FakeAPI.BINARY],
version_cap)
self.assertEqual('liberty', serializer.version_cap)
get_client.side_effect = fake_get_client
FakeAPI()
@mock.patch('cinder.objects.Service.get_minimum_rpc_version',
return_value=None)
@mock.patch('cinder.objects.Service.get_minimum_obj_version',
return_value=None)
@mock.patch('cinder.objects.base.CinderObjectSerializer')
@mock.patch('cinder.rpc.get_client')
def test_init_none_caps(self, get_client, serializer, get_min_obj,
get_min_rpc):
"""Test that with no service latest versions are selected."""
FakeAPI()
serializer.assert_called_once_with(base.OBJ_VERSIONS.get_current())
get_client.assert_called_once_with(mock.ANY,
version_cap=FakeAPI.RPC_API_VERSION,
serializer=serializer.return_value)
self.assertTrue(get_min_obj.called)
self.assertTrue(get_min_rpc.called)
@mock.patch('cinder.objects.Service.get_minimum_rpc_version')
@mock.patch('cinder.objects.Service.get_minimum_obj_version')
@mock.patch('cinder.rpc.get_client')
@mock.patch('cinder.rpc.LAST_RPC_VERSIONS', {'cinder-scheduler': '1.4'})
@mock.patch('cinder.rpc.LAST_OBJ_VERSIONS', {'cinder-scheduler': '1.3'})
def test_init_cached_caps(self, get_client, get_min_obj, get_min_rpc):
def fake_get_client(target, version_cap, serializer):
self.assertEqual(FakeAPI.TOPIC, target.topic)
self.assertEqual(FakeAPI.RPC_API_VERSION, target.version)
self.assertEqual('1.4', version_cap)
self.assertEqual('1.3', serializer.version_cap)
get_client.side_effect = fake_get_client
FakeAPI()
self.assertFalse(get_min_obj.called)
self.assertFalse(get_min_rpc.called)
|
Add the Drop-in UI with a few lines of code to get a full-featured checkout with credit card and PayPal payments.
Accept more payment types with your existing checkout form by adding buttons for PayPal, Apple Pay, Google Pay, and Venmo.
Rolling your own checkout UI? Use credit card tokenization to save customer card information.
These instructions are for version 3.x of our iOS SDK. We recommend using the latest version of our SDK; use the selector near the top of this page.
For additional requirements and installation options, see the iOS Client SDK Guide.
Your server is responsible for generating a client token, which contains the authorization and configuration details that your client needs to initialize the client SDK.
Your app should request a client token from your server. This example uses our sample integration server; please adapt it to use your own backend API.
// As an example, you may wish to present our Drop-in UI at this point.
You should obtain a new client token often, at least as often as your app restarts. For the best experience, you should kick off this network operation before it would block a user interaction.
You must generate a client token on your server once per user checkout session. The endpoint we provide in this example is for demonstration purposes only.
We generated a demo client token for you so you can jump right in. This is for testing purposes only!
The above demo client token is for temporary use. You must change this client token in order to process payments with your Braintree sandbox or production account.
At this point, you are ready to collect payment information from your customer.
Drop-in is the easiest way to get started. It provides a fully fledged payments experience out of the box. You can also choose to create a custom UI and then tokenize the payment information directly.
Declare a class that conforms to the BTDropInViewControllerDelegate protocol to receive the user's payment method.
In your implementation, use the client token obtained from your server to initialize the Braintree SDK. Then, create a BTDropInViewController.
// If you haven't already, create and retain a `Braintree` instance with the client token.
// Typically, you only need to do this once per session.
// The way you present your BTDropInViewController instance is up to you. |
import sys
import json
#try: import simplejson as json
#except ImportError: import json
DEBUG = True
STATES = {
'AK': 'Alaska',
'AL': 'Alabama',
'AR': 'Arkansas',
'AS': 'American Samoa',
'AZ': 'Arizona',
'CA': 'California',
'CO': 'Colorado',
'CT': 'Connecticut',
'DC': 'District of Columbia',
'DE': 'Delaware',
'FL': 'Florida',
'GA': 'Georgia',
'GU': 'Guam',
'HI': 'Hawaii',
'IA': 'Iowa',
'ID': 'Idaho',
'IL': 'Illinois',
'IN': 'Indiana',
'KS': 'Kansas',
'KY': 'Kentucky',
'LA': 'Louisiana',
'MA': 'Massachusetts',
'MD': 'Maryland',
'ME': 'Maine',
'MI': 'Michigan',
'MN': 'Minnesota',
'MO': 'Missouri',
'MP': 'Northern Mariana Islands',
'MS': 'Mississippi',
'MT': 'Montana',
'NA': 'National',
'NC': 'North Carolina',
'ND': 'North Dakota',
'NE': 'Nebraska',
'NH': 'New Hampshire',
'NJ': 'New Jersey',
'NM': 'New Mexico',
'NV': 'Nevada',
'NY': 'New York',
'OH': 'Ohio',
'OK': 'Oklahoma',
'OR': 'Oregon',
'PA': 'Pennsylvania',
'PR': 'Puerto Rico',
'RI': 'Rhode Island',
'SC': 'South Carolina',
'SD': 'South Dakota',
'TN': 'Tennessee',
'TX': 'Texas',
'UT': 'Utah',
'VA': 'Virginia',
'VI': 'Virgin Islands',
'VT': 'Vermont',
'WA': 'Washington',
'WI': 'Wisconsin',
'WV': 'West Virginia',
'WY': 'Wyoming'
}
def loadscores(fp):
scores = {}
for line in fp:
term, score = line.split("\t") # The file is tab-delimited. "\t" means "tab character"
scores[term] = int(score) # Convert the score to an integer.
#if (DEBUG)
#print scores.items() # Print every (term, score) pair in the dictionary
return scores
def calcscore(s_str, scores_dic):
twt_score_int = 0
#print s_str
for wd in s_str.split(' '):
word = wd.lower()
#print 'looking score for ', word.lower()
#print scores.keys()
if word in scores_dic.keys():
sc = scores_dic[word]
twt_score_int += sc
#print word , ' found in dic with score of ', sc
#print 'total score = ', twt_score
return twt_score_int
def findlocation_using_place(place_dic):
'''
if 'location' is not null, try to find location
'''
pass
def find_location_using_cdt(cdt_lst):
'''
find location based on 'coordinates' if 'location' is null
'''
pass
def tweetscore(tw_file, sent_file):
scores_dic = loadscores(sent_file)
json_dic = {}
scores_lst = []
sc = 0 #score for each tweet
state_scores = {}
for line in tw_file:
sc = 0 #reinit
try: json_dic = json.loads(line)
except ValueError: continue
if 'lang' in json_dic:
lang = json_dic[u'lang']
if (lang.encode('utf-8').find('en') != -1):
unicode_string = json_dic[u'text']
encoded_string = unicode_string.encode('utf-8')
#print encoded_string
sc = calcscore(encoded_string, scores_dic)
# now find location
place_dic = json_dic[u'place']
if (not place_dic):
continue
#print place_dic
country = place_dic[u'country']
if (country):
if ( (country.encode('utf-8').find('US') == -1)
and (country.encode('utf-8').find('United States') == -1)
):
continue
state = place_dic[u'name']
if (not state):
continue
#print (country, ',', state)
if (state in state_scores.keys()):
state_scores[state] += sc
else:
state_scores[state] = sc
hap_state = ''
for key, value in sorted(state_scores.iteritems(), key=lambda (k,v): (v,k), reverse=True):
#print "%s %s" % (key, value)
hap_state = key
break
#return scores_lst
def main():
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
tweetscore(tweet_file, sent_file)
if __name__ == '__main__':
main()
|
No outside food or drinks are permitted. You will, however, be able to purchase food from a variety of vendors at the Showdown.
1. Is there a parking fee?
Parking is FREE! Accessible parking is also available with proper state-issued vehicle credentials.
2. Can I bring a pet?
Pets are not allowed at the Showdown. Registered service animals, however, are permitted. With hundreds of vendors, and more than 5,000 people expected to attend this year’s event, restricting pets helps to maintain food safety standards.
3. Can I bring my own food?
4. What can I do to beat the heat?
There will be two large dining tents near the stage. Additionally, we recommend wearing hats, cool clothing, and bringing something like a small ‘sun’brella for shade. There will not be enough space to accommodate personal tents or the like.
5. Will ATMs be available for cash withdrawal?
Yes! ATMs will be available at the main gate and in the children’s area.
6. What other food options will be available at the Beltway BBQ Showdown?
Vendors will be available to offer an assortment of domestic and ethnic foods including everything from appetizers to main dishes and desserts!
7. What about the kids?
Don’t worry, we didn’t forget about the kids! Our Children’s Area is full of fun with crafts, games, bounce inflatables and many other entertaining activities!
8. Where is the Lost & Found?
The Lost & Found will be located at the front entrance under the large, green Star Shade/Information Tent.
9. How can I sample cooking from the teams?
Timing is everything! Starting after 2 pm, the Tasting Tent will host two events for a small fee: the Sauce Boss competition and the Buck A Bone. Dip pulled-chicken into sauces submitted by each team, and purchase rib bones for $1 each - then vote for your favorite! It will be a finger-licking good time! |
"""
Django management command to fetch course structures for given course ids
"""
import json
from logging import getLogger
from django.core.management.base import BaseCommand
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from philu_commands.helpers import generate_course_structure
log = getLogger(__name__)
class Command(BaseCommand):
"""
A command to fetch course structures for provided course ids
"""
help = """
This command prints the course structure for all the course ids given in arguments
example:
manage.py ... fetch_course_structures course_id_1 course_id_2
"""
def add_arguments(self, parser):
parser.add_argument('course_ids', nargs='+', help='Course ids for which we require the course structures.')
def handle(self, *args, **options):
course_structures = []
course_ids = options['course_ids']
for course_id in course_ids:
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
log.error('Invalid course id provided: {}'.format(course_id))
continue
course_structure = generate_course_structure(course_key)
course_structure['course_id'] = course_id
course_structures.append(course_structure)
if course_structures:
# pylint: disable=superfluous-parens
print ('-' * 80)
print('Course structures for given course ids: ')
print(json.dumps(course_structures))
print('-' * 80)
else:
log.error('All course ids provided are invalid')
|
Published 04/25/2019 01:43:27 pm at 04/25/2019 01:43:27 pm in Oak Cabinet Pulls.
oak cabinet pulls oak drawer pulls knobs oak cabinet pulls large size of door knobs pewter kitchen knobs and vintage kitchen cabinets vintage kitchen cabinet pulls vintage vintage.
beautiful special unnamed file kitchen colors with light oak medium size of cabinets kitchen colors with dark wood unnamed file light oak kitchens on modern, san diego long media cabinet kitchen contemporary with oak cabinets san diego long media cabinet kitchen contemporary with oak cabinets modern and drawer pulls open shelving, knobs for kitchen cabinets restoration hardware kitchen cabinet knobs for kitchen cabinets restoration hardware kitchen cabinet knobs and pulls inspirational best kitchen cabinet hardware, hardware for oak cabinets ideas hardware for light oak cabinets hardware for oak cabinets hardware for golden oak kitchen cabinets com best hardware for light oak hardware for oak cabinets , cabinet tab pulls surprise rift swan white oak kitchen cabinet second life marketplace oak kitchen cabinet, oak front cabinets belle awesome glass cabinet pulls kitchen photos of oak front cabinets belle awesome glass cabinet pulls, cabinet hardware mission style arts and crafts style cabinet related post, oak cabinet pulls wood unfinished oak pullhandle door dresser oak cabinet with iron ring pulls by james mont american s at stdibs, best cabinet pulls for oak cabinets best knobs for oak kitchen cabinet pulls for oak cabinet oak cabinet hardware oak kitchen, square cabinet pulls kitchen hardware for oak cabinets modern drawer square cabinet pulls kitchen hardware for oak cabinets modern drawer pertaining to prepare , the d lawless hardware blog how to measure cabinet pulls or what how to measure cabinet pulls or what is center to center. |
#!/usr/bin/python
"""
Example to get and set variables via AGI.
You can call directly this script with AGI() in Asterisk dialplan.
"""
from asterisk.agi import *
agi = AGI()
agi.answer()
agi.verbose("python agi started")
# record file <filename> <format> <escape_digits> <timeout> [<offset samples>] [<BEEP>] [<s=silence>]
# record_file(self, filename, format='gsm', escape_digits='#', timeout=20000, offset=0, beep='beep')
# agi.record_file('/tmp/test2.ulaw','ulaw')
#RECORD FILE $tmpname $format \"$intkey\" \"$abs_timeout\" $beep \"$silence\"\n";
filename = '/tmp/test5'
format = 'ulaw'
intkey = '#'
timeout = 20000
beep = 'beep'
offset = '0'
silence = 's=5'
agi.execute('RECORD FILE', (filename), (format), (intkey), (timeout), (offset), (beep), (silence))
# agi.record_file((filename), (format))
"""
while True:
agi.stream_file('/var/lib/asterisk/sounds/en/tt-codezone')
result = agi.wait_for_digit(-1)
agi.verbose("got digit %s" % result)
if result.isdigit():
agi.say_number(result)
else:
agi.verbose("bye!")
agi.hangup()
sys.exit()
"""
# result = agi.wait_for_digit()
# agi.verbose("got digit %s" % result)
# Get variable environment
extension = agi.env['agi_extension']
# Get variable in dialplan
phone_exten = agi.get_variable('PHONE_EXTEN')
# Set variable, it will be available in dialplan
agi.set_variable('EXT_CALLERID', (digit))
|
One of my favorite things to do is to talk with churches and help them solve problems. Often, the same general issues arise as I speak with churches. Church communicators and leaders struggle with how to be more effective in how they’re communicating. They wrestle with being efficient in their work and with having limited budgets. They desire to improve, but their time for learning is limited because they’re too busy maintaining to step away and learn anything new in-depth.
This month we’re going to focus all of our resources around one topic that seems to come up more often than most others. Church websites. Because churches are so often overwhelmed by their most pressing and recurring communications tasks (e.g. daily emails, social media posts, bulletins!), their church website often falls by the wayside. And it’s no surprise because website development and maintenance are often far outside of the expertise of most staff.
With a variety of articles, webinars, and other resources, my hope is that by the end of the month, you’ll have a deeper understanding of the website development process, some new tools, and a renewed vision for your church’s website. |
from ibolc.database import (
Column,
db,
Email,
Model,
PhoneNumber,
ReferenceCol,
relationship,
SSN,
SurrogatePK,
Zipcode
)
# pylint: disable=too-few-public-methods
class State(Model, SurrogatePK):
__tablename__ = 'state'
code = Column(db.String(2), nullable=False)
name = Column(db.String, nullable=False)
def __repr__(self):
return "<State({})>".format(self.name)
class Address(Model, SurrogatePK):
__tablename__ = 'address'
address1 = Column(db.String, nullable=False)
address2 = Column(db.String)
address3 = Column(db.String)
city = Column(db.String, nullable=False)
state_id = ReferenceCol('state')
zipcode = Column(Zipcode, nullable=False)
state = relationship('State')
def __repr__(self):
return "<Address({}...)>".format(self.address1[:10])
class Person(Model, SurrogatePK):
__tablename__ = 'person'
first_name = Column(db.String, nullable=False)
middle_name = Column(db.String)
last_name = Column(db.String, nullable=False)
ssn = Column(SSN, nullable=False)
dob = Column(db.Date, nullable=False)
country_id = ReferenceCol('country')
country = relationship('Country')
address_id = ReferenceCol('address')
address = relationship('Address')
cell_phone = Column(PhoneNumber)
email = Column(Email, nullable=False)
type = Column(db.String)
__mapper_args__ = {
'polymorphic_identity': 'person',
'polymorphic_on': type
}
def __repr__(self):
return "<Person({})>".format(self.last_name)
|
The secret behind managing such considerable volumes of cargo is our state-of-the-art IT System that tracks every element of every shipment.
To strengthen our offering, all logistics modules are supported by SAP-software. With all systems linked directly to the Internet, each Client can now track each shipment in Real Time from anywhere in the world.
Get up-to-date information on your shipments using Track & Trace. Reach out to GMT for a full demo of all the possibilities. |
# dialog.py --- A Python interface to the ncurses-based "dialog" utility
# -*- coding: utf-8 -*-
#
# Copyright (C) 2002, 2003, 2004, 2009, 2010, 2013 Florent Rougon
# Copyright (C) 2004 Peter Åstrand
# Copyright (C) 2000 Robb Shecter, Sultanbek Tezadov
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301 USA.
"""Python interface to dialog-like programs.
This module provides a Python interface to dialog-like programs such
as 'dialog' and 'Xdialog'.
It provides a Dialog class that retains some parameters such as the
program name and path as well as the values to pass as DIALOG*
environment variables to the chosen program.
For a quick start, you should look at the simple_example.py file that
comes with pythondialog. It is a very simple and straightforward
example using a few basic widgets. Then, you could study the demo.py
file that illustrates most features of pythondialog, or more directly
dialog.py.
See the Dialog class documentation for general usage information,
list of available widgets and ways to pass options to dialog.
Notable exceptions
------------------
Here is the hierarchy of notable exceptions raised by this module:
error
ExecutableNotFound
BadPythonDialogUsage
PythonDialogSystemError
PythonDialogOSError
PythonDialogIOError (should not be raised starting from
Python 3.3, as IOError becomes an
alias of OSError)
PythonDialogErrorBeforeExecInChildProcess
PythonDialogReModuleError
UnexpectedDialogOutput
DialogTerminatedBySignal
DialogError
UnableToCreateTemporaryDirectory
UnableToRetrieveBackendVersion
UnableToParseBackendVersion
UnableToParseDialogBackendVersion
InadequateBackendVersion
PythonDialogBug
ProbablyPythonBug
As you can see, every exception 'exc' among them verifies:
issubclass(exc, error)
so if you don't need fine-grained error handling, simply catch
'error' (which will probably be accessible as dialog.error from your
program) and you should be safe.
Changed in version 2.12: PythonDialogIOError is now a subclass of
PythonDialogOSError in order to help with the transition from IOError
to OSError in the Python language. With this change, you can safely
replace "except PythonDialogIOError" clauses with
"except PythonDialogOSError" even if running under Python < 3.3.
"""
from __future__ import with_statement, unicode_literals, print_function
import collections
from itertools import imap
from itertools import izip
from io import open
import locale
_VersionInfo = collections.namedtuple(
"VersionInfo", ("major", "minor", "micro", "releasesuffix"))
class VersionInfo(_VersionInfo):
def __unicode__(self):
res = ".".join( ( unicode(elt) for elt in self[:3] ) )
if self.releasesuffix:
res += self.releasesuffix
return res
def __repr__(self):
# Unicode strings are not supported as the result of __repr__()
# in Python 2.x (cf. <http://bugs.python.org/issue5876>).
return b"{0}.{1}".format(__name__, _VersionInfo.__repr__(self))
version_info = VersionInfo(3, 0, 1, None)
__version__ = unicode(version_info)
import sys, os, tempfile, random, re, warnings, traceback
from contextlib import contextmanager
from textwrap import dedent
# This is not for calling programs, only to prepare the shell commands that are
# written to the debug log when debugging is enabled.
try:
from shlex import quote as _shell_quote
except ImportError:
def _shell_quote(s):
return "'%s'" % s.replace("'", "'\"'\"'")
# Exceptions raised by this module
#
# When adding, suppressing, renaming exceptions or changing their
# hierarchy, don't forget to update the module's docstring.
class error(Exception):
"""Base class for exceptions in pythondialog."""
def __init__(self, message=None):
self.message = message
def __unicode__(self):
return self.complete_message()
def __repr__(self):
# Unicode strings are not supported as the result of __repr__()
# in Python 2.x (cf. <http://bugs.python.org/issue5876>).
return b"{0}.{1}({2!r})".format(__name__, self.__class__.__name__,
self.message)
def complete_message(self):
if self.message:
return "{0}: {1}".format(self.ExceptionShortDescription,
self.message)
else:
return self.ExceptionShortDescription
ExceptionShortDescription = "{0} generic exception".format("pythondialog")
# For backward-compatibility
#
# Note: this exception was not documented (only the specific ones were), so
# the backward-compatibility binding could be removed relatively easily.
PythonDialogException = error
class ExecutableNotFound(error):
"""Exception raised when the dialog executable can't be found."""
ExceptionShortDescription = "Executable not found"
class PythonDialogBug(error):
"""Exception raised when pythondialog finds a bug in his own code."""
ExceptionShortDescription = "Bug in pythondialog"
# Yeah, the "Probably" makes it look a bit ugly, but:
# - this is more accurate
# - this avoids a potential clash with an eventual PythonBug built-in
# exception in the Python interpreter...
class ProbablyPythonBug(error):
"""Exception raised when pythondialog behaves in a way that seems to \
indicate a Python bug."""
ExceptionShortDescription = "Bug in python, probably"
class BadPythonDialogUsage(error):
"""Exception raised when pythondialog is used in an incorrect way."""
ExceptionShortDescription = "Invalid use of pythondialog"
class PythonDialogSystemError(error):
"""Exception raised when pythondialog cannot perform a "system \
operation" (e.g., a system call) that should work in "normal" situations.
This is a convenience exception: PythonDialogIOError, PythonDialogOSError
and PythonDialogErrorBeforeExecInChildProcess all derive from this
exception. As a consequence, watching for PythonDialogSystemError instead
of the aformentioned exceptions is enough if you don't need precise
details about these kinds of errors.
Don't confuse this exception with Python's builtin SystemError
exception.
"""
ExceptionShortDescription = "System error"
class PythonDialogOSError(PythonDialogSystemError):
"""Exception raised when pythondialog catches an OSError exception that \
should be passed to the calling program."""
ExceptionShortDescription = "OS error"
class PythonDialogIOError(PythonDialogOSError):
"""Exception raised when pythondialog catches an IOError exception that \
should be passed to the calling program.
This exception should not be raised starting from Python 3.3, as
the built-in exception IOError becomes an alias of OSError.
"""
ExceptionShortDescription = "IO error"
class PythonDialogErrorBeforeExecInChildProcess(PythonDialogSystemError):
"""Exception raised when an exception is caught in a child process \
before the exec sytem call (included).
This can happen in uncomfortable situations such as:
- the system being out of memory;
- the maximum number of open file descriptors being reached;
- the dialog-like program being removed (or made
non-executable) between the time we found it with
_find_in_path and the time the exec system call attempted to
execute it;
- the Python program trying to call the dialog-like program
with arguments that cannot be represented in the user's
locale (LC_CTYPE)."""
ExceptionShortDescription = "Error in a child process before the exec " \
"system call"
class PythonDialogReModuleError(PythonDialogSystemError):
"""Exception raised when pythondialog catches a re.error exception."""
ExceptionShortDescription = "'re' module error"
class UnexpectedDialogOutput(error):
"""Exception raised when the dialog-like program returns something not \
expected by pythondialog."""
ExceptionShortDescription = "Unexpected dialog output"
class DialogTerminatedBySignal(error):
"""Exception raised when the dialog-like program is terminated by a \
signal."""
ExceptionShortDescription = "dialog-like terminated by a signal"
class DialogError(error):
"""Exception raised when the dialog-like program exits with the \
code indicating an error."""
ExceptionShortDescription = "dialog-like terminated due to an error"
class UnableToCreateTemporaryDirectory(error):
"""Exception raised when we cannot create a temporary directory."""
ExceptionShortDescription = "Unable to create a temporary directory"
class UnableToRetrieveBackendVersion(error):
"""Exception raised when we cannot retrieve the version string of the \
dialog-like backend."""
ExceptionShortDescription = "Unable to retrieve the version of the \
dialog-like backend"
class UnableToParseBackendVersion(error):
"""Exception raised when we cannot parse the version string of the \
dialog-like backend."""
ExceptionShortDescription = "Unable to parse as a dialog-like backend \
version string"
class UnableToParseDialogBackendVersion(UnableToParseBackendVersion):
"""Exception raised when we cannot parse the version string of the dialog \
backend."""
ExceptionShortDescription = "Unable to parse as a dialog version string"
class InadequateBackendVersion(error):
"""Exception raised when the backend version in use is inadequate \
in a given situation."""
ExceptionShortDescription = "Inadequate backend version"
@contextmanager
def _OSErrorHandling():
try:
yield
except OSError, e:
raise PythonDialogOSError(unicode(e))
except IOError, e:
raise PythonDialogIOError(unicode(e))
try:
# Values accepted for checklists
_on_cre = re.compile(r"on$", re.IGNORECASE)
_off_cre = re.compile(r"off$", re.IGNORECASE)
_calendar_date_cre = re.compile(
r"(?P<day>\d\d)/(?P<month>\d\d)/(?P<year>\d\d\d\d)$")
_timebox_time_cre = re.compile(
r"(?P<hour>\d\d):(?P<minute>\d\d):(?P<second>\d\d)$")
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
# From dialog(1):
#
# All options begin with "--" (two ASCII hyphens, for the benefit of those
# using systems with deranged locale support).
#
# A "--" by itself is used as an escape, i.e., the next token on the
# command-line is not treated as an option, as in:
# dialog --title -- --Not an option
def _dash_escape(args):
"""Escape all elements of 'args' that need escaping.
'args' may be any sequence and is not modified by this function.
Return a new list where every element that needs escaping has
been escaped.
An element needs escaping when it starts with two ASCII hyphens
('--'). Escaping consists in prepending an element composed of
two ASCII hyphens, i.e., the string '--'.
"""
res = []
for arg in args:
if arg.startswith("--"):
res.extend(("--", arg))
else:
res.append(arg)
return res
# We need this function in the global namespace for the lambda
# expressions in _common_args_syntax to see it when they are called.
def _dash_escape_nf(args): # nf: non-first
"""Escape all elements of 'args' that need escaping, except the first one.
See _dash_escape() for details. Return a new list.
"""
if not args:
raise PythonDialogBug("not a non-empty sequence: {0!r}".format(args))
l = _dash_escape(args[1:])
l.insert(0, args[0])
return l
def _simple_option(option, enable):
"""Turn on or off the simplest dialog Common Options."""
if enable:
return (option,)
else:
# This will not add any argument to the command line
return ()
# This dictionary allows us to write the dialog common options in a Pythonic
# way (e.g. dialog_instance.checklist(args, ..., title="Foo", no_shadow=True)).
#
# Options such as --separate-output should obviously not be set by the user
# since they affect the parsing of dialog's output:
_common_args_syntax = {
"ascii_lines": lambda enable: _simple_option("--ascii-lines", enable),
"aspect": lambda ratio: _dash_escape_nf(("--aspect", unicode(ratio))),
"backtitle": lambda backtitle: _dash_escape_nf(("--backtitle", backtitle)),
# Obsolete according to dialog(1)
"beep": lambda enable: _simple_option("--beep", enable),
# Obsolete according to dialog(1)
"beep_after": lambda enable: _simple_option("--beep-after", enable),
# Warning: order = y, x!
"begin": lambda coords: _dash_escape_nf(
("--begin", unicode(coords[0]), unicode(coords[1]))),
"cancel_label": lambda s: _dash_escape_nf(("--cancel-label", s)),
# Old, unfortunate choice of key, kept for backward compatibility
"cancel": lambda s: _dash_escape_nf(("--cancel-label", s)),
"clear": lambda enable: _simple_option("--clear", enable),
"colors": lambda enable: _simple_option("--colors", enable),
"column_separator": lambda s: _dash_escape_nf(("--column-separator", s)),
"cr_wrap": lambda enable: _simple_option("--cr-wrap", enable),
"create_rc": lambda filename: _dash_escape_nf(("--create-rc", filename)),
"date_format": lambda s: _dash_escape_nf(("--date-format", s)),
"defaultno": lambda enable: _simple_option("--defaultno", enable),
"default_button": lambda s: _dash_escape_nf(("--default-button", s)),
"default_item": lambda s: _dash_escape_nf(("--default-item", s)),
"exit_label": lambda s: _dash_escape_nf(("--exit-label", s)),
"extra_button": lambda enable: _simple_option("--extra-button", enable),
"extra_label": lambda s: _dash_escape_nf(("--extra-label", s)),
"help": lambda enable: _simple_option("--help", enable),
"help_button": lambda enable: _simple_option("--help-button", enable),
"help_label": lambda s: _dash_escape_nf(("--help-label", s)),
"help_status": lambda enable: _simple_option("--help-status", enable),
"help_tags": lambda enable: _simple_option("--help-tags", enable),
"hfile": lambda filename: _dash_escape_nf(("--hfile", filename)),
"hline": lambda s: _dash_escape_nf(("--hline", s)),
"ignore": lambda enable: _simple_option("--ignore", enable),
"insecure": lambda enable: _simple_option("--insecure", enable),
"item_help": lambda enable: _simple_option("--item-help", enable),
"keep_tite": lambda enable: _simple_option("--keep-tite", enable),
"keep_window": lambda enable: _simple_option("--keep-window", enable),
"max_input": lambda size: _dash_escape_nf(("--max-input", unicode(size))),
"no_cancel": lambda enable: _simple_option("--no-cancel", enable),
"nocancel": lambda enable: _simple_option("--nocancel", enable),
"no_collapse": lambda enable: _simple_option("--no-collapse", enable),
"no_kill": lambda enable: _simple_option("--no-kill", enable),
"no_label": lambda s: _dash_escape_nf(("--no-label", s)),
"no_lines": lambda enable: _simple_option("--no-lines", enable),
"no_mouse": lambda enable: _simple_option("--no-mouse", enable),
"no_nl_expand": lambda enable: _simple_option("--no-nl-expand", enable),
"no_ok": lambda enable: _simple_option("--no-ok", enable),
"no_shadow": lambda enable: _simple_option("--no-shadow", enable),
"no_tags": lambda enable: _simple_option("--no-tags", enable),
"ok_label": lambda s: _dash_escape_nf(("--ok-label", s)),
# cf. Dialog.maxsize()
"print_maxsize": lambda enable: _simple_option("--print-maxsize",
enable),
"print_size": lambda enable: _simple_option("--print-size", enable),
# cf. Dialog.backend_version()
"print_version": lambda enable: _simple_option("--print-version",
enable),
"scrollbar": lambda enable: _simple_option("--scrollbar", enable),
"separate_output": lambda enable: _simple_option("--separate-output",
enable),
"separate_widget": lambda s: _dash_escape_nf(("--separate-widget", s)),
"shadow": lambda enable: _simple_option("--shadow", enable),
# Obsolete according to dialog(1)
"size_err": lambda enable: _simple_option("--size-err", enable),
"sleep": lambda secs: _dash_escape_nf(("--sleep", unicode(secs))),
"stderr": lambda enable: _simple_option("--stderr", enable),
"stdout": lambda enable: _simple_option("--stdout", enable),
"tab_correct": lambda enable: _simple_option("--tab-correct", enable),
"tab_len": lambda n: _dash_escape_nf(("--tab-len", unicode(n))),
"time_format": lambda s: _dash_escape_nf(("--time-format", s)),
"timeout": lambda secs: _dash_escape_nf(("--timeout", unicode(secs))),
"title": lambda title: _dash_escape_nf(("--title", title)),
"trace": lambda filename: _dash_escape_nf(("--trace", filename)),
"trim": lambda enable: _simple_option("--trim", enable),
"version": lambda enable: _simple_option("--version", enable),
"visit_items": lambda enable: _simple_option("--visit-items", enable),
"yes_label": lambda s: _dash_escape_nf(("--yes-label", s)) }
def _find_in_path(prog_name):
"""Search an executable in the PATH.
If PATH is not defined, the default path ":/bin:/usr/bin" is
used.
Return a path to the file or None if no readable and executable
file is found.
Notable exception: PythonDialogOSError
"""
with _OSErrorHandling():
# Note that the leading empty component in the default value for PATH
# could lead to the returned path not being absolute.
PATH = os.getenv("PATH", ":/bin:/usr/bin") # see the execvp(3) man page
for d in PATH.split(":"):
file_path = os.path.join(d, prog_name)
if os.path.isfile(file_path) \
and os.access(file_path, os.R_OK | os.X_OK):
return file_path
return None
def _path_to_executable(f):
"""Find a path to an executable.
Find a path to an executable, using the same rules as the POSIX
exec*p functions (see execvp(3) for instance).
If 'f' contains a '/', it is assumed to be a path and is simply
checked for read and write permissions; otherwise, it is looked
for according to the contents of the PATH environment variable,
which defaults to ":/bin:/usr/bin" if unset.
The returned path is not necessarily absolute.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
"""
with _OSErrorHandling():
if '/' in f:
if os.path.isfile(f) and \
os.access(f, os.R_OK | os.X_OK):
res = f
else:
raise ExecutableNotFound("%s cannot be read and executed" % f)
else:
res = _find_in_path(f)
if res is None:
raise ExecutableNotFound(
"can't find the executable for the dialog-like "
"program")
return res
def _to_onoff(val):
"""Convert boolean expressions to "on" or "off".
Return:
- "on" if 'val' is True, a non-zero integer, "on" or any case
variation thereof;
- "off" if 'val' is False, 0, "off" or any case variation thereof.
Notable exceptions:
PythonDialogReModuleError
BadPythonDialogUsage
"""
if isinstance(val, (bool, int)):
return "on" if val else "off"
elif isinstance(val, basestring):
try:
if _on_cre.match(val):
return "on"
elif _off_cre.match(val):
return "off"
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
raise BadPythonDialogUsage("invalid boolean value: {0!r}".format(val))
def _compute_common_args(mapping):
"""Compute the list of arguments for dialog common options.
Compute a list of the command-line arguments to pass to dialog
from a keyword arguments dictionary for options listed as "common
options" in the manual page for dialog. These are the options
that are not tied to a particular widget.
This allows to specify these options in a pythonic way, such as:
d.checklist(<usual arguments for a checklist>,
title="...",
backtitle="...")
instead of having to pass them with strings like "--title foo" or
"--backtitle bar".
Notable exceptions: None
"""
args = []
for option, value in mapping.items():
args.extend(_common_args_syntax[option](value))
return args
def _create_temporary_directory():
"""Create a temporary directory (securely).
Return the directory path.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogOSError
- exceptions raised by the tempfile module
"""
find_temporary_nb_attempts = 5
for i in xrange(find_temporary_nb_attempts):
with _OSErrorHandling():
tmp_dir = os.path.join(tempfile.gettempdir(),
"%s-%d" \
% ("pythondialog",
random.randint(0, sys.maxsize)))
try:
os.mkdir(tmp_dir, 0700)
except os.error:
continue
else:
break
else:
raise UnableToCreateTemporaryDirectory(
"somebody may be trying to attack us")
return tmp_dir
# Classes for dealing with the version of dialog-like backend programs
if sys.hexversion >= 0x030200F0:
import abc
# Abstract base class
class BackendVersion():
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __unicode__(self):
raise NotImplementedError()
if sys.hexversion >= 0x030300F0:
@classmethod
@abc.abstractmethod
def fromstring(cls, s):
raise NotImplementedError()
else: # for Python 3.2
@abc.abstractclassmethod
def fromstring(cls, s):
raise NotImplementedError()
@abc.abstractmethod
def __lt__(self, other):
raise NotImplementedError()
@abc.abstractmethod
def __le__(self, other):
raise NotImplementedError()
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError()
@abc.abstractmethod
def __ne__(self, other):
raise NotImplementedError()
@abc.abstractmethod
def __gt__(self, other):
raise NotImplementedError()
@abc.abstractmethod
def __ge__(self, other):
raise NotImplementedError()
else:
class BackendVersion(object):
pass
class DialogBackendVersion(BackendVersion):
"""Class representing possible versions of the dialog backend.
The purpose of this class is to make it easy to reliably compare
between versions of the dialog backend. It encapsulates the
specific details of the backend versioning scheme to allow
eventual adaptations to changes in this scheme without affecting
external code.
The version is represented by two components in this class: the
"dotted part" and the "rest". For instance, in the '1.2' version
string, the dotted part is [1, 2] and the rest is the empty
string. However, in version '1.2-20130902', the dotted part is
still [1, 2], but the rest is the string '-20130902'.
Instances of this class can be created with the constructor by
specifying the dotted part and the rest. Alternatively, an
instance can be created from the corresponding version string
(e.g., '1.2-20130902') using the fromstring() class method. This
is particularly useful with the result of d.backend_version(),
where 'd' is a Dialog instance. Actually, the main constructor
detects if its first argument is a string and calls fromstring()
in this case as a convenience. Therefore, all of the following
expressions are valid to create a DialogBackendVersion instance:
DialogBackendVersion([1, 2])
DialogBackendVersion([1, 2], "-20130902")
DialogBackendVersion("1.2-20130902")
DialogBackendVersion.fromstring("1.2-20130902")
If 'bv' is a DialogBackendVersion instance, unicode(bv) is a string
representing the same version (for instance, "1.2-20130902").
Two DialogBackendVersion instances can be compared with the usual
comparison operators (<, <=, ==, !=, >=, >). The algorithm is
designed so that the following order is respected (after
instanciation with fromstring()):
1.2 < 1.2-20130902 < 1.2-20130903 < 1.2.0 < 1.2.0-20130902
among other cases. Actually, the "dotted parts" are the primary
keys when comparing and "rest" strings act as secondary keys.
Dotted parts are compared with the standard Python list
comparison and "rest" strings using the standard Python string
comparison.
"""
try:
_backend_version_cre = re.compile(r"""(?P<dotted> (\d+) (\.\d+)* )
(?P<rest>.*)$""", re.VERBOSE)
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
def __init__(self, dotted_part_or_str, rest=""):
"""Create a DialogBackendVersion instance.
Please see the class docstring for details.
"""
if isinstance(dotted_part_or_str, basestring):
if rest:
raise BadPythonDialogUsage(
"non-empty 'rest' with 'dotted_part_or_str' as string: "
"{0!r}".format(rest))
else:
tmp = self.__class__.fromstring(dotted_part_or_str)
dotted_part_or_str, rest = tmp.dotted_part, tmp.rest
for elt in dotted_part_or_str:
if not isinstance(elt, int):
raise BadPythonDialogUsage(
"when 'dotted_part_or_str' is not a string, it must "
"be a sequence (or iterable) of integers; however, "
"{0!r} is not an integer.".format(elt))
self.dotted_part = list(dotted_part_or_str)
self.rest = rest
def __repr__(self):
# Unicode strings are not supported as the result of __repr__()
# in Python 2.x (cf. <http://bugs.python.org/issue5876>).
return b"{0}.{1}({2!r}, rest={3!r})".format(
__name__, self.__class__.__name__, self.dotted_part, self.rest)
def __unicode__(self):
return '.'.join(imap(unicode, self.dotted_part)) + self.rest
@classmethod
def fromstring(cls, s):
try:
mo = cls._backend_version_cre.match(s)
if not mo:
raise UnableToParseDialogBackendVersion(s)
dotted_part = [ int(x) for x in mo.group("dotted").split(".") ]
rest = mo.group("rest")
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
return cls(dotted_part, rest)
def __lt__(self, other):
return (self.dotted_part, self.rest) < (other.dotted_part, other.rest)
def __le__(self, other):
return (self.dotted_part, self.rest) <= (other.dotted_part, other.rest)
def __eq__(self, other):
return (self.dotted_part, self.rest) == (other.dotted_part, other.rest)
# Python 3.2 has a decorator (functools.total_ordering) to automate this.
def __ne__(self, other):
return not (self == other)
def __gt__(self, other):
return not (self <= other)
def __ge__(self, other):
return not (self < other)
def widget(func):
"""Decorator to mark Dialog methods that provide widgets.
This allows code to perform automatic operations on these
specific methods. For instance, one can define a class that
behaves similarly to Dialog, except that after every
widget-producing call, it spawns a "confirm quit" dialog if the
widget returned Dialog.ESC, and loops in case the user doesn't
actually want to quit.
When it is unclear whether a method should have the decorator or
not, the return value is used to draw the line. For instance,
among 'gauge_start', 'gauge_update' and 'gauge_stop', only the
last one has the decorator because it returns a Dialog exit code,
whereas the first two don't return anything meaningful.
Note:
Some widget-producing methods return the Dialog exit code, but
other methods return a *sequence*, the first element of which
is the Dialog exit code; the 'retval_is_code' attribute, which
is set by the decorator of the same name, allows to
programmatically discover the interface a given method conforms
to.
"""
func.is_widget = True
return func
def retval_is_code(func):
"""Decorator for Dialog widget-producing methods whose return value is \
the Dialog exit code.
This decorator is intended for widget-producing methods whose
return value consists solely of the Dialog exit code. When this
decorator is *not* used on a widget-producing method, the Dialog
exit code must be the first element of the return value.
"""
func.retval_is_code = True
return func
def _obsolete_property(name, replacement=None):
if replacement is None:
replacement = name
def getter(self):
warnings.warn("the DIALOG_{name} attribute of Dialog instances is "
"obsolete; use the Dialog.{repl} class attribute "
"instead.".format(name=name, repl=replacement),
DeprecationWarning)
return getattr(self, replacement)
return getter
# Main class of the module
class Dialog(object):
"""Class providing bindings for dialog-compatible programs.
This class allows you to invoke dialog or a compatible program in
a pythonic way to build quicky and easily simple but nice text
interfaces.
An application typically creates one instance of the Dialog class
and uses it for all its widgets, but it is possible to
concurrently use several instances of this class with different
parameters (such as the background title) if you have a need
for this.
Public methods of the Dialog class (mainly widgets)
===================================================
The Dialog class has the following methods that produce or update
widgets:
buildlist
calendar
checklist
dselect
editbox
form
fselect
gauge_start
gauge_update
gauge_stop
infobox
inputbox
inputmenu
menu
mixedform
mixedgauge
msgbox
passwordbox
passwordform
pause
programbox
progressbox
radiolist
rangebox
scrollbox
tailbox
textbox
timebox
treeview
yesno
All these widgets are described in the docstrings of the
corresponding Dialog methods. Many of these descriptions are
adapted from the dialog(1) manual page, with the kind permission
of Thomas Dickey.
The Dialog class also has a few other methods, that are not
related to a particular widget:
add_persistent_args
backend_version (see "Checking the backend version" below)
maxsize
set_background_title
clear (has been OBSOLETE for many years!)
setBackgroundTitle (has been OBSOLETE for many years!)
Passing dialog "Common Options"
===============================
Every widget method has a **kwargs argument allowing you to pass
dialog so-called Common Options (see the dialog(1) manual page)
to dialog for this widget call. For instance, if 'd' is a Dialog
instance, you can write:
d.checklist(args, ..., title="A Great Title", no_shadow=True)
The no_shadow option is worth looking at:
1. It is an option that takes no argument as far as dialog is
concerned (unlike the "--title" option, for instance). When
you list it as a keyword argument, the option is really
passed to dialog only if the value you gave it evaluates to
True in a boolean context. For instance, "no_shadow=True"
will cause "--no-shadow" to be passed to dialog whereas
"no_shadow=False" will cause this option not to be passed to
dialog at all.
2. It is an option that has a hyphen (-) in its name, which you
must change into an underscore (_) to pass it as a Python
keyword argument. Therefore, "--no-shadow" is passed by
giving a "no_shadow=True" keyword argument to a Dialog method
(the leading two dashes are also consistently removed).
Return value of widget-producing methods
========================================
Most Dialog methods that create a widget (actually: all methods
that supervise the exit of a widget) return a value which fits
into one of these categories:
1. The return value is a Dialog exit code (see below).
2. The return value is a sequence whose first element is a
Dialog exit code (the rest of the sequence being related to
what the user entered in the widget).
"Dialog exit code" (high-level)
-------------------------------
A Dialog exit code is a string such as "ok", "cancel", "esc",
"help" and "extra", respectively available as Dialog.OK,
Dialog.CANCEL, Dialog.ESC, Dialog.HELP and Dialog.EXTRA, i.e.
attributes of the Dialog class. These are the standard Dialog
exit codes, also known as "high-level exit codes", that user code
should deal with. They indicate how/why the widget ended. Some
widgets may return additional, non-standard exit codes; for
instance, the inputmenu widget may return "accepted" or "renamed"
in addition to the standard Dialog exit codes.
When getting a Dialog exit code from a widget-producing method,
user code should compare it with Dialog.OK and friends (or
equivalently, with "ok" and friends) using the == operator. This
allows to easily replace Dialog.OK and friends with objects that
compare the same with "ok" and u"ok" in Python 2, for instance.
"dialog exit status" (low-level)
--------------------------------
The standard Dialog exit codes are derived from the dialog exit
status, also known as "low-level exit code". This low-level exit
code is an integer returned by the dialog backend whose different
possible values are referred to as DIALOG_OK, DIALOG_CANCEL,
DIALOG_ESC, DIALOG_ERROR, DIALOG_EXTRA, DIALOG_HELP and
DIALOG_ITEM_HELP in the dialog(1) manual page. Note that:
- DIALOG_HELP and DIALOG_ITEM_HELP both map to Dialog.HELP in
pythondialog, because they both correspond to the same user
action and the difference brings no information that the
caller does not already have;
- DIALOG_ERROR has no counterpart as a Dialog attribute,
because it is automatically translated into a DialogError
exception when received.
In pythondialog 2.x, the low-level exit codes were available
as the DIALOG_OK, DIALOG_CANCEL, etc. attributes of Dialog
instances. For compatibility, the Dialog class has attributes of
the same names mapped to Dialog.OK, Dialog.CANCEL, etc., but
their use is deprecated as of pythondialog 3.0.
Adding a Extra button
=====================
With most widgets, it is possible to add a supplementary button
called "Extra button". To do that, you simply have to use
'extra_button=True' (keyword argument) in the widget call.
By default, the button text is "Extra", but you can specify
another string with the 'extra_label' keyword argument.
When the widget exits, you know if the Extra button was pressed
if the Dialog exit code is Dialog.EXTRA ("extra"). Normally, the
rest of the return value is the same as if the widget had been
closed with OK. Therefore, if the widget normally returns a list
of three integers, for instance, you can expect to get the same
information if Extra is pressed instead of OK.
Providing on-line help facilities
=================================
With most dialog widgets, it is possible to provide online help
to the final user. At the time of this writing (October 2013),
there are three main options governing these help facilities in
the dialog backend: --help-button, --item-help and --help-status.
Since dialog 1.2-20130902, there is also --help-tags that
modifies the way --item-help works. As explained previously, to
use these options in pythondialog, you can pass the
'help_button', 'item_help', 'help_status' and 'help_tags' keyword
arguments to Dialog widget-producing methods.
Adding a Help button
--------------------
In order to provide a Help button in addition to the normal
buttons of a widget, you can pass help_button=True (keyword
argument) to the corresponding Dialog method. For instance, if
'd' is a Dialog instance, you can write:
code = d.yesno("<text>", height=10, width=40, help_button=True)
or
code, answer = d.inputbox("<text>", init="<init>",
help_button=True)
When the method returns, the exit code is Dialog.HELP (i.e., the
string "help") if the user pressed the Help button. Apart from
that, it works exactly as if 'help_button=True' had not been
used. In the last example, if the user presses the Help button,
'answer' will contain the user input, just as if OK had been
pressed. Similarly, if you write:
code, t = d.checklist(
"<text>", height=0, width=0, list_height=0,
choices=[ ("Tag 1", "Item 1", False),
("Tag 2", "Item 2", True),
("Tag 3", "Item 3", True) ],
help_button=True)
and find that code == Dialog.HELP, then 't' contains the tag
string for the highlighted item when the Help button was pressed.
Finally, note that it is possible to choose the text written on
the Help button by supplying a string as the 'help_label' keyword
argument.
Providing inline per-item help
------------------------------
In addition to, or instead of the Help button, you can provide
item-specific help that is normally displayed at the bottom of
the widget. This can be done by passing the 'item_help=True'
keyword argument to the widget-producing method and by including
the item-specific help strings in the appropriate argument.
For widgets where item-specific help makes sense (i.e., there are
several elements that can be highlighted), there is usually a
parameter, often called 'elements', 'choices', 'nodes'..., that
must be provided as a sequence describing the various
lines/items/nodes/... that can be highlighted in the widget. When
'item_help=True' is passed, every element of this sequence must
be completed with a string which is the item-help string of the
element (dialog(1) terminology). For instance, the following call
with no inline per-item help support:
code, t = d.checklist(
"<text>", height=0, width=0, list_height=0,
choices=[ ("Tag 1", "Item 1", False),
("Tag 2", "Item 2", True),
("Tag 3", "Item 3", True) ],
help_button=True)
can be altered this way to provide inline item-specific help:
code, t = d.checklist(
"<text>", height=0, width=0, list_height=0,
choices=[ ("Tag 1", "Item 1", False, "Help 1"),
("Tag 2", "Item 2", True, "Help 2"),
("Tag 3", "Item 3", True, "Help 3") ],
help_button=True, item_help=True, help_tags=True)
With this modification, the item-help string for the highlighted
item is displayed in the bottom line of the screen and updated as
the user highlights other items.
If you don't want a Help button, just use 'item_help=True'
without 'help_button=True' ('help_tags' doesn't matter). Then,
you have the inline help at the bottom of the screen, and the
following discussion about the return value can be ignored.
If the user chooses the Help button, 'code' will be equal to
Dialog.HELP ("help") and 't' will contain the tag string
corresponding to the highlighted item when the Help button was
pressed ("Tag 1/2/3" in the example). This is because of the
'help_tags' option; without it (or with 'help_tags=False'), 't'
would have contained the item-help string of the highlighted
choice ("Help 1/2/3" in the example).
If you remember what was said earlier, if 'item_help=True' had
not been used in the previous example, 't' would still contain
the tag of the highlighted choice if the user closed the widget
with the Help button. This is the same as when using
'item_help=True' in combination with 'help_tags=True'; however,
you would get the item-help string instead if 'help_tags' were
False (which is the default, as in the dialog backend, and in
order to preserve compatibility with the 'menu' implementation
that is several years old).
Therefore, I recommend for consistency to use 'help_tags=True'
whenever possible when specifying 'item_help=True'. This makes
"--help-tags" a good candidate for use with
Dialog.add_persistent_args() to avoid repeating it over and over.
However, there are two cases where 'help_tags=True' cannot be
used:
- when the version of the dialog backend is lower than
1.2-20130902 (the --help-tags option was added in this
version);
- when using empty or otherwise identical tags for presentation
purposes (unless you don't need to tell which element was
highlighted when the Help button was pressed, in which case
it doesn't matter to be unable to discriminate between the
tags).
Getting the widget status before the Help button was pressed
------------------------------------------------------------
Typically, when the user chooses Help in a widget, the
application will display a dialog box such as 'textbox', 'msgbox'
or 'scrollbox' and redisplay the original widget afterwards. For
simple widgets such as 'inputbox', when the Dialog exit code is
equal to Dialog.HELP, the return value contains enough
information to redisplay the widget in the same state it had when
Help was chosen. However, for more complex widgets such as
'radiolist', 'checklist', 'form' and its derivatives, knowing the
highlighted item is not enough to restore the widget state after
processing the help request: one needs to know the checked item /
list of checked items / form contents.
This is where the 'help_status' keyword argument becomes useful.
Example:
code, t = d.checklist(
"<text>", height=0, width=0, list_height=0,
choices=[ ("Tag 1", "Item 1", False),
("Tag 2", "Item 2", True),
("Tag 3", "Item 3", True) ],
help_button=True, help_status=True)
When Help is chosen, code == Dialog.HELP and 't' is a tuple of the
form (tag, selected_tags, choices) where:
- 'tag' gives the tag string of the highlighted item (which
would be the value of 't' if 'help_status' were set to
False);
- 'selected_tags' is the... list of selected tags (note that
highlighting and selecting an item are different things!);
- 'choices' is a list built from the original 'choices'
argument of the 'checklist' call and from the list of
selected tags, that can be used as is to create a widget with
the same items and selection state as the original widget had
when Help was chosen.
Normally, pythondialog should always provide something similar to
the last item in the previous example in order to make it as easy
as possible to redisplay the widget in the appropriate state. To
know precisely what is returned with 'help_status=True', the best
ways are usually to experiment or read the code (by the way,
there are many examples of widgets with various combinations of
'help_button', 'item_help' and 'help_status' in the demo).
As can be inferred from the last sentence, the various options
related to help support are not mutually exclusive and may be
used together to provide good help support.
It is also worth noting that the docstrings of the various
widgets are written, in most cases, under the assumption that the
widget was closed "normally" (typically, with the OK or Extra
button). For instance, a docstring may state that the method
returns a tuple of the form (code, tag) where 'tag' is ..., but
actually, if using 'item_help=True' with 'help_tags=False', the
'tag' may very well be an item-help string, and if using
'help_status=True', it is likely to be a structured object such
as a tuple or list. Of course, handling all these possible
variations for all widgets would be a tedious task and would
probably significantly degrade the readability of said
docstrings.
Checking the backend version
============================
The Dialog constructor retrieves the version string of the dialog
backend and stores it as an instance of a BackendVersion subclass
into the 'cached_backend_version' attribute. This allows doing
things such as ('d' being a Dialog instance):
if d.compat == "dialog" and \\
d.cached_backend_version >= DialogBackendVersion("1.2-20130902"):
...
in a reliable way, allowing to fix the parsing and comparison
algorithms right in the appropriate BackendVersion subclass,
should the dialog-like backend versioning scheme change in
unforeseen ways.
As Xdialog seems to be dead and not to support --print-version,
the 'cached_backend_version' attribute is set to None in
Xdialog-compatibility mode (2013-09-12). Should this ever change,
one should define an XDialogBackendVersion class to handle the
particularities of the Xdialog versioning scheme.
Exceptions
==========
Please refer to the specific methods' docstrings or simply to the
module's docstring for a list of all exceptions that might be
raised by this class' methods.
"""
try:
_print_maxsize_cre = re.compile(r"""^MaxSize:[ \t]+
(?P<rows>\d+),[ \t]*
(?P<columns>\d+)[ \t]*$""",
re.VERBOSE)
_print_version_cre = re.compile(
r"^Version:[ \t]+(?P<version>.+?)[ \t]*$", re.MULTILINE)
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
# DIALOG_OK, DIALOG_CANCEL, etc. are environment variables controlling
# the dialog backend exit status in the corresponding situation ("low-level
# exit status/code").
#
# Note:
# - 127 must not be used for any of the DIALOG_* values. It is used
# when a failure occurs in the child process before it exec()s
# dialog (where "before" includes a potential exec() failure).
# - 126 is also used (although in presumably rare situations).
_DIALOG_OK = 0
_DIALOG_CANCEL = 1
_DIALOG_ESC = 2
_DIALOG_ERROR = 3
_DIALOG_EXTRA = 4
_DIALOG_HELP = 5
_DIALOG_ITEM_HELP = 6
# cf. also _lowlevel_exit_codes and _dialog_exit_code_ll_to_hl which are
# created by __init__(). It is not practical to define everything here,
# because there is no equivalent of 'self' for the class outside method
# definitions.
_lowlevel_exit_code_varnames = frozenset(("OK", "CANCEL", "ESC", "ERROR",
"EXTRA", "HELP", "ITEM_HELP"))
# High-level exit codes, AKA "Dialog exit codes". These are the codes that
# pythondialog-based applications should use.
OK = "ok"
CANCEL = "cancel"
ESC = "esc"
EXTRA = "extra"
HELP = "help"
# Define properties to maintain backward-compatibility while warning about
# the obsolete attributes (which used to refer to the low-level exit codes
# in pythondialog 2.x).
DIALOG_OK = property(_obsolete_property("OK"),
doc="Obsolete property superseded by Dialog.OK")
DIALOG_CANCEL = property(_obsolete_property("CANCEL"),
doc="Obsolete property superseded by Dialog.CANCEL")
DIALOG_ESC = property(_obsolete_property("ESC"),
doc="Obsolete property superseded by Dialog.ESC")
DIALOG_EXTRA = property(_obsolete_property("EXTRA"),
doc="Obsolete property superseded by Dialog.EXTRA")
DIALOG_HELP = property(_obsolete_property("HELP"),
doc="Obsolete property superseded by Dialog.HELP")
# We treat DIALOG_ITEM_HELP and DIALOG_HELP the same way in pythondialog,
# since both indicate the same user action ("Help" button pressed).
DIALOG_ITEM_HELP = property(_obsolete_property("ITEM_HELP",
replacement="HELP"),
doc="Obsolete property superseded by Dialog.HELP")
@property
def DIALOG_ERROR(self):
warnings.warn("the DIALOG_ERROR attribute of Dialog instances is "
"obsolete. Since the corresponding exit status is "
"automatically translated into a DialogError exception, "
"users should not see nor need this attribute. If you "
"think you have a good reason to use it, please expose "
"your situation on the pythondialog mailing-list.",
DeprecationWarning)
# There is no corresponding high-level code; and if the user *really*
# wants to know the (integer) error exit status, here it is...
return self._DIALOG_ERROR
def __init__(self, dialog="dialog", DIALOGRC=None,
compat="dialog", use_stdout=None):
"""Constructor for Dialog instances.
dialog -- name of (or path to) the dialog-like program to
use; if it contains a '/', it is assumed to be
a path and is used as is; otherwise, it is
looked for according to the contents of the
PATH environment variable, which defaults to
":/bin:/usr/bin" if unset.
DIALOGRC -- string to pass to the dialog-like program as
the DIALOGRC environment variable, or None if
no modification to the environment regarding
this variable should be done in the call to the
dialog-like program
compat -- compatibility mode (see below)
use_stdout -- read dialog's standard output stream instead of
its standard error stream in order to get
most 'results' (user-supplied strings, etc.;
basically everything apart from the exit
status). This is for compatibility with Xdialog
and should only be used if you have a good
reason to do so.
The officially supported dialog-like program in pythondialog
is the well-known dialog program written in C, based on the
ncurses library. It is also known as cdialog and its home
page is currently (2013-08-12) located at:
http://invisible-island.net/dialog/dialog.html
If you want to use a different program such as Xdialog, you
should indicate the executable file name with the 'dialog'
argument *and* the compatibility type that you think it
conforms to with the 'compat' argument. Currently, 'compat'
can be either "dialog" (for dialog; this is the default) or
"Xdialog" (for, well, Xdialog).
The 'compat' argument allows me to cope with minor
differences in behaviour between the various programs
implementing the dialog interface (not the text or graphical
interface, I mean the "API"). However, having to support
various APIs simultaneously is ugly and I would really prefer
you to report bugs to the relevant maintainers when you find
incompatibilities with dialog. This is for the benefit of
pretty much everyone that relies on the dialog interface.
Notable exceptions:
ExecutableNotFound
PythonDialogOSError
UnableToRetrieveBackendVersion
UnableToParseBackendVersion
"""
# DIALOGRC differs from the Dialog._DIALOG_* attributes in that:
# 1. It is an instance attribute instead of a class attribute.
# 2. It should be a string if not None.
# 3. We may very well want it to be unset.
if DIALOGRC is not None:
self.DIALOGRC = DIALOGRC
# Mapping from "OK", "CANCEL", ... to the corresponding dialog exit
# statuses (integers).
self._lowlevel_exit_codes = dict((
name, getattr(self, "_DIALOG_" + name))
for name in self._lowlevel_exit_code_varnames)
# Mapping from dialog exit status (integer) to Dialog exit code ("ok",
# "cancel", ... strings referred to by Dialog.OK, Dialog.CANCEL, ...);
# in other words, from low-level to high-level exit code.
self._dialog_exit_code_ll_to_hl = {}
for name in self._lowlevel_exit_code_varnames:
intcode = self._lowlevel_exit_codes[name]
if name == "ITEM_HELP":
self._dialog_exit_code_ll_to_hl[intcode] = self.HELP
elif name == "ERROR":
continue
else:
self._dialog_exit_code_ll_to_hl[intcode] = getattr(self, name)
self._dialog_prg = _path_to_executable(dialog)
self.compat = compat
self.dialog_persistent_arglist = []
# Use stderr or stdout for reading dialog's output?
if self.compat == "Xdialog":
# Default to using stdout for Xdialog
self.use_stdout = True
else:
self.use_stdout = False
if use_stdout is not None:
# Allow explicit setting
self.use_stdout = use_stdout
if self.use_stdout:
self.add_persistent_args(["--stdout"])
self.setup_debug(False)
if compat == "dialog":
self.cached_backend_version = DialogBackendVersion.fromstring(
self.backend_version())
else:
# Xdialog doesn't seem to offer --print-version (2013-09-12)
self.cached_backend_version = None
@classmethod
def dash_escape(cls, args):
"""Escape all elements of 'args' that need escaping.
'args' may be any sequence and is not modified by this method.
Return a new list where every element that needs escaping has
been escaped.
An element needs escaping when it starts with two ASCII hyphens
('--'). Escaping consists in prepending an element composed of
two ASCII hyphens, i.e., the string '--'.
All high-level Dialog methods automatically perform dash
escaping where appropriate. In particular, this is the case
for every method that provides a widget: yesno(), msgbox(),
etc. You only need to do it yourself when calling a low-level
method such as add_persistent_args().
"""
return _dash_escape(args)
@classmethod
def dash_escape_nf(cls, args):
"""Escape all elements of 'args' that need escaping, except the first one.
See dash_escape() for details. Return a new list.
All high-level Dialog methods automatically perform dash
escaping where appropriate. In particular, this is the case
for every method that provides a widget: yesno(), msgbox(),
etc. You only need to do it yourself when calling a low-level
method such as add_persistent_args().
"""
return _dash_escape_nf(args)
def add_persistent_args(self, args):
"""Add arguments to use for every subsequent dialog call.
This method cannot guess which elements of 'args' are dialog
options (such as '--title') and which are not (for instance,
you might want to use '--title' or even '--' as an argument
to a dialog option). Therefore, this method does not perform
any kind of dash escaping; you have to do it yourself.
dash_escape() and dash_escape_nf() may be useful for this
purpose.
"""
self.dialog_persistent_arglist.extend(args)
def set_background_title(self, text):
"""Set the background title for dialog.
text -- string to use as the background title
"""
self.add_persistent_args(self.dash_escape_nf(("--backtitle", text)))
# For compatibility with the old dialog
def setBackgroundTitle(self, text):
"""Set the background title for dialog.
text -- string to use as the background title
This method is obsolete. Please remove calls to it from your
programs.
"""
warnings.warn("Dialog.setBackgroundTitle() has been obsolete for "
"many years; use Dialog.set_background_title() instead",
DeprecationWarning)
self.set_background_title(text)
def setup_debug(self, enable, file=None, always_flush=False):
"""Setup the debugging parameters.
When enabled, all dialog commands are written to 'file' using
Bourne shell syntax.
enable -- boolean indicating whether to enable or
disable debugging
file -- file object where to write debugging
information
always_flush -- boolean indicating whether to call
file.flush() after each command written
"""
self._debug_enabled = enable
if not hasattr(self, "_debug_logfile"):
self._debug_logfile = None
# Allows to switch debugging on and off without having to pass the file
# object again and again.
if file is not None:
self._debug_logfile = file
if enable and self._debug_logfile is None:
raise BadPythonDialogUsage(
"you must specify a file object when turning debugging on")
self._debug_always_flush = always_flush
self._debug_first_output = True
def _write_command_to_file(self, env, arglist):
envvar_settings_list = []
if "DIALOGRC" in env:
envvar_settings_list.append(
"DIALOGRC={0}".format(_shell_quote(env["DIALOGRC"])))
for var in self._lowlevel_exit_code_varnames:
varname = "DIALOG_" + var
envvar_settings_list.append(
"{0}={1}".format(varname, _shell_quote(env[varname])))
command_str = ' '.join(envvar_settings_list +
list(imap(_shell_quote, arglist)))
s = "{separator}{cmd}\n\nArgs: {args!r}\n".format(
separator="" if self._debug_first_output else ("-" * 79) + "\n",
cmd=command_str, args=arglist)
self._debug_logfile.write(s)
if self._debug_always_flush:
self._debug_logfile.flush()
self._debug_first_output = False
def _call_program(self, cmdargs, **kwargs):
"""Do the actual work of invoking the dialog-like program.
Communication with the dialog-like program is performed
through one pipe(2) and optionally a user-specified file
descriptor, depending on 'redir_child_stdin_from_fd'. The
pipe allows the parent process to read what dialog writes on
its standard error[*] stream.
If 'use_persistent_args' is True (the default), the elements
of self.dialog_persistent_arglist are passed as the first
arguments to self._dialog_prg; otherwise,
self.dialog_persistent_arglist is not used at all. The
remaining arguments are those computed from kwargs followed
by the elements of 'cmdargs'.
If 'dash_escape' is the string "non-first", then every
element of 'cmdargs' that starts with '--' is escaped by
prepending an element consisting of '--', except the first
one (which is usually a dialog option such as '--yesno').
In order to disable this escaping mechanism, pass the string
"none" as 'dash_escape'.
If 'redir_child_stdin_from_fd' is not None, it should be an
open file descriptor (i.e., an integer). That file descriptor
will be connected to dialog's standard input. This is used by
the gauge widget to feed data to dialog, as well as for
progressbox() to allow dialog to read data from a
possibly-growing file.
If 'redir_child_stdin_from_fd' is None, the standard input in
the child process (which runs dialog) is not redirected in
any way.
If 'close_fds' is passed, it should be a sequence of
file descriptors that will be closed by the child process
before it exec()s the dialog-like program.
[*] standard ouput stream with 'use_stdout'
Notable exception: PythonDialogOSError (if any of the pipe(2)
or close(2) system calls fails...)
"""
if 'close_fds' in kwargs: close_fds = kwargs['close_fds']; del kwargs['close_fds']
else: close_fds = ()
if 'redir_child_stdin_from_fd' in kwargs: redir_child_stdin_from_fd = kwargs['redir_child_stdin_from_fd']; del kwargs['redir_child_stdin_from_fd']
else: redir_child_stdin_from_fd = None
if 'use_persistent_args' in kwargs: use_persistent_args = kwargs['use_persistent_args']; del kwargs['use_persistent_args']
else: use_persistent_args = True
if 'dash_escape' in kwargs: dash_escape = kwargs['dash_escape']; del kwargs['dash_escape']
else: dash_escape = "non-first"
# We want to define DIALOG_OK, DIALOG_CANCEL, etc. in the
# environment of the child process so that we know (and
# even control) the possible dialog exit statuses.
new_environ = {}
new_environ.update(os.environ)
for var, value in self._lowlevel_exit_codes.items():
varname = "DIALOG_" + var
new_environ[varname] = unicode(value)
if hasattr(self, "DIALOGRC"):
new_environ["DIALOGRC"] = self.DIALOGRC
if dash_escape == "non-first":
# Escape all elements of 'cmdargs' that start with '--', except the
# first one.
cmdargs = self.dash_escape_nf(cmdargs)
elif dash_escape != "none":
raise PythonDialogBug("invalid value for 'dash_escape' parameter: "
"{0!r}".format(dash_escape))
arglist = [ self._dialog_prg ]
if use_persistent_args:
arglist.extend(self.dialog_persistent_arglist)
arglist.extend(_compute_common_args(kwargs) + cmdargs)
if self._debug_enabled:
# Write the complete command line with environment variables
# setting to the debug log file (Bourne shell syntax for easy
# copy-pasting into a terminal, followed by repr(arglist)).
self._write_command_to_file(new_environ, arglist)
# Create a pipe so that the parent process can read dialog's
# output on stderr (stdout with 'use_stdout')
with _OSErrorHandling():
# rfd = File Descriptor for Reading
# wfd = File Descriptor for Writing
(child_output_rfd, child_output_wfd) = os.pipe()
child_pid = os.fork()
if child_pid == 0:
# We are in the child process. We MUST NOT raise any exception.
try:
# 1) If the write end of a pipe isn't closed, the read end
# will never see EOF, which can indefinitely block the
# child waiting for input. To avoid this, the write end
# must be closed in the father *and* child processes.
# 2) The child process doesn't need child_output_rfd.
for fd in close_fds + (child_output_rfd,):
os.close(fd)
# We want:
# - to keep a reference to the father's stderr for error
# reporting (and use line-buffering for this stream);
# - dialog's output on stderr[*] to go to child_output_wfd;
# - data written to fd 'redir_child_stdin_from_fd'
# (if not None) to go to dialog's stdin.
#
# [*] stdout with 'use_stdout'
#
# We'll just print the result of traceback.format_exc() to
# father_stderr, which is a byte string in Python 2, hence the
# binary mode.
father_stderr = open(os.dup(2), mode="wb")
os.dup2(child_output_wfd, 1 if self.use_stdout else 2)
if redir_child_stdin_from_fd is not None:
os.dup2(redir_child_stdin_from_fd, 0)
os.execve(self._dialog_prg, arglist, new_environ)
except:
print(traceback.format_exc(), file=father_stderr)
father_stderr.close()
os._exit(127)
# Should not happen unless there is a bug in Python
os._exit(126)
# We are in the father process.
#
# It is essential to close child_output_wfd, otherwise we will never
# see EOF while reading on child_output_rfd and the parent process
# will block forever on the read() call.
# [ after the fork(), the "reference count" of child_output_wfd from
# the operating system's point of view is 2; after the child exits,
# it is 1 until the father closes it itself; then it is 0 and a read
# on child_output_rfd encounters EOF once all the remaining data in
# the pipe has been read. ]
with _OSErrorHandling():
os.close(child_output_wfd)
return (child_pid, child_output_rfd)
def _wait_for_program_termination(self, child_pid, child_output_rfd):
"""Wait for a dialog-like process to terminate.
This function waits for the specified process to terminate,
raises the appropriate exceptions in case of abnormal
termination and returns the Dialog exit code (high-level) and
stderr[*] output of the process as a tuple:
(hl_exit_code, output_string).
'child_output_rfd' must be the file descriptor for the
reading end of the pipe created by self._call_program(), the
writing end of which was connected by self._call_program()
to the child process's standard error[*].
This function reads the process' output on standard error[*]
from 'child_output_rfd' and closes this file descriptor once
this is done.
[*] actually, standard output if self.use_stdout is True
Notable exceptions:
DialogTerminatedBySignal
DialogError
PythonDialogErrorBeforeExecInChildProcess
PythonDialogIOError if the Python version is < 3.3
PythonDialogOSError
PythonDialogBug
ProbablyPythonBug
"""
# Read dialog's output on its stderr (stdout with 'use_stdout')
with _OSErrorHandling():
with open(child_output_rfd, "r") as f:
child_output = f.read()
# The closing of the file object causes the end of the pipe we used
# to read dialog's output on its stderr to be closed too. This is
# important, otherwise invoking dialog enough times would
# eventually exhaust the maximum number of open file descriptors.
exit_info = os.waitpid(child_pid, 0)[1]
if os.WIFEXITED(exit_info):
ll_exit_code = os.WEXITSTATUS(exit_info)
# As we wait()ed for the child process to terminate, there is no
# need to call os.WIFSTOPPED()
elif os.WIFSIGNALED(exit_info):
raise DialogTerminatedBySignal("the dialog-like program was "
"terminated by signal %d" %
os.WTERMSIG(exit_info))
else:
raise PythonDialogBug("please report this bug to the "
"pythondialog maintainer(s)")
if ll_exit_code == self._DIALOG_ERROR:
raise DialogError(
"the dialog-like program exited with status {0} (which was "
"passed to it as the DIALOG_ERROR environment variable). "
"Sometimes, the reason is simply that dialog was given a "
"height or width parameter that is too big for the terminal "
"in use. Its output, with leading and trailing whitespace "
"stripped, was:\n\n{1}".format(ll_exit_code,
child_output.strip()))
elif ll_exit_code == 127:
raise PythonDialogErrorBeforeExecInChildProcess(dedent("""\
possible reasons include:
- the dialog-like program could not be executed (this can happen
for instance if the Python program is trying to call the
dialog-like program with arguments that cannot be represented
in the user's locale [LC_CTYPE]);
- the system is out of memory;
- the maximum number of open file descriptors has been reached;
- a cosmic ray hit the system memory and flipped nasty bits.
There ought to be a traceback above this message that describes
more precisely what happened."""))
elif ll_exit_code == 126:
raise ProbablyPythonBug(
"a child process returned with exit status 126; this might "
"be the exit status of the dialog-like program, for some "
"unknown reason (-> probably a bug in the dialog-like "
"program); otherwise, we have probably found a python bug")
try:
hl_exit_code = self._dialog_exit_code_ll_to_hl[ll_exit_code]
except KeyError:
raise PythonDialogBug(
"unexpected low-level exit status (new code?): {0!r}".format(
ll_exit_code))
return (hl_exit_code, child_output)
def _perform(self, cmdargs, **kwargs):
"""Perform a complete dialog-like program invocation.
This function invokes the dialog-like program, waits for its
termination and returns the appropriate Dialog exit code
(high-level) along with whatever output it produced.
See _call_program() for a description of the parameters.
Notable exceptions:
any exception raised by self._call_program() or
self._wait_for_program_termination()
"""
if 'use_persistent_args' in kwargs: use_persistent_args = kwargs['use_persistent_args']; del kwargs['use_persistent_args']
else: use_persistent_args = True
if 'dash_escape' in kwargs: dash_escape = kwargs['dash_escape']; del kwargs['dash_escape']
else: dash_escape = "non-first"
(child_pid, child_output_rfd) = \
self._call_program(cmdargs, dash_escape=dash_escape,
use_persistent_args=use_persistent_args,
**kwargs)
(exit_code, output) = \
self._wait_for_program_termination(child_pid,
child_output_rfd)
return (exit_code, output)
def _strip_xdialog_newline(self, output):
"""Remove trailing newline (if any) in Xdialog compatibility mode"""
if self.compat == "Xdialog" and output.endswith("\n"):
output = output[:-1]
return output
# This is for compatibility with the old dialog.py
def _perform_no_options(self, cmd):
"""Call dialog without passing any more options."""
warnings.warn("Dialog._perform_no_options() has been obsolete for "
"many years", DeprecationWarning)
return os.system(self._dialog_prg + ' ' + cmd)
# For compatibility with the old dialog.py
def clear(self):
"""Clear the screen. Equivalent to the dialog --clear option.
This method is obsolete. Please remove calls to it from your
programs. You may use the clear(1) program to clear the screen.
cf. clear_screen() in demo.py for an example.
"""
warnings.warn("Dialog.clear() has been obsolete for many years.\n"
"You may use the clear(1) program to clear the screen.\n"
"cf. clear_screen() in demo.py for an example",
DeprecationWarning)
self._perform_no_options('--clear')
def _help_status_on(self, kwargs):
return ("--help-status" in self.dialog_persistent_arglist
or kwargs.get("help_status", False))
def _parse_quoted_string(self, s, start=0):
"""Parse a quoted string from a dialog help output."""
if start >= len(s) or s[start] != '"':
raise PythonDialogBug("quoted string does not start with a double "
"quote: {0!r}".format(s))
l = []
i = start + 1
while i < len(s) and s[i] != '"':
if s[i] == "\\":
i += 1
if i >= len(s):
raise PythonDialogBug(
"quoted string ends with a backslash: {0!r}".format(s))
l.append(s[i])
i += 1
if s[i] != '"':
raise PythonDialogBug("quoted string does not and with a double "
"quote: {0!r}".format(s))
return (''.join(l), i+1)
def _split_shellstyle_arglist(self, s):
"""Split an argument list with shell-style quoting performed by dialog.
Any argument in 's' may or may not be quoted. Quoted
arguments are always expected to be enclosed in double quotes
(more restrictive than what the POSIX shell allows).
This function could maybe be replaced with shlex.split(),
however:
- shlex only handles Unicode strings in Python 2.7.3 and
above;
- the bulk of the work is done by _parse_quoted_string(),
which is probably still needed in _parse_help(), where
one needs to parse things such as 'HELP <id> <status>' in
which <id> may be quoted but <status> is never quoted,
even if it contains spaces or quotes.
"""
s = s.rstrip()
l = []
i = 0
while i < len(s):
if s[i] == '"':
arg, i = self._parse_quoted_string(s, start=i)
if i < len(s) and s[i] != ' ':
raise PythonDialogBug(
"expected a space or end-of-string after quoted "
"string in {0!r}, but found {1!r}".format(s, s[i]))
# Start of the next argument, or after the end of the string
i += 1
l.append(arg)
else:
try:
end = s.index(' ', i)
except ValueError:
end = len(s)
l.append(s[i:end])
# Start of the next argument, or after the end of the string
i = end + 1
return l
def _parse_help(self, output, kwargs, **_3to2kwargs):
"""Parse the dialog help output from a widget.
'kwargs' should contain the keyword arguments used in the
widget call that produced the help output.
'multival' is for widgets that return a list of values as
opposed to a single value.
'raw_format' is for widgets that don't start their help
output with the string "HELP ".
"""
if 'raw_format' in _3to2kwargs: raw_format = _3to2kwargs['raw_format']; del _3to2kwargs['raw_format']
else: raw_format = False
if 'multival_on_single_line' in _3to2kwargs: multival_on_single_line = _3to2kwargs['multival_on_single_line']; del _3to2kwargs['multival_on_single_line']
else: multival_on_single_line = False
if 'multival' in _3to2kwargs: multival = _3to2kwargs['multival']; del _3to2kwargs['multival']
else: multival = False
l = output.splitlines()
if raw_format:
# This format of the help output is either empty or consists of
# only one line (possibly terminated with \n). It is
# encountered with --calendar and --inputbox, among others.
if len(l) > 1:
raise PythonDialogBug("raw help feedback unexpected as "
"multiline: {0!r}".format(output))
elif len(l) == 0:
return ""
else:
return l[0]
# Simple widgets such as 'yesno' will fall in this case if they use
# this method.
if not l:
return None
# The widgets that actually use --help-status always have the first
# help line indicating the active item; there is no risk of
# confusing this line with the first line produced by --help-status.
if not l[0].startswith("HELP "):
raise PythonDialogBug(
"unexpected help output that does not start with 'HELP ': "
"{0!r}".format(output))
# Everything that follows "HELP "; what it contains depends on whether
# --item-help and/or --help-tags were passed to dialog.
s = l[0][5:]
if not self._help_status_on(kwargs):
return s
if multival:
if multival_on_single_line:
args = self._split_shellstyle_arglist(s)
if not args:
raise PythonDialogBug(
"expected a non-empty space-separated list of "
"possibly-quoted strings in this help output: {0!r}"
.format(output))
return (args[0], args[1:])
else:
return (s, l[1:])
else:
if not s:
raise PythonDialogBug(
"unexpected help output whose first line is 'HELP '")
elif s[0] != '"':
l2 = s.split(' ', 1)
if len(l2) == 1:
raise PythonDialogBug(
"expected 'HELP <id> <status>' in the help output, "
"but couldn't find any space after 'HELP '")
else:
return tuple(l2)
else:
help_id, after_index = self._parse_quoted_string(s)
if not s[after_index:].startswith(" "):
raise PythonDialogBug(
"expected 'HELP <quoted_id> <status>' in the help "
"output, but couldn't find any space after "
"'HELP <quoted_id>'")
return (help_id, s[after_index+1:])
def _widget_with_string_output(self, args, kwargs,
strip_xdialog_newline=False,
raw_help=False):
"""Generic implementation for a widget that produces a single string.
The help output must be present regardless of whether
--help-status was passed or not.
"""
code, output = self._perform(args, **kwargs)
if strip_xdialog_newline:
output = self._strip_xdialog_newline(output)
if code == self.HELP:
# No check for --help-status
help_data = self._parse_help(output, kwargs, raw_format=raw_help)
return (code, help_data)
else:
return (code, output)
def _widget_with_no_output(self, widget_name, args, kwargs):
"""Generic implementation for a widget that produces no output."""
code, output = self._perform(args, **kwargs)
if output:
raise PythonDialogBug(
"expected an empty output from {0!r}, but got: {1!r}".format(
widget_name, output))
return code
def _dialog_version_check(self, version_string, feature):
if self.compat == "dialog":
minimum_version = DialogBackendVersion.fromstring(version_string)
if self.cached_backend_version < minimum_version:
raise InadequateBackendVersion(
"the programbox widget requires dialog {0} or later, "
"but you seem to be using version {1}".format(
minimum_version, self.cached_backend_version))
def backend_version(self):
"""Get the version of the dialog-like program (backend).
If the version of the dialog-like program can be retrieved,
return it as a string; otherwise, raise
UnableToRetrieveBackendVersion.
This version is not to be confused with the pythondialog
version.
In most cases, you should rather use the
'cached_backend_version' attribute of Dialog instances,
because:
- it avoids calling the backend every time one needs the
version;
- it is a BackendVersion instance (or instance of a
subclass) that allows easy and reliable comparisons
between versions;
- the version string corresponding to a BackendVersion
instance (or instance of a subclass) can be obtained with
unicode().
Notable exceptions:
UnableToRetrieveBackendVersion
PythonDialogReModuleError
any exception raised by self._perform()
"""
code, output = self._perform(["--print-version"],
use_persistent_args=False)
if code == self.OK:
try:
mo = self._print_version_cre.match(output)
if mo:
return mo.group("version")
else:
raise UnableToRetrieveBackendVersion(
"unable to parse the output of '{0} --print-version': "
"{1!r}".format(self._dialog_prg, output))
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
else:
raise UnableToRetrieveBackendVersion(
"exit code {0!r} from the backend".format(code))
def maxsize(self, **kwargs):
"""Get the maximum size of dialog boxes.
If the exit code from the backend is self.OK, return a
(lines, cols) tuple of integers; otherwise, return None.
If you want to obtain the number of lines and columns of the
terminal, you should call this method with
use_persistent_args=False, because arguments such as
--backtitle modify the values returned.
Notable exceptions:
PythonDialogReModuleError
any exception raised by self._perform()
"""
code, output = self._perform(["--print-maxsize"], **kwargs)
if code == self.OK:
try:
mo = self._print_maxsize_cre.match(output)
if mo:
return tuple(imap(int, mo.group("rows", "columns")))
else:
raise PythonDialogBug(
"Unable to parse the output of '{0} --print-maxsize': "
"{1!r}".format(self._dialog_prg, output))
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
else:
return None
@widget
def buildlist(self, text, height=0, width=0, list_height=0, items=[],
**kwargs):
"""Display a buildlist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- height of the selected and unselected list
boxes
items -- a list of (tag, item, status) tuples where
'status' specifies the initial
selected/unselected state of each entry; can
be True or False, 1 or 0, "on" or "off" (True,
1 and "on" meaning selected), or any case
variation of these two strings.
A buildlist dialog is similar in logic to the checklist but
differs in presentation. In this widget, two lists are
displayed, side by side. The list on the left shows
unselected items. The list on the right shows selected items.
As items are selected or unselected, they move between the
two lists. The 'status' component of 'items' specifies which
items are initially selected.
Return a tuple of the form (code, tags) where:
- 'code' is the Dialog exit code;
- 'tags' is a list of the tags corresponding to the
selected items, in the order they have in the list on the
right.
Keys: SPACE select or deselect the highlighted item, i.e.,
move it between the left and right lists
^ move the focus to the left list
$ move the focus to the right list
TAB move focus (see 'visit_items' below)
ENTER press the focused button
If called with 'visit_items=True', the TAB key can move the
focus to the left and right lists, which is probably more
intuitive for users than the default behavior that requires
using ^ and $ for this purpose.
This widget requires dialog >= 1.2 (2012-12-30).
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
self._dialog_version_check("1.2", "the buildlist widget")
cmd = ["--buildlist", text, unicode(height), unicode(width), unicode(list_height)]
for t in items:
cmd.extend([ t[0], t[1], _to_onoff(t[2]) ] + list(t[3:]))
code, output = self._perform(cmd, **kwargs)
if code == self.HELP:
help_data = self._parse_help(output, kwargs, multival=True,
multival_on_single_line=True)
if self._help_status_on(kwargs):
help_id, selected_tags = help_data
updated_items = []
for elt in items:
tag, item, status = elt[:3]
rest = elt[3:]
updated_items.append([ tag, item, tag in selected_tags ]
+ list(rest))
return (code, (help_id, selected_tags, updated_items))
else:
return (code, help_data)
elif code in (self.OK, self.EXTRA):
return (code, self._split_shellstyle_arglist(output))
else:
return (code, None)
def _calendar_parse_date(self, date_str):
try:
mo = _calendar_date_cre.match(date_str)
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
if not mo:
raise UnexpectedDialogOutput(
"the dialog-like program returned the following "
"unexpected output (a date string was expected) from the "
"calendar box: {0!r}".format(date_str))
return [ int(s) for s in mo.group("day", "month", "year") ]
@widget
def calendar(self, text, height=6, width=0, day=0, month=0, year=0,
**kwargs):
"""Display a calendar dialog box.
text -- text to display in the box
height -- height of the box (minus the calendar height)
width -- width of the box
day -- inititial day highlighted
month -- inititial month displayed
year -- inititial year selected (0 causes the current date
to be used as the initial date)
A calendar box displays month, day and year in separately
adjustable windows. If the values for day, month or year are
missing or negative, the current date's corresponding values
are used. You can increment or decrement any of those using
the left, up, right and down arrows. Use tab or backtab to
move between windows. If the year is given as zero, the
current date is used as an initial value.
Return a tuple of the form (code, date) where:
- 'code' is the Dialog exit code;
- 'date' is a list of the form [day, month, year], where
'day', 'month' and 'year' are integers corresponding to
the date chosen by the user.
Notable exceptions:
- any exception raised by self._perform()
- UnexpectedDialogOutput
- PythonDialogReModuleError
"""
(code, output) = self._perform(
["--calendar", text, unicode(height), unicode(width), unicode(day),
unicode(month), unicode(year)],
**kwargs)
if code == self.HELP:
# The output does not depend on whether --help-status was passed
# (dialog 1.2-20130902).
help_data = self._parse_help(output, kwargs, raw_format=True)
return (code, self._calendar_parse_date(help_data))
elif code in (self.OK, self.EXTRA):
return (code, self._calendar_parse_date(output))
else:
return (code, None)
@widget
def checklist(self, text, height=15, width=54, list_height=7,
choices=[], **kwargs):
"""Display a checklist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a list of tuples (tag, item, status) where
'status' specifies the initial on/off state of
each entry; can be True or False, 1 or 0, "on"
or "off" (True, 1 and "on" meaning checked),
or any case variation of these two strings.
Return a tuple of the form (code, [tag, ...]) with the tags
for the entries that were selected by the user. 'code' is the
Dialog exit code.
If the user exits with ESC or CANCEL, the returned tag list
is empty.
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
cmd = ["--checklist", text, unicode(height), unicode(width), unicode(list_height)]
for t in choices:
t = [ t[0], t[1], _to_onoff(t[2]) ] + list(t[3:])
cmd.extend(t)
# The dialog output cannot be parsed reliably (at least in dialog
# 0.9b-20040301) without --separate-output (because double quotes in
# tags are escaped with backslashes, but backslashes are not
# themselves escaped and you have a problem when a tag ends with a
# backslash--the output makes you think you've encountered an embedded
# double-quote).
kwargs["separate_output"] = True
(code, output) = self._perform(cmd, **kwargs)
# Since we used --separate-output, the tags are separated by a newline
# in the output. There is also a final newline after the last tag.
if code == self.HELP:
help_data = self._parse_help(output, kwargs, multival=True)
if self._help_status_on(kwargs):
help_id, selected_tags = help_data
updated_choices = []
for elt in choices:
tag, item, status = elt[:3]
rest = elt[3:]
updated_choices.append([ tag, item, tag in selected_tags ]
+ list(rest))
return (code, (help_id, selected_tags, updated_choices))
else:
return (code, help_data)
else:
return (code, output.split('\n')[:-1])
def _form_updated_items(self, status, elements):
"""Return a complete list with up-to-date items from 'status'.
Return a new list of same length as 'elements'. Items are
taken from 'status', except when data inside 'elements'
indicates a read-only field: such items are not output by
dialog ... --help-status ..., and therefore have to be
extracted from 'elements' instead of 'status'.
Actually, for 'mixedform', the elements that are defined as
read-only using the attribute instead of a non-positive
field_length are not concerned by this function, since they
are included in the --help-status output.
"""
res = []
for i, elt in enumerate(elements):
label, yl, xl, item, yi, xi, field_length = elt[:7]
res.append(status[i] if field_length > 0 else item)
return res
def _generic_form(self, widget_name, method_name, text, elements, height=0,
width=0, form_height=0, **kwargs):
cmd = ["--%s" % widget_name, text, unicode(height), unicode(width),
unicode(form_height)]
if not elements:
raise BadPythonDialogUsage(
"{0}.{1}.{2}: empty ELEMENTS sequence: {3!r}".format(
__name__, type(self).__name__, method_name, elements))
elt_len = len(elements[0]) # for consistency checking
for i, elt in enumerate(elements):
if len(elt) != elt_len:
raise BadPythonDialogUsage(
"{0}.{1}.{2}: ELEMENTS[0] has length {3}, whereas "
"ELEMENTS[{4}] has length {5}".format(
__name__, type(self).__name__, method_name,
elt_len, i, len(elt)))
# Give names to make the code more readable
if widget_name in ("form", "passwordform"):
label, yl, xl, item, yi, xi, field_length, input_length = \
elt[:8]
rest = elt[8:] # optional "item_help" string
elif widget_name == "mixedform":
label, yl, xl, item, yi, xi, field_length, input_length, \
attributes = elt[:9]
rest = elt[9:] # optional "item_help" string
else:
raise PythonDialogBug(
"unexpected widget name in {0}.{1}._generic_form(): "
"{2!r}".format(__name__, type(self).__name__, widget_name))
for name, value in (("LABEL", label), ("ITEM", item)):
if not isinstance(value, basestring):
raise BadPythonDialogUsage(
"{0}.{1}.{2}: {3} element not a string: {4!r}".format(
__name__, type(self).__name__,
method_name, name, value))
cmd.extend((label, unicode(yl), unicode(xl), item, unicode(yi), unicode(xi),
unicode(field_length), unicode(input_length)))
if widget_name == "mixedform":
cmd.append(unicode(attributes))
# "item help" string when using --item-help, nothing otherwise
cmd.extend(rest)
(code, output) = self._perform(cmd, **kwargs)
if code == self.HELP:
help_data = self._parse_help(output, kwargs, multival=True)
if self._help_status_on(kwargs):
help_id, status = help_data
# 'status' does not contain the fields marked as read-only in
# 'elements'. Build a list containing all up-to-date items.
updated_items = self._form_updated_items(status, elements)
# Reconstruct 'elements' with the updated items taken from
# 'status'.
updated_elements = []
for elt, updated_item in izip(elements, updated_items):
label, yl, xl, item = elt[:4]
rest = elt[4:]
updated_elements.append([ label, yl, xl, updated_item ]
+ list(rest))
return (code, (help_id, status, updated_elements))
else:
return (code, help_data)
else:
return (code, output.split('\n')[:-1])
@widget
def form(self, text, elements, height=0, width=0, form_height=0, **kwargs):
"""Display a form consisting of labels and fields.
text -- text to display in the box
elements -- sequence describing the labels and fields (see
below)
height -- height of the box
width -- width of the box
form_height -- number of form lines displayed at the same time
A form box consists in a series of fields and associated
labels. This type of dialog is suitable for adjusting
configuration parameters and similar tasks.
Each element of 'elements' must itself be a sequence
(LABEL, YL, XL, ITEM, YI, XI, FIELD_LENGTH, INPUT_LENGTH)
containing the various parameters concerning a given field
and the associated label.
LABEL is a string that will be displayed at row YL, column
XL. ITEM is a string giving the initial value for the field,
which will be displayed at row YI, column XI (row and column
numbers starting from 1).
FIELD_LENGTH and INPUT_LENGTH are integers that respectively
specify the number of characters used for displaying the
field and the maximum number of characters that can be
entered for this field. These two integers also determine
whether the contents of the field can be modified, as
follows:
- if FIELD_LENGTH is zero, the field cannot be altered and
its contents determines the displayed length;
- if FIELD_LENGTH is negative, the field cannot be altered
and the opposite of FIELD_LENGTH gives the displayed
length;
- if INPUT_LENGTH is zero, it is set to FIELD_LENGTH.
Return a tuple of the form (code, list) where 'code' is the
Dialog exit code and 'list' gives the contents of every
editable field on exit, with the same order as in 'elements'.
Notable exceptions:
BadPythonDialogUsage
any exception raised by self._perform()
"""
return self._generic_form("form", "form", text, elements,
height, width, form_height, **kwargs)
@widget
def passwordform(self, text, elements, height=0, width=0, form_height=0,
**kwargs):
"""Display a form consisting of labels and invisible fields.
This widget is identical to the form box, except that all
text fields are treated as passwordbox widgets rather than
inputbox widgets.
By default (as in dialog), nothing is echoed to the terminal
as the user types in the invisible fields. This can be
confusing to users. Use the 'insecure' keyword argument if
you want an asterisk to be echoed for each character entered
by the user.
Notable exceptions:
BadPythonDialogUsage
any exception raised by self._perform()
"""
return self._generic_form("passwordform", "passwordform", text,
elements, height, width, form_height,
**kwargs)
@widget
def mixedform(self, text, elements, height=0, width=0, form_height=0,
**kwargs):
"""Display a form consisting of labels and fields.
text -- text to display in the box
elements -- sequence describing the labels and fields (see
below)
height -- height of the box
width -- width of the box
form_height -- number of form lines displayed at the same time
A mixedform box is very similar to a form box, and differs
from the latter by allowing field attributes to be specified.
Each element of 'elements' must itself be a sequence (LABEL,
YL, XL, ITEM, YI, XI, FIELD_LENGTH, INPUT_LENGTH, ATTRIBUTES)
containing the various parameters concerning a given field
and the associated label.
ATTRIBUTES is a bit mask with the following meaning:
bit 0 -- the field should be hidden (e.g., a password)
bit 1 -- the field should be read-only (e.g., a label)
For all other parameters, please refer to the documentation
of the form box.
The return value is the same as would be with the form box,
except that field marked as read-only with bit 1 of
ATTRIBUTES are also included in the output list.
Notable exceptions:
BadPythonDialogUsage
any exception raised by self._perform()
"""
return self._generic_form("mixedform", "mixedform", text, elements,
height, width, form_height, **kwargs)
@widget
def dselect(self, filepath, height=0, width=0, **kwargs):
"""Display a directory selection dialog box.
filepath -- initial path
height -- height of the box
width -- width of the box
The directory-selection dialog displays a text-entry window
in which you can type a directory, and above that a window
with directory names.
Here, filepath can be a filepath in which case the directory
window will display the contents of the path and the
text-entry window will contain the preselected directory.
Use tab or arrow keys to move between the windows. Within the
directory window, use the up/down arrow keys to scroll the
current selection. Use the space-bar to copy the current
selection into the text-entry window.
Typing any printable characters switches focus to the
text-entry window, entering that character as well as
scrolling the directory window to the closest match.
Use a carriage return or the "OK" button to accept the
current value in the text-entry window and exit.
Return a tuple of the form (code, path) where 'code' is the
Dialog exit code and 'path' is the directory chosen by the
user.
Notable exceptions:
any exception raised by self._perform()
"""
# The help output does not depend on whether --help-status was passed
# (dialog 1.2-20130902).
return self._widget_with_string_output(
["--dselect", filepath, unicode(height), unicode(width)],
kwargs, raw_help=True)
@widget
def editbox(self, filepath, height=0, width=0, **kwargs):
"""Display a basic text editor dialog box.
filepath -- file which determines the initial contents of
the dialog box
height -- height of the box
width -- width of the box
The editbox dialog displays a copy of the file contents. You
may edit it using the Backspace, Delete and cursor keys to
correct typing errors. It also recognizes Page Up and Page
Down. Unlike the inputbox, you must tab to the "OK" or
"Cancel" buttons to close the dialog. Pressing the "Enter"
key within the box will split the corresponding line.
Return a tuple of the form (code, text) where 'code' is the
Dialog exit code and 'text' is the contents of the text entry
window on exit.
Notable exceptions:
any exception raised by self._perform()
"""
return self._widget_with_string_output(
["--editbox", filepath, unicode(height), unicode(width)],
kwargs)
@widget
def fselect(self, filepath, height=0, width=0, **kwargs):
"""Display a file selection dialog box.
filepath -- initial file path
height -- height of the box
width -- width of the box
The file-selection dialog displays a text-entry window in
which you can type a filename (or directory), and above that
two windows with directory names and filenames.
Here, filepath can be a file path in which case the file and
directory windows will display the contents of the path and
the text-entry window will contain the preselected filename.
Use tab or arrow keys to move between the windows. Within the
directory or filename windows, use the up/down arrow keys to
scroll the current selection. Use the space-bar to copy the
current selection into the text-entry window.
Typing any printable character switches focus to the
text-entry window, entering that character as well as
scrolling the directory and filename windows to the closest
match.
Use a carriage return or the "OK" button to accept the
current value in the text-entry window, or the "Cancel"
button to cancel.
Return a tuple of the form (code, path) where 'code' is the
Dialog exit code and 'path' is the path chosen by the user
(the last element of which may be a directory or a file).
Notable exceptions:
any exception raised by self._perform()
"""
# The help output does not depend on whether --help-status was passed
# (dialog 1.2-20130902).
return self._widget_with_string_output(
["--fselect", filepath, unicode(height), unicode(width)],
kwargs, strip_xdialog_newline=True, raw_help=True)
def gauge_start(self, text="", height=8, width=54, percent=0, **kwargs):
"""Display gauge box.
text -- text to display in the box
height -- height of the box
width -- width of the box
percent -- initial percentage shown in the meter
A gauge box displays a meter along the bottom of the box. The
meter indicates a percentage.
This function starts the dialog-like program telling it to
display a gauge box with a text in it and an initial
percentage in the meter.
Return value: undefined.
Gauge typical usage
-------------------
Gauge typical usage (assuming that 'd' is an instance of the
Dialog class) looks like this:
d.gauge_start()
# do something
d.gauge_update(10) # 10% of the whole task is done
# ...
d.gauge_update(100, "any text here") # work is done
exit_code = d.gauge_stop() # cleanup actions
Notable exceptions:
- any exception raised by self._call_program()
- PythonDialogOSError
"""
with _OSErrorHandling():
# We need a pipe to send data to the child (dialog) process's
# stdin while it is running.
# rfd = File Descriptor for Reading
# wfd = File Descriptor for Writing
(child_stdin_rfd, child_stdin_wfd) = os.pipe()
(child_pid, child_output_rfd) = self._call_program(
["--gauge", text, unicode(height), unicode(width), unicode(percent)],
redir_child_stdin_from_fd=child_stdin_rfd,
close_fds=(child_stdin_wfd,), **kwargs)
# fork() is done. We don't need child_stdin_rfd in the father
# process anymore.
os.close(child_stdin_rfd)
self._gauge_process = {
"pid": child_pid,
"stdin": open(child_stdin_wfd, "w"),
"child_output_rfd": child_output_rfd
}
def gauge_update(self, percent, text="", update_text=False):
"""Update a running gauge box.
percent -- new percentage (integer) to show in the gauge
meter
text -- new text to optionally display in the box
update_text -- boolean indicating whether to update the
text in the box
This function updates the percentage shown by the meter of a
running gauge box (meaning 'gauge_start' must have been
called previously). If update_text is True, the text
displayed in the box is also updated.
See the 'gauge_start' function's documentation for
information about how to use a gauge.
Return value: undefined.
Notable exception: PythonDialogIOError (PythonDialogOSError
from Python 3.3 onwards) can be raised if
there is an I/O error while writing to the
pipe used to talk to the dialog-like
program.
"""
if not isinstance(percent, int):
raise BadPythonDialogUsage(
"the 'percent' argument of gauge_update() must be an integer, "
"but {0!r} is not".format(percent))
if update_text:
gauge_data = "XXX\n{0}\n{1}\nXXX\n".format(percent, text)
else:
gauge_data = "{0}\n".format(percent)
with _OSErrorHandling():
self._gauge_process["stdin"].write(gauge_data)
self._gauge_process["stdin"].flush()
# For "compatibility" with the old dialog.py...
def gauge_iterate(*args, **kwargs):
warnings.warn("Dialog.gauge_iterate() has been obsolete for "
"many years", DeprecationWarning)
gauge_update(*args, **kwargs)
@widget
@retval_is_code
def gauge_stop(self):
"""Terminate a running gauge widget.
This function performs the appropriate cleanup actions to
terminate a running gauge (started with 'gauge_start').
See the 'gauge_start' function's documentation for
information about how to use a gauge.
Return value: the Dialog exit code from the backend.
Notable exceptions:
- any exception raised by
self._wait_for_program_termination()
- PythonDialogIOError (PythonDialogOSError from
Python 3.3 onwards) can be raised if closing the pipe
used to talk to the dialog-like program fails.
"""
p = self._gauge_process
# Close the pipe that we are using to feed dialog's stdin
with _OSErrorHandling():
p["stdin"].close()
# According to dialog(1), the output should always be empty.
exit_code = \
self._wait_for_program_termination(p["pid"],
p["child_output_rfd"])[0]
return exit_code
@widget
@retval_is_code
def infobox(self, text, height=10, width=30, **kwargs):
"""Display an information dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
An info box is basically a message box. However, in this
case, dialog will exit immediately after displaying the
message to the user. The screen is not cleared when dialog
exits, so that the message will remain on the screen after
the method returns. This is useful when you want to inform
the user that some operations are carrying on that may
require some time to finish.
Return the Dialog exit code from the backend.
Notable exceptions:
any exception raised by self._perform()
"""
return self._widget_with_no_output(
"infobox",
["--infobox", text, unicode(height), unicode(width)],
kwargs)
@widget
def inputbox(self, text, height=10, width=30, init='', **kwargs):
"""Display an input dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
init -- default input string
An input box is useful when you want to ask questions that
require the user to input a string as the answer. If init is
supplied it is used to initialize the input string. When
entering the string, the BACKSPACE key can be used to
correct typing errors. If the input string is longer than
can fit in the dialog box, the input field will be scrolled.
Return a tuple of the form (code, string) where 'code' is the
Dialog exit code and 'string' is the string entered by the
user.
Notable exceptions:
any exception raised by self._perform()
"""
# The help output does not depend on whether --help-status was passed
# (dialog 1.2-20130902).
return self._widget_with_string_output(
["--inputbox", text, unicode(height), unicode(width), init],
kwargs, strip_xdialog_newline=True, raw_help=True)
@widget
def inputmenu(self, text, height=0, width=60, menu_height=7, choices=[],
**kwargs):
"""Display an inputmenu dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
menu_height -- height of the menu (scrollable part)
choices -- a sequence of (tag, item) tuples, the meaning
of which is explained below
Overview
--------
An inputmenu box is a dialog box that can be used to present
a list of choices in the form of a menu for the user to
choose. Choices are displayed in the given order. The main
differences with the menu dialog box are:
* entries are not automatically centered, but
left-adjusted;
* the current entry can be renamed by pressing the Rename
button, which allows editing the 'item' part of the
current entry.
Each menu entry consists of a 'tag' string and an 'item'
string. The tag gives the entry a name to distinguish it from
the other entries in the menu and to provide quick keyboard
access. The item is a short description of the option that
the entry represents.
The user can move between the menu entries by pressing the
UP/DOWN keys or the first letter of the tag as a hot key.
There are 'menu_height' lines (not entries!) displayed in the
scrollable part of the menu at one time.
BEWARE!
It is strongly advised not to put any space in tags,
otherwise the dialog output can be ambiguous if the
corresponding entry is renamed, causing pythondialog to
return a wrong tag string and new item text.
The reason is that in this case, the dialog output is
"RENAMED <tag> <item>" (without angle brackets) and
pythondialog cannot guess whether spaces after the
"RENAMED " prefix belong to the <tag> or the new <item>
text.
Note: there is no point in calling this method with
'help_status=True', because it is not possible to
rename several items nor is it possible to choose the
Help button (or any button other than Rename) once one
has started to rename an item.
Return value
------------
Return a tuple of the form (exit_info, tag, new_item_text)
where:
'exit_info' is either:
- the string "accepted", meaning that an entry was accepted
without renaming;
- the string "renamed", meaning that an entry was accepted
after being renamed;
- one of the standard Dialog exit codes Dialog.CANCEL,
Dialog.ESC, Dialog.HELP.
'tag' indicates which entry was accepted (with or without
renaming), if any. If no entry was accepted (e.g., if the
dialog was exited with the Cancel button), then 'tag' is
None.
'new_item_text' gives the new 'item' part of the renamed
entry if 'exit_info' is "renamed", otherwise it is None.
Notable exceptions:
any exception raised by self._perform()
"""
cmd = ["--inputmenu", text, unicode(height), unicode(width), unicode(menu_height)]
for t in choices:
cmd.extend(t)
(code, output) = self._perform(cmd, **kwargs)
if code == self.HELP:
help_id = self._parse_help(output, kwargs)
return (code, help_id, None)
elif code == self.OK:
return ("accepted", output, None)
elif code == self.EXTRA:
if not output.startswith("RENAMED "):
raise PythonDialogBug(
"'output' does not start with 'RENAMED ': {0!r}".format(
output))
t = output.split(' ', 2)
return ("renamed", t[1], t[2])
else:
return (code, None, None)
@widget
def menu(self, text, height=15, width=54, menu_height=7, choices=[],
**kwargs):
"""Display a menu dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
menu_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a sequence of (tag, item) tuples (see below)
Overview
--------
As its name suggests, a menu box is a dialog box that can be
used to present a list of choices in the form of a menu for
the user to choose. Choices are displayed in the given order.
Each menu entry consists of a 'tag' string and an 'item'
string. The tag gives the entry a name to distinguish it from
the other entries in the menu and to provide quick keyboard
access. The item is a short description of the option that
the entry represents.
The user can move between the menu entries by pressing the
UP/DOWN keys, the first letter of the tag as a hot key, or
the number keys 1-9. There are 'menu_height' entries
displayed in the menu at one time, but the menu will be
scrolled if there are more entries than that.
Return value
------------
Return a tuple of the form (code, tag) where 'code' is the
Dialog exit code and 'tag' the tag string of the item that
the user chose.
Notable exceptions:
any exception raised by self._perform()
"""
cmd = ["--menu", text, unicode(height), unicode(width), unicode(menu_height)]
for t in choices:
cmd.extend(t)
return self._widget_with_string_output(
cmd, kwargs, strip_xdialog_newline=True)
@widget
@retval_is_code
def mixedgauge(self, text, height=0, width=0, percent=0, elements=[],
**kwargs):
"""Display a mixed gauge dialog box.
text -- text to display in the middle of the box,
between the elements list and the progress bar
height -- height of the box
width -- width of the box
percent -- integer giving the percentage for the global
progress bar
elements -- a sequence of (tag, item) tuples, the meaning
of which is explained below
A mixedgauge box displays a list of "elements" with status
indication for each of them, followed by a text and finally a
(global) progress bar along the bottom of the box.
The top part ('elements') is suitable for displaying a task
list. One element is displayed per line, with its 'tag' part
on the left and its 'item' part on the right. The 'item' part
is a string that is displayed on the right of the same line.
The 'item' of an element can be an arbitrary string, but
special values listed in the dialog(3) manual page translate
into a status indication for the corresponding task ('tag'),
such as: "Succeeded", "Failed", "Passed", "Completed", "Done",
"Skipped", "In Progress", "Checked", "N/A" or a progress
bar.
A progress bar for an element is obtained by supplying a
negative number for the 'item'. For instance, "-75" will
cause a progress bar indicating 75 % to be displayed on the
corresponding line.
For your convenience, if an 'item' appears to be an integer
or a float, it will be converted to a string before being
passed to the dialog-like program.
'text' is shown as a sort of caption between the list and the
global progress bar. The latter displays 'percent' as the
percentage of completion.
Contrary to the gauge widget, mixedgauge is completely
static. You have to call mixedgauge() several times in order
to display different percentages in the global progress bar,
or status indicators for a given task.
Return the Dialog exit code from the backend.
Notable exceptions:
any exception raised by self._perform()
"""
cmd = ["--mixedgauge", text, unicode(height), unicode(width), unicode(percent)]
for t in elements:
cmd.extend( (t[0], unicode(t[1])) )
return self._widget_with_no_output("mixedgauge", cmd, kwargs)
@widget
@retval_is_code
def msgbox(self, text, height=10, width=30, **kwargs):
"""Display a message dialog box, with scrolling and line wrapping.
text -- text to display in the box
height -- height of the box
width -- width of the box
Display a text in a message box, with a scrollbar and
percentage indication if the text is too long to fit in a
single "screen".
A message box is very similar to a yes/no box. The only
difference between a message box and a yes/no box is that a
message box has only a single OK button. You can use this
dialog box to display any message you like. After reading
the message, the user can press the Enter key so that dialog
will exit and the calling program can continue its
operation.
msgbox() performs automatic line wrapping. If you want to
force a newline at some point, simply insert it in 'text'. In
other words (with the default settings), newline characters
in 'text' *are* respected; the line wrapping process
performed by dialog only inserts *additional* newlines when
needed. If you want no automatic line wrapping, consider
using scrollbox().
Return the Dialog exit code from the backend.
Notable exceptions:
any exception raised by self._perform()
"""
return self._widget_with_no_output(
"msgbox",
["--msgbox", text, unicode(height), unicode(width)],
kwargs)
@widget
@retval_is_code
def pause(self, text, height=15, width=60, seconds=5, **kwargs):
"""Display a pause dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
seconds -- number of seconds to pause for (integer)
A pause box displays a text and a meter along the bottom of
the box, during a specified amount of time ('seconds'). The
meter indicates how many seconds remain until the end of the
pause. The widget exits when the specified number of seconds
is elapsed, or immediately if the user presses the OK button,
the Cancel button or the Esc key.
Return the Dialog exit code, which is Dialog.OK if the pause
ended automatically after 'seconds' seconds or if the user
pressed the OK button.
Notable exceptions:
any exception raised by self._perform()
"""
return self._widget_with_no_output(
"pause",
["--pause", text, unicode(height), unicode(width), unicode(seconds)],
kwargs)
@widget
def passwordbox(self, text, height=10, width=60, init='', **kwargs):
"""Display a password input dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
init -- default input password
A password box is similar to an input box, except that the
text the user enters is not displayed. This is useful when
prompting for passwords or other sensitive information. Be
aware that if anything is passed in "init", it will be
visible in the system's process table to casual snoopers.
Also, it is very confusing to the user to provide them with a
default password they cannot see. For these reasons, using
"init" is highly discouraged.
By default (as in dialog), nothing is echoed to the terminal
as the user enters the sensitive text. This can be confusing
to users. Use the 'insecure' keyword argument if you want an
asterisk to be echoed for each character entered by the user.
Return a tuple of the form (code, password) where 'code' is
the Dialog exit code and 'password' is the password entered
by the user.
Notable exceptions:
any exception raised by self._perform()
"""
# The help output does not depend on whether --help-status was passed
# (dialog 1.2-20130902).
return self._widget_with_string_output(
["--passwordbox", text, unicode(height), unicode(width), init],
kwargs, strip_xdialog_newline=True, raw_help=True)
def _progressboxoid(self, widget, file_path=None, file_flags=os.O_RDONLY,
fd=None, text=None, height=20, width=78, **kwargs):
if (file_path is None and fd is None) or \
(file_path is not None and fd is not None):
raise BadPythonDialogUsage(
"{0}.{1}.{2}: either 'file_path' or 'fd' must be provided, and "
"not both at the same time".format(
__name__, self.__class__.__name__, widget))
with _OSErrorHandling():
if file_path is not None:
if fd is not None:
raise PythonDialogBug(
"unexpected non-None value for 'fd': {0!r}".format(fd))
# No need to pass 'mode', as the file is not going to be
# created here.
fd = os.open(file_path, file_flags)
try:
args = [ "--{0}".format(widget) ]
if text is not None:
args.append(text)
args.extend([unicode(height), unicode(width)])
kwargs["redir_child_stdin_from_fd"] = fd
code = self._widget_with_no_output(widget, args, kwargs)
finally:
with _OSErrorHandling():
if file_path is not None:
# We open()ed file_path ourselves, let's close it now.
os.close(fd)
return code
@widget
@retval_is_code
def progressbox(self, file_path=None, file_flags=os.O_RDONLY,
fd=None, text=None, height=20, width=78, **kwargs):
"""Display a possibly growing stream in a dialog box, as with "tail -f".
file_path -- path to the file that is going to be displayed
file_flags -- flags used when opening 'file_path'; those
are passed to os.open() function (not the
built-in open function!). By default, only
one flag is used: os.O_RDONLY.
OR, ALTERNATIVELY:
fd -- file descriptor for the stream to be displayed
text -- caption continuously displayed at the top, above the
stream text, or None to disable the caption
height -- height of the box
width -- width of the box
Display the contents of the specified file, updating the
dialog box whenever the file grows, as with the "tail -f"
command.
The file can be specified in two ways:
- either by giving its path (and optionally os.open()
flags) with parameters 'file_path' and 'file_flags';
- or by passing its file descriptor with parameter 'fd' (in
which case it may not even be a file; for instance, it
could be an anonymous pipe created with os.pipe()).
Return the Dialog exit code from the backend.
Notable exceptions:
PythonDialogIOError if the Python version is < 3.3
PythonDialogOSError
any exception raised by self._perform()
"""
return self._progressboxoid(
"progressbox", file_path=file_path, file_flags=file_flags,
fd=fd, text=text, height=height, width=width, **kwargs)
@widget
@retval_is_code
def programbox(self, file_path=None, file_flags=os.O_RDONLY,
fd=None, text=None, height=20, width=78, **kwargs):
"""Display a possibly growing stream in a dialog box, as with "tail -f".
A programbox is very similar to a progressbox. The only
difference between a program box and a progress box is that a
program box displays an OK button, but only after the input
stream has been exhausted (i.e., End Of File has been
reached).
This dialog box can be used to display the piped output of an
external program. After the program completes, the user can
press the Enter key to close the dialog and resume execution
of the calling program.
The parameters and exceptions are the same as for
'progressbox'. Please refer to the corresponding
documentation.
This widget requires dialog >= 1.1 (2011-03-02).
"""
self._dialog_version_check("1.1", "the programbox widget")
return self._progressboxoid(
"programbox", file_path=file_path, file_flags=file_flags,
fd=fd, text=text, height=height, width=width, **kwargs)
@widget
def radiolist(self, text, height=15, width=54, list_height=7,
choices=[], **kwargs):
"""Display a radiolist box.
text -- text to display in the box
height -- height of the box
width -- width of the box
list_height -- number of entries displayed in the box (which
can be scrolled) at a given time
choices -- a list of tuples (tag, item, status) where
'status' specifies the initial on/off state of
each entry; can be True or False, 1 or 0, "on"
or "off" (True and 1 meaning "on"), or any case
variation of these two strings. No more than
one entry should be set to True.
A radiolist box is similar to a menu box. The main difference
is that you can indicate which entry is initially selected,
by setting its status to True.
Return a tuple of the form (code, tag) with the tag for the
entry that was chosen by the user. 'code' is the Dialog exit
code from the backend.
If the user exits with ESC or CANCEL, or if all entries were
initially set to False and not altered before the user chose
OK, the returned tag is the empty string.
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
cmd = ["--radiolist", text, unicode(height), unicode(width), unicode(list_height)]
for t in choices:
cmd.extend([ t[0], t[1], _to_onoff(t[2]) ] + list(t[3:]))
(code, output) = self._perform(cmd, **kwargs)
output = self._strip_xdialog_newline(output)
if code == self.HELP:
help_data = self._parse_help(output, kwargs)
if self._help_status_on(kwargs):
help_id, selected_tag = help_data
# Reconstruct 'choices' with the selected item inferred from
# 'selected_tag'.
updated_choices = []
for elt in choices:
tag, item, status = elt[:3]
rest = elt[3:]
updated_choices.append([ tag, item, tag == selected_tag ]
+ list(rest))
return (code, (help_id, selected_tag, updated_choices))
else:
return (code, help_data)
else:
return (code, output)
@widget
def rangebox(self, text, height=0, width=0, min=None, max=None, init=None,
**kwargs):
"""Display an range dialog box.
text -- text to display above the actual range control
height -- height of the box
width -- width of the box
min -- minimum value for the range control
max -- maximum value for the range control
init -- initial value for the range control
The rangebox dialog allows the user to select from a range of
values using a kind of slider. The range control shows the
current value as a bar (like the gauge dialog).
The return value is a tuple of the form (code, val) where
'code' is the Dialog exit code and 'val' is an integer: the
value chosen by the user.
The Tab and arrow keys move the cursor between the buttons
and the range control. When the cursor is on the latter, you
can change the value with the following keys:
Left/Right arrows select a digit to modify
+/- increment/decrement the selected digit
by one unit
0-9 set the selected digit to the given
value
Some keys are also recognized in all cursor positions:
Home/End set the value to its minimum or maximum
PageUp/PageDown decrement/increment the value so that
the slider moves by one column
This widget requires dialog >= 1.2 (2012-12-30).
Notable exceptions:
any exception raised by self._perform()
"""
self._dialog_version_check("1.2", "the rangebox widget")
for name in ("min", "max", "init"):
if not isinstance(locals()[name], int):
raise BadPythonDialogUsage(
"'{0}' argument not an int: {1!r}".format(name,
locals()[name]))
(code, output) = self._perform(
["--rangebox", text] + [ unicode(i) for i in
(height, width, min, max, init) ],
**kwargs)
if code == self.HELP:
help_data = self._parse_help(output, kwargs, raw_format=True)
# The help output does not depend on whether --help-status was
# passed (dialog 1.2-20130902).
return (code, int(help_data))
elif code in (self.OK, self.EXTRA):
return (code, int(output))
else:
return (code, None)
@widget
@retval_is_code
def scrollbox(self, text, height=20, width=78, **kwargs):
"""Display a string in a scrollable box, with no line wrapping.
text -- string to display in the box
height -- height of the box
width -- width of the box
This method is a layer on top of textbox. The textbox widget
in dialog allows to display file contents only. This method
allows you to display any text in a scrollable box. This is
simply done by creating a temporary file, calling textbox() and
deleting the temporary file afterwards.
The text is not automatically wrapped. New lines in the
scrollable box will be placed exactly as in 'text'. If you
want automatic line wrapping, you should use the msgbox
widget instead (the 'textwrap' module from the Python
standard library is also worth knowing about).
Return the Dialog exit code from the backend.
Notable exceptions:
- UnableToCreateTemporaryDirectory
- PythonDialogIOError if the Python version is < 3.3
- PythonDialogOSError
- exceptions raised by the tempfile module (which are
unfortunately not mentioned in its documentation, at
least in Python 2.3.3...)
"""
# In Python < 2.3, the standard library does not have
# tempfile.mkstemp(), and unfortunately, tempfile.mktemp() is
# insecure. So, I create a non-world-writable temporary directory and
# store the temporary file in this directory.
with _OSErrorHandling():
tmp_dir = _create_temporary_directory()
fName = os.path.join(tmp_dir, "text")
# If we are here, tmp_dir *is* created (no exception was raised),
# so chances are great that os.rmdir(tmp_dir) will succeed (as
# long as tmp_dir is empty).
#
# Don't move the _create_temporary_directory() call inside the
# following try statement, otherwise the user will always see a
# PythonDialogOSError instead of an
# UnableToCreateTemporaryDirectory because whenever
# UnableToCreateTemporaryDirectory is raised, the subsequent
# os.rmdir(tmp_dir) is bound to fail.
try:
# No race condition as with the deprecated tempfile.mktemp()
# since tmp_dir is not world-writable.
with open(fName, mode="w") as f:
f.write(text)
# Ask for an empty title unless otherwise specified
if kwargs.get("title", None) is None:
kwargs["title"] = ""
return self._widget_with_no_output(
"textbox",
["--textbox", fName, unicode(height), unicode(width)],
kwargs)
finally:
if os.path.exists(fName):
os.unlink(fName)
os.rmdir(tmp_dir)
@widget
@retval_is_code
def tailbox(self, filename, height=20, width=60, **kwargs):
"""Display the contents of a file in a dialog box, as with "tail -f".
filename -- name of the file, the contents of which is to be
displayed in the box
height -- height of the box
width -- width of the box
Display the contents of the specified file, updating the
dialog box whenever the file grows, as with the "tail -f"
command.
Return the Dialog exit code from the backend.
Notable exceptions:
any exception raised by self._perform()
"""
return self._widget_with_no_output(
"tailbox",
["--tailbox", filename, unicode(height), unicode(width)],
kwargs)
# No tailboxbg widget, at least for now.
@widget
@retval_is_code
def textbox(self, filename, height=20, width=60, **kwargs):
"""Display the contents of a file in a dialog box.
filename -- name of the file whose contents is to be
displayed in the box
height -- height of the box
width -- width of the box
A text box lets you display the contents of a text file in a
dialog box. It is like a simple text file viewer. The user
can move through the file by using the UP/DOWN, PGUP/PGDN
and HOME/END keys available on most keyboards. If the lines
are too long to be displayed in the box, the LEFT/RIGHT keys
can be used to scroll the text region horizontally. For more
convenience, forward and backward searching functions are
also provided.
Return the Dialog exit code from the backend.
Notable exceptions:
any exception raised by self._perform()
"""
# This is for backward compatibility... not that it is
# stupid, but I prefer explicit programming.
if kwargs.get("title", None) is None:
kwargs["title"] = filename
return self._widget_with_no_output(
"textbox",
["--textbox", filename, unicode(height), unicode(width)],
kwargs)
def _timebox_parse_time(self, time_str):
try:
mo = _timebox_time_cre.match(time_str)
except re.error, e:
raise PythonDialogReModuleError(unicode(e))
if not mo:
raise UnexpectedDialogOutput(
"the dialog-like program returned the following "
"unexpected output (a time string was expected) with the "
"--timebox option: {0!r}".format(time_str))
return [ int(s) for s in mo.group("hour", "minute", "second") ]
@widget
def timebox(self, text, height=3, width=30, hour=-1, minute=-1,
second=-1, **kwargs):
"""Display a time dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
hour -- inititial hour selected
minute -- inititial minute selected
second -- inititial second selected
A dialog is displayed which allows you to select hour, minute
and second. If the values for hour, minute or second are
negative (or not explicitely provided, as they default to
-1), the current time's corresponding values are used. You
can increment or decrement any of those using the left-, up-,
right- and down-arrows. Use tab or backtab to move between
windows.
Return a tuple of the form (code, time) where:
- 'code' is the Dialog exit code;
- 'time' is a list of the form [hour, minute, second],
where 'hour', 'minute' and 'second' are integers
corresponding to the time chosen by the user.
Notable exceptions:
- any exception raised by self._perform()
- PythonDialogReModuleError
- UnexpectedDialogOutput
"""
(code, output) = self._perform(
["--timebox", text, unicode(height), unicode(width),
unicode(hour), unicode(minute), unicode(second)],
**kwargs)
if code == self.HELP:
help_data = self._parse_help(output, kwargs, raw_format=True)
# The help output does not depend on whether --help-status was
# passed (dialog 1.2-20130902).
return (code, self._timebox_parse_time(help_data))
elif code in (self.OK, self.EXTRA):
return (code, self._timebox_parse_time(output))
else:
return (code, None)
@widget
def treeview(self, text, height=0, width=0, list_height=0,
nodes=[], **kwargs):
"""Display a treeview box.
text -- text to display at the top of the box
height -- height of the box
width -- width of the box
list_height -- number of lines reserved for the main part of
the box, where the tree is displayed
nodes -- a list of (tag, item, status, depth) tuples
describing nodes, where:
- 'tag' is used to indicate which node was
selected by the user on exit;
- 'item' is the text displayed for the node;
- 'status' specifies the initial on/off
state of each node; can be True or False,
1 or 0, "on" or "off" (True, 1 and "on"
meaning selected), or any case variation
of these two strings;
- 'depth' is a non-negative integer
indicating the depth of the node in the
tree (0 for the root node).
Display nodes organized in a tree structure. Each node has a
tag, an 'item' text, a selected status, and a depth in the
tree. Only the 'item' texts are displayed in the widget; tags
are only used for the return value. Only one node can be
selected at a given time, as for the radiolist widget.
Return a tuple of the form (code, tag) where:
- 'code' is the Dialog exit code from the backend;
- 'tag' is the tag of the selected node.
This widget requires dialog >= 1.2 (2012-12-30).
Notable exceptions:
any exception raised by self._perform() or _to_onoff()
"""
self._dialog_version_check("1.2", "the treeview widget")
cmd = ["--treeview", text, unicode(height), unicode(width), unicode(list_height)]
nselected = 0
for i, t in enumerate(nodes):
if not isinstance(t[3], int):
raise BadPythonDialogUsage(
"fourth element of node {0} not an int: {1!r}".format(
i, t[3]))
status = _to_onoff(t[2])
if status == "on":
nselected += 1
cmd.extend([ t[0], t[1], status, unicode(t[3]) ] + list(t[4:]))
if nselected != 1:
raise BadPythonDialogUsage(
"exactly one node must be selected, not {0}".format(nselected))
(code, output) = self._perform(cmd, **kwargs)
if code == self.HELP:
help_data = self._parse_help(output, kwargs)
if self._help_status_on(kwargs):
help_id, selected_tag = help_data
# Reconstruct 'nodes' with the selected item inferred from
# 'selected_tag'.
updated_nodes = []
for elt in nodes:
tag, item, status = elt[:3]
rest = elt[3:]
updated_nodes.append([ tag, item, tag == selected_tag ]
+ list(rest))
return (code, (help_id, selected_tag, updated_nodes))
else:
return (code, help_data)
elif code in (self.OK, self.EXTRA):
return (code, output)
else:
return (code, None)
@widget
@retval_is_code
def yesno(self, text, height=10, width=30, **kwargs):
"""Display a yes/no dialog box.
text -- text to display in the box
height -- height of the box
width -- width of the box
A yes/no dialog box of size 'height' rows by 'width' columns
will be displayed. The string specified by 'text' is
displayed inside the dialog box. If this string is too long
to fit in one line, it will be automatically divided into
multiple lines at appropriate places. The text string can
also contain the sub-string "\\n" or newline characters to
control line breaking explicitly. This dialog box is useful
for asking questions that require the user to answer either
yes or no. The dialog box has a Yes button and a No button,
in which the user can switch between by pressing the TAB
key.
Return the Dialog exit code from the backend.
Notable exceptions:
any exception raised by self._perform()
"""
return self._widget_with_no_output(
"yesno",
["--yesno", text, unicode(height), unicode(width)],
kwargs)
|
Join us for a soundwalk and a map workshop led by artist and sound designer José Rivera. As an invitation to deepen our connection to the environment through sound, the program will include a range of activities integrating sensory perception, physical action, and the art of spatial thinking.
Walk will take place rain or shine! Please dress for walking and the weather. |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from datetime import datetime,timedelta
from frappe.utils import cstr, flt, get_datetime, get_time, getdate, cint ,get_defaults
from dateutil.relativedelta import relativedelta
from erpnext.manufacturing.doctype.manufacturing_settings.manufacturing_settings import get_mins_between_operations
class OverlapError(frappe.ValidationError): pass
class OverProductionLoggedError(frappe.ValidationError): pass
class NotSubmittedError(frappe.ValidationError): pass
class NegativeHoursError(frappe.ValidationError): pass
from frappe.model.document import Document
class TimeLog(Document):
def validate(self):
self.set_status()
self.set_title()
if not(cint(get_defaults("fs_simplified_time_log"))):
self.validate_overlap()
self.validate_timings()
self.calculate_total_hours()
self.validate_time_log_for()
self.check_workstation_timings()
self.validate_production_order()
self.validate_manufacturing()
self.set_project_if_missing()
self.update_cost()
def on_submit(self):
self.update_production_order()
self.update_task_and_project()
def on_cancel(self):
self.update_production_order()
self.update_task_and_project()
def before_update_after_submit(self):
self.set_status()
def before_cancel(self):
self.set_status()
def set_status(self):
self.status = {
0: "Draft",
1: "Submitted",
2: "Cancelled"
}[self.docstatus or 0]
if self.time_log_batch:
self.status="Batched for Billing"
if self.sales_invoice:
self.status="Billed"
def set_title(self):
"""Set default title for the Time Log"""
if self.production_order:
self.title = _("{0} for {1}").format(self.operation, self.production_order)
elif self.activity_type :
self.title = _("{0}").format(self.activity_type)
if self.quotation_:
self.title += " for " + self.quotation_
if self.task:
self.title += " for " + self.task
if self.project:
self.title += " for " + self.project
if self.support_ticket:
self.title += " for " + self.support_ticket
def validate_overlap(self):
"""Checks if 'Time Log' entries overlap for a user, workstation. """
self.validate_overlap_for("user")
self.validate_overlap_for("employee")
self.validate_overlap_for("workstation")
def validate_overlap_for(self, fieldname):
existing = self.get_overlap_for(fieldname)
if existing:
frappe.throw(_("This Time Log conflicts with {0} for {1} {2}").format(existing.name,
self.meta.get_label(fieldname), self.get(fieldname)), OverlapError)
def get_overlap_for(self, fieldname):
if not self.get(fieldname):
return
existing = frappe.db.sql("""select name, from_time, to_time from `tabTime Log`
where `{0}`=%(val)s and
(
(%(from_time)s > from_time and %(from_time)s < to_time) or
(%(to_time)s > from_time and %(to_time)s < to_time) or
(%(from_time)s <= from_time and %(to_time)s >= to_time))
and name!=%(name)s
and docstatus < 2""".format(fieldname),
{
"val": self.get(fieldname),
"from_time": self.from_time,
"to_time": self.to_time,
"name": self.name or "No Name"
}, as_dict=True)
return existing[0] if existing else None
def validate_timings(self):
if self.to_time and self.from_time and get_datetime(self.to_time) <= get_datetime(self.from_time):
frappe.throw(_("To Time must be greater than From Time"), NegativeHoursError)
def calculate_total_hours(self):
if self.to_time and self.from_time:
from frappe.utils import time_diff_in_seconds
self.hours = flt(time_diff_in_seconds(self.to_time, self.from_time)) / 3600
def set_project_if_missing(self):
"""Set project if task is set"""
if self.task and not self.project:
self.project = frappe.db.get_value("Task", self.task, "project")
def validate_time_log_for(self):
if not self.for_manufacturing:
for fld in ["production_order", "operation", "workstation", "completed_qty"]:
self.set(fld, None)
else:
self.activity_type=None
def check_workstation_timings(self):
"""Checks if **Time Log** is between operating hours of the **Workstation**."""
if self.workstation and self.from_time and self.to_time:
from erpnext.manufacturing.doctype.workstation.workstation import check_if_within_operating_hours
check_if_within_operating_hours(self.workstation, self.operation, self.from_time, self.to_time)
def validate_production_order(self):
"""Throws 'NotSubmittedError' if **production order** is not submitted. """
if self.production_order:
if frappe.db.get_value("Production Order", self.production_order, "docstatus") != 1 :
frappe.throw(_("You can make a time log only against a submitted production order"), NotSubmittedError)
def update_production_order(self):
"""Updates `start_date`, `end_date`, `status` for operation in Production Order."""
if self.production_order and self.for_manufacturing:
if not self.operation_id:
frappe.throw(_("Operation ID not set"))
dates = self.get_operation_start_end_time()
summary = self.get_time_log_summary()
pro = frappe.get_doc("Production Order", self.production_order)
for o in pro.operations:
if o.name == self.operation_id:
o.actual_start_time = dates.start_date
o.actual_end_time = dates.end_date
o.completed_qty = summary.completed_qty
o.actual_operation_time = summary.mins
break
pro.flags.ignore_validate_update_after_submit = True
pro.update_operation_status()
pro.calculate_operating_cost()
pro.set_actual_dates()
pro.save()
def get_operation_start_end_time(self):
"""Returns Min From and Max To Dates of Time Logs against a specific Operation. """
return frappe.db.sql("""select min(from_time) as start_date, max(to_time) as end_date from `tabTime Log`
where production_order = %s and operation = %s and docstatus=1""",
(self.production_order, self.operation), as_dict=1)[0]
def move_to_next_day(self):
"""Move start and end time one day forward"""
self.from_time = get_datetime(self.from_time) + relativedelta(day=1)
def move_to_next_working_slot(self):
"""Move to next working slot from workstation"""
workstation = frappe.get_doc("Workstation", self.workstation)
slot_found = False
for working_hour in workstation.working_hours:
if get_datetime(self.from_time).time() < get_time(working_hour.start_time):
self.from_time = getdate(self.from_time).strftime("%Y-%m-%d") + " " + working_hour.start_time
slot_found = True
break
if not slot_found:
# later than last time
self.from_time = getdate(self.from_time).strftime("%Y-%m-%d") + " " + workstation.working_hours[0].start_time
self.move_to_next_day()
def move_to_next_non_overlapping_slot(self):
"""If in overlap, set start as the end point of the overlapping time log"""
overlapping = self.get_overlap_for("workstation") \
or self.get_overlap_for("employee") \
or self.get_overlap_for("user")
if not overlapping:
frappe.throw("Logical error: Must find overlapping")
self.from_time = get_datetime(overlapping.to_time) + get_mins_between_operations()
def get_time_log_summary(self):
"""Returns 'Actual Operating Time'. """
return frappe.db.sql("""select
sum(hours*60) as mins, sum(completed_qty) as completed_qty
from `tabTime Log`
where production_order = %s and operation_id = %s and docstatus=1""",
(self.production_order, self.operation_id), as_dict=1)[0]
def validate_manufacturing(self):
if self.for_manufacturing:
if not self.production_order:
frappe.throw(_("Production Order is Mandatory"))
if not self.completed_qty:
self.completed_qty = 0
production_order = frappe.get_doc("Production Order", self.production_order)
pending_qty = flt(production_order.qty) - flt(production_order.produced_qty)
if flt(self.completed_qty) > pending_qty:
frappe.throw(_("Completed Qty cannot be more than {0} for operation {1}").format(pending_qty, self.operation),
OverProductionLoggedError)
else:
self.production_order = None
self.operation = None
self.quantity = None
def update_cost(self):
rate = get_activity_cost(self.employee, self.activity_type)
if rate:
self.costing_rate = flt(rate.get('costing_rate'))
self.billing_rate = flt(rate.get('billing_rate'))
self.costing_amount = self.costing_rate * self.hours
if self.billable:
self.billing_amount = self.billing_rate * self.hours
else:
self.billing_amount = 0
if self.additional_cost and self.billable:
self.billing_amount += self.additional_cost
def update_task_and_project(self):
"""Update costing rate in Task or Project if either is set"""
if self.task:
task = frappe.get_doc("Task", self.task)
task.update_time_and_costing()
task.save(ignore_permissions=True)
elif self.project:
frappe.get_doc("Project", self.project).update_project()
@frappe.whitelist()
def get_events(start, end, filters=None):
"""Returns events for Gantt / Calendar view rendering.
:param start: Start date-time.
:param end: End date-time.
:param filters: Filters like workstation, project etc.
"""
from frappe.desk.calendar import get_event_conditions
conditions = get_event_conditions("Time Log", filters)
if (cint(get_defaults("fs_simplified_time_log"))):
date_cond = "date_worked between %(start)s and %(end)s"
else:
date_cond = "( from_time between %(start)s and %(end)s or to_time between %(start)s and %(end)s )"
data = frappe.db.sql("""select name, from_time, to_time,
activity_type, task, project, production_order, workstation, date_worked, employee, hours from `tabTime Log`
where docstatus < 2 and {date_cond}
{conditions}""".format(conditions=conditions,date_cond=date_cond), {
"start": start,
"end": end
}, as_dict=True, update={"allDay": 0})
#aligns the assorted time logs so they are layed out sequentially
if(cint(get_defaults("fs_simplified_time_log"))):
slist = {}
for idx,da in enumerate(data):
if (da.employee not in slist):
slist[da.employee]={}
if (da.date_worked not in slist[da.employee]):
slist[da.employee][da.date_worked]=[]
slist[da.employee][da.date_worked].append([idx,da.from_time,da.to_time,da.hours])
for e in slist:
for d in slist[e]:
temp = slist[e][d][0]
temp[1]= datetime.combine(d,get_time("8:00:00"))
temp[2]= temp[1] + timedelta(hours=temp[3])
for idx,l in enumerate(slist[e][d][1:]):
data[l[0]]["from_time"]= l[1] = slist[e][d][idx][2]
data[l[0]]["to_time"] = l[2] = l[1]+ timedelta(hours=l[3])
l= slist[e][d][0]
data[temp[0]]["from_time"]= slist[e][d][0][1]
data[temp[0]]["to_time"] = slist[e][d][0][2]
for d in data:
d.title = d.name + ": " + (d.activity_type or d.production_order or "")
if d.task:
d.title += " for Task: " + d.task
if d.project:
d.title += " for Project: " + d.project
return data
@frappe.whitelist()
def get_activity_cost(employee=None, activity_type=None):
rate = frappe.db.get_values("Activity Cost", {"employee": employee,
"activity_type": activity_type}, ["costing_rate", "billing_rate"], as_dict=True)
if not rate:
rate = frappe.db.get_values("Activity Type", {"activity_type": activity_type},
["costing_rate", "billing_rate"], as_dict=True)
return rate[0] if rate else {}
|
Everything else good has been dropped … as far as I can see, which is only as far as the big search engines let me look. They don’t seem to like similar site search much, either. Short of irrelevant pictures and videos.
This entry was posted in Uncategorized on July 19, 2016 by crabfiles. |
#! /usr/bin/python
#
# Copyright (c) 2014 IBM, Corp. 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 datetime
import six
from six.moves import range
from thirdparty_dateutil import parser as datetime_parser
class DatetimeBuiltins(object):
# casting operators (used internally)
@classmethod
def to_timedelta(cls, x):
if isinstance(x, six.string_types):
fields = x.split(":")
num_fields = len(fields)
args = {}
keys = ['seconds', 'minutes', 'hours', 'days', 'weeks']
for i in range(0, len(fields)):
args[keys[i]] = int(fields[num_fields - 1 - i])
return datetime.timedelta(**args)
else:
return datetime.timedelta(seconds=x)
@classmethod
def to_datetime(cls, x):
return datetime_parser.parse(x, ignoretz=True)
# current time
@classmethod
def now(cls):
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# extraction and creation of datetimes
@classmethod
def unpack_time(cls, x):
x = cls.to_datetime(x)
return (x.hour, x.minute, x.second)
@classmethod
def unpack_date(cls, x):
x = cls.to_datetime(x)
return (x.year, x.month, x.day)
@classmethod
def unpack_datetime(cls, x):
x = cls.to_datetime(x)
return (x.year, x.month, x.day, x.hour, x.minute, x.second)
@classmethod
def pack_time(cls, hour, minute, second):
return "{}:{}:{}".format(hour, minute, second)
@classmethod
def pack_date(cls, year, month, day):
return "{}-{}-{}".format(year, month, day)
@classmethod
def pack_datetime(cls, year, month, day, hour, minute, second):
return "{}-{}-{} {}:{}:{}".format(
year, month, day, hour, minute, second)
# extraction/creation convenience function
@classmethod
def extract_date(cls, x):
return str(cls.to_datetime(x).date())
@classmethod
def extract_time(cls, x):
return str(cls.to_datetime(x).time())
# conversion to seconds
@classmethod
def datetime_to_seconds(cls, x):
since1900 = cls.to_datetime(x) - datetime.datetime(year=1900,
month=1,
day=1)
return int(since1900.total_seconds())
# native operations on datetime
@classmethod
def datetime_plus(cls, x, y):
return str(cls.to_datetime(x) + cls.to_timedelta(y))
@classmethod
def datetime_minus(cls, x, y):
return str(cls.to_datetime(x) - cls.to_timedelta(y))
@classmethod
def datetime_lessthan(cls, x, y):
return cls.to_datetime(x) < cls.to_datetime(y)
@classmethod
def datetime_lessthanequal(cls, x, y):
return cls.to_datetime(x) <= cls.to_datetime(y)
@classmethod
def datetime_greaterthan(cls, x, y):
return cls.to_datetime(x) > cls.to_datetime(y)
@classmethod
def datetime_greaterthanequal(cls, x, y):
return cls.to_datetime(x) >= cls.to_datetime(y)
@classmethod
def datetime_equal(cls, x, y):
return cls.to_datetime(x) == cls.to_datetime(y)
# the registry for builtins
_builtin_map = {
'comparison': [
{'func': 'lt(x,y)', 'num_inputs': 2, 'code': lambda x, y: x < y},
{'func': 'lteq(x,y)', 'num_inputs': 2, 'code': lambda x, y: x <= y},
{'func': 'equal(x,y)', 'num_inputs': 2, 'code': lambda x, y: x == y},
{'func': 'gt(x,y)', 'num_inputs': 2, 'code': lambda x, y: x > y},
{'func': 'gteq(x,y)', 'num_inputs': 2, 'code': lambda x, y: x >= y},
{'func': 'max(x,y,z)', 'num_inputs': 2,
'code': lambda x, y: max(x, y)}],
'arithmetic': [
{'func': 'plus(x,y,z)', 'num_inputs': 2, 'code': lambda x, y: x + y},
{'func': 'minus(x,y,z)', 'num_inputs': 2, 'code': lambda x, y: x - y},
{'func': 'mul(x,y,z)', 'num_inputs': 2, 'code': lambda x, y: x * y},
{'func': 'div(x,y,z)', 'num_inputs': 2, 'code': lambda x, y: x / y},
{'func': 'float(x,y)', 'num_inputs': 1, 'code': lambda x: float(x)},
{'func': 'int(x,y)', 'num_inputs': 1, 'code': lambda x: int(x)}],
'string': [
{'func': 'concat(x,y,z)', 'num_inputs': 2, 'code': lambda x, y: x + y},
{'func': 'len(x, y)', 'num_inputs': 1, 'code': lambda x: len(x)}],
'datetime': [
{'func': 'now(x)', 'num_inputs': 0,
'code': DatetimeBuiltins.now},
{'func': 'unpack_date(x, year, month, day)', 'num_inputs': 1,
'code': DatetimeBuiltins.unpack_date},
{'func': 'unpack_time(x, hours, minutes, seconds)', 'num_inputs': 1,
'code': DatetimeBuiltins.unpack_time},
{'func': 'unpack_datetime(x, y, m, d, h, i, s)', 'num_inputs': 1,
'code': DatetimeBuiltins.unpack_datetime},
{'func': 'pack_time(hours, minutes, seconds, result)', 'num_inputs': 3,
'code': DatetimeBuiltins.pack_time},
{'func': 'pack_date(year, month, day, result)', 'num_inputs': 3,
'code': DatetimeBuiltins.pack_date},
{'func': 'pack_datetime(y, m, d, h, i, s, result)', 'num_inputs': 6,
'code': DatetimeBuiltins.pack_datetime},
{'func': 'extract_date(x, y)', 'num_inputs': 1,
'code': DatetimeBuiltins.extract_date},
{'func': 'extract_time(x, y)', 'num_inputs': 1,
'code': DatetimeBuiltins.extract_time},
{'func': 'datetime_to_seconds(x, y)', 'num_inputs': 1,
'code': DatetimeBuiltins.datetime_to_seconds},
{'func': 'datetime_plus(x,y,z)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_plus},
{'func': 'datetime_minus(x,y,z)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_minus},
{'func': 'datetime_lt(x,y)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_lessthan},
{'func': 'datetime_lteq(x,y)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_lessthanequal},
{'func': 'datetime_gt(x,y)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_greaterthan},
{'func': 'datetime_gteq(x,y)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_greaterthanequal},
{'func': 'datetime_equal(x,y)', 'num_inputs': 2,
'code': DatetimeBuiltins.datetime_equal}]}
class CongressBuiltinPred(object):
def __init__(self, name, arglist, num_inputs, code):
self.predname = name
self.predargs = arglist
self.num_inputs = num_inputs
self.code = code
self.num_outputs = len(arglist) - num_inputs
def string_to_pred(self, predstring):
try:
self.predname = predstring.split('(')[0]
self.predargs = predstring.split('(')[1].split(')')[0].split(',')
except Exception:
print("Unexpected error in parsing predicate string")
def __str__(self):
return self.predname + '(' + ",".join(self.predargs) + ')'
class CongressBuiltinCategoryMap(object):
def __init__(self, start_builtin_map):
self.categorydict = dict()
self.preddict = dict()
for key, value in start_builtin_map.items():
self.categorydict[key] = []
for predtriple in value:
pred = self.dict_predtriple_to_pred(predtriple)
self.categorydict[key].append(pred)
self.sync_with_predlist(pred.predname, pred, key, 'add')
def mapequal(self, othercbc):
if self.categorydict == othercbc.categorydict:
return True
else:
return False
def dict_predtriple_to_pred(self, predtriple):
ncode = predtriple['code']
ninputs = predtriple['num_inputs']
nfunc = predtriple['func']
nfunc_pred = nfunc.split("(")[0]
nfunc_arglist = nfunc.split("(")[1].split(")")[0].split(",")
pred = CongressBuiltinPred(nfunc_pred, nfunc_arglist, ninputs, ncode)
return pred
def add_map(self, newmap):
for key, value in newmap.items():
if key not in self.categorydict:
self.categorydict[key] = []
for predtriple in value:
pred = self.dict_predtriple_to_pred(predtriple)
if not self.builtin_is_registered(pred):
self.categorydict[key].append(pred)
self.sync_with_predlist(pred.predname, pred, key, 'add')
def delete_map(self, newmap):
for key, value in newmap.items():
for predtriple in value:
predtotest = self.dict_predtriple_to_pred(predtriple)
for pred in self.categorydict[key]:
if pred.predname == predtotest.predname:
if pred.num_inputs == predtotest.num_inputs:
self.categorydict[key].remove(pred)
self.sync_with_predlist(pred.predname,
pred, key, 'del')
if self.categorydict[key] == []:
del self.categorydict[key]
def sync_with_predlist(self, predname, pred, category, operation):
if operation == 'add':
self.preddict[predname] = [pred, category]
if operation == 'del':
if predname in self.preddict:
del self.preddict[predname]
def delete_builtin(self, category, name, inputs):
if category not in self.categorydict:
self.categorydict[category] = []
for pred in self.categorydict[category]:
if pred.num_inputs == inputs and pred.predname == name:
self.categorydict[category].remove(pred)
self.sync_with_predlist(name, pred, category, 'del')
def get_category_name(self, predname, predinputs):
if predname in self.preddict:
if self.preddict[predname][0].num_inputs == predinputs:
return self.preddict[predname][1]
return None
def exists_category(self, category):
return category in self.categorydict
def insert_category(self, category):
self.categorydict[category] = []
def delete_category(self, category):
if category in self.categorydict:
categorypreds = self.categorydict[category]
for pred in categorypreds:
self.sync_with_predlist(pred.predname, pred, category, 'del')
del self.categorydict[category]
def insert_to_category(self, category, pred):
if category in self.categorydict:
self.categorydict[category].append(pred)
self.sync_with_predlist(pred.predname, pred, category, 'add')
else:
assert("Category does not exist")
def delete_from_category(self, category, pred):
if category in self.categorydict:
self.categorydict[category].remove(pred)
self.sync_with_predlist(pred.predname, pred, category, 'del')
else:
assert("Category does not exist")
def delete_all_in_category(self, category):
if category in self.categorydict:
categorypreds = self.categorydict[category]
for pred in categorypreds:
self.sync_with_predlist(pred.predname, pred, category, 'del')
self.categorydict[category] = []
else:
assert("Category does not exist")
def builtin_is_registered(self, predtotest):
"""Given a CongressBuiltinPred, check if it has been registered."""
pname = predtotest.predname
if pname in self.preddict:
if self.preddict[pname][0].num_inputs == predtotest.num_inputs:
return True
return False
def is_builtin(self, table, arity=None):
"""Given a Tablename and arity, check if it is a builtin."""
if table.table in self.preddict:
if not arity:
return True
if len(self.preddict[table.table][0].predargs) == arity:
return True
return False
def builtin(self, table):
"""Return a CongressBuiltinPred for given Tablename or None."""
if not isinstance(table, six.string_types):
table = table.table
if table in self.preddict:
return self.preddict[table][0]
return None
def list_available_builtins(self):
"""Print out the list of builtins, by category."""
for key, value in self.categorydict.items():
predlist = self.categorydict[key]
for pred in predlist:
print(str(pred))
# a Singleton that serves as the entry point for builtin functionality
builtin_registry = CongressBuiltinCategoryMap(_builtin_map)
|
A new group of talented youth joined Pakistan’s No.1 Data Network Company, Zong 4G, under the umbrella of its Graduate Trainee Program -2018. Through its talent development initiative for fresh graduates, a total of 50 new graduates have entered into the corporate world.
The company shortlisted graduates from various universities of Pakistan, to encourage and provide them with an opportunity to grow as the Leaders of tomorrow by allowing the trainees to experience the practical world and gain experience in the diverse fields of Engineering, Information Technology, Sales and Marketing etc.
Zong 4G’s, Leaders of Tomorrow-Graduate Trainee Program, has a well-structured and comprehensive recruitment process, where hundreds of fresh graduates undergo extensive evaluation through an aptitude test, assessment center as well as a sequence of panel interviews.
This year, the telecom company received a record number of more than 18,000 applications for the programme and shortlisted the best lot through a rigorous recruitment process to ensure that some of Pakistan’s finest graduates become the successors to achieving the vision of Zong 4G, Leading the digital innovation in Pakistan.
Fostering a learning environment for graduates from various backgrounds, the 1 to 1.5 year program renders to providing in depth training coupled with real-time learning through maximum exposure and project management.
The program also incorporates behavioral developmental training programs that aim to equip young graduates with essential business skills coupled with the know-how of the digital and industrial ecosystem. Essential management skills are included for them to effectively become the ‘leaders of tomorrow’.
It is heartening to see that every year the program grows to encourage those who are seeking work experience with Pakistan’s No.1 Data Network Company and determined to build a career in the telecom industry.
Adhering to its brand promise of New Dreams, Zong 4G’s perseverance for development of youth and nurturing the leaders in Telecommunication sector is aligned with the country’s vision of youth development. |
#!/usr/bin/python
#
# utility library
#
# lasinfo: parser library that parses LASFILE.info.txt files
# created by: lasinfo -i LASFILE -o ../meta/LASFILE.info.txt -compute_density -repair
# rawdata: helpers to clean up ASCII rawdata
#
import os
import re
import simplejson
from gps import gps_week_from_doy
class lasinfo:
def __init__(self):
""" setup new LASInfo parser """
self.meta = {}
# define methods to use when parsing metadata
self.attr_methods = {
# search pattern attribute key func to call
'file signature' : ['File Signature','set_signature'],
'file source ID' : ['File Source ID','set_int'],
'global_encoding' : ['Global Encoding','set_int'],
'project ID GUID data 1-4' : ['Project ID - GUID data','set_str'],
'version major.minor' : ['Version','set_version'],
'system identifier' : ['System Identifier','set_system_identifier'],
'generating software' : ['Generating Software','set_str'],
'file creation day/year' : ['File Creation','set_creation'],
'header size' : ['Header Size','set_int'],
'offset to point data' : ['Offset to point data','set_int'],
'number var. length records' : ['Number of Variable Length Records','set_int'],
'point data format' : ['Point Data Record Format','set_int'],
'point data record length' : ['Point Data Record Length','set_int'],
'number of point records' : ['Legacy Number of point records','set_int'],
'number of points by return' : ['Legacy Number of points by return','set_returns'],
'scale factor x y z' : ['Scale factor','set_xyz'],
'offset x y z' : ['Offset','set_xyz'],
'min x y z' : ['Min','set_xyz'],
'max x y z' : ['Max','set_xyz'],
'start of waveform data packet record' : ['Start of Waveform Data Packet Record','set_int'],
'start of first extended variable length record' : ['Start of first Extended Variable Length Record','set_int'],
'number of extended_variable length records' : ['Number of Extended Variable Length Records','set_int'],
'extended number of point records' : ['Number of point records','set_int'],
'extended number of points by return' : ['Number of points by return','set_returns'],
'overview over number of returns of given pulse' : ['returns_of_given_pulse','ignore'],
'covered area in square meters/kilometers' : ['area','set_area'],
'covered area in square units/kilounits' : ['area','set_area'],
'point density' : ['density','set_density'],
'spacing' : ['spacing','set_spacing'],
'number of first returns' : ['first_returns','ignore'],
'number of intermediate returns' : ['intermediate_returns','ignore'],
'number of last returns' : ['last_returns','ignore'],
'number of single returns' : ['single_returns','ignore'],
'overview over extended number of returns of given pulse' : ['extended_number_of_returns','ignore'],
'minimum and maximum for all LAS point record entries' : ['min_max','set_min_max'],
'histogram of classification of points' : ['class_histo','set_class_histo'],
'WARNING' : ['warning','ignore'],
'moretocomemaybe' : ['xxx','ignore'],
}
def read(self, fpath):
""" read file containing output of lasinfo and collect metadata """
with open(fpath) as f:
# set filename and size of corresponding .las file
lasname = re.sub(r'/meta/(.*).info.txt',r'/las/\1',fpath)
if os.path.exists(lasname):
self.meta['file_name'] = lasname
self.meta['file_size'] = os.path.getsize(lasname)
else:
raise NameError('%s does not exist' % lasname)
# set filenpaths to corresponding metafiles .info.txt, .hull.wkt, .traj.wkt if any
metafiles = {
'info' : fpath,
'hull' : re.sub('.info.txt','.hull.wkt',fpath),
'traj' : re.sub('.info.txt','.traj.wkt',fpath)
}
for ftype in metafiles:
if os.path.exists(metafiles[ftype]):
if not 'metafiles' in self.meta:
self.meta['metafiles'] = {}
self.meta['metafiles'][ftype] = metafiles[ftype]
# extract metadata from .info file
section = None
for line in f.readlines():
# set section if needed and skip lines if needed
if re.search('reporting all LAS header entries',line):
section = 'HEADER'
continue
elif re.search(r'^variable length header', line):
section = 'HEADER_VAR'
continue
elif re.search(r'^reporting minimum and maximum for all LAS point record entries', line):
section = 'MINMAX'
continue
elif re.search(r'^histogram of classification of points', line):
section = 'HISTO'
continue
elif re.search(r'^histogram of extended classification of points', line):
section = 'HISTO_EXT'
continue
elif re.search(r'^LASzip compression', line) or re.search(r'^LAStiling', line):
section = None
continue
elif re.search(r'flagged as synthetic', line) or re.search(r'flagged as keypoints', line) or re.search(r'flagged as withheld', line):
section = None
continue
else:
# what else?
pass
# reset section unless leading blanks are present in current line
if section and not re.search(r'^ +',line):
section = None
if section == 'HEADER':
# split up trimmed line on colon+blank
[key,val] = self.strip_whitespace(line).split(': ')
# set header attribute with corresponding key and method
getattr(self, self.attr_methods[key][1])(
self.attr_methods[key][0],
val
)
elif section == 'HEADER_VAR':
# extract SRID and projection name if available
self.set_srid_proj(line)
elif section == 'MINMAX':
# set min/max for point record entries
self.set_min_max(line)
elif section in ('HISTO','HISTO_EXT'):
# set classification histogram value, name and point count
self.set_class_histo(line)
else:
parts = self.strip_whitespace(line).split(': ')
if parts[0] in self.attr_methods:
# set attribute with corresponding key and method
getattr(self, self.attr_methods[parts[0]][1])(
self.attr_methods[parts[0]][0],
parts[1]
)
elif parts[0] in [
'bounding box is correct.',
'number of point records in header is correct.',
'number of points by return in header is correct.',
'extended number of point records in header is correct.',
'extended number of points by return in header is correct.'
]:
# ignore positive info from -repair
continue
elif parts[0] == 'bounding box was repaired.':
# tell user to re-run lasinfo as header has been updated and content in .info might not be correct anymore
print "RE-RUN sh /home/institut/rawdata/maintenance/scripts/als/get_lasinfo.sh %s rebuild" % self.meta['file']['las']
elif parts[0].startswith("lasinfo ("):
pass
else:
pass
print "TODO", parts, '(%s)' % f.name
def has_wkt_geometry(self,ftype=None):
""" return True if WKT geometry is present, false otherwise """
if 'metafiles' in self.meta and ftype in self.meta['metafiles']:
return True
else:
return False
def get_wkt_geometry(self,ftype=None):
""" read WKT geometry for hull or trajectory if any """
wkt = ''
if self.has_wkt_geometry(ftype):
with open(self.meta['metafiles'][ftype]) as f:
wkt = f.read()
return wkt.rstrip()
def as_json(self,obj=None,pretty=False):
""" return object as JSON """
if pretty:
return simplejson.dumps(obj,sort_keys=True, indent=4 * ' ')
else:
return simplejson.dumps(obj)
def strip_whitespace(self, val=None):
""" remove leading, trailing whitespace and replace successive blanks with one blank """
if type(val) == str:
return re.sub(r' +',' ',val.lstrip().rstrip())
else:
return val
def ignore(self,key,val):
""" ignore this attribute """
pass
def warning(self,key,val):
""" display warnings """
print "WARNING: %s=%s" % (key,val)
def set_str(self,key,val):
""" set value as string """
self.meta[key] = str(val)
def set_int(self,key,val):
""" set value as integer """
self.meta[key] = int(val)
def set_signature(self,key,val):
""" set file signature as string """
self.meta[key] = val.lstrip("'").rstrip("'")
def set_system_identifier(self,key,val):
self.meta[key] = val.lstrip("'").rstrip("'")
def set_version(self,key,val):
""" set major and minor version """
major,minor = [str(v) for v in val.split('.')]
self.meta['Version Major'] = major
self.meta['Version Minor'] = minor
def set_creation(self,key,val):
""" set file creation day/year """
doy,year = [int(v) for v in val.split('/')]
self.meta['File Creation Day of Year'] = doy
self.meta['File Creation Year'] = year
# compute GPS-week as well
self.meta['creation_gpsweek'] = gps_week_from_doy(doy,year)
def set_returns(self,key,val):
""" set number of points by return as list with five entries exactly """
pts = [int(v) for v in val.split(' ')]
if key == 'Legacy Number of points by return':
if len(pts) < 5:
# fill with zeros
for n in range(0,5-len(pts)):
pts.append(0)
self.meta['Legacy Number of points by return'] = pts[:5]
elif key == 'Number of points by return':
if len(pts) < 15:
# fill with zeros
for n in range(0,15-len(pts)):
pts.append(0)
self.meta['Number of points by return'] = pts[:15]
else:
pass
def set_xyz(self,key,val):
""" set x y z values as floats """
arr = [float(v) for v in val.split(' ')]
if key == 'Scale factor':
self.meta['X scale factor'] = arr[0]
self.meta['Y scale factor'] = arr[1]
self.meta['Z scale factor'] = arr[2]
elif key == 'Offset':
self.meta['X offset'] = arr[0]
self.meta['Y offset'] = arr[1]
self.meta['Z offset'] = arr[2]
elif key == 'Min':
self.meta['Min X'] = arr[0]
self.meta['Min Y'] = arr[1]
self.meta['Min Z'] = arr[2]
elif key == 'Max':
self.meta['Max X'] = arr[0]
self.meta['Max Y'] = arr[1]
self.meta['Max Z'] = arr[2]
else:
pass
def set_srid_proj(self,line):
""" set SRID and projection name if available """
if re.search('ProjectedCSTypeGeoKey',line):
srid,info = (re.sub(r'^key.*value_offset (\d+) - ProjectedCSTypeGeoKey: (.*)$',r'\1;\2',self.strip_whitespace(line))).split(';')
self.meta['projection_srid'] = int(srid)
self.meta['projection_info'] = info
def set_min_max(self,line):
""" set min, max values for attribute """
for k in ('minimum','maximum'):
if not k in self.meta:
self.meta[k] = {}
# isolate attribute name, min and max from line
parts = self.strip_whitespace(line).split(' ')
attr = ' '.join(parts[:-2])
if attr in ('X','Y','Z'):
# skip unscaled X,Y,Z values and assign regular min / max values instead that have been extracted before
self.meta['minimum'][attr.lower()] = self.meta['Min %s' % attr]
self.meta['maximum'][attr.lower()] = self.meta['Max %s' % attr]
return
self.meta['minimum'][attr] = float(parts[-2])
self.meta['maximum'][attr] = float(parts[-1])
def set_class_histo(self,line):
""" return classification histogram value, name and point count """
if not 'class_histo' in self.meta:
self.meta['class_histo'] = {}
parts = self.strip_whitespace(line).split(' ')
class_value = int(re.sub(r'[\(\)]','',parts[-1]))
class_name = ' '.join(parts[1:-1])
num_points = int(parts[0])
self.meta['class_histo'][class_value] = {
'name' : class_name,
'points' : num_points
}
def set_area(self,key,val):
""" return covered area in square meters/kilometers """
m2,km2 = [float(v) for v in val.split('/')]
self.meta['area_m2'] = float(m2)
self.meta['area_km2'] = float(km2)
def set_density(self,key,val):
""" return estimated point density for all returns and last returns per square meter """
all_r,last_r = (re.sub(r'all returns ([^ ]+) last only ([^ ]+) \(per square .*\)$',r'\1;\2',self.strip_whitespace(val))).split(';')
self.meta['density_per_m2_all'] = float(all_r)
self.meta['density_per_m2_last'] = float(last_r)
def set_spacing(self,key,val):
""" get spacing for all returns and last returns in meters """
all_r,last_r = (re.sub(r'all returns ([^ ]+) last only ([^ ]+) \(in .*\)$',r'\1;\2',self.strip_whitespace(val))).split(';')
self.meta['spacing_in_m_all'] = float(all_r)
self.meta['spacing_in_m_last'] = float(last_r)
# check if metadata has been collected
def has_metadata(self):
""" return True if file signature has been set to 'LASF' as required by specification, False otherwise """
return ('File Signature' in self.meta and self.meta['File Signature'] == 'LASF')
def get_points(self):
""" get number of points from regular or legacy number of points """
if 'Number of point records' in self.meta and self.meta['Number of point records'] != 0:
return self.meta['Number of point records']
elif 'Legacy Number of point records' in self.meta and self.meta['Legacy Number of point records'] != 0:
return self.meta['Legacy Number of point records']
else:
return 0
def get_points_by_return(self):
""" get number of points by return from regular or legacy number of points by return """
if 'Number of points by return' in self.meta:
return self.meta['Number of points by return']
elif 'Legacy Number of points by return' in self.meta:
return self.meta['Legacy Number of points by return']
else:
return []
def get_attr(self,attrname,attrtype):
""" safely return meatdata attribute """
if not attrname in self.meta:
if attrtype == list:
return []
elif attrtype == dict:
return {}
else:
return None
else:
return self.meta[attrname]
def get_metadata(self,json=False,pretty=False):
""" return metadata collect during parsing """
if json:
return self.as_json(self.meta,pretty)
else:
return self.meta
def get_db_metadata(self,pretty=False):
""" return subset of metadata for database """
return {
'file_name' : self.get_attr('file_name',str).split('/')[-1],
'file_size' : self.get_attr('file_size',str),
'file_year' : self.get_attr('File Creation Year',int),
'file_doy' : self.get_attr('File Creation Day of Year',int),
'file_gpsweek' : self.get_attr('creation_gpsweek',int),
'srid' : self.get_attr('projection_srid',int),
'projection' : self.get_attr('projection_info',str),
'points' : self.get_points(),
'points_by_return' : self.get_points_by_return(),
'minimum' : self.get_attr('minimum',list),
'maximum' : self.get_attr('maximum',list),
'histogram' : self.get_attr('class_histo',dict),
'point_area' : self.get_attr('area_m2',float),
'point_density' : self.get_attr('density_per_m2_all',float),
'point_spacing' : self.get_attr('spacing_in_m_all',float),
'point_format' : self.get_attr('Point Data Record Format',int),
'system_identifier' : self.get_attr('System Identifier',str),
'global_encoding' : self.get_attr('Global Encoding',int),
}
class rawdata:
def __init__(self, req=None):
""" helpers to clean up ASCII rawdata """
self.known_attrs = {
't' : 'gpstime',
'x' : 'x coordinate',
'y' : 'y coordinate',
'z' : 'z coordinate',
'i' : 'intensity',
'n' : 'number of returns of given pulse',
'r' : 'number of return',
'c' : 'classification',
'u' : 'user data',
'p' : 'point source ID',
'a' : 'scan angle',
'e' : 'edge of flight line flag',
'd' : 'direction of scan flag',
'R' : 'red channel of RGB color',
'G' : 'green channel of RGB color',
'B' : 'blue channel of RGB color',
's' : 'skip number'
}
self.req = req
def strip_whitespace(self, val=None):
""" remove leading, trailing whitespace and replace successive blanks with one blank """
if type(val) == str:
return re.sub(r' +',' ',val.lstrip().rstrip())
else:
return val
def strip_utm32(self, val=None):
""" strip trailing 32 from UTM str, int or float x-coordinates """
if type(val) == str:
return val[2:]
elif type(val) in (float, int):
return val - 32000000
else:
return val
def parse_line(self, line=None, pattern=None):
""" split up line on blank and create list or dictionary with params by name """
# split up cleaned line on blank
row = self.strip_whitespace(line).split(' ')
# safely assign attributes when requested
if pattern:
# init return dictionary
rec = {}
# split up pattern
attrs = list(pattern)
# bail out if number of attributes does not match number of columns
if not len(row) == len(attrs):
raise ValueError('Number of columns and attributes in pattern do not match. Got %s, expected %s.\nline=%s\npattern=%s' % (
len(attrs),
len(row),
self.strip_whitespace(line),
pattern
))
# assign attributes
for i in range(0,len(row)):
if not attrs[i] in self.known_attrs:
raise ValueError('%s is not a valid attribute abreviation.' % attrs[i])
else:
# handle skip flag
if attrs[i] == 's':
continue
else:
rec[attrs[i]] = row[i]
return rec
else:
return row
|
Original Burger Press is rated 3.3 out of 5 by 6.
Whether you are grilling a mouthwatering burger topped with chesse or a vege burger cooked to perfection, the burger press is a must have. Designed to create uniformed half and quarter pound burger. Removeable handle for easy storage.
Rated 5 out of 5 by Kings from EXCELLENT!! I went to the Weber restaurant in St. Louis, MO and tested this product and I created the BEST burger that I've ever made. I purchased the Weber burger press later that night. Highly recommend.
Rated 1 out of 5 by dan lv from Poor design Do yourself a favor and find an old flexible plastic version of this item. One party company has been selling them for decades and has enough flex so you can easily get the patty out. They are stackable and interlocking so you can make patties ahead or even freeze them for future use complete with a snap on lid. Weber makes great grills, but this accessory falls flat. |
"""
cat.py -- Emulate UNIX cat.
Author: Corwin Brown
E-Mail: [email protected]
Date: 5/25/2015
"""
import os
import sys
class Cat(object):
def __init__(self, fname=None, stdin=None):
"""
Constructor
Args:
fname (str): File to print to screen
stdin (str): Input from sys.stdin to output.
Raises:
ValueError: If provided file doesn't exist or is a directory.
"""
self.fname = fname
self.stdin = stdin
def run(self):
"""
Emulate 'cat'.
Echo User input if a file is not provided, if a file is provided, print
it to the screen.
"""
if self.stdin:
self._cat_stdin(self.stdin)
return
if not self.fname:
self._cat_input()
return
if isinstance(self.fname, list):
for f in self.fname:
self._validate_file(f)
self._cat_file(f)
else:
self._validate_file(self.fname)
self._cat_file(self.fname)
def _cat_stdin(self, stdin):
"""
Print data provided in stdin.
Args:
stdin (str): The output of sys.stdin.read()
"""
print stdin
def _cat_file(self, fname):
"""
Print contents of a file.
Args:
fname: Name of file to print.
"""
with open(fname, 'r') as f:
sys.stdout.write((f.read()))
def _cat_input(self):
"""
Echo back user input.
"""
while True:
user_input = raw_input()
sys.stdout.write(user_input)
def _validate_file(self, fname):
"""
Ensure fname exists, and is not a directory.
Args:
fname (str): The file path to validate.
Raises:
ValueError: If file does not exist or is a directory.
"""
if not os.path.exists(fname):
raise ValueError('cat: {}: No such file or directory.'
.format(fname))
if os.path.isdir(fname):
raise ValueError('cat: {}: Is a directory.'
.format(fname))
|
We have something for everyone at T-Rex Bingo. Beginners to the most experienced players feel right at home in the jungle with a huge variety of 75-ball and 90-ball bingo games. There's also a giant selection of instant games like scratch cards and slots with big jackpots too!
All you have to do to start playing is sign up with just your name and email address. Make your first deposit of £10 and you're ready to join in the gigantic fun with £40! Chat with the roomies in the chat rooms and get ready to have a roarin' good time! We hand out loads of bingo bonuses every day! |
# coding: utf-8
import chainer
import numpy
import matplotlib
import matplotlib.pyplot as plt
import cv2
class Visualizer(object):
def __init__(self, network):
self.nnbase = network
self.model = network.model
plt.subplots_adjust(hspace=0.5)
def __convert_filters(self, layer, shape=(), T=False):
layer = self.model[layer]
self.bitmap = []
weight = []
if not T:
weight = chainer.cuda.to_cpu(layer.W)
else:
weight = chainer.cuda.to_cpu(layer.W.T)
if shape:
for bitmap in weight:
self.bitmap.append(bitmap.reshape(shape))
else:
for bitmap in weight:
self.bitmap.append(bitmap[0])
def plot_filters(self, layer, shape=(), T=False, title=True, interpolation=False):
int_mode = 'none'
if interpolation:
int_mode = 'hermite'
self.__convert_filters(layer, shape, T)
N = len(self.bitmap)
nrow = int(numpy.sqrt(N)) + 1
for i in range(N):
ax = plt.subplot(nrow, nrow, i + 1)
if title:
ax.set_title('filter %d' % (i + 1), fontsize=10)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.imshow(self.bitmap[i], interpolation=int_mode, cmap=matplotlib.cm.gray)
plt.show()
def write_filters(self, layer, path='./', identifier='img', type='bmp', shape=(), T=False):
self.__convert_filters(layer, shape, T)
N = len(self.bitmap)
# length of file indexes
maxlen = int(numpy.log10(N)) + 1
form = '{0:0>' + str(maxlen) + '}'
fmax = numpy.max(self.bitmap)
fmin = numpy.min(self.bitmap)
self.bitmap = ((self.bitmap - fmin) * 0xff / (fmax - fmin)).astype(numpy.uint8)
for i in range(N):
filename = path + '/' + identifier + form.format(i) + '.' + type
cv2.imwrite(filename, self.bitmap[i])
def save_raw_filter(self, dst):
for i in range(len(self.bitmap)):
numpy.savetxt(dst + '/%d' % (i + 1) + '.csv', self.bitmap[i], delimiter=',')
def __apply_filter(self, x, layer):
output = self.nnbase.output(x, layer)
# chainer.Variable -> numpy.ndarray (of GPUArray)
return chainer.cuda.to_cpu(output).data
def plot_output(self, x, layer):
output = self.__apply_filter(x, layer)
N = output.shape[0] * output.shape[1]
nrow = int(numpy.sqrt(N)) + 1
j = 0
for batch in output:
j += 1
i = 0
for img in batch:
i += 1
ax = plt.subplot(nrow, nrow, (j - 1) * output.shape[1] + i)
ax.set_title('img%d-filt%d' % (j + 1, i + 1), fontsize=10)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.imshow(chainer.cuda.to_cpu(img), interpolation='none', cmap=matplotlib.cm.gray)
plt.show()
def write_output(self, x, layer, path='./', identifier='img_', type='bmp'):
output = self.__apply_filter(x, layer)
maxlen_t = int(numpy.log10(output.shape[0])) + 1
tform = '{0:0>' + str(maxlen_t) + '}'
maxlen_f = int(numpy.log10(output.shape[1])) + 1
fform = '{0:0>' + str(maxlen_f) + '}'
j = 0
for batch in output:
j += 1
i = 0
for img in batch:
i += 1
bitmap = chainer.cuda.to_cpu(img)
fmax = numpy.max(bitmap)
fmin = numpy.min(bitmap)
bitmap = ((bitmap - fmin) * 0xff / (fmax - fmin)).astype(numpy.uint8)
filename = path + '/' + identifier + tform.format(j) + '_f' + fform.format(i) + '.' + type
cv2.imwrite(filename, bitmap)
def write_activation(self, x, layer, path='./', identifier='img_', type='bmp'):
output = self.__apply_filter(numpy.array([x]).astype(numpy.float32), layer)
fform = '{0:0>' + str(int(numpy.log10(output.shape[1])) + 1) + '}'
# filter num
i = 0
for img in output[0]:
i += 1
bitmap = chainer.cuda.to_cpu(img)
fmax = numpy.max(bitmap)
fmin = numpy.min(bitmap)
bitmap = ((bitmap - fmin) * 0xff / (fmax - fmin)).astype(numpy.uint8)
filename = path + '/' + identifier + 'f' + fform.format(i) + '.' + type
cv2.imwrite(filename, bitmap)
|
The delivery was fast. The thickness is great.
Item received in good order. Thank you. |
# 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/.
from Queue import PriorityQueue
from scipy.spatial.distance import *
from grid import Grid
def find_path(grid, start_cell, goal_cell, heuristic):
def distance(p1, p2, name=heuristic, dimensions=grid.num_dimensions):
p1 = p1.coordinates
p2 = p2.coordinates
if name == 'null':
return 0.0
elif name == 'minkowski-n':
return pdist([p1, p2],
'minkowski',
p=dimensions)
elif name == 'minkowski-0.5n':
return pdist([p1, p2],
'minkowski',
p=dimensions / 2)
else:
return pdist([p1, p2], name)
# print "started pathfinding"
start_frontier = PriorityQueue()
start_cell.cost_to = start_cell.cost
start_frontier.put(start_cell)
goal_frontier = PriorityQueue()
goal_cell.cost_from = goal_cell.cost
goal_frontier.put(goal_cell)
num_iterations = 0
while not start_frontier.empty() and not goal_frontier.empty():
num_iterations += 1
current_start_cell = start_frontier.get()
current_goal_cell = goal_frontier.get()
# print(str(current_start_cell) + " " + str(current_goal_cell))
if current_start_cell == current_goal_cell:
# print "0"
path = []
while current_start_cell.previous is not None:
path.append(current_start_cell)
current_start_cell = current_start_cell.previous
path.append(current_start_cell)
path.reverse()
path.append(current_goal_cell)
while not current_goal_cell.successor == goal_cell:
path.append(current_goal_cell)
current_goal_cell = current_goal_cell.successor
return path, num_iterations
if current_start_cell.visited_from_goal:
# print "1"
path = []
current = current_start_cell
while not current == goal_cell:
current.successor.previous = current
current = current.successor
current = goal_cell
while current.previous is not None:
path.append(current)
current = current.previous
path.append(current)
path.reverse()
return path, num_iterations
if current_goal_cell.visited_from_start:
# print "2"
path = []
current = current_goal_cell
while current.previous is not None:
path.append(current)
current = current.previous
path.append(current)
path.reverse()
current = current_goal_cell
while not current == goal_cell:
path.append(current.successor)
current = current.successor
return path, num_iterations
current_start_cell.closed = True
# add to start frontier
neighbors = current_start_cell.get_neighbors()
for neighbor in neighbors:
if neighbor.closed:
continue
cost_to = current_start_cell.cost_to + neighbor.cost
visited = neighbor.visited_from_start
if (not visited) or cost_to < neighbor.cost_to:
neighbor.visited_from_start = True
neighbor.previous = current_start_cell
if neighbor.predicted_cost_from == 100000000.0:
neighbor.predicted_cost_from = distance(neighbor, goal_cell)
neighbor.cost_to = cost_to
neighbor.predicted_cost_to = cost_to
neighbor.total_cost = neighbor.cost_to + neighbor.predicted_cost_from
if visited:
start_frontier.queue.remove(neighbor)
start_frontier.put(neighbor)
# add to goal frontier
neighbors = current_goal_cell.get_neighbors()
for neighbor in neighbors:
if neighbor.closed:
continue
cost_from = current_goal_cell.cost_from + neighbor.cost
visited = neighbor.visited_from_goal
if (not visited) or cost_from < neighbor.cost_from:
neighbor.visited_from_goal = True
neighbor.successor = current_goal_cell
if neighbor.predicted_cost_to == 100000000.0:
neighbor.predicted_cost_to = distance(neighbor, start_cell)
neighbor.cost_from = cost_from
neighbor.predicted_cost_from = cost_from
neighbor.total_cost = neighbor.cost_from + neighbor.predicted_cost_to
if visited:
try:
goal_frontier.queue.remove(neighbor)
except ValueError:
pass
goal_frontier.put(neighbor)
# np.set_printoptions(linewidth=500)
# g = Grid([5, 5], fill=True)
# print g.grid
# print g.get_cell([0,0])
# print g.get_cell([4,4])
# path, iter = find_path(g, g.get_cell([0, 0]), g.get_cell([4, 4]), heuristic='null')
# print [str(i) for i in path]
# print iter
|
With the introduction of personal assistants like Google Home and Amazon Echo, intelligent machines are no longer limited to private research and computing but are instead becoming a part of our everyday lives. This common use of artificial intelligence (AI) brings many things into question. Namely, how intelligent should machines be, and if there is no limit to their intelligence, how should they be regulated? What kind of fail-safes will be put into place? Many leaders in the tech field have asked themselves these questions, and as technology progresses, they find these inquiries more and more critical not only for the safety of individuals but for the preservation of humanity as a whole. |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# channeltools - Herramientas para trabajar con canales
# ------------------------------------------------------------
import os
import jsontools
from platformcode import config, logger
DEFAULT_UPDATE_URL = "/channels/"
dict_channels_parameters = dict()
def is_adult(channel_name):
logger.info("channel_name=" + channel_name)
channel_parameters = get_channel_parameters(channel_name)
return channel_parameters["adult"]
def is_enabled(channel_name):
logger.info("channel_name=" + channel_name)
return get_channel_parameters(channel_name)["active"] and get_channel_setting("enabled", channel=channel_name,
default=True)
def get_channel_parameters(channel_name):
global dict_channels_parameters
if channel_name not in dict_channels_parameters:
try:
channel_parameters = get_channel_json(channel_name)
# logger.debug(channel_parameters)
if channel_parameters:
# cambios de nombres y valores por defecto
channel_parameters["title"] = channel_parameters.pop("name")
channel_parameters["channel"] = channel_parameters.pop("id")
# si no existe el key se declaran valor por defecto para que no de fallos en las funciones que lo llaman
channel_parameters["update_url"] = channel_parameters.get("update_url", DEFAULT_UPDATE_URL)
channel_parameters["language"] = channel_parameters.get("language", ["all"])
channel_parameters["adult"] = channel_parameters.get("adult", False)
channel_parameters["active"] = channel_parameters.get("active", False)
channel_parameters["include_in_global_search"] = channel_parameters.get("include_in_global_search",
False)
channel_parameters["categories"] = channel_parameters.get("categories", list())
channel_parameters["thumbnail"] = channel_parameters.get("thumbnail", "")
channel_parameters["banner"] = channel_parameters.get("banner", "")
channel_parameters["fanart"] = channel_parameters.get("fanart", "")
# Imagenes: se admiten url y archivos locales dentro de "resources/images"
if channel_parameters.get("thumbnail") and "://" not in channel_parameters["thumbnail"]:
channel_parameters["thumbnail"] = os.path.join(config.get_runtime_path(), "resources", "media",
"channels", "thumb", channel_parameters["thumbnail"])
if channel_parameters.get("banner") and "://" not in channel_parameters["banner"]:
channel_parameters["banner"] = os.path.join(config.get_runtime_path(), "resources", "media",
"channels", "banner", channel_parameters["banner"])
if channel_parameters.get("fanart") and "://" not in channel_parameters["fanart"]:
channel_parameters["fanart"] = os.path.join(config.get_runtime_path(), "resources", "media",
"channels", "fanart", channel_parameters["fanart"])
# Obtenemos si el canal tiene opciones de configuración
channel_parameters["has_settings"] = False
if 'settings' in channel_parameters:
# if not isinstance(channel_parameters['settings'], list):
# channel_parameters['settings'] = [channel_parameters['settings']]
# if "include_in_global_search" in channel_parameters['settings']:
# channel_parameters["include_in_global_search"] = channel_parameters['settings']
# ["include_in_global_search"].get('default', False)
#
# found = False
# for el in channel_parameters['settings']:
# for key in el.items():
# if 'include_in' not in key:
# channel_parameters["has_settings"] = True
# found = True
# break
# if found:
# break
for s in channel_parameters['settings']:
if 'id' in s:
if s['id'] == "include_in_global_search":
channel_parameters["include_in_global_search"] = True
elif not s['id'].startswith("include_in_") and \
(s.get('enabled', False) or s.get('visible', False)):
channel_parameters["has_settings"] = True
del channel_parameters['settings']
# Compatibilidad
if 'compatible' in channel_parameters:
# compatible python
python_compatible = True
if 'python' in channel_parameters["compatible"]:
import sys
python_condition = channel_parameters["compatible"]['python']
if sys.version_info < tuple(map(int, (python_condition.split(".")))):
python_compatible = False
channel_parameters["compatible"] = python_compatible
else:
channel_parameters["compatible"] = True
dict_channels_parameters[channel_name] = channel_parameters
else:
# para evitar casos donde canales no están definidos como configuración
# lanzamos la excepcion y asi tenemos los valores básicos
raise Exception
except Exception, ex:
logger.error(channel_name + ".json error \n%s" % ex)
channel_parameters = dict()
channel_parameters["channel"] = ""
channel_parameters["adult"] = False
channel_parameters['active'] = False
channel_parameters["compatible"] = True
channel_parameters["language"] = ""
channel_parameters["update_url"] = DEFAULT_UPDATE_URL
return channel_parameters
return dict_channels_parameters[channel_name]
def get_channel_json(channel_name):
# logger.info("channel_name=" + channel_name)
import filetools
channel_json = None
try:
channel_path = filetools.join(config.get_runtime_path(), "channels", channel_name + ".json")
if filetools.isfile(channel_path):
# logger.info("channel_data=" + channel_path)
channel_json = jsontools.load(filetools.read(channel_path))
# logger.info("channel_json= %s" % channel_json)
except Exception, ex:
template = "An exception of type %s occured. Arguments:\n%r"
message = template % (type(ex).__name__, ex.args)
logger.error(" %s" % message)
return channel_json
def get_channel_controls_settings(channel_name):
# logger.info("channel_name=" + channel_name)
dict_settings = {}
list_controls = get_channel_json(channel_name).get('settings', list())
for c in list_controls:
if 'id' not in c or 'type' not in c or 'default' not in c:
# Si algun control de la lista no tiene id, type o default lo ignoramos
continue
# new dict with key(id) and value(default) from settings
dict_settings[c['id']] = c['default']
return list_controls, dict_settings
def get_channel_setting(name, channel, default=None):
"""
Retorna el valor de configuracion del parametro solicitado.
Devuelve el valor del parametro 'name' en la configuracion propia del canal 'channel'.
Busca en la ruta \addon_data\plugin.video.alfa\settings_channels el archivo channel_data.json y lee
el valor del parametro 'name'. Si el archivo channel_data.json no existe busca en la carpeta channels el archivo
channel.json y crea un archivo channel_data.json antes de retornar el valor solicitado. Si el parametro 'name'
tampoco existe en el el archivo channel.json se devuelve el parametro default.
@param name: nombre del parametro
@type name: str
@param channel: nombre del canal
@type channel: str
@param default: valor devuelto en caso de que no exista el parametro name
@type default: any
@return: El valor del parametro 'name'
@rtype: any
"""
file_settings = os.path.join(config.get_data_path(), "settings_channels", channel + "_data.json")
dict_settings = {}
dict_file = {}
if os.path.exists(file_settings):
# Obtenemos configuracion guardada de ../settings/channel_data.json
try:
dict_file = jsontools.load(open(file_settings, "rb").read())
if isinstance(dict_file, dict) and 'settings' in dict_file:
dict_settings = dict_file['settings']
except EnvironmentError:
logger.error("ERROR al leer el archivo: %s" % file_settings)
if not dict_settings or name not in dict_settings:
# Obtenemos controles del archivo ../channels/channel.json
try:
list_controls, default_settings = get_channel_controls_settings(channel)
except:
default_settings = {}
if name in default_settings: # Si el parametro existe en el channel.json creamos el channel_data.json
default_settings.update(dict_settings)
dict_settings = default_settings
dict_file['settings'] = dict_settings
# Creamos el archivo ../settings/channel_data.json
json_data = jsontools.dump(dict_file)
try:
open(file_settings, "wb").write(json_data)
except EnvironmentError:
logger.error("ERROR al salvar el archivo: %s" % file_settings)
# Devolvemos el valor del parametro local 'name' si existe, si no se devuelve default
return dict_settings.get(name, default)
def set_channel_setting(name, value, channel):
"""
Fija el valor de configuracion del parametro indicado.
Establece 'value' como el valor del parametro 'name' en la configuracion propia del canal 'channel'.
Devuelve el valor cambiado o None si la asignacion no se ha podido completar.
Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'.
Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.
@param name: nombre del parametro
@type name: str
@param value: valor del parametro
@type value: str
@param channel: nombre del canal
@type channel: str
@return: 'value' en caso de que se haya podido fijar el valor y None en caso contrario
@rtype: str, None
"""
# Creamos la carpeta si no existe
if not os.path.exists(os.path.join(config.get_data_path(), "settings_channels")):
os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))
file_settings = os.path.join(config.get_data_path(), "settings_channels", channel + "_data.json")
dict_settings = {}
dict_file = None
if os.path.exists(file_settings):
# Obtenemos configuracion guardada de ../settings/channel_data.json
try:
dict_file = jsontools.load(open(file_settings, "r").read())
dict_settings = dict_file.get('settings', {})
except EnvironmentError:
logger.error("ERROR al leer el archivo: %s" % file_settings)
dict_settings[name] = value
# comprobamos si existe dict_file y es un diccionario, sino lo creamos
if dict_file is None or not dict_file:
dict_file = {}
dict_file['settings'] = dict_settings
# Creamos el archivo ../settings/channel_data.json
try:
json_data = jsontools.dump(dict_file)
open(file_settings, "w").write(json_data)
except EnvironmentError:
logger.error("ERROR al salvar el archivo: %s" % file_settings)
return None
return value
|
Add cheese for £0.50 cheese & pepperoni for just 51p!
8 pieces.Tender chicken strip coated in crispy bread crumbs.
(Vegetarian, Hot) Onion, Sweetcorn, Pineapple, Mixed Pepper & Jalapeño Chillies.
Ham, Pepperoni, American Sausage & Spicy Beef.
Mushroom, Mixed Peppers, Chinese Chicken & Sweetcorn.
Mushroom, Mixed Peppers, Tandoori Chicken & Sweetcorn.
Smokey Bacon, Smokey Sausage, Fresh Tomatoes & Mushroom.
BBQ Sauce, Onions, Mixed Pepper, Sweetcorn, Tandoori Chicken & Chinese Chicken.
Pepperoni, Ham, Bacon & Mushroom. |
#!/usr/bin/env python
# encoding: utf-8
import json
import requests
import urllib
import hashlib
import io
from cortexutils.analyzer import Analyzer
class OTXQueryAnalyzer(Analyzer):
def __init__(self):
Analyzer.__init__(self)
self.otx_key = self.get_param('config.key', None, 'Missing OTX API key')
def _get_headers(self):
return {
'X-OTX-API-KEY': self.otx_key,
'Accept': 'application/json'
}
def otx_query_ip(self, data):
baseurl = "https://otx.alienvault.com:443/api/v1/indicators/IPv4/%s/" % data
headers = self._get_headers()
sections = [
'general',
'reputation',
'geo',
'malware',
'url_list',
'passive_dns'
]
ip_ = {}
try:
for section in sections:
queryurl = baseurl + section
ip_[section] = json.loads(requests.get(queryurl, headers=headers).content)
ip_general = ip_['general']
ip_geo = ip_['geo']
self.report({
'pulse_count': ip_general.get('pulse_info', {}).get('count', "0"),
'pulses': ip_general.get('pulse_info', {}).get('pulses', "-"),
'whois': ip_general.get('whois', "-"),
'continent_code': ip_geo.get('continent_code', "-"),
'country_code': ip_geo.get('country_code', "-"),
'country_name': ip_geo.get('country_name', "-"),
'city': ip_geo.get('city', "-"),
'longitude': ip_general.get('longitude', "-"),
'latitude': ip_general.get('latitude', "-"),
'asn': ip_geo.get('asn', "-"),
'malware_samples': ip_.get('malware', {}).get('result', "-"),
'url_list': ip_.get('url_list', {}).get('url_list', "-"),
'passive_dns': ip_.get('passive_dns', {}).get('passive_dns', "-")
})
except Exception:
self.error('API Error! Please verify data type is correct.')
def otx_query_domain(self, data):
baseurl = "https://otx.alienvault.com:443/api/v1/indicators/domain/%s/" % data
headers = self._get_headers()
sections = ['general', 'geo', 'malware', 'url_list', 'passive_dns']
ip_ = {}
try:
for section in sections:
queryurl = baseurl + section
ip_[section] = json.loads(requests.get(queryurl, headers=headers).content)
result = {
'pulse_count': ip_.get('general', {}).get('pulse_info', {}).get('count', "0"),
'pulses': ip_.get('general', {}).get('pulse_info', {}).get('pulses', "-"),
'whois': ip_.get('general', {}).get('whois', "-"),
'malware_samples': ip_.get('malware', {}).get('result', "-"),
'url_list': ip_.get('url_list', {}).get('url_list', "-"),
'passive_dns': ip_.get('passive_dns', {}).get('passive_dns', "-")
}
try:
result.update({
'continent_code': ip_.get('geo', {}).get('continent_code', "-"),
'country_code': ip_.get('geo', {}).get('country_code', "-"),
'country_name': ip_.get('geo', {}).get('country_name', "-"),
'city': ip_.get('geo', {}).get('city', "-"),
'asn': ip_.get('geo', {}).get('asn', "-")
})
except Exception:
pass
self.report(result)
except Exception:
self.error('API Error! Please verify data type is correct.')
def otx_query_file(self, data):
baseurl = "https://otx.alienvault.com:443/api/v1/indicators/file/%s/" % data
headers = self._get_headers()
sections = ['general', 'analysis']
ip_ = {}
try:
for section in sections:
queryurl = baseurl + section
ip_[section] = json.loads(requests.get(queryurl, headers=headers).content)
if ip_['analysis']['analysis']:
# file has been analyzed before
self.report({
'pulse_count': ip_.get('general', {}).get('pulse_info', {}).get('count', "0"),
'pulses': ip_.get('general', {}).get('pulse_info', {}).get('pulses', "-"),
'malware': ip_.get('analysis', {}).get('malware', "-"),
'page_type': ip_.get('analysis', {}).get('page_type', "-"),
'sha1': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get('sha1',
"-"),
'sha256': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get(
'sha256', "-"),
'md5': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get('md5',
"-"),
'file_class': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get(
'file_class', "-"),
'file_type': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get(
'file_type', "-"),
'filesize': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get(
'filesize', "-"),
'ssdeep': ip_.get('analysis', {}).get('analysis', {}).get('info', {}).get('results', {}).get(
'ssdeep')
})
else:
# file has not been analyzed before
self.report({
'errortext': 'File has not previously been analyzed by OTX!',
'pulse_count': ip_['general']['pulse_info']['count'],
'pulses': ip_['general']['pulse_info']['pulses']
})
except Exception:
self.error('API Error! Please verify data type is correct.')
def otx_query_url(self, data):
# urlencode the URL that we are searching for
data = urllib.quote_plus(data)
baseurl = "https://otx.alienvault.com:443/api/v1/indicators/url/%s/" % data
headers = self._get_headers()
sections = ['general', 'url_list']
IP_ = {}
try:
for section in sections:
queryurl = baseurl + section
IP_[section] = json.loads(requests.get(queryurl, headers=headers).content)
self.report({
'pulse_count': IP_.get('general', {}).get('pulse_info', {}).get('count', "0"),
'pulses': IP_.get('general', {}).get('pulse_info', {}).get('pulses', "-"),
'alexa': IP_.get('general', {}).get('alexa', "-"),
'whois': IP_.get('general', {}).get('whois', "-"),
'url_list': IP_.get('url_list', {}).get('url_list', "-")
})
except:
self.error('API Error! Please verify data type is correct.')
def summary(self, raw):
taxonomies = []
level = "info"
namespace = "OTX"
predicate = "Pulses"
value = "{}".format(raw["pulse_count"])
taxonomies.append(self.build_taxonomy(level, namespace, predicate, value))
return {"taxonomies": taxonomies}
def run(self):
Analyzer.run(self)
if self.data_type == 'file':
hashes = self.get_param('attachment.hashes', None)
if hashes is None:
filepath = self.get_param('file', None, 'File is missing')
sha256 = hashlib.sha256()
with io.open(filepath, 'rb') as fh:
while True:
data = fh.read(4096)
if not data:
break
sha256.update(data)
hash = sha256.hexdigest()
else:
# find SHA256 hash
hash = next(h for h in hashes if len(h) == 64)
self.otx_query_file(hash)
elif self.data_type == 'url':
data = self.get_param('data', None, 'Data is missing')
self.otx_query_url(data)
elif self.data_type == 'domain':
data = self.get_param('data', None, 'Data is missing')
self.otx_query_domain(data)
elif self.data_type == 'ip':
data = self.get_param('data', None, 'Data is missing')
self.otx_query_ip(data)
elif self.data_type == 'hash':
data = self.get_param('data', None, 'Data is missing')
self.otx_query_file(data)
else:
self.error('Invalid data type')
if __name__ == '__main__':
OTXQueryAnalyzer().run()
|
DuraTech provides an effective way to make your logos, product names and other branding materials to stand out with its domed label services. Domed labels, also called domed stickers, tags, nameplates, or domed decals, are a more durable type of adhesive label that are commonly found on consumer products, vehicles and appliances.
Whether you need a simple dome label solution or full color graphics, DuraTech maintains the best doming process in the industry.
Though doming is not a relatively new product on the market, it definitely is one that is under used. This clear protective polyurethane “dome” enhances any product and makes an impressive visual impact.
In either a selective or full-coverage application, DuraDome creates a 3D image that enhances clarity and color on any product it is used on.
Durable and tough – approved for automotive use and outdoor conditions.
Will not yellow and stands up to UV exposure.
Flexible for those applications that require adherence to slightly curved surfaces. |
# -*- coding: utf-8 -*-
#
# Copyright 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
from katello.client.api.base import KatelloAPI
class CustomInfoAPI(KatelloAPI):
"""
Connection class to access custom info calls
"""
def add_custom_info(self, informable_type, informable_id, keyname, value):
data = { 'keyname': keyname, 'value': value }
path = "/api/custom_info/%s/%s" % (informable_type, informable_id)
return self.server.POST(path, data)[1]
def get_custom_info(self, informable_type, informable_id, keyname = None):
if keyname:
path = "/api/custom_info/%s/%s/%s" % (informable_type, informable_id, keyname)
else:
path = "/api/custom_info/%s/%s" % (informable_type, informable_id)
return self.server.GET(path)[1]
def update_custom_info(self, informable_type, informable_id, keyname, new_value):
data = { 'value': new_value }
path = "/api/custom_info/%s/%s/%s" % (informable_type, informable_id, keyname)
return self.server.PUT(path, data)[1]
def remove_custom_info(self, informable_type, informable_id, keyname):
path = "/api/custom_info/%s/%s/%s" % (informable_type, informable_id, keyname)
return self.server.DELETE(path)[1]
|
John Puchala delivers exceptional designs for plumbing systems. With almost 40 years of experience, he has a strong background in effective project planning and implementation. John’s portfolio includes plumbing and fire protection design and construction phase services for a variety of commercial office buildings, residential, data center, healthcare, and government projects. |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio 1.x style error handling.
Logs exceptions to database and sends emails. Works only in connection with
register_exception().
**Configuration**
======================== ======================================================
`LOGGING_LEGACY_LEVEL` Log level threshold for handler. **Default:**
``ERROR``.
======================== ======================================================
"""
from __future__ import absolute_import
import logging
from ..handlers import InvenioLegacyHandler
from ..formatters import InvenioExceptionFormatter
def setup_app(app):
"""Invenio 1.x log handler."""
if not app.debug:
app.config.setdefault('LOGGING_LEGACY_LEVEL', 'ERROR')
handler = InvenioLegacyHandler()
handler.setFormatter(InvenioExceptionFormatter())
handler.setLevel(getattr(logging, app.config['LOGGING_LEGACY_LEVEL']))
# Add handler to application logger
app.logger.addHandler(handler)
|
As a senior in high school, I have had my fair share of time to observe and experience high school relationships first hand. After dating a few boys my freshman and sophomore year, I have come to the realization that high school relationships are taken way too seriously. Many people get caught up in the initial romance and love the constant attention. I hate to be the bearer of bad news, but THE INITIAL SPARK WILL FADE. Don’t spend all your time with your significant other and miss out on all the other amazing opportunities high school has to offer.
Unfortunately, I learned this the hard way. I was in a “very serious” relationship my sophomore year that lasted seven whole months. I abandoned all of my friends. When my boyfriend and I broke up, I was left with no one but my mom and dog.
At first, I thought my world was literally ending, as if the the sun would stop shining and the world would stop turning just because my relationship ended. How naive was I to really think that I would never be whole again?
Contrary to my belief, life continued, whether I wanted it to or not. I couldn’t see the big picture at the time, but that’s the thing about the teenage mind; it isn’t fully developed yet. As teenagers, we are mentally incapable of understanding what is or is not beneficial for our future selves. We are impulsive and irrational in every sense. One day, I want to get a tattoo and go skydiving, and the next, I realize that getting an anchor inked on my ankle is something I’ll probably regret when I’m 30 years old. One week, I want to move across the country for college, but the next day, I can’t imagine being more than an hour away from my home and family.
As a sophomore in high school, I was genuinely incapable of understanding true love. I was selfish and impulsive, much like any other 15-year-old.
Don’t get me wrong, relationships can be fun if you balance your time between your friends and your significant other.
If you’re currently in a relationship, don’t forget to go out with your friends, stay in with your family to watch a movie, go to yoga, and sit in a coffee shop alone and enjoy your own company. Hang out with your significant other as much as you want but don’t take it too seriously. Understand that only two percent of high school relationships end in marriage, so enjoy the fun times you have while you can. Go on long drives in the middle of the night and bake Christmas cookies. |
# test will be skipped if MySqlDB is unavailable
import unittest, string
from testlib import testutil, SkipTest, PygrTestProgram
from pygr import sqlgraph, seqdb, classutil, logger
class SQLSequence_Test(unittest.TestCase):
'''Basic SQL sequence class tests
This test setup uses the common (?) method of having the
SQLSequence objects created by a SQLTable object rather than
instantiating the SQLSequence objects directly.
'''
def setUp(self, serverInfo=None, dbname='test.sqlsequence_test'):
if not testutil.mysql_enabled():
raise SkipTest, "no MySQL installed"
createTable = """\
CREATE TABLE %s
(primary_id INTEGER PRIMARY KEY %%(AUTO_INCREMENT)s, sequence TEXT)
""" % dbname
self.db = sqlgraph.SQLTable(dbname, serverInfo=serverInfo,
dropIfExists=True,
createTable=createTable,
attrAlias=dict(seq='sequence'))
self.db.cursor.execute("""\
INSERT INTO %s (sequence)
VALUES ('CACCCTGCCCCATCTCCCCAGCCTGGCCCCTCGTGTCTCAGAACCCTCGGGGGGAGGCACAGAAGCCTTCGGGG')
""" % dbname)
self.db.cursor.execute("""\
INSERT INTO %s (sequence)
VALUES ('GAAAGAAAGAAAGAAAGAAAGAAAGAGAGAGAGAGAGACAGAAG')
""" % dbname)
class DNASeqRow(seqdb.DNASQLSequence):
def __len__(self): # just speed optimization
return self._select('length(sequence)') # SQL SELECT expression
# force the table object to return DNASeqRow objects
self.db.objclass(DNASeqRow)
self.row1 = self.db[1]
self.row2 = self.db[2]
self.EQ = self.assertEqual
def tearDown(self):
self.db.cursor.execute('drop table if exists test.sqlsequence_test')
def test_print(self):
"Testing identities"
self.EQ(str(self.row2), 'GAAAGAAAGAAAGAAAGAAAGAAAGAGAGAGAGAGAGACAGAAG')
self.EQ(repr(self.row2), '2[0:44]')
def test_len(self):
"Testing lengths"
self.EQ(len(self.row2), 44)
def test_strslice(self):
"Testing slices"
self.EQ(self.row2.strslice(3,10), 'AGAAAGA')
def init_subclass_test(self):
"Testing subclassing"
self.row2._init_subclass(self.db)
class SQLiteSequence_Test(testutil.SQLite_Mixin, SQLSequence_Test):
def sqlite_load(self):
SQLSequence_Test.setUp(self, self.serverInfo, 'sqlsequence_test')
def get_suite():
"Returns the testsuite"
tests = []
# detect mysql
if testutil.mysql_enabled():
tests.append(SQLSequence_Test)
else:
testutil.info('*** skipping SQLSequence_Test')
if testutil.sqlite_enabled():
tests.append(SQLiteSequence_Test)
else:
testutil.info('*** skipping SQLSequence_Test')
return testutil.make_suite(tests)
if __name__ == '__main__':
PygrTestProgram(verbosity=2)
|
It can save your expenses. It can save your expenses. Original Factory Hyster F187 S2. I believe that would be what you need. I believe that would be what you need.
Hyster E114 E1 50xm E1 75xm E2 00xm E2 00xms Europe Service Shop Manual Forklift Workshop Repair Book can be very useful guide, and hyster e114 e1 50xm e1 75xm e2 00xm e2 00xms europe service shop manual forklift workshop repair book play an important role in your products. This Parts Manual has easy-to-read text sections with top quality diagrams and instructions. It is great to have, will save you a lot and know more about your Hyster F001 H1. It can zoom in anywhere on your computer , so you can see it clearly. This Parts Manual has easy-to-read text sections with top quality diagrams and instructions. Original Factory Hyster E114 E1.
This Parts Manual has easy-to-read text sections with top quality diagrams and instructions. I believe that would be what you need. The problem is that once you have gotten your nifty new product, the hyster e114 e1 50xm e1 75xm e2 00xm e2 00xms europe service shop manual forklift workshop repair book gets a brief glance, maybe a once over, but it often tends to get discarded or lost with the original packaging. This entry was posted in on by. Do not hesitate, after your payment, you will immediately get the manual.
Save time and money by doing it yourself, with the confidence only a Hyster G108 E2. Do not hesitate, after your payment, you will immediately get the manual. It can save your expenses. It is great to have, will save you a lot and know more about your Hyster D114 E1. I believe that would be what you need.
It can zoom in anywhere on your computer , so you can see it clearly. It can zoom in anywhere on your computer, so you can see it clearly. This Parts Manual has easy-to-read text sections with top quality diagrams and instructions. Save time and money by doing it yourself, with the confidence only a Hyster L005 H3. This is the same information the dealer technicians and mechanics use to diagnose and repair your vehicle. Repair manual for Hyster Class 5 Internal Combustion Engine Trucks — Pneumatic Tire Hyster D005 H60E H70E H80E H100E H110E Americas Forklift Hyster D005 H60E H70E H80E H100E H110E Americas Forklift Service Repair Factory Manual is an electronic version of the best original maintenance manual.
Original Factory Hyster F004 S3. Compared to the electronic version and paper version , there is a great advantage. I believe that would be what you need. Original Factory Hyster G108 E2. Compared to the electronic version and paper version , there is a great advantage. This entry was posted in and tagged on by. It can zoom in anywhere on your computer , so you can see it clearly.
It is great to have, will save you a lot and know more about your Hyster J160 J1. Do not hesitate, after your payment, you will immediately get the manual. Original Factory Hyster G007 H8. Do not hesitate, after your payment, you will immediately get the manual. This entry was posted in and tagged on by.
Compared to the electronic version and paper version , there is a great advantage. Compared to the electronic version and paper version , there is a great advantage. Save time and money by doing it yourself, with the confidence only a Hyster D114 E1. It can save your expenses. Original Factory Hyster F019 H13. |
# Code from Chapter 6 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no warranty of any kind.
# Stephen Marsland, 2008, 2014
# The Kernel PCA algorithm
import numpy as np
import pylab as pl
def kernelmatrix(data,kernel,param=np.array([3,2])):
if kernel=='linear':
return np.dot(data,transpose(data))
elif kernel=='gaussian':
K = np.zeros((np.shape(data)[0],np.shape(data)[0]))
for i in range(np.shape(data)[0]):
for j in range(i+1,np.shape(data)[0]):
K[i,j] = np.sum((data[i,:]-data[j,:])**2)
K[j,i] = K[i,j]
return np.exp(-K**2/(2*param[0]**2))
elif kernel=='polynomial':
return (np.dot(data,np.transpose(data))+param[0])**param[1]
def kernelpca(data,kernel,redDim):
nData = np.shape(data)[0]
nDim = np.shape(data)[1]
K = kernelmatrix(data,kernel)
# Compute the transformed data
D = np.sum(K,axis=0)/nData
E = np.sum(D)/nData
J = np.ones((nData,1))*D
K = K - J - np.transpose(J) + E*np.ones((nData,nData))
# Perform the dimensionality reduction
evals,evecs = np.linalg.eig(K)
indices = np.argsort(evals)
indices = indices[::-1]
evecs = evecs[:,indices[:redDim]]
evals = evals[indices[:redDim]]
sqrtE = np.zeros((len(evals),len(evals)))
for i in range(len(evals)):
sqrtE[i,i] = np.sqrt(evals[i])
#print shape(sqrtE), shape(data)
newData = np.transpose(np.dot(sqrtE,np.transpose(evecs)))
return newData
#data = array([[0.1,0.1],[0.2,0.2],[0.3,0.3],[0.35,0.3],[0.4,0.4],[0.6,0.4],[0.7,0.45],[0.75,0.4],[0.8,0.35]])
#newData = kernelpca(data,'gaussian',2)
#plot(data[:,0],data[:,1],'o',newData[:,0],newData[:,0],'.')
#show()
|
GREAT SERVICE,SHAME ABOUT OUT OF STOCK ITEMS AND BABYCITY NOTIFING ME.
Absolutely wonderful ! The recipients loved the gift. All positive.
I love to shop on-line with babycity.
Navigation of website is easy.
Bath time is all about adding a splash of fun whilst your little one is bathed to be squeaky clean! We have gathered a selection of adorable bath time accessories by your favourite brands to make sure the experience goes down smoothly. Choose from bath toy scoops and hammocks to store your little one’s bath time toys, or sponges and wash mitts made from lavishly soft materials to gently clean the delicate skin of your little one. Wrap your baby up in a warm fluffy towel by Obaby or use a cuddle robe by Hello Kitty that promises to keep your little one cosy after a baby bath. |
#!/usr/bin/env python3
import sys
from datetime import datetime
TEMPLATE = """
---
Title: {title}
Date: {year}-{month}-{day} {hour}:{minute:02d}
Modified: {year}-{month}-{day} {hour}:{minute:02d}
Category:
Tags:
Authors: procamora
Slug: {slug}
Summary:
Status: draft
---
"""
def make_entrymdAntiguo(title):
today = datetime.today()
slug = title.lower().strip().replace(' ', '-')
f_create = "content/draft/{}_{:0>2}_{:0>2}_{}.md".format(
today.year, today.month, today.day, slug)
t = TEMPLATE.strip().format(title=title,
year=today.year,
month=today.month,
day=today.day,
hour=today.hour,
minute=today.minute,
slug="{}_{:0>2}_{:0>2}_{}".format(today.year, today.month, today.day, slug))
with open(f_create, 'w') as w:
w.write(t)
print("File created -> " + f_create)
def make_entrymd(title):
today = datetime.today()
slug = title.lower().strip().replace(' ', '_').replace(':', '').replace('.','')
f_create = "content/draft/{}.md".format(slug)
t = TEMPLATE.strip().format(title=title,
year=today.year,
month=today.month,
day=today.day,
hour=today.hour,
minute=today.minute,
slug=slug)
with open(f_create, 'w') as w:
w.write(t)
print("File created -> " + f_create)
if __name__ == '__main__':
if len(sys.argv) > 1:
make_entrymd(sys.argv[1])
else:
print("No title given")
|
If there is another election soon it is vital that the Tories have policies that are appealing to voters and their own base. The party needs to appeal to young, working class and middle class urban voters. I suggest that the four main planks should be on housing, investment, infrastructure and a stable Brexit.
1. Housing and rents. Rents are very high in most prosperous parts of the country and many people, especially young people, spend half their paycheques or more on small, cramped flats. Renting is insecure, and Labour’s rent controls and three-year lease policies are appealing to anyone who has had a bad landlord.
The Conservatives have to embrace reforms that will change this. And for rents to fall, we need more houses. Even if the green belt is an untouchable third rail, there’s a lot that we can do within cities to allow denser and more liveable developments. Get rid of height restrictions, allow people to add extra stories to their properties, allow streets to be turned into terraces, and stop micro-managing design.
Give councils a financial incentive to allow more development by giving them the power to buy land without planning permission and sell it off with permission, or sell off planning permission directly. Neutralise Labour’s advantage on long-term leases by offering something similar (we’ll have more on this in the coming weeks). Rent controls would be stupid but the Conservatives must have a bold vision for cutting the cost of housing if they want to win younger voters.
Corporations that make capital investments are required to deduct the costs of these investments over a number of years according to a schedule. Asset lives vary by type of assets and countries vary in how quickly they allow companies to depreciate them. The longer capital assets are written off, the more corporations need to pay and the more the government collects in tax over the life of an investment. This is because deductions made over time lose value due to both inflation and the time value of money.
In one respect Osborne’s corporation tax cuts made this worse, because they were partially paid for by reducing the value of deductions for machines and industrial buildings. Corporations now cannot write off the cost of investing in buildings at all.
This means that, in effect, many forms of investment face higher taxes under the new regime than under the old one, even though the headline rate is lower. This is counter-effective. Along with this, business rates act as a tax on property and machinery investment because they are calculated on the basis of the property value, not the land value. The more you invest the higher your tax bill. All of this means less productive jobs and lower wages for ordinary workers.
The Tories need to change this. If they propose immediate expensing of all business investment, they will have effectively replaced the corporation tax with a “cash flow tax” that does not tax business investment. It could be doing revenue-neutrally without raising the headline rate with some other tweaks to the system (like the tax favouring of debt over equity financing). Labour were able to win people over to taxing corporations more — this reform ensures that we wouldn’t be taxing businesses that invest.
Combined with a reform to business rates, it would be rocket fuel for the economy and produce a surge of investment that would mean better jobs for workers, and the kind of capital-intensive, manufacturing jobs that people really seem to want.
3. Privately-funded infrastructure. As the Telegraph’s Juliet Samuel has pointed out, pension funds hold trillions of pounds that they are dying to invest in safe projects that will give a steady, reliable, return. Infrastructure — new roads, railway lines, airports and more — can do that. Australia’s system seems to work: the government builds, then sells to investors upon completion. They get a new, safe asset, and we get a new railway to ease the pressure on other ways of getting to work.
This, and other infrastructure spending, doesn’t have to be done by central government. Giving local government the power to issue bonds to fund new capital projects and decentralising transport spending would help to end the London-centricism that ends up with 84% of total UK infrastructure spending going on London and the South East.
They said it offered the electorate a chance to show the world we backed our prime minister’s plans for a hard version of Brexit, and to make no compromises on immigration and the European Court of Justice. They said that victory on June 8 would be the vindication of a rougher-edged, more populist model of Conservatism than the soppy and limp-wristed model Cameroons had tried to build.
Fair enough, then. Let this election be the test of that hypothesis.
I think it’s now clear that the Conservatives will be badly punished if they push ahead with a hard Brexit, and it’s unlikely that they’ll be able to anyway with Scottish and Northern Irish MPs now being so important to the new government’s majority. Jeremy Corbyn is just a few MPs away from power and we cannot afford to have the sort of recession that a hard Brexit would likely cause.
Brexit has not turned out to be the electoral trump card that May thought it would be. Brexit should still happen, because that’s what people voted for, but it should be as smooth an exit as possible and one that can win the support of most of the country. Forcing through a hard Brexit, where we leave the Single Market and face substantial regulatory barriers to trade with Europe, would be an economic and electoral disaster. The Tories should offer to take the politics out of the Brexit process, bringing in representatives from Labour, the SNP and the Liberal Democrats to the process and aiming for a final deal that can win support across the House. Something like a cross-party war cabinet.
Labour might reject this. If they do, fine. But Brexit is the most important event in post-Cold War British history, and for a minority government to force their version of it through after failing to win an election during which their Brexit stance was one of the key issues would be potentially disastrous. Freedom of movement could be moderated to be a ‘free movement of workers’ — any EU citizen with a job offer may move to Britain, but otherwise, no. An “EEA Option” like the one I outlined immediately after the Brexit vote would get us out, but avoid the risk of a major recession and long-term fall in incomes. Softly does it.
We need a manifesto that uses the private sector to solve the problems that low- and middle-income household have, and does not throw the country into recession just to win some pyrrhic victory over Brexit. The cack-handed, intellectually bankrupt clique that gave the Conservative Party one of its worst humiliations in its history on Thursday will never give us this. I hope eventually we get a Conservative leader who will. |
#tested beta
#function [U] = rot3z(a)
#% --------------------------------------------------------------------------
#% ROT3Z.M Form rotation matrix U to rotate the vector a to a point along
#% the positive z-axis.
#%
#% Version 1.0
#% Last amended I M Smith 2 May 2002.
#% Created I M Smith 2 May 2002.
#% --------------------------------------------------------------------------
#% Input
#% a Vector.
#% Dimension: 3 x 1.
#%
#% Output
#% U Rotation matrix with U * a = [0 0 z]', z > 0.
#% Dimension: 3 x 3.
#%
#% Modular structure: GR.M.
#%
#% [U] = rot3z(a)
#% --------------------------------------------------------------------------
#
#% form first Givens rotation
# [W, c1, s1] = gr(a(2), a(3));
# z = c1*a(2) + s1*a(3);
# V = [1 0 0; 0 s1 -c1; 0 c1 s1];
#%
#% form second Givens rotation
# [W, c2, s2] = gr(a(1), z);
#%
#% check positivity
# if c2 * a(1) + s2 * z < 0
# c2 = -c2;
# s2 = -s2;
# end % if
#%
# W = [s2 0 -c2; 0 1 0; c2 0 s2];
# U = W * V;
#% --------------------------------------------------------------------------
#% End of ROT3Z.M.
import math
import numpy as np
from gr import *
import types
def rot3z(a=None):
"""function [U] = rot3z(a)
rot3z.py Form rotation matrix U to rotate the vector a to a point along
the positive z-axis.
Input
a Vector.
Dimension: 3 x 1.
Output
U Rotation matrix with U * a = [0 0 z]', r > 0.
Dimension: 3 x 3.
Modular structure: gr.py """
#form first Givens rotation
if a!=None:
a=np.mat(a);
m,n=a.shape;
if n!=1:
a=a.T
else:
raise ArithmeticError, "A is None"
W, c1, s1= gr(a[1,0], a[2,0]);
z = c1*a[1,0] + s1*a[2,0];
V = np.mat([[1.0 ,0.0 ,0.0],[0.0 ,s1,-c1],[ 0.0 ,c1 ,s1]]);
#form second Givens rotation
W, c2, s2 = gr(a[0,0], z);
#check positivity
if c2 * a[0,0] + s2 * z < 0:
c2 = -c2;
s2 = -s2;
# end % if
#%
W = np.mat([[s2,0.0,-c2],[0.0,1.0,0.0], [c2,0.0,s2]])
U = W * V;
return U
if __name__=="__main__":
print rot3z.__doc__
a=np.mat([[1.0],
[1/np.sqrt(2)],
[1/np.sqrt(2)]])
r=rot3z(a)
print a
print r
# r: 0.707106781186548 -0.5 -0.5
# 0 0.707106781186548 -0.707106781186548
# 0.707106781186548 0.5 0.5
|
If you waited patiently for the release of Star Trek: The Next Generation Season One on Blu-ray Disc only to find yourself fiddling with your surround sound system because of an audio issue, you’ll be happy to know Paramount is promptly supplying replacement discs. Apparently, an anomaly affecting the English 7.1 DTS Master Audio track has been detected on discs 1, 3, and 4. The defect (described as the front channel designations being incorrectly mapped), causes playback problems in both 7.1 and 5.1 channel surround sound.
CBS and Paramount responded quickly to the problem after TNG Season One was released on July 24, and will supply replacement discs free-of-charge. To get replacement discs, email [email protected] or call 877-DELUXE6 (877-335-8936) Monday-Friday between 8am and 6pm PT for more details. |
from odoo import api, models, fields
class ReportLabelWizard(models.TransientModel):
_name = "report.label.wizard"
_description = "Report Label Wizard"
@api.model
def _default_line_ids(self):
""" Compute line_ids based on context """
active_model = self.env.context.get("active_model")
active_ids = self.env.context.get("active_ids", [])
if not active_model or not active_ids:
return False
return [
(0, 0, {
"res_id": res_id,
"quantity": 1,
})
for res_id in active_ids
]
model_id = fields.Many2one(
"ir.model",
"Model",
required=True,
default=lambda self: self.env.context.get("res_model_id"),
)
label_paperformat_id = fields.Many2one(
"report.paperformat.label",
"Label Paper Format",
readonly=True,
required=True,
default=lambda self: self.env.context.get("label_paperformat_id"),
)
label_template = fields.Char(
"Label QWeb Template",
readonly=True,
required=True,
default=lambda self: self.env.context.get("label_template"),
)
offset = fields.Integer(
help="Number of labels to skip when printing",
)
line_ids = fields.One2many(
"report.label.wizard.line",
"wizard_id",
"Lines",
default=_default_line_ids,
required=True,
)
def _prepare_report_data(self):
self.ensure_one()
return {
"label_format": self.label_paperformat_id.read()[0],
"label_template": self.label_template,
"offset": self.offset,
"res_model": self.model_id.model,
"lines": [
{
"res_id": line.res_id,
"quantity": line.quantity,
}
for line in self.line_ids
],
}
def print_report(self):
self.ensure_one()
report = self.env.ref("report_label.report_label")
action = report.report_action(self, data=self._prepare_report_data())
action["context"] = {
"paperformat_id": self.label_paperformat_id.paperformat_id.id,
}
return action
class ReportLabelWizardLine(models.TransientModel):
_name = "report.label.wizard.line"
_description = "Report Label Wizard Line"
_order = "sequence"
wizard_id = fields.Many2one(
"report.label.wizard",
"Wizard",
required=True,
ondelete="cascade",
)
sequence = fields.Integer(default=10)
res_id = fields.Integer("Resource ID", required=True)
res_name = fields.Char(compute="_compute_res_name")
quantity = fields.Integer(default=1, required=True)
@api.depends("wizard_id.model_id", "res_id")
def _compute_res_name(self):
wizard = self.mapped("wizard_id")
wizard.ensure_one()
res_model = wizard.model_id.model
res_ids = self.mapped("res_id")
names_map = dict(self.env[res_model].browse(res_ids).name_get())
for rec in self:
rec.res_name = names_map.get(rec.res_id)
|
forward to everything that comes next from the creators of LifterLMS! As it says in the name of the plugin, it is a Learning Management System. So that everything in the site is placed properly and it is easier for the users to find the lessons. Creating Coupons If you want to run a premium education site with this plugin, Im sure you would like to have the coupon system for your site to create boost sales with promotional offers, this system offers you the option to create promotional offers right. You can also assign roles to each member and they will be able to access the system depending on the authority level assigned to their roles. LifterLMS brings more to than any other LMS plugin that you will find for WordPress out there. Another good news is that LifterLMS system integrates perfectly with some of the key WordPress plugins like BuddyPress and WooCommerce. There are a few, lifterLMS plans that you can consider for your website. Know Everything About WordPress Best Products in Your Inbox Subscribe to our mailing list and we will surprise you with amazing WordPress freebies Thank you for subscribing. In less than 10 months weve gone from 0 to 300K in revenue with LifterLMS playing a huge part in that! And you need to link the respective pages accordingly so that it doesnt show you any error.
See a full list of the. The built in email sending option is another best part of LifterLMS system, you can setup the email options in the email settings section to ad the senders email ID and customize the header and footer of the email. A quality learning cycle starts with the courses you offer and after completing the course the exam you get the certificate. The image above nicely describes the overall features of this amazing learning management system. Support As this is a premium product and relatively new in the market, Im sure there will be occasions when you will need support from the team behind this learning management system. LifterLMS is one such tool which will help you to organize your courses perfectly and help you to make revenue through your online coerces. Using LifterLMS, you can teach and sell courses, create custom sidebars for different membership levels and more. LifterLMS Overview Getting Started, lifterLMS is not just another WordPress plugin, after looking at the feature I consider this as a comprehensive application for online education. On activation of the plugin, it creates a few pages on your site which is used to carry on different functionality related to this plugin. |
from datetime import datetime, timedelta
import time
from openerp import pooler, tools
from openerp.osv import fields, osv
from openerp.tools.translate import _
import math
import base64
from openerp import netsvc
import openerp.addons.decimal_precision as dp
def print_barcode(code):
import barcodes
from barcodes import code128
from barcodes.write import CairoRender
def get_geometry(s):
spl = s.split("x", 1)
if len(spl) == 2:
try:
return int(spl[0]), int(spl[1])
except ValueError:
pass
raise ValueError("invalid geometry")
barcode = code128.Code128.from_unicode(code)
#width, height = get_geometry("2000x442")
width, height = get_geometry("708x342")
data = CairoRender(barcode, margin=8).get_png(width, height)
from subprocess import call
fn='barcode_image_data.png'
fp=open(fn,'wb')
fp.write(data)
fp.close()
call(['lpr', fn])
import os
os.unlink(fn)
class product_product(osv.osv):
_inherit="product.product"
def print_barcode_label(self, cr, uid, ids, context=None):
for p in self.browse(cr, uid, ids):
print_barcode(p.default_code)
product_product()
class sale_order(osv.osv):
_inherit="sale.order"
def print_barcode_label(self, cr, uid, ids, context=None):
for p in self.browse(cr, uid, ids):
print_barcode(p.name)
sale_order()
class purchase_order(osv.osv):
_inherit="purchase.order"
def print_barcode_label(self, cr, uid, ids, context=None):
for p in self.browse(cr, uid, ids):
print_barcode(p.name)
purchase_order()
class stock_picking(osv.osv):
_inherit="stock.picking"
def print_barcode_label(self, cr, uid, ids, context=None):
for p in self.browse(cr, uid, ids):
print_barcode(p.name)
stock_picking()
class stock_picking_out(osv.osv):
_inherit="stock.picking.out"
def print_barcode_label(self, cr, uid, ids, context=None):
for p in self.browse(cr, uid, ids):
print_barcode(p.name)
stock_picking_out()
class stock_picking_in(osv.osv):
_inherit="stock.picking.in"
def print_barcode_label(self, cr, uid, ids, context=None):
for p in self.browse(cr, uid, ids):
print_barcode(p.name)
stock_picking_in()
|
Synchronous behavior is fascinating to me, because once you are aware of it you see it happening all the time. Unintentional synchronization happens in every day life as well as in the lab. It happens most notably with someone who you are around for an extended period of time, or who you perform specific tasks with on a daily basis. For instance, a couple who lives together will have a synchronous morning routine. They will move around each other, knowing or understanding where and what the other person will do next. It makes for a fluid scene. Synchronous behavior can also be seen in nature, with animals such as dolphins. Dolphins will swim at high speeds underwater, and leap into the air at random intervals. Often, multiple dolphins will surface at the same exact time, arching through the air in a seemingly rehearsed fashion. Are the dolphins communicating with each other before these aerial displays or are they so in tune with each other that it comes naturally?
I used to work in an upscale Italian restaurant. For about a year there another server and I quickly began unintentionally synchronizing our movements in the kitchen, near the tables, and around the point of sale. I worked closely with this person on numerous shifts and we got to know how one another moved. During the heat of a busy shift in a restaurant, time can become everything. We want to get drinks and food out as quickly as possible for the best tips. In reading this chapter, I was able to make that connection that we did exactly what the author is talking about. We became synchronous with each other in how we maneuvered around the restaurant in order to efficiently do our jobs. |
from enigma import eDVBDB, eDVBResourceManager
from Screens.Screen import Screen
from Components.SystemInfo import SystemInfo
from Components.ActionMap import ActionMap
from Components.ConfigList import ConfigListScreen
from Components.NimManager import nimmanager
from Components.Button import Button
from Components.Label import Label
from Components.SelectionList import SelectionList, SelectionEntryComponent
from Components.config import getConfigListEntry, config, configfile, ConfigNothing, ConfigSatlist, ConfigYesNo
from Components.Sources.StaticText import StaticText
from Components.Sources.List import List
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.ServiceStopScreen import ServiceStopScreen
from Screens.AutoDiseqc import AutoDiseqc
from Tools.BoundFunction import boundFunction
from boxbranding import getBoxType
from time import mktime, localtime
from datetime import datetime
from os import path
def isFBCTuner(nim):
if nim.description.find("FBC") == -1:
return False
return True
def isFBCRoot(nim):
if nim.slot %8 < 2:
return True
return False
def isFBCLink(nim):
if isFBCTuner(nim) and not isFBCRoot(nim):
return True
return False
class NimSetup(Screen, ConfigListScreen, ServiceStopScreen):
def createSimpleSetup(self, list, mode):
nim = self.nimConfig
if mode == "single":
self.singleSatEntry = getConfigListEntry(_("Satellite"), nim.diseqcA)
list.append(self.singleSatEntry)
if nim.diseqcA.value in ("360", "560"):
list.append(getConfigListEntry(_("Use circular LNB"), nim.simpleDiSEqCSetCircularLNB))
list.append(getConfigListEntry(_("Send DiSEqC"), nim.simpleSingleSendDiSEqC))
else:
list.append(getConfigListEntry(_("Port A"), nim.diseqcA))
if mode in ("toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"):
list.append(getConfigListEntry(_("Port B"), nim.diseqcB))
if mode == "diseqc_a_b_c_d":
list.append(getConfigListEntry(_("Port C"), nim.diseqcC))
list.append(getConfigListEntry(_("Port D"), nim.diseqcD))
if mode != "toneburst_a_b":
list.append(getConfigListEntry(_("Set voltage and 22KHz"), nim.simpleDiSEqCSetVoltageTone))
list.append(getConfigListEntry(_("Send DiSEqC only on satellite change"), nim.simpleDiSEqCOnlyOnSatChange))
def createPositionerSetup(self, list):
nim = self.nimConfig
if nim.diseqcMode.value == "positioner_select":
self.selectSatsEntry = getConfigListEntry(_("Press OK to select satellites"), self.nimConfig.pressOKtoList)
list.append(self.selectSatsEntry)
list.append(getConfigListEntry(_("Longitude"), nim.longitude))
list.append(getConfigListEntry(" ", nim.longitudeOrientation))
list.append(getConfigListEntry(_("Latitude"), nim.latitude))
list.append(getConfigListEntry(" ", nim.latitudeOrientation))
if SystemInfo["CanMeasureFrontendInputPower"]:
self.advancedPowerMeasurement = getConfigListEntry(_("Use power measurement"), nim.powerMeasurement)
list.append(self.advancedPowerMeasurement)
if nim.powerMeasurement.value:
list.append(getConfigListEntry(_("Power threshold in mA"), nim.powerThreshold))
self.turningSpeed = getConfigListEntry(_("Rotor turning speed"), nim.turningSpeed)
list.append(self.turningSpeed)
if nim.turningSpeed.value == "fast epoch":
self.turnFastEpochBegin = getConfigListEntry(_("Begin time"), nim.fastTurningBegin)
self.turnFastEpochEnd = getConfigListEntry(_("End time"), nim.fastTurningEnd)
list.append(self.turnFastEpochBegin)
list.append(self.turnFastEpochEnd)
else:
if nim.powerMeasurement.value:
nim.powerMeasurement.value = False
nim.powerMeasurement.save()
if not hasattr(self, 'additionalMotorOptions'):
self.additionalMotorOptions = ConfigYesNo(False)
self.showAdditionalMotorOptions = getConfigListEntry(_("Extra motor options"), self.additionalMotorOptions)
self.list.append(self.showAdditionalMotorOptions)
if self.additionalMotorOptions.value:
self.list.append(getConfigListEntry(" " + _("Horizontal turning speed") + " [" + chr(176) + "/sec]", nim.turningspeedH))
self.list.append(getConfigListEntry(" " + _("Vertical turning speed") + " [" + chr(176) + "/sec]", nim.turningspeedV))
self.list.append(getConfigListEntry(" " + _("Turning step size") + " [" + chr(176) + "]", nim.tuningstepsize))
self.list.append(getConfigListEntry(" " + _("Max memory positions"), nim.rotorPositions))
def createConfigMode(self):
if self.nim.isCompatible("DVB-S"):
choices = {"nothing": _("not configured"),
"simple": _("Simple"),
"advanced": _("Advanced")}
if len(nimmanager.canEqualTo(self.slotid)) > 0:
choices["equal"] = _("Equal to")
if len(nimmanager.canDependOn(self.slotid)) > 0:
choices["satposdepends"] = _("Second cable of motorized LNB")
if len(nimmanager.canConnectTo(self.slotid)) > 0:
choices["loopthrough"] = _("Loop through to")
if isFBCLink(self.nim):
choices = { "nothing": _("not configured"),
"advanced": _("advanced")}
self.nimConfig.configMode.setChoices(choices, default = "simple")
def createSetup(self):
print "Creating setup"
self.list = [ ]
self.multiType = None
self.configMode = None
self.diseqcModeEntry = None
self.advancedSatsEntry = None
self.advancedLnbsEntry = None
self.advancedDiseqcMode = None
self.advancedUsalsEntry = None
self.advancedLof = None
self.advancedPowerMeasurement = None
self.turningSpeed = None
self.turnFastEpochBegin = None
self.turnFastEpochEnd = None
self.toneburst = None
self.committedDiseqcCommand = None
self.uncommittedDiseqcCommand = None
self.commandOrder = None
self.cableScanType = None
self.have_advanced = False
self.advancedUnicable = None
self.advancedType = None
self.advancedManufacturer = None
self.advancedSCR = None
self.advancedDiction = None
self.advancedConnected = None
self.advancedUnicableTuningAlgo = None
self.showAdditionalMotorOptions = None
self.selectSatsEntry = None
self.advancedSelectSatsEntry = None
self.singleSatEntry = None
if self.nim.isMultiType():
try:
multiType = self.nimConfig.multiType
self.multiType = getConfigListEntry(_("Tuner type"), multiType)
self.list.append(self.multiType)
except:
self.multiType = None
if self.nim.isCompatible("DVB-S"):
self.configMode = getConfigListEntry(_("Configuration mode"), self.nimConfig.configMode)
self.list.append(self.configMode)
if self.nimConfig.configMode.value == "simple": #simple setup
self.diseqcModeEntry = getConfigListEntry(pgettext("Satellite configuration mode", "Mode"), self.nimConfig.diseqcMode)
self.list.append(self.diseqcModeEntry)
if self.nimConfig.diseqcMode.value in ("single", "toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"):
self.createSimpleSetup(self.list, self.nimConfig.diseqcMode.value)
if self.nimConfig.diseqcMode.value in ("positioner", "positioner_select"):
self.createPositionerSetup(self.list)
elif self.nimConfig.configMode.value == "equal":
choices = []
nimlist = nimmanager.canEqualTo(self.nim.slot)
for id in nimlist:
choices.append((str(id), nimmanager.getNimDescription(id)))
self.nimConfig.connectedTo.setChoices(choices)
self.list.append(getConfigListEntry(_("Tuner"), self.nimConfig.connectedTo))
elif self.nimConfig.configMode.value == "satposdepends":
choices = []
nimlist = nimmanager.canDependOn(self.nim.slot)
for id in nimlist:
choices.append((str(id), nimmanager.getNimDescription(id)))
self.nimConfig.connectedTo.setChoices(choices)
self.list.append(getConfigListEntry(_("Tuner"), self.nimConfig.connectedTo))
elif self.nimConfig.configMode.value == "loopthrough":
choices = []
print "connectable to:", nimmanager.canConnectTo(self.slotid)
connectable = nimmanager.canConnectTo(self.slotid)
for id in connectable:
choices.append((str(id), nimmanager.getNimDescription(id)))
self.nimConfig.connectedTo.setChoices(choices)
self.list.append(getConfigListEntry(_("Connected to"), self.nimConfig.connectedTo))
elif self.nimConfig.configMode.value == "nothing":
pass
elif self.nimConfig.configMode.value == "advanced": # advanced
# SATs
self.advancedSatsEntry = getConfigListEntry(_("Satellite"), self.nimConfig.advanced.sats)
self.list.append(self.advancedSatsEntry)
current_config_sats = self.nimConfig.advanced.sats.value
if current_config_sats in ("3605", "3606"):
self.advancedSelectSatsEntry = getConfigListEntry(_("Press OK to select satellites"), self.nimConfig.pressOKtoList)
self.list.append(self.advancedSelectSatsEntry)
self.fillListWithAdvancedSatEntrys(self.nimConfig.advanced.sat[int(current_config_sats)])
else:
cur_orb_pos = self.nimConfig.advanced.sats.orbital_position
satlist = self.nimConfig.advanced.sat.keys()
if cur_orb_pos is not None:
if cur_orb_pos not in satlist:
cur_orb_pos = satlist[0]
self.fillListWithAdvancedSatEntrys(self.nimConfig.advanced.sat[cur_orb_pos])
self.have_advanced = True
if path.exists("/proc/stb/frontend/%d/tone_amplitude" % self.nim.slot) and config.usage.setup_level.index >= 2: # expert
self.list.append(getConfigListEntry(_("Tone amplitude"), self.nimConfig.toneAmplitude))
if path.exists("/proc/stb/frontend/%d/use_scpc_optimized_search_range" % self.nim.slot) and config.usage.setup_level.index >= 2: # expert
self.list.append(getConfigListEntry(_("SCPC optimized search range"), self.nimConfig.scpcSearchRange))
if path.exists("/proc/stb/frontend/fbc/force_lnbon") and config.usage.setup_level.index >= 2: # expert
self.list.append(getConfigListEntry(_("Force LNB Power"), self.nimConfig.forceLnbPower))
if path.exists("/proc/stb/frontend/fbc/force_toneburst") and config.usage.setup_level.index >= 2: # expert
self.list.append(getConfigListEntry(_("Force ToneBurst"), self.nimConfig.forceToneBurst))
elif self.nim.isCompatible("DVB-C"):
self.configMode = getConfigListEntry(_("Configuration mode"), self.nimConfig.configMode)
self.list.append(self.configMode)
if self.nimConfig.configMode.value == "enabled":
self.list.append(getConfigListEntry(_("Network ID"), self.nimConfig.cable.scan_networkid))
self.cableScanType=getConfigListEntry(_("Used service scan type"), self.nimConfig.cable.scan_type)
self.list.append(self.cableScanType)
if self.nimConfig.cable.scan_type.value == "provider":
self.list.append(getConfigListEntry(_("Provider to scan"), self.nimConfig.cable.scan_provider))
else:
if self.nimConfig.cable.scan_type.value == "bands":
# TRANSLATORS: option name, indicating which type of (DVB-C) band should be scanned. The name of the band is printed in '%s'. E.g.: 'Scan EU MID band'
self.list.append(getConfigListEntry(_("Scan %s band") % "EU VHF I", self.nimConfig.cable.scan_band_EU_VHF_I))
self.list.append(getConfigListEntry(_("Scan %s band") % "EU MID", self.nimConfig.cable.scan_band_EU_MID))
self.list.append(getConfigListEntry(_("Scan %s band") % "EU VHF III", self.nimConfig.cable.scan_band_EU_VHF_III))
self.list.append(getConfigListEntry(_("Scan %s band") % "EU UHF IV", self.nimConfig.cable.scan_band_EU_UHF_IV))
self.list.append(getConfigListEntry(_("Scan %s band") % "EU UHF V", self.nimConfig.cable.scan_band_EU_UHF_V))
self.list.append(getConfigListEntry(_("Scan %s band") % "EU SUPER", self.nimConfig.cable.scan_band_EU_SUPER))
self.list.append(getConfigListEntry(_("Scan %s band") % "EU HYPER", self.nimConfig.cable.scan_band_EU_HYPER))
self.list.append(getConfigListEntry(_("Scan %s band") % "US LOW", self.nimConfig.cable.scan_band_US_LOW))
self.list.append(getConfigListEntry(_("Scan %s band") % "US MID", self.nimConfig.cable.scan_band_US_MID))
self.list.append(getConfigListEntry(_("Scan %s band") % "US HIGH", self.nimConfig.cable.scan_band_US_HIGH))
self.list.append(getConfigListEntry(_("Scan %s band") % "US SUPER", self.nimConfig.cable.scan_band_US_SUPER))
self.list.append(getConfigListEntry(_("Scan %s band") % "US HYPER", self.nimConfig.cable.scan_band_US_HYPER))
elif self.nimConfig.cable.scan_type.value == "steps":
self.list.append(getConfigListEntry(_("Frequency scan step size(khz)"), self.nimConfig.cable.scan_frequency_steps))
# TRANSLATORS: option name, indicating which type of (DVB-C) modulation should be scanned. The modulation type is printed in '%s'. E.g.: 'Scan QAM16'
self.list.append(getConfigListEntry(_("Scan %s") % "QAM16", self.nimConfig.cable.scan_mod_qam16))
self.list.append(getConfigListEntry(_("Scan %s") % "QAM32", self.nimConfig.cable.scan_mod_qam32))
self.list.append(getConfigListEntry(_("Scan %s") % "QAM64", self.nimConfig.cable.scan_mod_qam64))
self.list.append(getConfigListEntry(_("Scan %s") % "QAM128", self.nimConfig.cable.scan_mod_qam128))
self.list.append(getConfigListEntry(_("Scan %s") % "QAM256", self.nimConfig.cable.scan_mod_qam256))
self.list.append(getConfigListEntry(_("Scan %s") % "SR6900", self.nimConfig.cable.scan_sr_6900))
self.list.append(getConfigListEntry(_("Scan %s") % "SR6875", self.nimConfig.cable.scan_sr_6875))
self.list.append(getConfigListEntry(_("Scan additional SR"), self.nimConfig.cable.scan_sr_ext1))
self.list.append(getConfigListEntry(_("Scan additional SR"), self.nimConfig.cable.scan_sr_ext2))
self.have_advanced = False
elif self.nim.isCompatible("DVB-T"):
self.configMode = getConfigListEntry(_("Configuration mode"), self.nimConfig.configMode)
self.list.append(self.configMode)
self.have_advanced = False
if self.nimConfig.configMode.value == "enabled":
self.list.append(getConfigListEntry(_("Terrestrial provider"), self.nimConfig.terrestrial))
if not getBoxType() in ('spycat'):
self.list.append(getConfigListEntry(_("Enable 5V for active antenna"), self.nimConfig.terrestrial_5V))
else:
self.have_advanced = False
self["config"].list = self.list
self["config"].l.setList(self.list)
def newConfig(self):
self.setTextKeyBlue()
checkList = (self.configMode, self.diseqcModeEntry, self.advancedSatsEntry,
self.advancedLnbsEntry, self.advancedDiseqcMode, self.advancedUsalsEntry,
self.advancedLof, self.advancedPowerMeasurement, self.turningSpeed,
self.advancedType, self.advancedSCR, self.advancedDiction, self.advancedManufacturer, self.advancedUnicable, self.advancedConnected, self.advancedUnicableTuningAlgo,
self.toneburst, self.committedDiseqcCommand, self.uncommittedDiseqcCommand, self.singleSatEntry,
self.commandOrder, self.showAdditionalMotorOptions, self.cableScanType, self.multiType)
if self["config"].getCurrent() == self.multiType:
update_slots = [self.slotid]
from Components.NimManager import InitNimManager
InitNimManager(nimmanager, update_slots)
self.nim = nimmanager.nim_slots[self.slotid]
self.nimConfig = self.nim.config
for x in checkList:
if self["config"].getCurrent() == x:
self.createSetup()
break
def run(self):
if self.nimConfig.configMode.value == "simple":
autodiseqc_ports = 0
if self.nimConfig.diseqcMode.value == "single":
if self.nimConfig.diseqcA.orbital_position == 3600:
autodiseqc_ports = 1
elif self.nimConfig.diseqcMode.value == "diseqc_a_b":
if self.nimConfig.diseqcA.orbital_position == 3600 or self.nimConfig.diseqcB.orbital_position == 3600:
autodiseqc_ports = 2
elif self.nimConfig.diseqcMode.value == "diseqc_a_b_c_d":
if self.nimConfig.diseqcA.orbital_position == 3600 or self.nimConfig.diseqcB.orbital_position == 3600 or self.nimConfig.diseqcC.orbital_position == 3600 or self.nimConfig.diseqcD.orbital_position == 3600:
autodiseqc_ports = 4
if autodiseqc_ports:
self.autoDiseqcRun(autodiseqc_ports)
return False
if self.have_advanced and self.nim.config_mode == "advanced":
self.fillAdvancedList()
for x in self.list:
if x in (self.turnFastEpochBegin, self.turnFastEpochEnd):
# workaround for storing only hour*3600+min*60 value in configfile
# not really needed.. just for cosmetics..
tm = localtime(x[1].value)
dt = datetime(1970, 1, 1, tm.tm_hour, tm.tm_min)
x[1].value = int(mktime(dt.timetuple()))
x[1].save()
nimmanager.sec.update()
self.saveAll()
return True
def autoDiseqcRun(self, ports):
self.session.openWithCallback(self.autoDiseqcCallback, AutoDiseqc, self.slotid, ports, self.nimConfig.simpleDiSEqCSetVoltageTone, self.nimConfig.simpleDiSEqCOnlyOnSatChange)
def autoDiseqcCallback(self, result):
from Screens.Wizard import Wizard
if Wizard.instance is not None:
Wizard.instance.back()
else:
self.createSetup()
def fillListWithAdvancedSatEntrys(self, Sat):
lnbnum = int(Sat.lnb.value)
currLnb = self.nimConfig.advanced.lnb[lnbnum]
diction = None
if isinstance(currLnb, ConfigNothing):
currLnb = None
# LNBs
self.advancedLnbsEntry = getConfigListEntry(_("LNB"), Sat.lnb)
self.list.append(self.advancedLnbsEntry)
if currLnb:
if isFBCLink(self.nim):
if currLnb.lof.value != "unicable":
currLnb.lof.value = "unicable"
self.list.append(getConfigListEntry(_("Priority"), currLnb.prio))
self.advancedLof = getConfigListEntry("LOF", currLnb.lof)
self.list.append(self.advancedLof)
if currLnb.lof.value == "user_defined":
self.list.append(getConfigListEntry("LOF/L", currLnb.lofl))
self.list.append(getConfigListEntry("LOF/H", currLnb.lofh))
self.list.append(getConfigListEntry(_("Threshold"), currLnb.threshold))
if currLnb.lof.value == "unicable":
self.advancedUnicable = getConfigListEntry("Unicable "+_("Configuration mode"), currLnb.unicable)
self.list.append(self.advancedUnicable)
if currLnb.unicable.value == "unicable_user":
self.advancedDiction = getConfigListEntry(_("Diction"), currLnb.dictionuser)
self.list.append(self.advancedDiction)
if currLnb.dictionuser.value == "EN50494":
satcr = currLnb.satcruserEN50494
stcrvco = currLnb.satcrvcouserEN50494[currLnb.satcruserEN50494.index]
elif currLnb.dictionuser.value == "EN50607":
satcr = currLnb.satcruserEN50607
stcrvco = currLnb.satcrvcouserEN50607[currLnb.satcruserEN50607.index]
self.advancedSCR = getConfigListEntry(_("Channel"), satcr)
self.list.append(self.advancedSCR)
self.list.append(getConfigListEntry(_("Frequency"), stcrvco))
self.list.append(getConfigListEntry("LOF/L", currLnb.lofl))
self.list.append(getConfigListEntry("LOF/H", currLnb.lofh))
self.list.append(getConfigListEntry(_("Threshold"), currLnb.threshold))
elif currLnb.unicable.value == "unicable_matrix":
nimmanager.sec.reconstructUnicableDate(currLnb.unicableMatrixManufacturer, currLnb.unicableMatrix, currLnb)
manufacturer_name = currLnb.unicableMatrixManufacturer.value
manufacturer = currLnb.unicableMatrix[manufacturer_name]
product_name = manufacturer.product.value
self.advancedManufacturer = getConfigListEntry(_("Manufacturer"), currLnb.unicableMatrixManufacturer)
self.list.append(self.advancedManufacturer)
if product_name in manufacturer.scr:
diction = manufacturer.diction[product_name].value
self.advancedType = getConfigListEntry(_("Type"), manufacturer.product)
self.advancedSCR = getConfigListEntry(_("Channel"), manufacturer.scr[product_name])
self.list.append(self.advancedType)
self.list.append(self.advancedSCR)
self.list.append(getConfigListEntry(_("Frequency"), manufacturer.vco[product_name][manufacturer.scr[product_name].index]))
elif currLnb.unicable.value == "unicable_lnb":
nimmanager.sec.reconstructUnicableDate(currLnb.unicableLnbManufacturer, currLnb.unicableLnb, currLnb)
manufacturer_name = currLnb.unicableLnbManufacturer.value
manufacturer = currLnb.unicableLnb[manufacturer_name]
product_name = manufacturer.product.value
self.advancedManufacturer = getConfigListEntry(_("Manufacturer"), currLnb.unicableLnbManufacturer)
self.list.append(self.advancedManufacturer)
if product_name in manufacturer.scr:
diction = manufacturer.diction[product_name].value
self.advancedType = getConfigListEntry(_("Type"), manufacturer.product)
self.advancedSCR = getConfigListEntry(_("Channel"), manufacturer.scr[product_name])
self.list.append(self.advancedType)
self.list.append(self.advancedSCR)
self.list.append(getConfigListEntry(_("Frequency"), manufacturer.vco[product_name][manufacturer.scr[product_name].index]))
self.advancedUnicableTuningAlgo = getConfigListEntry(_("Tuning algorithm"), currLnb.unicableTuningAlgo)
self.list.append(self.advancedUnicableTuningAlgo)
choices = []
connectable = nimmanager.canConnectTo(self.slotid)
for id in connectable:
choices.append((str(id), nimmanager.getNimDescription(id)))
if len(choices):
if isFBCLink(self.nim):
if self.nimConfig.advanced.unicableconnected.value != True:
self.nimConfig.advanced.unicableconnected.value = True
self.advancedConnected = getConfigListEntry(_("connected"), self.nimConfig.advanced.unicableconnected)
self.list.append(self.advancedConnected)
if self.nimConfig.advanced.unicableconnected.value:
self.nimConfig.advanced.unicableconnectedTo.setChoices(choices)
self.list.append(getConfigListEntry(_("Connected to"),self.nimConfig.advanced.unicableconnectedTo))
else: #no Unicable
self.list.append(getConfigListEntry(_("Voltage mode"), Sat.voltage))
self.list.append(getConfigListEntry(_("Increased voltage"), currLnb.increased_voltage))
self.list.append(getConfigListEntry(_("Tone mode"), Sat.tonemode))
if lnbnum < 65 and diction !="EN50607":
self.advancedDiseqcMode = getConfigListEntry(_("DiSEqC mode"), currLnb.diseqcMode)
self.list.append(self.advancedDiseqcMode)
if currLnb.diseqcMode.value != "none":
self.list.append(getConfigListEntry(_("Fast DiSEqC"), currLnb.fastDiseqc))
self.toneburst = getConfigListEntry(_("Toneburst"), currLnb.toneburst)
self.list.append(self.toneburst)
self.committedDiseqcCommand = getConfigListEntry(_("DiSEqC 1.0 command"), currLnb.commitedDiseqcCommand)
self.list.append(self.committedDiseqcCommand)
if currLnb.diseqcMode.value == "1_0":
if currLnb.toneburst.index and currLnb.commitedDiseqcCommand.index:
self.list.append(getConfigListEntry(_("Command order"), currLnb.commandOrder1_0))
else:
self.uncommittedDiseqcCommand = getConfigListEntry(_("DiSEqC 1.1 command"), currLnb.uncommittedDiseqcCommand)
self.list.append(self.uncommittedDiseqcCommand)
if currLnb.uncommittedDiseqcCommand.index:
if currLnb.commandOrder.value == "ct":
currLnb.commandOrder.value = "cut"
elif currLnb.commandOrder.value == "tc":
currLnb.commandOrder.value = "tcu"
else:
if currLnb.commandOrder.index & 1:
currLnb.commandOrder.value = "tc"
else:
currLnb.commandOrder.value = "ct"
self.commandOrder = getConfigListEntry(_("Command order"), currLnb.commandOrder)
if 1 < ((1 if currLnb.uncommittedDiseqcCommand.index else 0) + (1 if currLnb.commitedDiseqcCommand.index else 0) + (1 if currLnb.toneburst.index else 0)):
self.list.append(self.commandOrder)
if currLnb.uncommittedDiseqcCommand.index:
self.list.append(getConfigListEntry(_("DiSEqC 1.1 repeats"), currLnb.diseqcRepeats))
self.list.append(getConfigListEntry(_("Sequence repeat"), currLnb.sequenceRepeat))
if currLnb.diseqcMode.value == "1_2":
if SystemInfo["CanMeasureFrontendInputPower"]:
self.advancedPowerMeasurement = getConfigListEntry(_("Use power measurement"), currLnb.powerMeasurement)
self.list.append(self.advancedPowerMeasurement)
if currLnb.powerMeasurement.value:
self.list.append(getConfigListEntry(_("Power threshold in mA"), currLnb.powerThreshold))
self.turningSpeed = getConfigListEntry(_("Rotor turning speed"), currLnb.turningSpeed)
self.list.append(self.turningSpeed)
if currLnb.turningSpeed.value == "fast epoch":
self.turnFastEpochBegin = getConfigListEntry(_("Begin time"), currLnb.fastTurningBegin)
self.turnFastEpochEnd = getConfigListEntry(_("End time"), currLnb.fastTurningEnd)
self.list.append(self.turnFastEpochBegin)
self.list.append(self.turnFastEpochEnd)
else:
if currLnb.powerMeasurement.value:
currLnb.powerMeasurement.value = False
currLnb.powerMeasurement.save()
self.advancedUsalsEntry = getConfigListEntry(_("Use USALS for this sat"), Sat.usals)
if lnbnum < 65:
self.list.append(self.advancedUsalsEntry)
if Sat.usals.value:
self.list.append(getConfigListEntry(_("Longitude"), currLnb.longitude))
self.list.append(getConfigListEntry(" ", currLnb.longitudeOrientation))
self.list.append(getConfigListEntry(_("Latitude"), currLnb.latitude))
self.list.append(getConfigListEntry(" ", currLnb.latitudeOrientation))
else:
self.list.append(getConfigListEntry(_("Stored position"), Sat.rotorposition))
if not hasattr(self, 'additionalMotorOptions'):
self.additionalMotorOptions = ConfigYesNo(False)
self.showAdditionalMotorOptions = getConfigListEntry(_("Extra motor options"), self.additionalMotorOptions)
self.list.append(self.showAdditionalMotorOptions)
if self.additionalMotorOptions.value:
self.list.append(getConfigListEntry(" " + _("Horizontal turning speed") + " [" + chr(176) + "/sec]", currLnb.turningspeedH))
self.list.append(getConfigListEntry(" " + _("Vertical turning speed") + " [" + chr(176) + "/sec]", currLnb.turningspeedV))
self.list.append(getConfigListEntry(" " + _("Turning step size") + " [" + chr(176) + "]", currLnb.tuningstepsize))
self.list.append(getConfigListEntry(" " + _("Max memory positions"), currLnb.rotorPositions))
def fillAdvancedList(self):
self.list = [ ]
self.configMode = getConfigListEntry(_("Configuration mode"), self.nimConfig.configMode)
self.list.append(self.configMode)
self.advancedSatsEntry = getConfigListEntry(_("Satellite"), self.nimConfig.advanced.sats)
self.list.append(self.advancedSatsEntry)
for x in self.nimConfig.advanced.sat.keys():
Sat = self.nimConfig.advanced.sat[x]
self.fillListWithAdvancedSatEntrys(Sat)
self["config"].list = self.list
def unicableconnection(self):
if self.nimConfig.configMode.value == "advanced":
connect_count = 0
dvbs_slots = nimmanager.getNimListOfType('DVB-S')
dvbs_slots_len = len(dvbs_slots)
for x in dvbs_slots:
try:
nim_slot = nimmanager.nim_slots[x]
if nim_slot == self.nimConfig:
self_idx = x
if nim_slot.config.configMode.value == "advanced":
if nim_slot.config.advanced.unicableconnected.value == True:
connect_count += 1
except: pass
print "adenin conections %d %d" %(connect_count, dvbs_slots_len)
if connect_count >= dvbs_slots_len:
return False
self.slot_dest_list = []
def checkRecursiveConnect(slot_id):
if slot_id in self.slot_dest_list:
print slot_id
return False
self.slot_dest_list.append(slot_id)
slot_config = nimmanager.nim_slots[slot_id].config
if slot_config.configMode.value == "advanced":
try:
connected = slot_config.advanced.unicableconnected.value
except:
connected = False
if connected == True:
return checkRecursiveConnect(int(slot_config.advanced.unicableconnectedTo.value))
return True
return checkRecursiveConnect(self.slotid)
def checkLoopthrough(self):
if self.nimConfig.configMode.value == "loopthrough":
loopthrough_count = 0
dvbs_slots = nimmanager.getNimListOfType('DVB-S')
dvbs_slots_len = len(dvbs_slots)
for x in dvbs_slots:
try:
nim_slot = nimmanager.nim_slots[x]
if nim_slot == self.nimConfig:
self_idx = x
if nim_slot.config.configMode.value == "loopthrough":
loopthrough_count += 1
except: pass
if loopthrough_count >= dvbs_slots_len:
return False
self.slot_dest_list = []
def checkRecursiveConnect(slot_id):
if slot_id in self.slot_dest_list:
return False
self.slot_dest_list.append(slot_id)
slot_config = nimmanager.nim_slots[slot_id].config
if slot_config.configMode.value == "loopthrough":
return checkRecursiveConnect(int(slot_config.connectedTo.value))
return True
return checkRecursiveConnect(self.slotid)
def keyOk(self):
if self["config"].getCurrent() == self.advancedSelectSatsEntry:
conf = self.nimConfig.advanced.sat[int(self.nimConfig.advanced.sats.value)].userSatellitesList
self.session.openWithCallback(boundFunction(self.updateConfUserSatellitesList, conf), SelectSatsEntryScreen, userSatlist=conf.value)
elif self["config"].getCurrent() == self.selectSatsEntry:
conf = self.nimConfig.userSatellitesList
self.session.openWithCallback(boundFunction(self.updateConfUserSatellitesList, conf), SelectSatsEntryScreen, userSatlist=conf.value)
else:
self.keySave()
def updateConfUserSatellitesList(self, conf, val=None):
if val is not None:
conf.value = val
conf.save()
def keySave(self):
if not self.unicableconnection():
self.session.open(MessageBox, _("The unicable connection setting is wrong.\n Maybe recursive connection of tuners."),MessageBox.TYPE_ERROR,timeout=10)
return
if not self.checkLoopthrough():
self.session.open(MessageBox, _("The loopthrough setting is wrong."),MessageBox.TYPE_ERROR,timeout=10)
return
old_configured_sats = nimmanager.getConfiguredSats()
if not self.run():
return
new_configured_sats = nimmanager.getConfiguredSats()
self.unconfed_sats = old_configured_sats - new_configured_sats
self.satpos_to_remove = None
self.deleteConfirmed((None, "no"))
def deleteConfirmed(self, confirmed):
if confirmed is None:
confirmed = (None, "no")
if confirmed[1] == "yes" or confirmed[1] == "yestoall":
eDVBDB.getInstance().removeServices(-1, -1, -1, self.satpos_to_remove)
if self.satpos_to_remove is not None:
self.unconfed_sats.remove(self.satpos_to_remove)
self.satpos_to_remove = None
for orbpos in self.unconfed_sats:
self.satpos_to_remove = orbpos
orbpos = self.satpos_to_remove
try:
# why we need this cast?
sat_name = str(nimmanager.getSatDescription(orbpos))
except:
if orbpos > 1800: # west
orbpos = 3600 - orbpos
h = _("W")
else:
h = _("E")
sat_name = ("%d.%d" + h) % (orbpos / 10, orbpos % 10)
if confirmed[1] == "yes" or confirmed[1] == "no":
# TRANSLATORS: The satellite with name '%s' is no longer used after a configuration change. The user is asked whether or not the satellite should be deleted.
self.session.openWithCallback(self.deleteConfirmed, ChoiceBox, _("%s is no longer used. Should it be deleted?") % sat_name, [(_("Yes"), "yes"), (_("No"), "no"), (_("Yes to all"), "yestoall"), (_("No to all"), "notoall")], None, 1)
if confirmed[1] == "yestoall" or confirmed[1] == "notoall":
self.deleteConfirmed(confirmed)
break
else:
self.restoreService(_("Zap back to service before tuner setup?"))
def __init__(self, session, slotid):
Screen.__init__(self, session)
Screen.setTitle(self, _("Tuner settings"))
self.list = [ ]
ServiceStopScreen.__init__(self)
self.stopService()
ConfigListScreen.__init__(self, self.list)
self["key_red"] = Label(_("Close"))
self["key_green"] = Label(_("Save"))
self["key_yellow"] = Label(_("Configuration mode"))
self["key_blue"] = Label()
self["actions"] = ActionMap(["SetupActions", "SatlistShortcutAction", "ColorActions"],
{
"ok": self.keyOk,
"save": self.keySave,
"cancel": self.keyCancel,
"changetype": self.changeConfigurationMode,
"nothingconnected": self.nothingConnectedShortcut,
"red": self.keyCancel,
"green": self.keySave,
}, -2)
self.slotid = slotid
self.nim = nimmanager.nim_slots[slotid]
self.nimConfig = self.nim.config
self.createConfigMode()
self.createSetup()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(_("Reception Settings"))
def keyLeft(self):
if isFBCLink(self.nim):
checkList = (self.advancedLof, self.advancedConnected)
curEntry = self["config"].getCurrent()
if curEntry in checkList:
return
ConfigListScreen.keyLeft(self)
if self["config"].getCurrent() in (self.advancedSelectSatsEntry, self.selectSatsEntry):
self.keyOk()
else:
self.newConfig()
def setTextKeyBlue(self):
self["key_blue"].setText("")
if self["config"].isChanged():
self["key_blue"].setText(_("Set default"))
def keyRight(self):
if isFBCLink(self.nim):
checkList = (self.advancedLof, self.advancedConnected)
curEntry = self["config"].getCurrent()
if curEntry in checkList:
return
ConfigListScreen.keyRight(self)
if self["config"].getCurrent() in (self.advancedSelectSatsEntry, self.selectSatsEntry):
self.keyOk()
else:
self.newConfig()
def handleKeyFileCallback(self, answer):
ConfigListScreen.handleKeyFileCallback(self, answer)
self.newConfig()
def keyCancel(self):
if self["config"].isChanged():
self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"), default = False)
else:
self.restoreService(_("Zap back to service before tuner setup?"))
def saveAll(self):
if self.nim.isCompatible("DVB-S"):
# reset connectedTo to all choices to properly store the default value
choices = []
nimlist = nimmanager.getNimListOfType("DVB-S", self.slotid)
for id in nimlist:
choices.append((str(id), nimmanager.getNimDescription(id)))
self.nimConfig.connectedTo.setChoices(choices)
# sanity check for empty sat list
if self.nimConfig.configMode.value != "satposdepends" and len(nimmanager.getSatListForNim(self.slotid)) < 1:
self.nimConfig.configMode.value = "nothing"
for x in self["config"].list:
x[1].save()
configfile.save()
def cancelConfirm(self, result):
if not result:
return
for x in self["config"].list:
x[1].cancel()
# we need to call saveAll to reset the connectedTo choices
self.saveAll()
self.restoreService(_("Zap back to service before tuner setup?"))
def changeConfigurationMode(self):
if self.configMode:
self.nimConfig.configMode.selectNext()
self["config"].invalidate(self.configMode)
self.setTextKeyBlue()
self.createSetup()
def nothingConnectedShortcut(self):
if self["config"].isChanged():
for x in self["config"].list:
x[1].cancel()
self.setTextKeyBlue()
self.createSetup()
class NimSelection(Screen):
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Tuner configuration"))
self.list = [None] * nimmanager.getSlotCount()
self["nimlist"] = List(self.list)
self.loadFBCLinks()
self.updateList()
self.setResultClass()
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Select"))
self["actions"] = ActionMap(["SetupActions", "ColorActions", "MenuActions", "ChannelSelectEPGActions"],
{
"ok": self.okbuttonClick,
"info": self.extraInfo,
"epg": self.extraInfo,
"cancel": self.close,
"red": self.close,
"green": self.okbuttonClick,
"menu": self.exit,
}, -2)
self.setTitle(_("Choose Tuner"))
def loadFBCLinks(self):
for x in nimmanager.nim_slots:
slotid = x.slot
nimConfig = nimmanager.getNimConfig(x.slot)
configMode = nimConfig.configMode.value
if self.showNim(x):
if x.isCompatible("DVB-S"):
if isFBCLink(x) and configMode != "advanced":
from enigma import getLinkedSlotID
link = getLinkedSlotID(x.slot)
if link == -1:
nimConfig.configMode.value = "nothing"
else:
nimConfig.configMode.value = "loopthrough"
nimConfig.connectedTo.value = str(link)
def exit(self):
self.close(True)
def setResultClass(self):
self.resultclass = NimSetup
def extraInfo(self):
nim = self["nimlist"].getCurrent()
nim = nim and nim[3]
if config.usage.setup_level.index >= 2 and nim is not None:
text = _("Capabilities: ") + ",".join(eDVBResourceManager.getInstance().getFrontendCapabilities(nim.slot).splitlines())
self.session.open(MessageBox, text, MessageBox.TYPE_INFO, simple=True)
def okbuttonClick(self):
nim = self["nimlist"].getCurrent()
nim = nim and nim[3]
nimConfig = nimmanager.getNimConfig(nim.slot)
if isFBCLink(nim) and nimConfig.configMode.value == "loopthrough":
return
if nim is not None and not nim.empty and nim.isSupported():
self.session.openWithCallback(boundFunction(self.NimSetupCB, self["nimlist"].getIndex()), self.resultclass, nim.slot)
def NimSetupCB(self, index=None):
self.loadFBCLinks()
self.updateList()
def showNim(self, nim):
return True
def updateList(self, index=None):
self.list = [ ]
for x in nimmanager.nim_slots:
slotid = x.slot
nimConfig = nimmanager.getNimConfig(x.slot)
text = nimConfig.configMode.value
if self.showNim(x):
if x.isCompatible("DVB-S"):
if nimConfig.configMode.value in ("loopthrough", "equal", "satposdepends"):
text = { "loopthrough": _("Loop through to"),
"equal": _("Equal to"),
"satposdepends": _("Second cable of motorized LNB") } [nimConfig.configMode.value]
if len(x.input_name) > 1:
text += " " + _("Tuner") + " " + ["A1", "A2", "B", "C"][int(nimConfig.connectedTo.value)]
else:
text += " " + _("Tuner") + " " + chr(ord('A')+int(nimConfig.connectedTo.value))
elif nimConfig.configMode.value == "nothing":
text = _("not configured")
elif nimConfig.configMode.value == "simple":
if nimConfig.diseqcMode.value in ("single", "toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"):
text = {"single": _("Single"), "toneburst_a_b": _("Toneburst A/B"), "diseqc_a_b": _("DiSEqC A/B"), "diseqc_a_b_c_d": _("DiSEqC A/B/C/D")}[nimConfig.diseqcMode.value] + "\n"
text += _("Sats") + ": "
satnames = []
if nimConfig.diseqcA.orbital_position < 3600:
satnames.append(nimmanager.getSatName(int(nimConfig.diseqcA.value)))
if nimConfig.diseqcMode.value in ("toneburst_a_b", "diseqc_a_b", "diseqc_a_b_c_d"):
if nimConfig.diseqcB.orbital_position < 3600:
satnames.append(nimmanager.getSatName(int(nimConfig.diseqcB.value)))
if nimConfig.diseqcMode.value == "diseqc_a_b_c_d":
if nimConfig.diseqcC.orbital_position < 3600:
satnames.append(nimmanager.getSatName(int(nimConfig.diseqcC.value)))
if nimConfig.diseqcD.orbital_position < 3600:
satnames.append(nimmanager.getSatName(int(nimConfig.diseqcD.value)))
if len(satnames) <= 2:
text += ", ".join(satnames)
elif len(satnames) > 2:
# we need a newline here, since multi content lists don't support automtic line wrapping
text += ", ".join(satnames[:2]) + ",\n"
text += " " + ", ".join(satnames[2:])
elif nimConfig.diseqcMode.value in ("positioner", "positioner_select"):
text = {"positioner": _("Positioner"), "positioner_select": _("Positioner (selecting satellites)")}[nimConfig.diseqcMode.value]
text += ":"
if nimConfig.positionerMode.value == "usals":
text += "USALS"
elif nimConfig.positionerMode.value == "manual":
text += _("Manual")
else:
text = _("Simple")
elif nimConfig.configMode.value == "advanced":
text = _("Advanced")
if isFBCLink(x) and nimConfig.configMode.value != "advanced":
text += _("\n<This tuner is configured automatically>")
elif x.isCompatible("DVB-T") or x.isCompatible("DVB-C"):
if nimConfig.configMode.value == "nothing":
text = _("nothing connected")
elif nimConfig.configMode.value == "enabled":
text = _("Enabled")
if x.isMultiType():
text = _("Switchable tuner types:") + "(" + ','.join(x.getMultiTypeList().values()) + ")" + "\n" + text
if not x.isSupported():
text = _("Tuner is not supported")
self.list.append((slotid, x.friendly_full_description, text, x))
self["nimlist"].setList(self.list)
self["nimlist"].updateList(self.list)
if index is not None:
self["nimlist"].setIndex(index)
class SelectSatsEntryScreen(Screen):
skin = """
<screen name="SelectSatsEntryScreen" position="center,center" size="560,410" title="Select Sats Entry" >
<ePixmap name="red" position="0,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
<ePixmap name="green" position="140,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
<ePixmap name="yellow" position="280,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
<ePixmap name="blue" position="420,0" zPosition="2" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
<widget name="key_red" position="0,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;17" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
<widget name="key_green" position="140,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;17" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
<widget name="key_yellow" position="280,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;17" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
<widget name="key_blue" position="420,0" size="140,40" valign="center" halign="center" zPosition="4" foregroundColor="white" font="Regular;17" transparent="1" shadowColor="background" shadowOffset="-2,-2" />
<widget name="list" position="10,40" size="540,330" scrollbarMode="showNever" />
<ePixmap pixmap="skin_default/div-h.png" position="0,375" zPosition="1" size="540,2" transparent="1" alphatest="on" />
<widget name="hint" position="10,380" size="540,25" font="Regular;19" halign="center" transparent="1" />
</screen>"""
def __init__(self, session, userSatlist=[]):
Screen.__init__(self, session)
self["key_red"] = Button(_("Cancel"))
self["key_green"] = Button(_("Save"))
self["key_yellow"] = Button(_("Sort by"))
self["key_blue"] = Button(_("Select all"))
self["hint"] = Label(_("Press OK to toggle the selection"))
SatList = []
for sat in nimmanager.getSatList():
selected = False
if isinstance(userSatlist, str) and str(sat[0]) in userSatlist:
selected = True
SatList.append((sat[0], sat[1], sat[2], selected))
sat_list = [SelectionEntryComponent(x[1], x[0], x[2], x[3]) for x in SatList]
self["list"] = SelectionList(sat_list, enableWrapAround=True)
self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
{
"red": self.cancel,
"green": self.save,
"yellow": self.sortBy,
"blue": self["list"].toggleAllSelection,
"save": self.save,
"cancel": self.cancel,
"ok": self["list"].toggleSelection,
}, -2)
self.setTitle(_("Select satellites"))
def save(self):
val = [x[0][1] for x in self["list"].list if x[0][3]]
self.close(str(val))
def cancel(self):
self.close(None)
def sortBy(self):
lst = self["list"].list
if len(lst) > 1:
menu = [(_("Reverse list"), "2"), (_("Standard list"), "1")]
connected_sat = [x[0][1] for x in lst if x[0][3]]
if len(connected_sat) > 0:
menu.insert(0,(_("Connected satellites"), "3"))
def sortAction(choice):
if choice:
reverse_flag = False
sort_type = int(choice[1])
if choice[1] == "2":
sort_type = reverse_flag = 1
elif choice[1] == "3":
reverse_flag = not reverse_flag
self["list"].sort(sortType=sort_type, flag=reverse_flag)
self["list"].moveToIndex(0)
self.session.openWithCallback(sortAction, ChoiceBox, title= _("Select sort method:"), list=menu)
|
This will be my 12th year teaching elementary school! I have taught third grade, second grade, and kindergarten. This is my seventh year at Cumberland Heights. I have a bachelor's degree in psychology and a master's degree in educational theory and practice. I have been married for 14 years to my wife Molly, and we have two children Brock (4) and Delilah (2). I am a member of the worship band at my church where I play guitar, bass and ukulele. I enjoy making spray paint art, reading, watching Chicago sports, games, and movies. |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Canonical
#
# Authors:
# Olivier Tilloy
#
# 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; version 3.
#
# 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 gi.repository import GObject
from gi.repository import Gtk, Gdk
import logging
import datetime
from gettext import gettext as _
from softwarecenter.ui.gtk3.em import get_em
from softwarecenter.ui.gtk3.widgets.spinner import SpinnerNotebook
from basepane import BasePane
from softwarecenter.enums import Icons
from softwarecenter.ui.gtk3.session.viewmanager import get_viewmanager
from softwarecenter.ui.gtk3.session.displaystate import DisplayState
class HistoryPane(Gtk.VBox, BasePane):
__gsignals__ = {
"app-list-changed": (GObject.SignalFlags.RUN_LAST,
None,
(int, ),
),
"history-pane-created": (GObject.SignalFlags.RUN_FIRST,
None,
()),
}
(COL_WHEN, COL_ACTION, COL_PKG) = range(3)
COL_TYPES = (object, int, object)
(ALL, INSTALLED, REMOVED, UPGRADED) = range(4)
ICON_SIZE = 1.2 * get_em()
PADDING = 4
# pages for the spinner notebook
(PAGE_HISTORY_VIEW,
PAGE_SPINNER) = range(2)
def __init__(self, cache, db, distro, icons):
Gtk.VBox.__init__(self)
self.cache = cache
self.db = db
self.distro = distro
self.icons = icons
self.apps_filter = None
self.state = DisplayState()
self.pane_name = _("History")
# Icon cache, invalidated upon icon theme changes
self._app_icon_cache = {}
self._reset_icon_cache()
self.icons.connect('changed', self._reset_icon_cache)
self._emblems = {}
self._get_emblems(self.icons)
vm = get_viewmanager()
self.searchentry = vm.get_global_searchentry()
self.toolbar = Gtk.Toolbar()
self.toolbar.show()
self.toolbar.set_style(Gtk.ToolbarStyle.TEXT)
self.pack_start(self.toolbar, False, True, 0)
all_action = Gtk.RadioAction('filter_all', _('All Changes'), None,
None, self.ALL)
all_action.connect('changed', self.change_filter)
all_button = all_action.create_tool_item()
self.toolbar.insert(all_button, 0)
installs_action = Gtk.RadioAction('filter_installs',
_('Installations'), None, None, self.INSTALLED)
installs_action.join_group(all_action)
installs_button = installs_action.create_tool_item()
self.toolbar.insert(installs_button, 1)
upgrades_action = Gtk.RadioAction(
'filter_upgrads', _('Updates'), None, None, self.UPGRADED)
upgrades_action.join_group(all_action)
upgrades_button = upgrades_action.create_tool_item()
self.toolbar.insert(upgrades_button, 2)
removals_action = Gtk.RadioAction(
'filter_removals', _('Removals'), None, None, self.REMOVED)
removals_action.join_group(all_action)
removals_button = removals_action.create_tool_item()
self.toolbar.insert(removals_button, 3)
self.toolbar.connect('draw', self.on_toolbar_draw)
self._actions_list = all_action.get_group()
self._set_actions_sensitive(False)
self.view = Gtk.TreeView()
self.view.set_headers_visible(False)
self.view.show()
self.history_view = Gtk.ScrolledWindow()
self.history_view.set_policy(Gtk.PolicyType.AUTOMATIC,
Gtk.PolicyType.AUTOMATIC)
self.history_view.show()
self.history_view.add(self.view)
# make a spinner to display while history is loading
self.spinner_notebook = SpinnerNotebook(
self.history_view, _('Loading history'))
self.pack_start(self.spinner_notebook, True, True, 0)
self.store = Gtk.TreeStore(*self.COL_TYPES)
self.visible_changes = 0
self.store_filter = self.store.filter_new(None)
self.store_filter.set_visible_func(self.filter_row, None)
self.view.set_model(self.store_filter)
all_action.set_active(True)
self.last = None
# to save (a lot of) time at startup we load history later, only when
# it is selected to be viewed
self.history = None
self.column = Gtk.TreeViewColumn(_('Date'))
self.view.append_column(self.column)
self.cell_icon = Gtk.CellRendererPixbuf()
self.cell_icon.set_padding(self.PADDING, self.PADDING / 2)
self.column.pack_start(self.cell_icon, False)
self.column.set_cell_data_func(self.cell_icon, self.render_cell_icon)
self.cell_text = Gtk.CellRendererText()
self.column.pack_start(self.cell_text, True)
self.column.set_cell_data_func(self.cell_text, self.render_cell_text)
self.cell_time = Gtk.CellRendererText()
self.cell_time.set_padding(6, 0)
self.cell_time.set_alignment(1.0, 0.5)
self.column.pack_end(self.cell_time, False)
self.column.set_cell_data_func(self.cell_time, self.render_cell_time)
# busy cursor
self.busy_cursor = Gdk.Cursor.new(Gdk.CursorType.WATCH)
def init_view(self):
if self.history is None:
# if the history is not yet initialized we have to load and parse
# it show a spinner while we do that
self.realize()
window = self.get_window()
window.set_cursor(self.busy_cursor)
self.spinner_notebook.show_spinner()
self.load_and_parse_history()
self.spinner_notebook.hide_spinner()
self._set_actions_sensitive(True)
window.set_cursor(None)
self.emit("history-pane-created")
def on_toolbar_draw(self, widget, cr):
a = widget.get_allocation()
context = widget.get_style_context()
color = context.get_border_color(widget.get_state_flags())
cr.set_source_rgba(color.red, color.green, color.blue, 0.5)
cr.set_line_width(1)
cr.move_to(0.5, a.height - 0.5)
cr.rel_line_to(a.width - 1, 0)
cr.stroke()
def _get_emblems(self, icons):
from softwarecenter.enums import USE_PACKAGEKIT_BACKEND
if USE_PACKAGEKIT_BACKEND:
emblem_names = ("pk-package-add",
"pk-package-delete",
"pk-package-update")
else:
emblem_names = ("package-install",
"package-remove",
"package-upgrade")
for i, emblem in enumerate(emblem_names):
pb = icons.load_icon(emblem, self.ICON_SIZE, 0)
self._emblems[i + 1] = pb
def _set_actions_sensitive(self, sensitive):
for action in self._actions_list:
action.set_sensitive(sensitive)
def _reset_icon_cache(self, theme=None):
self._app_icon_cache.clear()
try:
missing = self.icons.load_icon(Icons.MISSING_APP, self.ICON_SIZE,
0)
except GObject.GError:
missing = None
self._app_icon_cache[Icons.MISSING_APP] = missing
def load_and_parse_history(self):
from softwarecenter.db.history import get_pkg_history
self.history = get_pkg_history()
# FIXME: a signal from AptHistory is nicer
while not self.history.history_ready:
while Gtk.events_pending():
Gtk.main_iteration()
self.parse_history()
self.history.set_on_update(self.parse_history)
def parse_history(self):
date = None
when = None
last_row = None
day = self.store.get_iter_first()
if day is not None:
date = self.store.get_value(day, self.COL_WHEN)
if len(self.history.transactions) == 0:
logging.debug("AptHistory is currently empty")
return
new_last = self.history.transactions[0].start_date
for trans in self.history.transactions:
while Gtk.events_pending():
Gtk.main_iteration()
when = trans.start_date
if self.last is not None and when <= self.last:
break
if when.date() != date:
date = when.date()
day = self.store.append(None, (date, self.ALL, None))
last_row = None
actions = {self.INSTALLED: trans.install,
self.REMOVED: trans.remove,
self.UPGRADED: trans.upgrade,
}
for action, pkgs in actions.items():
for pkgname in pkgs:
row = (when, action, pkgname)
last_row = self.store.insert_after(day, last_row, row)
self.last = new_last
self.update_view()
def on_search_terms_changed(self, entry, terms):
self.update_view()
def change_filter(self, action, current):
self.filter = action.get_current_value()
self.update_view()
def update_view(self):
self.store_filter.refilter()
self.view.collapse_all()
# Expand all the matching rows
if self.searchentry.get_text():
self.view.expand_all()
# Compute the number of visible changes
# don't do this atm - the spec doesn't mention that the history pane
# should have a status text and it gives us a noticeable performance
# gain if we don't calculate this
#self.visible_changes = 0
#day = self.store_filter.get_iter_first()
#while day is not None:
# self.visible_changes += self.store_filter.iter_n_children(day)
# day = self.store_filter.iter_next(day)
# Expand the most recent day
day = self.store.get_iter_first()
if day is not None:
path = self.store.get_path(day)
self.view.expand_row(path, False)
self.view.scroll_to_cell(path)
#self.emit('app-list-changed', self.visible_changes)
def _row_matches(self, store, iter):
# Whether a child row matches the current filter and the search entry
pkg = store.get_value(iter, self.COL_PKG) or ''
filter_values = (self.ALL, store.get_value(iter, self.COL_ACTION))
filter_matches = self.filter in filter_values
search_matches = self.searchentry.get_text().lower() in pkg.lower()
return filter_matches and search_matches
def filter_row(self, store, iter, user_data):
pkg = store.get_value(iter, self.COL_PKG)
if pkg is not None:
return self._row_matches(store, iter)
else:
i = store.iter_children(iter)
while i is not None:
if self._row_matches(store, i):
return True
i = store.iter_next(i)
return False
def render_cell_icon(self, column, cell, store, iter, user_data):
pkg = store.get_value(iter, self.COL_PKG)
if pkg is None:
cell.set_visible(False)
return
cell.set_visible(True)
when = store.get_value(iter, self.COL_WHEN)
if isinstance(when, datetime.datetime):
action = store.get_value(iter, self.COL_ACTION)
cell.set_property('pixbuf', self._emblems[action])
#~ icon_name = Icons.MISSING_APP
#~ for m in self.db.xapiandb.postlist("AP" + pkg):
#~ doc = self.db.xapiandb.get_document(m.docid)
#~ icon_value = doc.get_value(XapianValues.ICON)
#~ if icon_value:
#~ icon_name = os.path.splitext(icon_value)[0]
#~ break
#~ if icon_name in self._app_icon_cache:
#~ icon = self._app_icon_cache[icon_name]
#~ else:
#~ try:
#~ icon = self.icons.load_icon(icon_name, self.ICON_SIZE,
#~ 0)
#~ except GObject.GError:
#~ icon = self._app_icon_cache[Icons.MISSING_APP]
#~ self._app_icon_cache[icon_name] = icon
def render_cell_text(self, column, cell, store, iter, user_data):
when = store.get_value(iter, self.COL_WHEN)
if isinstance(when, datetime.datetime):
pkg = store.get_value(iter, self.COL_PKG)
text = pkg
elif isinstance(when, datetime.date):
today = datetime.date.today()
monday = today - datetime.timedelta(days=today.weekday())
if when == today:
text = _("Today")
elif when >= monday:
# Current week, display the name of the day
text = when.strftime(_('%A'))
else:
if when.year == today.year:
# Current year, display the day and month
text = when.strftime(_('%d %B'))
else:
# Display the full date: day, month, year
text = when.strftime(_('%d %B %Y'))
cell.set_property('markup', text)
def render_cell_time(self, column, cell, store, iter, user_data):
when = store.get_value(iter, self.COL_WHEN)
text = ''
if isinstance(when, datetime.datetime):
action = store.get_value(iter, self.COL_ACTION)
# Translators : time displayed in history, display hours
# (0-12), minutes and AM/PM. %H should be used instead
# of %I to display hours 0-24
time_text = when.time().strftime(_('%I:%M %p'))
if self.filter is not self.ALL:
action_text = time_text
else:
if action == self.INSTALLED:
action_text = _('installed %s') % time_text
elif action == self.REMOVED:
action_text = _('removed %s') % time_text
elif action == self.UPGRADED:
action_text = _('updated %s') % time_text
color = {'color': '#8A8A8A', 'action': action_text}
text = '<span color="%(color)s">%(action)s</span>' % color
cell.set_property('markup', text)
|
When you are working in the Project Files section, the Project Explorer functions as a file manager for your topic files and the folders where they are stored. If you are working in uncompressed XML format (Professional and Server versions only, .hmxp project file) the files and folders are stored directly on your hard drive. In the compressed single-file .hmxz format the files and folders are stored inside the compressed .hmxz file, which is actually a normal ZIP archive.
You can use include options to "filter" the display of your topics in the TOC and Topic Files section of the Project Explorer. This makes it possible for you to see only the topics that will be included in a specific build, so that you can preview the results of specific build options without publishing your project.
1.Apply build options to one or more topics. If you don't do this filtering will not have any effect! See Conditions and Customized Output for details.
2.Select Explore > Filter in Project > Manage Topics and set the filter options you want to apply. The filter settings are also available from the right-click menu in the Project Explorer (Explore > Filter).
This works both in the TOC and in Topic Files. This only filters entire topics, it does not filter conditional text tagged within your topics.
•The current build settings of topics are shown in the Project Explorer, next to the topic caption in the TOC. Topics and chapters set to All Builds (the default) will always be included, of course – you cannot hide them.
•Filtered topics will be either shown in a different color or hidden completely. This depends on your settings for When filtering the table of contents... in View > Program Options > General. See Program Options - General for details on these settings.
Tip: You can check whether a topic file has a TOC entry with the In TOC column above the file list on the right. By default this is the last column on the right so it may not be visible immediately. You can rearrange the columns by dragging them left and right with the mouse.
You can check whether topic files have TOC entries with the In TOC column above the file list on the right. You can also sort and group files by this option (see below). In addition to this you can also locate files that do not have TOC entries with the Report Tool in the Project tab.
You can sort and group files by several different criteria (name, modification status, modification date, build option, topic status). You can combine sorting and grouping: When the files are grouped the sorting options are applied within each group.
Just left-click in the column header you want to sort by. Alternatively you can also right-click in the column header and select the sort option in the context menu.
Right-click in the column header and select the group option in the context menu, or select Ungroup to return to an ungrouped list.
You can create additional folders in the Topic Files section to organize your files to make them easier to manage. For example, it is a good idea to keep topic files without TOC entries in separate folders.
All folders you create must be sub-folders of the main Topics folder. You cannot create additional top-level folders on the same level as the Topics folder.
1.Select the folder in which you want to create your new folder – either the main Topics folder or a sub-folder that you have already created.
2.Right-click and select Add New Folder in the context menu, or select Add File > Add New Folder in Project > Manage Topics.
3. Enter the name for the new folder and select OK.
Cutting and pasting is not possible with topic files in the Topic Files section because you are actually dealing with physical files. (See Moving, cutting and pasting topics for instructions on working with topic entries in the TOC.) However you can move files between folders and delete files in the Topic Files section.
To move a topic file from one folder to another just drag it to the new folder with the mouse. You can also move folders in the same way.
Just select the topic file in the Explorer and press DEL or right-click and select Delete File.
You cannot rename topic files directly. To rename the topic file you need to edit the Topic ID.
1.Select the topic file in the Explorer.
2.Select the Topic Options tab on the left of the main editor window, edit the Topic ID and save your project to update the Topic Files display.
All references to the topic in the project will be updated automatically. However, since the ID changes any references to the topic from other help projects or elsewhere will no longer work. This includes links to specific topics in WebHelp from other websites, because the topic ID is also the name of the HTML topic file in WebHelp.
You should thus be cautious about renaming topics, particularly topics that get a lot of traffic on your website. |
import logging
from netort.resource import manager as resource
from . import info
from . import instance_plan as ip
from . import load_plan as lp
from . import missile
from .mark import get_marker
from .module_exceptions import StepperConfigurationError, AmmoFileError
class ComponentFactory():
def __init__(
self,
rps_schedule=None,
http_ver='1.1',
ammo_file=None,
instances_schedule=None,
instances=1000,
loop_limit=-1,
ammo_limit=-1,
uris=None,
headers=None,
autocases=None,
enum_ammo=False,
ammo_type='phantom',
chosen_cases=None,
use_cache=True):
self.log = logging.getLogger(__name__)
self.ammo_file = ammo_file
self.ammo_type = ammo_type
self.rps_schedule = rps_schedule
self.http_ver = http_ver
self.instances_schedule = instances_schedule
loop_limit = int(loop_limit)
if loop_limit == -1: # -1 means infinite
loop_limit = None
ammo_limit = int(ammo_limit)
if ammo_limit == -1: # -1 means infinite
ammo_limit = None
if loop_limit is None and ammo_limit is None and not rps_schedule:
# we should have only one loop if we have instance_schedule
loop_limit = 1
info.status.loop_limit = loop_limit
info.status.ammo_limit = ammo_limit
info.status.publish("instances", instances)
self.uris = uris
if self.uris and loop_limit:
info.status.ammo_limit = len(self.uris) * loop_limit
self.headers = headers
self.marker = get_marker(autocases, enum_ammo)
self.chosen_cases = chosen_cases or []
self.use_cache = use_cache
def get_load_plan(self):
"""
return load plan (timestamps generator)
"""
if self.rps_schedule and self.instances_schedule:
raise StepperConfigurationError(
'Both rps and instances schedules specified. You must specify only one of them'
)
elif self.rps_schedule:
info.status.publish('loadscheme', self.rps_schedule)
return lp.create(self.rps_schedule)
elif self.instances_schedule:
info.status.publish('loadscheme', self.instances_schedule)
return ip.create(self.instances_schedule)
else:
self.instances_schedule = []
info.status.publish('loadscheme', self.instances_schedule)
return ip.create(self.instances_schedule)
def get_ammo_generator(self):
"""
return ammo generator
"""
af_readers = {
'phantom': missile.AmmoFileReader,
'slowlog': missile.SlowLogReader,
'line': missile.LineReader,
'uri': missile.UriReader,
'uripost': missile.UriPostReader,
'access': missile.AccessLogReader,
'caseline': missile.CaseLineReader,
}
if self.uris and self.ammo_file:
raise StepperConfigurationError(
'Both uris and ammo file specified. You must specify only one of them'
)
elif self.uris:
ammo_gen = missile.UriStyleGenerator(
self.uris, self.headers, http_ver=self.http_ver)
elif self.ammo_file:
if self.ammo_type in af_readers:
if self.ammo_type == 'phantom':
opener = resource.get_opener(self.ammo_file)
with opener(self.use_cache) as ammo:
try:
if not ammo.next()[0].isdigit():
self.ammo_type = 'uri'
self.log.info(
"Setting ammo_type 'uri' because ammo is not started with digit and you did not specify ammo format"
)
else:
self.log.info(
"Default ammo type ('phantom') used, use 'phantom.ammo_type' option to override it"
)
except StopIteration:
self.log.exception(
"Couldn't read first line of ammo file")
raise AmmoFileError(
"Couldn't read first line of ammo file")
else:
raise NotImplementedError(
'No such ammo type implemented: "%s"' % self.ammo_type)
ammo_gen = af_readers[self.ammo_type](
self.ammo_file, headers=self.headers, http_ver=self.http_ver, use_cache=self.use_cache)
else:
raise StepperConfigurationError(
'Ammo not found. Specify uris or ammo file')
self.log.info("Using %s ammo reader" % type(ammo_gen).__name__)
return ammo_gen
def get_marker(self):
return self.marker
def get_filter(self):
if len(self.chosen_cases):
def is_chosen_case(ammo_tuple):
return ammo_tuple[1] in self.chosen_cases
return is_chosen_case
else:
return lambda ammo_tuple: True
|
This Smart Bracelet has been developed for the Malaysian company Nxsense and it’s a wearable life saver device for heart attacks.
In case of a stroke it calls an emergency number and as well when the accelerometer detects a fall. Constant monitoring with no need of a connected smartphone, the data are crunched by artificial intelligence and sent to the app. Maia has been developed in Shenzhen by Supernova and it’s currently in pre-order on the website for 249 RM. |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c)2013 Rackspace US, 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.
from __future__ import print_function
import os
import six
import pyrax
import pyrax.exceptions as exc
pyrax.set_setting("identity_type", "rackspace")
creds_file = os.path.expanduser("~/.rackspace_cloud_credentials")
pyrax.set_credential_file(creds_file)
pq = pyrax.queues
queues = pq.list()
if not queues:
print("There are no queues to post to. Please create one before proceeding.")
exit()
if len(queues) == 1:
queue = queues[0]
print("Only one queue available; using '%s'." % queue.name)
else:
print("Queues:")
for pos, queue in enumerate(queues):
print("%s - %s" % (pos, queue.name))
snum = six.moves.input("Enter the number of the queue you wish to list "
"messages from: ")
if not snum:
exit()
try:
num = int(snum)
except ValueError:
print("'%s' is not a valid number." % snum)
exit()
if not 0 <= num < len(queues):
print("'%s' is not a valid queue number." % snum)
exit()
queue = queues[num]
echo = claimed = False
secho = six.moves.input("Do you want to include your own messages? [y/N]")
if secho:
echo = secho in ("Yy")
sclaimed = six.moves.input("Do you want to include claimed messages? [y/N]")
if sclaimed:
claimed = sclaimed in ("Yy")
msgs = pq.list_messages(queue, echo=echo, include_claimed=claimed)
if not msgs:
print("There are no messages available in this queue.")
exit()
for msg in msgs:
print("ID:", msg.id)
print("Age:", msg.age)
print("TTL:", msg.ttl)
print("Claim ID:", msg.claim_id)
print("Body:", msg.body)
print()
|
Why backup if I have replication?
This has come up a number of times recently so I thought I’d put my perspective down. Maybe it will help. But first, why backup, why replicate?
Editor's Note: John Savill contributes Frequently Asked Questions about Azure, PowerShell, and other Microsoft products and services three times each week here at Windows IT Pro. He is a well-respected member of the Microsoft tech community and a frequent speaker at industry events.
His training classes through our e-learning portal will help you become more knowledgeable about these various technologies. This tip is just one example of what he will be teaching in an upcoming Master Class. |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import StringIO
from telemetry.internal.backends.chrome_inspector import websocket
class InspectorConsole(object):
def __init__(self, inspector_websocket):
self._inspector_websocket = inspector_websocket
self._inspector_websocket.RegisterDomain('Console', self._OnNotification)
self._message_output_stream = None
self._last_message = None
self._console_enabled = False
def _OnNotification(self, msg):
if msg['method'] == 'Console.messageAdded':
assert self._message_output_stream
if msg['params']['message']['url'] == 'chrome://newtab/':
return
self._last_message = '(%s) %s:%i: %s' % (
msg['params']['message']['level'],
msg['params']['message']['url'],
msg['params']['message']['line'],
msg['params']['message']['text'])
self._message_output_stream.write(
'%s\n' % self._last_message)
elif msg['method'] == 'Console.messageRepeatCountUpdated':
if self._message_output_stream:
self._message_output_stream.write(
'%s\n' % self._last_message)
def GetCurrentConsoleOutputBuffer(self, timeout=10):
self._message_output_stream = StringIO.StringIO()
self._EnableConsoleOutputStream(timeout)
try:
self._inspector_websocket.DispatchNotifications(timeout)
return self._message_output_stream.getvalue()
except websocket.WebSocketTimeoutException:
return self._message_output_stream.getvalue()
finally:
self._DisableConsoleOutputStream(timeout)
self._message_output_stream.close()
self._message_output_stream = None
def _EnableConsoleOutputStream(self, timeout):
self._inspector_websocket.SyncRequest({'method': 'Console.enable'}, timeout)
def _DisableConsoleOutputStream(self, timeout):
self._inspector_websocket.SyncRequest(
{'method': 'Console.disable'}, timeout)
|
– February is American Heart Month and in regards to the Dedication to raising awareness and increasing our knowledge of heart disease, its symptoms, and ways we could reduce our risks. But interestingly enough, the symptoms differ between women and men. So what better time to discuss these symptoms for women and explore ways we can decrease the risks through diet and exercise?
With such high numbers, it’s extremely important for women to comprehend the symptoms, should you have any, and the risk factors involved.
The most frequent symptom which is associated with a soul Attack is pressure, discomfort, or pain at your chest. This is a key difference between men.
The Mayo Clinic carries a few other heart attack symptoms for women which might not appear related to a heart attack, but may very well be one. These include shortness of breath, pain in one of arms, nausea or vomiting, sweating, lightheadedness or nausea, and unusual fatigue.
Since the symptoms above tend to be more subtle, women may not think they’re having a heart attack, so when they end up at the Emergency Room, the harm is already done. Even more, a reason to be watching out for these issues.
Other symptoms, from the CDC, in addition to a heart attack Include arrhythmia (“fluttering feelings in the chest”), heart failure (“shortness of breath, fatigue, swelling of the feet/ankles/legs/stomach”), and stroke (“sudden weakness, paralysis or numbness of these face/arms/legs, especially on one side of the body”).
Whether or not we will be affected by specific diseases. All these are what we can try to improve! The most frequent risk factors for both women and men are high blood pressure, higher LDL cholesterol, smoking, and obesity.
For women though, There Are Numerous others that encounter Play diabetes, psychological stress and sadness, lack of action, a bad diet, and pregnancy complications (high blood pressure or diabetes during pregnancy can increase the long term risk of high blood pressure and diabetes).
Some of these risk factors are more readily improved and can actually affect others (think better diet, better cholesterol). So let us talk about two areas in our lives where we could make a big impact, lack of diet and activity.
What Activities That You Need To Do?
We hear over and over again, from all kinds of resources that we must work out. And it’s true. Regular exercise can reduce the risk of coronary disease (and obviously a ton of additional negative things too). Sounds easy right? But we all know it is not.
“I hate cardio” “I do not even know what workouts to perform.” These are all common excuses which we can get rid of right now! Because exercising does NOT have to be complex, elaborate, expensive, or time-consuming.
First things first, you want to decide exactly what you prefer to do. Do you like running? Great! Or maybe tennis? Also terrific. How about weight lifting? Or online videos you’ll be able to follow along with? You will find a million distinct activities out there which you may select from to help you get going.
Choose a program which is right for YOU, which you like, and one that you can keep performing for more than a couple of months. The goal here is to exercise for 30 minutes, 5 days a week.
As Soon as you find out everything you like to do, or you find a program that interests you, figure out when you’ll work out. Does your job have an office fitness center or is there one close by you could use during your lunch break? Or perhaps, the only option is to have it completed in the day after most of the kids have gone to bed.
Does not matter which you select because there are experts and Cons to each. And you do not have to adhere to a single set program. Sometimes you simply have to be flexible.
When at the office, park farther away so you need to walk.
Use a standing desk if that is not possible, take regular breaks to get up and move around or attempt some seated exercises.
Always be prepared ahead of time for your workout. Lay Out your clothes and shoes plus whatever extras you may want the day before. You will be less likely to bypass it when the time comes.
Find a workout buddy or a liability group to join. It is always easier to stay on course when you have somebody else to support you.
Buy an action tracker, like a Fit bit, to help you reach your objectives.
If you don’t have time to get a full 30-minute workout, Split it up into 10-minute segments throughout the day.
Instead of visiting a family movie, choose a more Engaging activity. Subscribe for a group race!
When doing everyday house chores, add a little bit of exercise. Does leg lift while brushing your teeth? The choices are endless.
Connotation. Most individuals don’t like to diet. Or don’t want to die. And who can blame them? Diets are often restricting, limiting, and difficult to maintain for extended intervals. But eating healthy can reduce the chance of cardiovascular disease and contains countless other advantages for our lives. So rather than dieting, just clean this up.
First things first, you need to minimize the number of Processed foods and fast food eaten every day. Additionally, they bring about higher cholesterol.
Should you prefer to cook, but find yourself cooking not so healthy foods because they are fast and easy, get a brand new recipe book, or check out some of those wonderful sites on the market for new recipes? You don’t have to skimp on flavor or invest more time in the kitchen just because you’re cooking healthier!
Enhance your diet and reduce your chance of cardiovascular disease.
Watch portion sizes. Look up the correct portions and Stick to them.
Eat more fruits. These will keep you full through the meal and help you to remain on track.
Cook with less butter. Instead, use olive oil.
Replace one meal per week. Salmon is a great Choice because it is saturated in omega-3 fatty acids.
Drink low-fat milk or skim, over the whole.
Plan your meals in Advance and if possible, prep ahead Of time too. You’ll be less likely to make (or buy) something fast and greasy if you’ve got a plan.
Choose whole grain instead of white. Brown rice White too!
Do not limit yourself. If you’re craving pizza, eat pizza. But do not let this be the catalyst into a whole day or week of binging.
It’s so essential for all of us to understand the symptoms, the Risk factors, and what we can do to stop it. A Couple of alterations to our diet, an Addition of activity, and we’ll be well on our way into a healthier life. Bear in Mind, it does not Have to be complicated, elaborate, expensive, or time-Consuming!
Next Give Your Body Balance From Gluten Intolerance – How To Heal From It? |
"""
Test retrieval of SBAddress from function/symbol, disassembly, and SBAddress APIs.
"""
import os, time
import re
import unittest2
import lldb, lldbutil
from lldbtest import *
class DisasmAPITestCase(TestBase):
mydir = os.path.join("python_api", "function_symbol")
@unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin")
@python_api_test
@dsym_test
def test_with_dsym(self):
"""Exercise getting SBAddress objects, disassembly, and SBAddress APIs."""
self.buildDsym()
self.disasm_and_address_api()
@python_api_test
@dwarf_test
def test_with_dwarf(self):
"""Exercise getting SBAddress objects, disassembly, and SBAddress APIs."""
self.buildDwarf()
self.disasm_and_address_api()
def setUp(self):
# Call super's setUp().
TestBase.setUp(self)
# Find the line number to of function 'c'.
self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.')
self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.')
def disasm_and_address_api(self):
"""Exercise getting SBAddress objects, disassembly, and SBAddress APIs."""
exe = os.path.join(os.getcwd(), "a.out")
# Create a target by the debugger.
target = self.dbg.CreateTarget(exe)
self.assertTrue(target, VALID_TARGET)
# Now create the two breakpoints inside function 'a'.
breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
#print "breakpoint1:", breakpoint1
#print "breakpoint2:", breakpoint2
self.assertTrue(breakpoint1 and
breakpoint1.GetNumLocations() == 1,
VALID_BREAKPOINT)
self.assertTrue(breakpoint2 and
breakpoint2.GetNumLocations() == 1,
VALID_BREAKPOINT)
# Now launch the process, and do not stop at entry point.
process = target.LaunchSimple(None, None, os.getcwd())
self.assertTrue(process, PROCESS_IS_VALID)
# Frame #0 should be on self.line1.
self.assertTrue(process.GetState() == lldb.eStateStopped)
thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
frame0 = thread.GetFrameAtIndex(0)
lineEntry = frame0.GetLineEntry()
self.assertTrue(lineEntry.GetLine() == self.line1)
address1 = lineEntry.GetStartAddress()
#print "address1:", address1
# Now call SBTarget.ResolveSymbolContextForAddress() with address1.
context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything)
self.assertTrue(context1)
if self.TraceOn():
print "context1:", context1
# Continue the inferior, the breakpoint 2 should be hit.
process.Continue()
self.assertTrue(process.GetState() == lldb.eStateStopped)
thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
frame0 = thread.GetFrameAtIndex(0)
lineEntry = frame0.GetLineEntry()
self.assertTrue(lineEntry.GetLine() == self.line2)
# Verify that the symbol and the function has the same address range per function 'a'.
symbol = context1.GetSymbol()
function = frame0.GetFunction()
self.assertTrue(symbol and function)
disasm_output = lldbutil.disassemble(target, symbol)
if self.TraceOn():
print "symbol:", symbol
print "disassembly=>\n", disasm_output
disasm_output = lldbutil.disassemble(target, function)
if self.TraceOn():
print "function:", function
print "disassembly=>\n", disasm_output
sa1 = symbol.GetStartAddress()
#print "sa1:", sa1
#print "sa1.GetFileAddress():", hex(sa1.GetFileAddress())
#ea1 = symbol.GetEndAddress()
#print "ea1:", ea1
sa2 = function.GetStartAddress()
#print "sa2:", sa2
#print "sa2.GetFileAddress():", hex(sa2.GetFileAddress())
#ea2 = function.GetEndAddress()
#print "ea2:", ea2
self.assertTrue(sa1 and sa2 and sa1 == sa2,
"The two starting addresses should be the same")
from lldbutil import get_description
desc1 = get_description(sa1)
desc2 = get_description(sa2)
self.assertTrue(desc1 and desc2 and desc1 == desc2,
"SBAddress.GetDescription() API of sa1 and sa2 should return the same string")
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lambda: lldb.SBDebugger.Terminate())
unittest2.main()
|
We have a quantity of these mid-century stacking tubular steel chairs with slatted beech seats and backs.
In the original red, white, blue and yellow paintwork, beeswaxed to stabilize and revive. It’s first come first served on these beauties! |
from __future__ import with_statement
from datetime import datetime
import copy
import getpass
import sys
import paramiko
from nose.tools import with_setup
from fudge import (Fake, clear_calls, clear_expectations, patch_object, verify,
with_patched_object, patched_context, with_fakes)
from fabric.context_managers import settings, hide, show
from fabric.network import (HostConnectionCache, join_host_strings, normalize,
denormalize)
from fabric.io import output_loop
import fabric.network # So I can call patch_object correctly. Sigh.
from fabric.state import env, output, _get_system_username
from fabric.operations import run, sudo
from utils import *
from server import (server, PORT, RESPONSES, PASSWORDS, CLIENT_PRIVKEY, USER,
CLIENT_PRIVKEY_PASSPHRASE)
#
# Subroutines, e.g. host string normalization
#
class TestNetwork(FabricTest):
def test_host_string_normalization(self):
username = _get_system_username()
for description, input, output_ in (
("Sanity check: equal strings remain equal",
'localhost', 'localhost'),
("Empty username is same as get_system_username",
'localhost', username + '@localhost'),
("Empty port is same as port 22",
'localhost', 'localhost:22'),
("Both username and port tested at once, for kicks",
'localhost', username + '@localhost:22'),
):
eq_.description = "Host-string normalization: %s" % description
yield eq_, normalize(input), normalize(output_)
del eq_.description
def test_normalization_without_port(self):
"""
normalize() and join_host_strings() omit port if omit_port given
"""
eq_(
join_host_strings(*normalize('user@localhost', omit_port=True)),
'user@localhost'
)
def test_nonword_character_in_username(self):
"""
normalize() will accept non-word characters in the username part
"""
eq_(
normalize('[email protected]')[0],
'user-with-hyphens'
)
def test_normalization_of_empty_input(self):
empties = ('', '', '')
for description, input in (
("empty string", ''),
("None", None)
):
template = "normalize() returns empty strings for %s input"
eq_.description = template % description
yield eq_, normalize(input), empties
del eq_.description
def test_host_string_denormalization(self):
username = _get_system_username()
for description, string1, string2 in (
("Sanity check: equal strings remain equal",
'localhost', 'localhost'),
("Empty username is same as get_system_username",
'localhost:22', username + '@localhost:22'),
("Empty port is same as port 22",
'user@localhost', 'user@localhost:22'),
("Both username and port",
'localhost', username + '@localhost:22'),
):
eq_.description = "Host-string denormalization: %s" % description
yield eq_, denormalize(string1), denormalize(string2)
del eq_.description
#
# Connection caching
#
@staticmethod
@with_fakes
def check_connection_calls(host_strings, num_calls):
# Clear Fudge call stack
# Patch connect() with Fake obj set to expect num_calls calls
patched_connect = patch_object('fabric.network', 'connect',
Fake('connect', expect_call=True).times_called(num_calls)
)
try:
# Make new cache object
cache = HostConnectionCache()
# Connect to all connection strings
for host_string in host_strings:
# Obtain connection from cache, potentially calling connect()
cache[host_string]
finally:
# Restore connect()
patched_connect.restore()
def test_connection_caching(self):
for description, host_strings, num_calls in (
("Two different host names, two connections",
('localhost', 'other-system'), 2),
("Same host twice, one connection",
('localhost', 'localhost'), 1),
("Same host twice, different ports, two connections",
('localhost:22', 'localhost:222'), 2),
("Same host twice, different users, two connections",
('user1@localhost', 'user2@localhost'), 2),
):
TestNetwork.check_connection_calls.description = description
yield TestNetwork.check_connection_calls, host_strings, num_calls
#
# Connection loop flow
#
@server()
def test_saved_authentication_returns_client_object(self):
cache = HostConnectionCache()
assert isinstance(cache[env.host_string], paramiko.SSHClient)
@server()
@with_fakes
def test_prompts_for_password_without_good_authentication(self):
env.password = None
with password_response(PASSWORDS[env.user], times_called=1):
cache = HostConnectionCache()
cache[env.host_string]
@mock_streams('stdout')
@server()
def test_trailing_newline_line_drop(self):
"""
Trailing newlines shouldn't cause last line to be dropped.
"""
# Multiline output with trailing newline
cmd = "ls /"
output_string = RESPONSES[cmd]
# TODO: fix below lines, duplicates inner workings of tested code
prefix = "[%s] out: " % env.host_string
expected = prefix + ('\n' + prefix).join(output_string.split('\n'))
# Create, tie off thread
with settings(show('everything'), hide('running')):
result = run(cmd)
# Test equivalence of expected, received output
eq_(expected, sys.stdout.getvalue())
# Also test that the captured value matches, too.
eq_(output_string, result)
@server()
def test_sudo_prompt_kills_capturing(self):
"""
Sudo prompts shouldn't screw up output capturing
"""
cmd = "ls /simple"
with hide('everything'):
eq_(sudo(cmd), RESPONSES[cmd])
@server()
def test_password_memory_on_user_switch(self):
"""
Switching users mid-session should not screw up password memory
"""
def _to_user(user):
return join_host_strings(user, env.host, env.port)
user1 = 'root'
user2 = USER
with settings(hide('everything'), password=None):
# Connect as user1 (thus populating both the fallback and
# user-specific caches)
with settings(
password_response(PASSWORDS[user1]),
host_string=_to_user(user1)
):
run("ls /simple")
# Connect as user2: * First cxn attempt will use fallback cache,
# which contains user1's password, and thus fail * Second cxn
# attempt will prompt user, and succeed due to mocked p4p * but
# will NOT overwrite fallback cache
with settings(
password_response(PASSWORDS[user2]),
host_string=_to_user(user2)
):
# Just to trigger connection
run("ls /simple")
# * Sudo call should use cached user2 password, NOT fallback cache,
# and thus succeed. (I.e. p_f_p should NOT be called here.)
with settings(
password_response('whatever', times_called=0),
host_string=_to_user(user2)
):
sudo("ls /simple")
@mock_streams('stderr')
@server()
def test_password_prompt_displays_host_string(self):
"""
Password prompt lines should include the user/host in question
"""
env.password = None
env.no_agent = env.no_keys = True
output.everything = False
with password_response(PASSWORDS[env.user], silent=False):
run("ls /simple")
regex = r'^\[%s\] Login password: ' % env.host_string
assert_contains(regex, sys.stderr.getvalue())
@mock_streams('stderr')
@server(pubkeys=True)
def test_passphrase_prompt_displays_host_string(self):
"""
Passphrase prompt lines should include the user/host in question
"""
env.password = None
env.no_agent = env.no_keys = True
env.key_filename = CLIENT_PRIVKEY
output.everything = False
with password_response(CLIENT_PRIVKEY_PASSPHRASE, silent=False):
run("ls /simple")
regex = r'^\[%s\] Login password: ' % env.host_string
assert_contains(regex, sys.stderr.getvalue())
def test_sudo_prompt_display_passthrough(self):
"""
Sudo prompt should display (via passthrough) when stdout/stderr shown
"""
TestNetwork._prompt_display(True)
def test_sudo_prompt_display_directly(self):
"""
Sudo prompt should display (manually) when stdout/stderr hidden
"""
TestNetwork._prompt_display(False)
@staticmethod
@mock_streams('both')
@server(pubkeys=True, responses={'oneliner': 'result'})
def _prompt_display(display_output):
env.password = None
env.no_agent = env.no_keys = True
env.key_filename = CLIENT_PRIVKEY
output.output = display_output
with password_response(
(CLIENT_PRIVKEY_PASSPHRASE, PASSWORDS[env.user]),
silent=False
):
sudo('oneliner')
if display_output:
expected = """
[%(prefix)s] sudo: oneliner
[%(prefix)s] Login password:
[%(prefix)s] out: sudo password:
[%(prefix)s] out: Sorry, try again.
[%(prefix)s] out: sudo password:
[%(prefix)s] out: result
""" % {'prefix': env.host_string}
else:
# Note lack of first sudo prompt (as it's autoresponded to) and of
# course the actual result output.
expected = """
[%(prefix)s] sudo: oneliner
[%(prefix)s] Login password:
[%(prefix)s] out: Sorry, try again.
[%(prefix)s] out: sudo password: """ % {'prefix': env.host_string}
eq_(expected[1:], sys.stdall.getvalue())
@mock_streams('both')
@server(
pubkeys=True,
responses={'oneliner': 'result', 'twoliner': 'result1\nresult2'}
)
def test_consecutive_sudos_should_not_have_blank_line(self):
"""
Consecutive sudo() calls should not incur a blank line in-between
"""
env.password = None
env.no_agent = env.no_keys = True
env.key_filename = CLIENT_PRIVKEY
with password_response(
(CLIENT_PRIVKEY_PASSPHRASE, PASSWORDS[USER]),
silent=False
):
sudo('oneliner')
sudo('twoliner')
expected = """
[%(prefix)s] sudo: oneliner
[%(prefix)s] Login password:
[%(prefix)s] out: sudo password:
[%(prefix)s] out: Sorry, try again.
[%(prefix)s] out: sudo password:
[%(prefix)s] out: result
[%(prefix)s] sudo: twoliner
[%(prefix)s] out: sudo password:
[%(prefix)s] out: result1
[%(prefix)s] out: result2
""" % {'prefix': env.host_string}
eq_(expected[1:], sys.stdall.getvalue())
@mock_streams('both')
@server(pubkeys=True, responses={'silent': '', 'normal': 'foo'})
def test_silent_commands_should_not_have_blank_line(self):
"""
Silent commands should not generate an extra trailing blank line
After the move to interactive I/O, it was noticed that while run/sudo
commands which had non-empty stdout worked normally (consecutive such
commands were totally adjacent), those with no stdout (i.e. silent
commands like ``test`` or ``mkdir``) resulted in spurious blank lines
after the "run:" line. This looks quite ugly in real world scripts.
"""
env.password = None
env.no_agent = env.no_keys = True
env.key_filename = CLIENT_PRIVKEY
with password_response(CLIENT_PRIVKEY_PASSPHRASE, silent=False):
run('normal')
run('silent')
run('normal')
with hide('everything'):
run('normal')
run('silent')
expected = """
[%(prefix)s] run: normal
[%(prefix)s] Login password:
[%(prefix)s] out: foo
[%(prefix)s] run: silent
[%(prefix)s] run: normal
[%(prefix)s] out: foo
""" % {'prefix': env.host_string}
eq_(expected[1:], sys.stdall.getvalue())
|
This very appealing Tudor style home is now offered for sale after many years of enjoyment by its current owners. Tucked away in a lovely grove this home offers 5 bedrooms plus study, 3 bathrooms and large multiple living areas spread across 2 levels. Plenty of space for everyone and ideal for teenagers and extended family situations . Modern, upgraded kitchen and large dining room ideal for big social gatherings.
Great flow out to the sheltered balcony area, just perfect for relaxing on those long summer nights. Parking is well catered for also with a double internal access garage plus a carport. And as if that wasn’t enough there is an undercover pool and a separate spa room for everyone to enjoy. |
#!/usr/bin/env python
'''
Learning Python
Class#3
I. Create an IP address converter (dotted decimal to binary). This will be
similar to what we did in class2 except:
A. Make the IP address a command-line argument instead of prompting the user
for it.
./binary_converter.py 10.88.17.23
B. Simplify the script logic by using the flow-control statements that we
learned in this class.
C. Zero-pad the digits such that the binary output is always 8-binary digits
long. Strip off the leading '0b' characters. For example,
OLD: 0b1010
NEW: 00001010
D. Print to standard output using a dotted binary format. For example,
IP address Binary
10.88.17.23 00001010.01011000.00010001.00010111
Note, you will probably need to use a 'while' loop and a 'break' statement
for part C.
while True:
...
break # on some condition (exit the while loop)
Python will execute this loop again and again until the 'break' is encountered.
'''
from sys import argv
if len(argv) != 2:
exit("\tYou should pass one argument for this script.\n\tExample: ./test3_1.py <IP address>")
ip_addr = argv[1]
formatter = "%-20s%-60s"
column1 = "IP address"
column2 = "Binary"
octets = ip_addr.split('.')
ip_addr_bin = []
if len(octets) != 4:
exit("Invalid IP address entered")
for octet in octets:
octet = bin(int(octet))
octet = octet[2:]
octet = "0" * (8 - len(octet)) + octet
ip_addr_bin.append(octet)
ip_addr_bin = '.'.join(ip_addr_bin)
print "=" * 80
print formatter % (column1, column2)
print formatter % (ip_addr, ip_addr_bin)
print "=" * 80
# The END
|
If you have been following Swift from the start, you might be aware that Swift was initially started as personal project for my own needs. Later it was released a free theme on WordPress.Org and about two years later, it was released a premium theme. We have crossed several milestones along the way and when we started, we never even dreamt of anything close to the success we will achieved.
All this is made possible by wonderful Swiftler’s who offered their valuable feedback and suggestions. And the premium version users for supporting us financially.
That said we want to continue great products that simplify your workflow and help your business, provide even better support and work to achieve new heights. We have great eagerness, hunger and passion to deliver innovative solutions to help you grow your business.
In order for us to do that, we are going to be making few bold, but important changes.
Reduce the starting price of Swift from $57 to $47.
Increase the yearly renewal fee.
Increase the price of lifetime licenses.
We are dropping unlimited site usage in favour of 5 sites for personal license and 15 for developer license.
You can continue to use the themes on any number of sites you use, support and one click updates ( Not yet available) will be only to 5/15 sites for personal and developer licenses.
Our pricing changes won’t affect any of our current users.
Other theme makers also made changes to their pricing structure some time back, they forced lifetime users to switch to yearly pricing. The legality and the ethical grounds of taking something a user purchased is beyond my understanding. Unlike them, our pricing changes won’t affect any of our current users. If you bought a lifetime license, you will be able to use it for lifetime and get lifetime updates and support. We are loosing money like this, we have been offering support to users for as long as 6 years but, we made a promise and we are committed to keeping it and we are just glad that people stuck to our products so long.
However we twist our words or try to sugarcoat it, we are trying to be profitable and sustainable and stay long into the future.
We hope you will support our decision and understand the reasons behind these changes. We will make these changes in 2 days to give enough time to users who are yet to make a decision on whether to improve their business and sites user experience with Swift or not. |
# package org.apache.helix.model
#from org.apache.helix.model import *
#from java.util import ArrayList
#from java.util import Collections
#from java.util import Comparator
#from java.util import Date
#from java.util import List
#from java.util import Map
#from java.util import UUID
from org.apache.helix.HelixException import HelixException
from org.apache.helix.HelixProperty import HelixProperty
from org.apache.helix.InstanceType import InstanceType
#from org.apache.helix.PropertyKey import PropertyKey
#from org.apache.helix.PropertyKey import Builder
from org.apache.helix.ZNRecord import ZNRecord
from org.apache.helix.util.UserExceptions import IllegalArgumentException
from org.apache.helix.util.misc import enum
import time, uuid
MessageType = enum('STATE_TRANSITION', 'SCHEDULER_MSG', 'USER_DEFINE_MSG', 'CONTROLLER_MSG', 'TASK_REPLY', 'NO_OP', 'PARTICIPANT_ERROR_REPORT')
Attributes = enum('MSG_ID, SRC_SESSION_ID', 'TGT_SESSION_ID', 'SRC_NAME', 'TGT_NAME', 'SRC_INSTANCE_TYPE', 'MSG_STATE',
'PARTITION_NAME', 'RESOURCE_NAME', 'FROM_STATE', 'TO_STATE', 'STATE_MODEL_DEF',
'CREATE_TIMESTAMP', 'READ_TIMESTAMP', 'EXECUTE_START_TIMESTAMP',
'MSG_TYPE', 'MSG_SUBTYPE', 'CORRELATION_ID', 'MESSAGE_RESULT',
'EXE_SESSION_ID', 'TIMEOUT', 'RETRY_COUNT', 'STATE_MODEL_FACTORY_NAME', 'BUCKET_SIZE', 'PARENT_MSG_ID')
MessageState =enum('NEW', 'READ', 'UNPROCESSABLE')
class Message(HelixProperty):
# Attributes = enum('MSG_ID, SRC_SESSION_ID', 'TGT_SESSION_ID', 'SRC_NAME', 'TGT_NAME', 'SRC_INSTANCE_TYPE', 'MSG_STATE',
# 'PARTITION_NAME', 'RESOURCE_NAME', 'FROM_STATE', 'TO_STATE', 'STATE_MODEL_DEF',
# 'CREATE_TIMESTAMP', 'READ_TIMESTAMP', 'EXECUTE_START_TIMESTAMP',
# 'MSG_TYPE', 'MSG_SUBTYPE', 'CORRELATION_ID', 'MESSAGE_RESULT',
# 'EXE_SESSION_ID', 'TIMEOUT', 'RETRY_COUNT', 'STATE_MODEL_FACTORY_NAME', 'BUCKET_SIZE', 'PARENT_MSG_ID')
"""
Java modifiers:
final static
Type:
Comparator<Message>
"""
@staticmethod
def compare(m1, m2):
"""
Returns int
Parameters:
m1: Messagem2: Message
@Override
"""
return int(long(m1.getCreateTimeStamp()) - long(m2.getCreateTimeStamp()))
CREATE_TIME_COMPARATOR = compare
def __init__(self, *args):
if len(args) == 2 and (isinstance(args[1], str) or isinstance(args[1], unicode)):
self.__init__type_msgId(*args)
elif len(args) == 1 and isinstance(args[0], ZNRecord):
self.__init__record(*args)
elif len(args) == 2 and isinstance(args[0], ZNRecord):
self.__init__record_id(*args)
else:
raise IllegalArgumentException("Input arguments not supported. args = %s" % list(args))
"""
Parameters:
MessageType type
String msgId
"""
def __init__type_msgId(self, type, msgId):
super(Message,self).__init__(msgId)
self._record.setSimpleField("MSG_TYPE", MessageType.toString(type))
self.setMsgId(msgId)
self.setMsgState(MessageState.NEW)
self._record.setSimpleField('CREATE_TIMESTAMP', time.time())
"""
Parameters:
ZNRecord record
"""
def __init__record(self, record):
super(Message,self).__init__(record)
if self.getMsgState() == None:
self.setMsgState(MessageState.NEW)
if self.getCreateTimeStamp() == 0:
self._record.setSimpleField("CREATE_TIMESTAMP", "" + time.time())
def setCreateTimeStamp(self, timestamp):
"""
Returns void
Parameters:
timestamp: long
"""
self._record.setSimpleField("CREATE_TIMESTAMP", "" + timestamp)
"""
Parameters:
ZNRecord record
String id
"""
def __init__record_id(self, record, id):
super(Message,self).__init__(ZNRecord(record,id))
# super(ZNRecord(record, id))
self.setMsgId(id)
def setMsgSubType(self, subType):
"""
Returns void
Parameters:
subType: String
"""
self._record.setSimpleField("MSG_SUBTYPE", subType)
def getMsgSubType(self):
"""
Returns String
"""
return self._record.getSimpleField("MSG_SUBTYPE")
def setMsgType(self, type):
"""
Returns void
Parameters:
type: MessageType
"""
self._record.setSimpleField("MSG_TYPE", type.toString())
def getMsgType(self):
"""
Returns String
"""
return self._record.getSimpleField("MSG_TYPE")
def getTgtSessionId(self):
"""
Returns String
"""
return self._record.getSimpleField("TGT_SESSION_ID")
def setTgtSessionId(self, tgtSessionId):
"""
Returns void
Parameters:
tgtSessionId: String
"""
self._record.setSimpleField("TGT_SESSION_ID", tgtSessionId)
def getSrcSessionId(self):
"""
Returns String
"""
return self._record.getSimpleField("SRC_SESSION_ID")
def setSrcSessionId(self, srcSessionId):
"""
Returns void
Parameters:
srcSessionId: String
"""
self._record.setSimpleField("SRC_SESSION_ID", srcSessionId)
def getExecutionSessionId(self):
"""
Returns String
"""
return self._record.getSimpleField("EXE_SESSION_ID")
def setExecuteSessionId(self, exeSessionId):
"""
Returns void
Parameters:
exeSessionId: String
"""
self._record.setSimpleField("EXE_SESSION_ID", exeSessionId)
def getMsgSrc(self):
"""
Returns String
"""
return self._record.getSimpleField("SRC_NAME")
def setSrcInstanceType(self, type):
"""
Returns void
Parameters:
type: InstanceType
"""
self._record.setSimpleField("SRC_INSTANCE_TYPE", type.toString())
def getSrcInstanceType(self):
"""
Returns InstanceType
"""
if self._record.getSimpleFields().containsKey("SRC_INSTANCE_TYPE"):
return InstanceType.valueOf(self._record.getSimpleField("SRC_INSTANCE_TYPE"))
return InstanceType.PARTICIPANT
def setSrcName(self, msgSrc):
"""
Returns void
Parameters:
msgSrc: String
"""
self._record.setSimpleField("SRC_NAME", msgSrc)
def getTgtName(self):
"""
Returns String
"""
return self._record.getSimpleField("TGT_NAME")
def setMsgState(self, msgState):
"""
Returns void
Parameters:
msgState: MessageState
"""
self._record.setSimpleField("MSG_STATE", MessageState.toString(msgState).lower())
def getMsgState(self):
"""
Returns MessageState
"""
return getattr(MessageState, self._record.getSimpleField("MSG_STATE").upper())
def setPartitionName(self, partitionName):
"""
Returns void
Parameters:
partitionName: String
"""
self._record.setSimpleField("PARTITION_NAME", partitionName)
def getMsgId(self):
"""
Returns String
"""
return self._record.getSimpleField("MSG_ID")
def setMsgId(self, msgId):
"""
Returns void
Parameters:
msgId: String
"""
self._record.setSimpleField("MSG_ID", msgId)
def setFromState(self, state):
"""
Returns void
Parameters:
state: String
"""
self._record.setSimpleField("FROM_STATE", state)
def getFromState(self):
"""
Returns String
"""
return self._record.getSimpleField("FROM_STATE")
def setToState(self, state):
"""
Returns void
Parameters:
state: String
"""
self._record.setSimpleField("TO_STATE", state)
def getToState(self):
"""
Returns String
"""
return self._record.getSimpleField("TO_STATE")
def setTgtName(self, msgTgt):
"""
Returns void
Parameters:
msgTgt: String
"""
self._record.setSimpleField("TGT_NAME", msgTgt)
def getDebug(self):
"""
Returns Boolean
"""
return False
def getGeneration(self):
"""
Returns Integer
"""
return 1
def setResourceName(self, resourceName):
"""
Returns void
Parameters:
resourceName: String
"""
self._record.setSimpleField("RESOURCE_NAME", resourceName)
def getResourceName(self):
"""
Returns String
"""
return self._record.getSimpleField("RESOURCE_NAME")
def getPartitionName(self):
"""
Returns String
"""
return self._record.getSimpleField("PARTITION_NAME")
def getStateModelDef(self):
"""
Returns String
"""
return self._record.getSimpleField("STATE_MODEL_DEF")
def setStateModelDef(self, stateModelDefName):
"""
Returns void
Parameters:
stateModelDefName: String
"""
self._record.setSimpleField("STATE_MODEL_DEF", stateModelDefName)
def setReadTimeStamp(self, time):
"""
Returns void
Parameters:
time: long
"""
self._record.setSimpleField("READ_TIMESTAMP", "" + str(time))
def setExecuteStartTimeStamp(self, time):
"""
Returns void
Parameters:
time: long
"""
self._record.setSimpleField("EXECUTE_START_TIMESTAMP", "" + str(time))
def getReadTimeStamp(self):
"""
Returns long
"""
# String
timestamp = self._record.getSimpleField("READ_TIMESTAMP")
if timestamp == None:
return 0
else: return timestamp
def getExecuteStartTimeStamp(self):
"""
Returns long
"""
# String
timestamp = self._record.getSimpleField("EXECUTE_START_TIMESTAMP")
if timestamp == None:
return 0
else:
return timestamp
def getCreateTimeStamp(self):
"""
Returns long
"""
timestamp = self._record.getSimpleField("CREATE_TIMESTAMP")
if timestamp == None:
return 0
else:
return timestamp
def setCorrelationId(self, correlationId):
"""
Returns void
Parameters:
correlationId: String
"""
self._record.setSimpleField("CORRELATION_ID", correlationId)
def getCorrelationId(self):
"""
Returns String
"""
return self._record.getSimpleField("CORRELATION_ID")
def getExecutionTimeout(self):
"""
Returns int
"""
if not "TIMEOUT" in self._record.getSimpleFields():
return -1
return self._record.getSimpleField("TIMEOUT")
def setExecutionTimeout(self, timeout):
"""
Returns void
Parameters:
timeout: int
"""
self._record.setSimpleField("TIMEOUT", "" + str(timeout))
def setRetryCount(self, retryCount):
"""
Returns void
Parameters:
retryCount: int
"""
self._record.setSimpleField("RETRY_COUNT", "" + str(retryCount))
def getRetryCount(self):
"""
Returns int
"""
return self._record.getSimpleField("RETRY_COUNT")
def getResultMap(self):
"""
Returns Map<String, String>
"""
return self._record.getMapField("MESSAGE_RESULT")
def setResultMap(self, resultMap):
"""
Returns void
Parameters:
resultMap: Map<String, String>
"""
self._record.setMapField("MESSAGE_RESULT", resultMap)
def getStateModelFactoryName(self):
"""
Returns String
"""
return self._record.getSimpleField("STATE_MODEL_FACTORY_NAME")
def setStateModelFactoryName(self, factoryName):
"""
Returns void
Parameters:
factoryName: String
"""
self._record.setSimpleField("STATE_MODEL_FACTORY_NAME", factoryName)
def getBucketSize(self):
"""
Returns int
@Override
"""
# String
bucketSizeStr = self._record.getSimpleField("BUCKET_SIZE")
# int
bucketSize = 0
if bucketSizeStr != None:
try:
bucketSize = int(bucketSizeStr)
except ValueError, e: pass
return bucketSize
def setBucketSize(self, bucketSize):
"""
Returns void
Parameters:
bucketSize: int
@Override
"""
if bucketSize > 0:
self._record.setSimpleField("BUCKET_SIZE", "" + str(bucketSize))
def setAttribute(self, attr, val):
"""
Returns void
Parameters:
attr: Attributesval: String
"""
self._record.setSimpleField(attr.toString(), val)
def getAttribute(self, attr):
"""
Returns String
Parameters:
attr: Attributes
"""
return self._record.getSimpleField(attr.toString())
def createReplyMessage(srcMessage, instanceName, taskResultMap):
"""
Returns Message
Parameters:
srcMessage: MessageinstanceName: StringtaskResultMap: Map<String, String>
Java modifiers:
static
"""
if srcMessage.getCorrelationId() == None:
raise HelixException("Message " + srcMessage.getMsgId() + " does not contain correlation id")
# Message
replyMessage = Message(MessageType.TASK_REPLY, str(uuid.uuid4()))
replyMessage.setCorrelationId(srcMessage.getCorrelationId())
replyMessage.setResultMap(taskResultMap)
replyMessage.setTgtSessionId("*")
replyMessage.setMsgState(MessageState.NEW)
replyMessage.setSrcName(instanceName)
if srcMessage.getSrcInstanceType() == InstanceType.CONTROLLER:
replyMessage.setTgtName("Controller")
else:
replyMessage.setTgtName(srcMessage.getMsgSrc())
return replyMessage
def addPartitionName(self, partitionName):
"""
Returns void
Parameters:
partitionName: String
"""
if self._record.getListField("PARTITION_NAME") == None:
self._record.setListField("PARTITION_NAME", [])
# List<String>
partitionNames = self._record.getListField("PARTITION_NAME")
if not partitionNames.contains(partitionName):
partitionNames.add(partitionName)
def getPartitionNames(self):
"""
Returns List<String>
"""
# List<String>
partitionNames = self._record.getListField("PARTITION_NAME")
if partitionNames == None:
return []
return partitionNames
def isControlerMsg(self):
"""
Returns boolean
"""
return self.getTgtName().lower() == "controller"
def getKey(self, keyBuilder, instanceName):
"""
Returns PropertyKey
Parameters:
keyBuilder: BuilderinstanceName: String
"""
if self.isControlerMsg():
return keyBuilder.controllerMessage(self.getId())
else:
return keyBuilder.message(instanceName, self.getId())
def isNullOrEmpty(self, data):
"""
Returns boolean
Parameters:
data: String
Java modifiers:
private
"""
return data == None or len(data) == 0 or len(data.strip()) == 0
def isValid(self):
"""
Returns boolean
@Override
"""
if (self.getMsgType() == MessageType.toString(MessageType.STATE_TRANSITION)):
# boolean
isNotValid = self.isNullOrEmpty(self.getTgtName()) or self.isNullOrEmpty(self.getPartitionName()) or self.isNullOrEmpty(self.getResourceName()) or self.isNullOrEmpty(self.getStateModelDef()) or self.isNullOrEmpty(self.getToState()) or self.isNullOrEmpty(self.getStateModelFactoryName()) or self.isNullOrEmpty(self.getFromState())
return not isNotValid
return True
|
I guess the point is, that having had the teacake treat in the morning, I allowed my Dark Passenger to convince me that I may as well forget my rules and write the day off.
I won’t let it happen again, so I suppose it’s a lesson learned.
The good news is that I’m below 80kg again this morning, so I’m back on track.
Chocolate is, I have to agree, one of life’s guilty pleasures. But when your goal is to get back to the weight you were thirty odd years ago, it is in no way a very long lasting pleasure.
Thank you for your support, but my determination is back to full strength today, and I will resist such temptations from now on. |
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
# from userauth.forms import UserForm, UserProfileForm, ForgotForm
from maps.models import Report, Route
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
# Create your views here.
def test(request):
return HttpResponse('test')
def index(request):
if request.POST:
info = request.POST.get('scoreArray')
alat = info[0]
alng = info[1]
blat = info[2]
blng = info[3]
qual = request.POST.get('quality')
try:
rpt = Report()
rpt.quality = qual
rpt.desc = ""
rpt.lat = float(lat)
rpt.lng = float(lng)
rpt.save()
except:
return HttpResponse('something went wrong')
else:
try:
route = Route.objects.filter(a_lat=alat).filter(a_lng=alng).filter(b_lat=blat).filter(blng)
except:
pass
return render(request, 'index.html', {})
def slow(request):
return render(request, 'index_slow.html', {})
def get_slow(request):
if request.POST:
alat = request.POST.get("lat1")
alng = request.POST.get("lng1")
blat = request.POST.get("lat2")
blng = request.POST.get("lng2")
print alat, alng, blat, blng
try:
print Route.objects.all()
route = Route.objects.filter(a_lat=float(alat)).filter(a_lng=float(alng)).filter(b_lat=float(blat)).filter(b_lng=float(blng))
return HttpResponse(route[0].avg)
except Exception as e:
return HttpResponse(-1)
else:
print "2"
return HttpResponse(-1)
def report(request):
if request.POST:
a = request.POST.getlist("a[]")
b = request.POST.getlist("b[]")
alat = a[0]
alng = a[1]
blat = b[0]
blng = b[1]
qual = request.POST.get('rating')
try:
route = Route.objects.filter(a_lat=float(alat)).filter(a_lng=float(alng)).filter(b_lat=float(blat)).filter(b_lng=float(blng))
if len(route) == 0:
route = Route()
route.a_lat = alat
route.a_lng = alng
route.b_lat = blat
route.b_lng = blng
route.avg = qual
route.save()
return HttpResponse("created")
else:
route = route[0]
if route != None or route != "null":
route.avg -= route.avg / 10
route.avg += float(qual) / 10
route.save()
return HttpResponse("updated route")
except:
return HttpResponse(-1)
def get(request):
if request.POST:
result = []
array = request.POST.getlist("dict[]")
x = 0
while x < len(array):
alat = array[x]
alng = array[x+1]
blat = array[x+2]
blng = array[x+3]
x+=4
route = Route.objects.filter(a_lat=float(alat)).filter(a_lng=float(alng)).filter(b_lat=float(blat)).filter(b_lng=float(blng))
if len(route)==0:
result.append(-1)
else:
result.append(route[0].avg)
return HttpResponse(str(result))
else:
return HttpResponse(-1)
|
Most people are surprised to find out that the first stress placed on a child’s neck and back is during the birthing process. Do you think this could cause damage to your child’s spine and nervous system? Fact: The nervous system controls every c An estimated 60-90 lbs. of force is used on an infant’s neck during “normal” delivery.ell and organ (heart, lungs, brain, stomach) in your body. Equally surprising is the fact that 26% of children surveyed at school reported a history of back pain.
Have you watched your child play outside or with their friends? They run, jump, fall, roll, and tackle every day. Many adults that come to a chiropractor’s office show evidence of childhood injuries that can be the cause for their pain today. Do you think it is too early to teach your kids to take care of their teeth? When do you think it is a good time to have your child’s spine checked for serious signs of spinal imbalances or misalignments?
Fortunately, Chiropractic has had many positive results in children with common childhood problems. Problems like headache, scoliosis, asthma, colic, ear infections, asthma, and even some cases of behavioral problems respond well with chiropractic care. In fact, a recent study showed that children under chiropractic care suffered fewer ear infections than those whose parent took them to medical care alone.
Are chiropractic adjustments safe for children? Absolutely! Because a child’s skeletal system is still developing, only light pressure is needed to adjust a child’s spine. The few minutes you invest in your child’s spinal checkup may save them needless suffering now and in the future.
How can I tell if my child has spinal imbalances?
ï‚· Have your child bend over with arms dangling forward. When you run your hand over his or her spine, does it curve from side to side?
ï‚· Look at your child from the rear, does one shoulder blade stick out or appear to be higher than the other?
ï‚· When looking at your child from the rear, is one ear higher than the other?
ï‚· Does your child’s back appear to be humped or rounded?
ï‚· Do your child’s clothes fit properly; are hems and waistbands of skirts or pants even?
“home evaluations” are just a few indicators why your child may need chiropractic care.
ï‚· When your baby is lying on his back, does his head seem to tilt to one side?
ï‚· Does your baby prefer breastfeeding on one side?
ï‚· Does your baby arch her back when crying?
ï‚· Is your baby slow to develop adequate neck strength to hold his head up?
ï‚· An estimated 60-90 lbs. of force is used on an infant’s neck during “normal” delivery. Do you think this could cause damage to your child’s spine and nervous system? |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman
# Purpose: svg examples
# Created: 08.09.2010
# Copyright (C) 2010, Manfred Moitzi
# License: MIT License
try:
import svgwrite
except ImportError:
# if svgwrite is not 'installed' append parent dir of __file__ to sys.path
import sys, os
sys.path.insert(0, os.path.abspath(os.path.split(os.path.abspath(__file__))[0]+'/..'))
import svgwrite
def linearGradient(name):
dwg = svgwrite.Drawing(name, size=('20cm', '15cm'), profile='full', debug=True)
# set user coordinate space
dwg.viewbox(width=200, height=150)
# create a new linearGradient element
horizontal_gradient = dwg.linearGradient((0, 0), (1, 0))
vertical_gradient = dwg.linearGradient((0, 0), (0, 1))
diagonal_gradient = dwg.linearGradient((0, 0), (1, 1))
tricolor_gradient = dwg.linearGradient((0, 0), (1, 1))
# add gradient to the defs section of the drawing
dwg.defs.add(horizontal_gradient)
dwg.defs.add(vertical_gradient)
dwg.defs.add(diagonal_gradient)
dwg.defs.add(tricolor_gradient)
# define the gradient from white to red
horizontal_gradient.add_stop_color(0, 'white')
horizontal_gradient.add_stop_color(1, 'red')
# define the gradient from white to green
vertical_gradient.add_stop_color(0, 'white')
vertical_gradient.add_stop_color(1, 'green')
# define the gradient from white to blue
diagonal_gradient.add_stop_color(0, 'white')
diagonal_gradient.add_stop_color(1, 'blue')
# define the gradient from white to red to green to blue
tricolor_gradient.add_stop_color(0, 'white')
tricolor_gradient.add_stop_color(.33, 'red')
tricolor_gradient.add_stop_color(.66, 'green')
tricolor_gradient.add_stop_color(1, 'blue')
# use gradient for filling the rect
dwg.add(dwg.rect((10,10), (50,50), fill=horizontal_gradient.get_paint_server(default='currentColor')))
dwg.add(dwg.rect((70,10), (50,50), fill=vertical_gradient.get_paint_server(default='currentColor')))
dwg.add(dwg.rect((130,10), (50,50), fill=diagonal_gradient.get_paint_server(default='currentColor')))
dwg.add(dwg.rect((10,70), (50,50), fill=tricolor_gradient.get_paint_server(default='currentColor')))
# rotate gradient about 90 degree
# first copy gradient
tricolor2_gradient = tricolor_gradient.copy()
# rotate the gradient
tricolor2_gradient.rotate(90, (.5, .5))
# add gradient to the defs section of the drawing
dwg.defs.add(tricolor2_gradient)
# use the gradient
dwg.add(dwg.rect((70,70), (50,50), fill=tricolor2_gradient.get_paint_server(default='currentColor')))
updown = dwg.linearGradient()
dwg.defs.add(updown)
updown.add_colors(['red', 'white', 'red', 'white', 'red'], sweep=(.2, .8))
dwg.add(dwg.rect((130,70), (50,50), fill=updown.get_paint_server(default='currentColor')))
dwg.save()
if __name__ == '__main__':
linearGradient("linearGradient.svg")
|
Choosing a hotel would have been difficult if you did not have the qualifications for a hotel worth a visit. Do you want the best place you can get for an overnight stay? The answer is hotel, how do you know which hotel is a good hotel? No one wants to be stuck in a dirty and vague place where you do not feel safe to sit in bed let alone get into it. The hallmark of a good hotel is the service provided like your own home.
Look for reviews online, you can get a good overview of most of the hotels on your list. And with so many of the competition chains trying to be bigger and better than their competitors on the road which is only good news for us, the travelers and the ones who actually live in the rooms. Another good thing to look for is the facilities the hotel provides to repeat guests. |
#NAME: NIRZARI IYER
#Assignment-2
#ID NUMBER: 1001117633
#BATCH TIME- 6:00 to 8:00 p.m.
import MySQLdb
import io
import os
import cloudstorage as gcs
import csv
import timeit
from bottle import Bottle
from google.appengine.api import app_identity
from StringIO import StringIO
from bottle import route, request, response, template
bottle = Bottle()
#location of file into default bucket on google cloud storage
bucket_name = os.environ.get('BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
bucket = '/' + bucket_name
filename = bucket + '/earthquake.csv'
#Get filename from user
@bottle.route('/uploadform')
def uploadform():
return template('upload_form')
#Upload file into bucket on google cloud storage
@bottle.route('/uploadfile', method='POST')
def uploadfile():
start = timeit.default_timer()
filecontent = request.files.get('filecontent')
rawfilecontent = filecontent.file.read()
write_retry_params = gcs.RetryParams(backoff_factor=1.1)
gcs_file = gcs.open(filename,'w',content_type='text/plain',retry_params=write_retry_params)
gcs_file.write(rawfilecontent)
gcs_file.close()
stop = timeit.default_timer()
time_taken = stop - start
return template('upload_file',time_taken=time_taken)
#Read data from bucket and Insert data into google MySQLdb
def parse(filename, delimiter,c):
with gcs.open(filename, 'r') as gcs_file:
csv_reader = csv.reader(StringIO(gcs_file.read()), delimiter=',',
quotechar='"')
# Skip the header line
csv_reader.next()
try:
start = timeit.default_timer()
for row in csv_reader:
time = timestamp(row[0])
updated = timestamp(row[12])
for i in range (0,14):
if row[i] == '':
row[i] = "''"
place = str(row[13])
place = place.replace("'","")
insert = "INSERT INTO earthquake (time, latitude, longitude, depth, mag, magType, nst, gap, dmin, rms, net, id, updated,\
place, type) values('"+time+"',"+row[1]+","+row[2]+","+row[3]+","+row[4]+",'"+row[5]+"',"+row[6]+","+row[7]+",\
"+row[8]+","+row[9]+",'"+row[10]+"','"+row[11]+"','"+updated+"','"+place+"','"+row[14]+"')"
c.execute(insert)
stop = timeit.default_timer()
insert_time = stop - start
return insert_time
except Exception as e:
print ("Data can't be inserted" + str(e))
def timestamp(string):
ans = string[:10] + ' ' + string[11:19]
return ans
def query(mag,c):
query = 'SELECT week(time) as week, count(*) as count, mag as mag FROM earthquake WHERE mag = '+str(mag)+' GROUP BY week(time), mag'
c.execute(query)
ans_query = c.fetchall()
return ans_query
def bigquery(mag,c):
query = 'SELECT week(time) as week, count(*) as count, mag as mag FROM earthquake WHERE mag > '+str(mag)+' GROUP BY week(time), mag'
c.execute(query)
ans_query = c.fetchall()
return ans_query
def ans_format(mag):
table = "<table border='2'><tr><th>Week</th><th>Number of quakes</th><th>Magnitude</th></tr>"
ans = ""
for x in mag:
ans = ans +"<tr><td>" + str(x[0]) + "</td><td>" + str(x[1]) + "</td><td>" + str(x[2]) +"</td></tr>"
table += ans + "</table>"
return table
@bottle.route('/')
def main():
try:
connobj = MySQLdb.connect(unix_socket='/cloudsql/cloudcomp2-979:simple' ,user='root')
c = connobj.cursor()
createdb = 'CREATE DATABASE IF NOT EXISTS db'
c.execute(createdb)
connectdb = 'USE db'
c.execute(connectdb)
table = 'CREATE TABLE IF NOT EXISTS earthquake '\
'(time TIMESTAMP,'\
'latitude DOUBLE,'\
'longitude DOUBLE,'\
'depth DOUBLE,'\
'mag DOUBLE,'\
'magType varchar(500),'\
'nst DOUBLE,'\
'gap DOUBLE,'\
'dmin DOUBLE,'\
'rms DOUBLE,'\
'net varchar(500),'\
'id varchar(500),'\
'updated TIMESTAMP,'\
'place VARCHAR(500),'\
'type VARCHAR(500))'
c.execute(table)
c.execute("truncate table earthquake")
insert_time = parse(filename,',',c)
mag2 = query(2,c)
mag3 = query(3,c)
mag4 = query(4,c)
mag5 = query(5,c)
maggt5 = bigquery(5,c)
ans_mag2 = ans_format(mag2)
ans_mag3 = ans_format(mag3)
ans_mag4 = ans_format(mag4)
ans_mag5 = ans_format(mag5)
ans_maggt5 = ans_format(maggt5)
ans = "Final Result: <br><br> Time taken to Insert data into MySQL database is: <br>" +str(insert_time)+"<br><br>" \
"Earthquake of magnitude 2: <br> "+str(ans_mag2)+"<br><br> Earthquake of magnitude 3: <br>" \
+str(ans_mag3)+ "<br><br> Earthquake of magnitude 4: <br>" +str(ans_mag4)+ "<br><br> Earthquake" \
"of magnitude 5: <br>" +str(ans_mag5)+ "<br><br> Earthquake of magnitude greater than 5: <br>" +str(ans_maggt5)
return ans
except Exception as e:
print str(e)
return e
# Define an handler for 404 errors.
@bottle.error(404)
def error_404(error):
"""Return a custom error 404."""
return 'Sorry, nothing at this URL.'
# [END all]
|
If that you simply thinking to begin an enterprise with no investment consequently drop shipping is a ideal business meant for you. Which much more effective approach for you to commence a business organization. You might be astounded at how straightforward it is typically to begin a profitable business. It is undoubtedly possible to easily start a web-affiliated business with nearly no money down.
Men and women start up a business since they yearn intended for independence. A business is a sociable entity. When it’s your earliest company, if it is your 14th organization, you will have to deal with apprehension. Winning at any cost against your competition isn’t very plenty of to create a wonderful business.
Expense If perhaps you’re in big cities then certainly you’ve got to in addition face marvelous competition with big firms in small neighborhoods and areas, you can start off right from low funds as well. It is quite convenient to start and extremely low financial commitment is necessary. Purchase You only require a place at which you may adjust few autos it will take a huge community hall, two outlets or open location.
What Is Thus Amazing About Rewarding Organization?
Your online business thought must source a rock n roll solid gain that’s the legitimate primary to setting up personal wealth by results in of the passion driven business thought. The idea of business possession incorporates the publishing notion that you’ll end up being responsible for the success. Following reading the webpage until end, you will have lot of new commercial enterprise ideas in your head. So to start out with, you ought to do a couple of marketplace research to come across some tiny scale businesses then choose one which in turn it is simple to work.
Over the last few of years, yet , the company figured out how to consider the brick provider and change it in a thriving Web effort. A few tiny businesses fear an excess of success. When you wish to stay a solo business, the path to growth should be to keep up-leveling your clients.
Found in case it works, you’re running a business. Wedding planning business is one of the prosperous online business ideas devoid of investment on the list. Before investing in a bundle or provide, make sure that the services fit your requirements. Search engine optimisation sites are somewhat well-liked in the world wide web, since inextricably connected to him.
In the event that you’re going to begin a business in Pakistan but can’t say for sure specifically where to start with your trip then simply we are going to below to guide your. So if you’d like to move your company forward so you want to make a much better life, all of it starts with changing the character of what you do every day. Starting a drop shipping business is just one of the easiest methods to earn income.
If you’re here thinking to begin an enterprise with actually zero investment consequently drop shipping and delivery is a perfect organization with respect to you. Which much even more effective approach for you to begin a business organization. You’re going to be shocked at how basic it usually is to begin a profitable business. It is definitely possible to simply start a web-based business with almost no cash down.
Men and women take up a business simply because yearn for the purpose of independence. An organization is a social entity. When it’s your first company, if it is your fourteenth organization, you will have to deal with dread. Being victorious in at any cost against your competitors isn’t plenty of to create a wonderful business.
Expense Whenever you’re in big urban centers then absolutely you’ve received to equally face enormous competition with big businesses but also in minor towns and areas, you can initiate coming from low money as well. It’s very easy to begin and very low expense is essential. Purchase You only demand a place at which in turn you may adapt few autos it needs a huge corridor, two shops or available location.
What Is undoubtedly Therefore Interesting About Rewarding Business?
Your corporation thought must source a steel solid benefit that’s the legitimate key element to setting up personal wealth by ways of your passion motivated business thought. The concept of organization title incorporates the liberating idea that you’ll end up being in charge of the hair straighteners. Following studying the webpage until end, you’ll have number of new internet business ideas in your head. So to begin with, you ought to do some marketplace research to find some minimal scale businesses then select one which usually you can actually run.
During the last couple of years, yet , the company worked out how to take their can enterprise and enhance it into a thriving Web effort. A few tiny businesses fear an excessive amount of success. When you wish to stay a solo organization, the path to growth should be to keep up-leveling your buyers.
In case functions, you’re managing a business. Wedding ceremony planning business is one of the prosperous online business ideas with out investment on the list. Before committing to a plan or deliver, ensure that the services suit your requirements. Seo help will be alternatively well-liked about the net, because inextricably connected to him.
In cases where you’re gonna begin a organization in Pakistan although can’t say for sure exactly where to begin your trip consequently we are going to below to guide your. So if you want to move your organization forward and you also want to make a better life, it all starts with changing the character of what you do every single day. Starting a drop shipment business is just one of the most basic methods to make money.
If you will absolutely thinking to begin an enterprise with actually zero investment in that case drop shipment is a perfect organization for you. In which much extra successful approach for you to start a business enterprise. You’ll be shocked at exactly how basic it usually is to begin a profitable business. It is usually possible to easily start a web-affiliated organization with almost no funds down.
Men and women start a business simply because they yearn with regards to independence. A company is a sociable entity. When it’s your initial company, whether it’s your 14th organization, you will have to deal with fear. Success at all costs against your competitors merely more than enough to create a great venture.
Purchase In the event you’re in big urban centers then certainly you’ve acquired to equally face massive competition with big firms playing with minimal areas and areas, you can begin the process of right from low cash as well. It is rather easy to start off and extremely low investment is essential. Financial commitment You just require a place at which you may fine-tune few vehicles it requires a huge lounge, two shops or available location.
What Is Therefore Exciting About Profitable Business?
Your small business idea has to supply a rock and roll solid benefit that’s the actual key to setting up personal prosperity by means of your passion powered business idea. The idea of organization control features the liberating concept that you’ll end up being in charge of your lives. Following browsing the web page until end, you’ll have great deal of new commercial enterprise ideas in your thoughts. So to start out with, you ought to do a couple of industry research to come across some minimal scale businesses then select one which in turn it is simple to work.
During the last few of years, nevertheless , the company identified how to consider their stone provider and change it to a thriving Web effort. A lot of tiny businesses fear an excessive amount of success. When you need to continue to be a solo provider, the path to growth is to keep up-leveling your consumers.
In case functions, you’re operating a business. Wedding and reception scheduling business is probably the prosperous small enterprise ideas without investment out there. Before committing to a plan or perhaps present, make sure that the services suit your requirements. Search engine optimisation service are rather popular upon the web, mainly because with one another associated with him.
In the event that you’re likely to begin a business found in Pakistan nevertheless can’t say for sure exactly where to begin your trip then simply efficient here to guide your. So if you’d like to move your business forward and yourself want to make a much better life, all this starts with changing the character of what you do every day. Starting a drop delivery business is just one of the simplest methods to earn income.
If if you’re thinking to begin a company with totally free investment therefore drop shipping and delivery is a ideal business for you. Which much even more successful way for you to start a business business. You’ll certainly be shocked at how straightforward it can be to begin a profitable corporation. It is without question possible to simply start a web-affiliated organization with nearly no cash down.
Men and women begin a business simply because yearn with respect to independence. A company is a public entity. If it’s your earliest company, if it is your fourteenth organization, you will need to deal with fear. Winning without exceptions against your competitors genuinely more than enough to create a superb organization.
Expense Whenever you’re in big locations then definitely you’ve received to furthermore face fantastic competition with big companies but in small towns and areas, you can get started from low funds likewise. It’s easy to start off and very low financial commitment is essential. Expenditure You merely require a place at which will you may modify few automobiles it requires a huge area, two outlets or open up location.
What Can be Hence Exciting Regarding Profitable Organization?
Your online business thought should source a steel solid advantage that’s the actual essential to building personal prosperity by ways of your passion powered business thought. The concept of organization possession may include the liberating concept that you’ll get accountable for the success. Following browsing the page right up until end, you will still have wide range of new small company ideas in your thoughts. So to begin with, you ought to carry out some marketplace research to find some minimal scale businesses then choose one which usually you can easily run.
During the last couple of years, however , the company identified how to consider their large rock business and transform it to a thriving Net effort. Some tiny businesses fear an excessive amount of success. When you wish to continue to be a solo provider, the path to growth is always to keep up-leveling your clients.
Found in case functions, you’re operating a business. Wedding ceremony planning business is one of the prosperous small business ideas while not investment out there. Before committing to a deal or deliver, be sure the services fit in your requirements. Search engine optimization web sites happen to be alternatively popular on the web, because simultaneouslysynchronically, together, unitedly, with one another related to him.
Whenever you’re gonna begin a organization in Pakistan nevertheless how to start precisely where to begin your trip then wish here to guide your. So in order to move your business forward so you want to make a much better life, all this starts with changing the character of what you do every single day. Starting a drop shipping and delivery business is merely one of the easiest methods to earn money.
If that you simply thinking to begin a small business with actually zero investment in that case drop transport is a excellent organization to get you. You will find a much considerably more successful method for you to start a business business. You’ll be astounded at how basic it could be to begin a profitable organization. It is definitely possible to easily start a web-based business with almost no cash down.
Men and women start a business simply because yearn pertaining to independence. An organization is a social entity. If it’s your primary company, whether it’s your fourteenth organization, you will have to deal with fear. Taking at all costs against your competition is not really more than enough to create a wonderful enterprise.
Expense Whenever you’re in big urban centers then definitely you’ve received to additionally face significant competition with big firms however in minimal neighborhoods and areas, you can start coming from low money also. It’s convenient to commence and very low expenditure is needed. Investment You simply demand a place at which you can change few autos it will require a huge area, two outlets or open location.
What Is going to be Therefore Spellbinding About Money-making Organization?
Your enterprise idea has to source a pebble solid benefit that’s the serious essential to building personal riches by ways of the passion driven business thought. The idea of organization ownership incorporates the publishing idea that you’ll get accountable for the straighteners. Following reading the site right up until end, proceeding have lot of new internet business ideas in your thoughts. So to start with, you ought to do some industry research to come across some tiny scale businesses then select one which it is simple to work.
Over the last couple of years, nevertheless , the company identified how to have its large rock organization and change it right into a thriving Web effort. Some tiny businesses fear a lot of success. When you need to continue to be a one-person provider, the path to growth is always to keep up-leveling your buyers.
Found in case it works, you’re managing a business. Wedding ceremony planning business is one of the prosperous internet business ideas not having investment out there. Before committing to a bundle or deliver, make sure that the services fit in your requirements. Search engine optimisation service are somewhat popular upon the internet, since simultaneouslysynchronically, together, unitedly, with one another associated with him.
In the event that you’re gonna begin a business in Pakistan although how to start precisely where to begin with your trip in that case wish here to guide your. So in order to move your business forward and you also want to make a much better life, it all starts with changing the character of what you do each day. Starting a drop transport business is merely one of the easiest methods to earn income.
If if you’re thinking to begin a small business with no investment in that case drop delivery is a perfect organization for you. In which much even more effective method for you to commence a business enterprise. You’ll end up amazed at exactly how simple it is to begin a profitable organization. It can be possible to simply start a web-affiliated organization with practically no funds down.
Men and women take up a business simply because they yearn pertaining to independence. A company is a interpersonal entity. If it’s your 1st company, if it is your fourteenth organization, you’ll want to deal with apprehension. Wooing at any cost against your competition isn’t really enough to create a great business.
Purchase In cases where you’re in big cities then absolutely you’ve acquired to equally face remarkable competition with big firms employing tiny areas and areas, you can commence by low cash likewise. It’s convenient to start out and incredibly low financial commitment is needed. Investment You merely demand a place at which will you can correct few vehicles it will take a huge hall, two outlets or open location.
What Is certainly Therefore Captivating Regarding Successful Business?
Your corporation thought should source a small gravel solid advantage that’s the substantial key to setting up personal wealth by results in of the passion influenced business thought. The notion of business control incorporates the liberating idea that you’ll come to be accountable for your hair straightener. Following studying the webpage till end, you can have lots of new small company ideas in your head. So to start with, you ought to do some marketplace research to find some minor scale businesses then select one which usually you can easily run.
Over the last few of years, nevertheless , the company identified how to consider their brick business and transform it to a thriving Internet effort. Several tiny businesses fear excessive success. When you need to stay a one person organization, the path to growth is always to keep up-leveling your buyers.
Found in case it works, you’re managing a business. Wedding ceremony planning business is among the most prosperous small enterprise ideas with out investment out there. Before investing in a deal or present, be certain that the services match your requirements. Search engine optimization help will be rather well-liked about the world wide web, since accordingly related to him.
In cases where you’re likely to begin a organization found in Pakistan nevertheless can’t say for sure exactly where to begin with your trip after that our company is below to guide your. So if you want to move your company forward and you also want to make an improved life, all this starts with changing the character of what you do every day. Starting a drop transport business is merely one of the simplest methods to earn money.
If occur to be thinking to begin a business with stop investment then simply drop delivery is a ideal organization to get you. There’s a much more successful way for you to start a business business. You’ll end up astounded at exactly how simple it can also be to begin a profitable business. It is usually possible to easily start a web-based organization with almost no money down.
Men and women start a business given that they yearn designed for independence. A firm is a public entity. When it’s your first company, if it’s your 14th organization, you will need to deal with apprehension. Winning at all costs against your competitors just isn’t plenty of to create a great enterprise.
Financial commitment Whenever you’re in big metropolitan areas then definitely you’ve received to also face massive competition with big businesses playing with very little villages and areas, you can start out right from low funds likewise. It is rather easy to begin and incredibly low investment is required. Purchase You just require a place at which you are able to modify few autos it will take a huge area, two retailers or wide open location.
What Is usually Consequently Amazing Regarding Lucrative Organization?
Your online business thought has to supply a pebbles solid gain that’s the proper main to construction personal wealth by means of your passion influenced business thought. The notion of business title comprises of the delivering notion that you’ll end up being in charge of the lives. Following browsing the web page right up until end, likely to have wide range of new small companies ideas in your thoughts. So to begin with, you ought to do a couple of market research to come across some little scale business ideas then select one which usually you can actually work.
During the last few of years, yet , the company identified how to consider its stone enterprise and change it right into a thriving Web effort. A lot of tiny businesses fear excessive success. When you wish to continue to be a one-person firm, the path to growth is always to keep up-leveling your clients.
Found in case it works, you’re managing a business. Wedding preparation business is one of the prosperous small company ideas devoid of investment out there. Before committing to a package deal or perhaps offer, be sure the services match your requirements. Search engine optimisation programs are somewhat well-known in the net, mainly because with one another connected to him.
In the event you’re likely to begin a organization found in Pakistan but how to start exactly where to start your trip afterward wish here to guide the. So if you’d like to move your company forward and yourself want to make an improved life, all of it starts with changing the character of what you do each day. Starting a drop shipping business is merely one of the simplest methods to make money.
If most likely thinking to begin an enterprise with no investment then simply drop shipping and delivery is a excellent organization pertaining to you. In which much more effective approach for you to commence a business venture. You’ll certainly be shocked at exactly how basic it can also be to begin a profitable firm. It is certainly possible to simply start a web-affiliated business with almost no money down.
Men and women take up a business simply because yearn to get independence. A company is a public entity. When it’s your earliest company, if it is your fourteenth organization, you’ll want to deal with fear. Taking at all costs against your competition just isn’t enough to create a wonderful venture.
Expenditure Any time you’re in big metropolitan areas then definitely you’ve received to similarly face tremendous competition with big firms in minor cities and areas, you can start out from low funds as well. It’s convenient to commence and extremely low expense is needed. Financial commitment You merely require a place at which in turn you are able to change few autos it requires a huge lounge, two shops or open location.
What Can be Therefore Captivating About Profitable Organization?
Your small business idea should supply a mountain solid profit that’s the genuine key to construction personal riches by results in of the passion influenced business thought. The notion of business title comes with the delivering concept that you’ll get responsible for your success. After browsing the web page right up until end, you’d have great deal of new small company ideas in your thoughts. So to commence with, you ought to do a couple of marketplace research to find some very little scale business ideas then choose one which usually it is simple to work.
During the last few of years, nevertheless , the company worked out how to consider it is can company and transform it right into a thriving Internet effort. Several tiny businesses fear a lot of success. When you wish to continue to be a solo organization, the path to growth is always to keep up-leveling your clients.
In case functions, you’re operating a business. Wedding preparation business is one of the prosperous small business ideas devoid of investment out there. Before investing in a bunch or present, be sure the services fit in your requirements. Seo web sites will be rather well-liked upon the web, mainly because inextricably associated with him.
Any time you’re gonna begin a business in Pakistan but can’t say for sure accurately where to start with your trip in that case we are going to here to guide the. So if you want to move your company forward and yourself want to make a much better life, it all starts with changing the character of what you do every single day. Starting a drop delivery business is just one of the simplest methods to build an income.
If you aren’t thinking to begin a small business with stop investment afterward drop shipment is a excellent business with respect to you. There’s a much considerably more effective way for you to begin a business enterprise. You’ll certainly be amazed at how simple it is usually to begin a profitable company. It is certainly possible to easily start a web-affiliated business with nearly no cash down.
Men and women start a business since they yearn just for independence. A company is a friendly entity. If it’s your first company, if it is your 14th organization, you will have to deal with apprehension. Taking without exceptions against your competition actually more than enough to create a great business.
Purchase In the event you’re in big metropolitan areas then certainly you’ve received to in the same way face significant competition with big companies playing with minor villages and areas, you can get started out of low funds also. It’s convenient to start and incredibly low purchase is necessary. Purchase You merely demand a place at which usually you can regulate few autos it needs a huge area, two shops or wide open location.
What Is usually So Spellbinding Regarding Profitable Organization?
Your enterprise idea should supply a mountain solid benefit that’s the legitimate major to construction personal riches by means of the passion driven business thought. The notion of organization title includes the publishing notion that you’ll become responsible for the destiny. After examining the webpage right up until end, you will have number of new small companies ideas in your head. So to commence with, you ought to carry out some market research to find some little scale businesses then choose one which in turn it is simple to manage.
During the last couple of years, however , the company identified how to consider it is can enterprise and enhance it right into a thriving Web effort. A lot of tiny businesses fear an excessive amount of success. When you need to continue to be a solo provider, the path to growth should be to keep up-leveling your consumers.
In case it works, you’re running a business. Wedding and reception scheduling business is one of the prosperous internet business ideas without investment out there. Before committing to a deal or perhaps deliver, be certain that the services suit your requirements. Search engine9419 service will be somewhat well-liked upon the web, since inextricably related to him.
In the event you’re gonna begin a business in Pakistan yet don’t know accurately where to begin your trip therefore efficient right here to guide the. So in order to move your business forward so you want to make an improved life, all of it starts with changing the character of what you do each day. Starting a drop shipment business is merely one of the simplest methods to build an income.
If you aren’t thinking to begin an enterprise with no investment then simply drop shipment is a perfect organization intended for you. You will find a much more successful approach for you to begin a business business. You’re going to be astounded at exactly how simple it can be to begin a profitable organization. It is definitely possible to easily start a web-affiliated organization with nearly no funds down.
Men and women start a business simply because yearn with regards to independence. A corporation is a interpersonal entity. If it’s your earliest company, if it’s your fourteenth organization, you’ll need to deal with fear. Wooing without exceptions against your competitors just isn’t more than enough to create a great organization.
Expenditure Whenever you’re in big urban centers then absolutely you’ve received to moreover face massive competition with big companies but also in minor neighborhoods and areas, you can begin coming from low money as well. It is extremely convenient to begin and very low expense is necessary. Purchase You merely demand a place at which in turn you may alter few vehicles it will take a huge community hall, two outlets or open location.
What Is normally Hence Exciting Regarding Lucrative Business?
Your enterprise thought needs to supply a pebble solid profit that’s the proper essential to construction personal riches by ways of your passion influenced business idea. The notion of organization title comes with the liberating concept that you’ll become accountable for the hair straighteners. After browsing the page until end, you’d have great deal of new small company ideas in your thoughts. So to start out with, you ought to do a couple of market research to come across some small scale businesses then choose one which you can easily run.
During the last couple of years, nevertheless , the company identified how to have it is packet business and transform it into a thriving Internet effort. A lot of tiny businesses fear an excessive amount of success. If you want to continue to be a solo provider, the path to growth is always to keep up-leveling your customers.
In case it works, you’re managing a business. Wedding ceremony planning business is among the most prosperous online business ideas with no investment on the list. Before committing to a deal or perhaps offer, make sure that the services fit in your requirements. Search engine9419 help are somewhat well-liked in the net, because unitedlywith one another related to him.
In the event that you’re gonna begin a organization in Pakistan nonetheless how to start specifically where to start with your trip therefore i’m right here to guide the. So if you’d like to move your company forward and you also want to make a better life, everything starts with changing the character of what you do every single day. Starting a drop transport business is just one of the easiest methods to earn money. |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Decode from trained T2T models.
This binary performs inference using the Estimator API.
Example usage to decode from dataset:
t2t-decoder \
--data_dir ~/data \
--problems=algorithmic_identity_binary40 \
--model=transformer
--hparams_set=transformer_base
Set FLAGS.decode_interactive or FLAGS.decode_from_file for alternative decode
sources.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
# Dependency imports
from tensor2tensor.bin import t2t_trainer
from tensor2tensor.utils import decoding
from tensor2tensor.utils import trainer_lib
from tensor2tensor.utils import usr_dir
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
# Additional flags in bin/t2t_trainer.py and utils/flags.py
flags.DEFINE_string("checkpoint_path", None,
"Path to the model checkpoint. Overrides output_dir.")
flags.DEFINE_string("decode_from_file", None,
"Path to the source file for decoding")
flags.DEFINE_string("decode_to_file", None,
"Path to the decoded (output) file")
flags.DEFINE_bool("keep_timestamp", False,
"Set the mtime of the decoded file to the "
"checkpoint_path+'.index' mtime.")
flags.DEFINE_bool("decode_interactive", False,
"Interactive local inference mode.")
flags.DEFINE_integer("decode_shards", 1, "Number of decoding replicas.")
def create_hparams():
return trainer_lib.create_hparams(
FLAGS.hparams_set,
FLAGS.hparams,
data_dir=os.path.expanduser(FLAGS.data_dir),
problem_name=FLAGS.problems)
def create_decode_hparams():
decode_hp = decoding.decode_hparams(FLAGS.decode_hparams)
decode_hp.add_hparam("shards", FLAGS.decode_shards)
decode_hp.add_hparam("shard_id", FLAGS.worker_id)
return decode_hp
def decode(estimator, hparams, decode_hp):
if FLAGS.decode_interactive:
decoding.decode_interactively(estimator, hparams, decode_hp)
elif FLAGS.decode_from_file:
decoding.decode_from_file(estimator, FLAGS.decode_from_file, hparams,
decode_hp, FLAGS.decode_to_file,
checkpoint_path=FLAGS.checkpoint_path)
if FLAGS.checkpoint_path and FLAGS.keep_timestamp:
ckpt_time = os.path.getmtime(FLAGS.checkpoint_path + ".index")
os.utime(FLAGS.decode_to_file, (ckpt_time, ckpt_time))
else:
decoding.decode_from_dataset(
estimator,
FLAGS.problems.split("-"),
hparams,
decode_hp,
decode_to_file=FLAGS.decode_to_file,
dataset_split="test" if FLAGS.eval_use_test_set else None)
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
FLAGS.use_tpu = False # decoding not supported on TPU
hp = create_hparams()
decode_hp = create_decode_hparams()
estimator = trainer_lib.create_estimator(
FLAGS.model,
hp,
t2t_trainer.create_run_config(hp),
decode_hparams=decode_hp,
use_tpu=False)
decode(estimator, hp, decode_hp)
if __name__ == "__main__":
tf.app.run()
|
*Thank you Restaurantware for sponsoring* this post. All opinions are my own and would only recommend products that I personally use.
Summer pasta salads are a favorite go to for any BBQ, holiday or weeknight dinner. They are versatile and always a huge hit. I made this Pesto Caprese Pasta Salad to go along with grilled chicken. I wanted something simple but flavorful and this one hit it right on the head!
Penne pasta is tossed with diced fresh mozzarella, tomatoes and sliced black olives. Dressed simply with basil pesto, fresh sliced basil, salt and pepper. The ingredients are simple, the flavors are big and this Pesto Caprese Pasta Salad would be a great side dish this weekend for 4th of July or any day of the week in my book.
If you’re making this for a party, I found a really great way to serve them… how cool are these bamboo cones that are a fabulous way to serve snack mixes, roasted nuts or candies. If you are party planning then you need to check out the Restaurantware site, they’ve got everything to make your food look incredible!
Cook the pasta according to the package. Drain and rinse under cold water. Add the cooled and drained pasta to a large bowl.
Stir in the tomatoes, olives, fresh mozzarella, pesto, salt and pepper. Toss to coat.
Add in some sliced fresh basil and if the pasta seems a little dry go ahead and drizzle in a little olive oil.
That is a really cute way to serve pasta salad! That reminds me: I haven’t made pasta salad in FOREVER!! This looks so good!
Thanks so much! I love their products! Makes everything look gorgeous! |
# coding=utf-8
#
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import re
from requests.compat import urljoin
from requests.utils import dict_from_cookiejar
import sickrage
from sickrage.core.caches.tv_cache import TVCache
from sickrage.core.helpers import bs4_parser, try_int, convert_size
from sickrage.providers import TorrentProvider
class FileListProvider(TorrentProvider):
def __init__(self):
super(FileListProvider, self).__init__('FileList', 'http://filelist.ro', True)
# Credentials
self.username = None
self.password = None
# Torrent Stats
self.minseed = None
self.minleech = None
# URLs
self.urls.update({
"login": "{base_url}/takelogin.php".format(**self.urls),
"search": "{base_url}/browse.php".format(**self.urls),
})
# Proper Strings
self.proper_strings = ["PROPER", "REPACK"]
# Cache
self.cache = TVCache(self)
def login(self):
if any(dict_from_cookiejar(sickrage.app.wsession.cookies).values()):
return True
login_params = {
"username": self.username,
"password": self.password
}
try:
response = sickrage.app.wsession.post(self.urls["login"], data=login_params).text
except Exception:
sickrage.app.log.warning("Unable to connect to provider")
return False
if re.search("Invalid Username/password", response) \
or re.search("<title>Login :: FileList.ro</title>", response) \
or re.search("Login esuat!", response):
sickrage.app.log.warning("Invalid username or password. Check your settings")
return False
return True
def search(self, search_strings, age=0, ep_obj=None):
results = []
if not self.login():
return results
# Search Params
search_params = {
"search": "",
"cat": 0
}
for mode in search_strings:
sickrage.app.log.debug("Search Mode: {0}".format(mode))
for search_string in search_strings[mode]:
if mode != "RSS":
sickrage.app.log.debug("Search string: {}".format(search_string))
search_params["search"] = search_string
search_url = self.urls["search"]
try:
data = sickrage.app.wsession.get(search_url, params=search_params).text
results += self.parse(data, mode)
except Exception:
sickrage.app.log.debug("No data returned from provider")
return results
def parse(self, data, mode):
"""
Parse search results from data
:param data: response data
:param mode: search mode
:return: search results
"""
results = []
with bs4_parser(data, "html5lib") as html:
torrent_rows = html.find_all("div", class_="torrentrow")
# Continue only if at least one Release is found
if not torrent_rows:
sickrage.app.log.debug("Data returned from provider does not contain any torrents")
return results
# "Type", "Name", "Download", "Files", "Comments", "Added", "Size", "Snatched", "Seeders", "Leechers", "Upped by"
labels = []
columns = html.find_all("div", class_="colhead")
for index, column in enumerate(columns):
lbl = column.get_text(strip=True)
if lbl:
labels.append(str(lbl))
else:
lbl = column.find("img")
if lbl:
if lbl.has_attr("alt"):
lbl = lbl['alt']
labels.append(str(lbl))
else:
if index == 3:
lbl = "Download"
else:
lbl = str(index)
labels.append(lbl)
# Skip column headers
for result in torrent_rows:
try:
cells = result.find_all("div", class_="torrenttable")
if len(cells) < len(labels):
continue
title = cells[labels.index("Name")].find("a").find("b").get_text(strip=True)
download_url = urljoin(self.urls['base_url'],
cells[labels.index("Download")].find("a")["href"])
if not all([title, download_url]):
continue
seeders = try_int(cells[labels.index("Seeders")].find("span").get_text(strip=True))
leechers = try_int(cells[labels.index("Leechers")].find("span").get_text(strip=True))
torrent_size = cells[labels.index("Size")].find("span").get_text(strip=True)
size = convert_size(torrent_size, -1)
item = {'title': title, 'link': download_url, 'size': size, 'seeders': seeders,
'leechers': leechers, 'hash': None}
if mode != "RSS":
sickrage.app.log.debug("Found result: {}".format(title))
results.append(item)
except Exception:
sickrage.app.log.error("Failed parsing provider")
return results |
This is a sponsored post brought to you by Uncommon Goods. As always the opinions are completely my own based on my experience.
Hello Foxy Friends! This weekend we are headed to a wedding, which got me thinking, we have very few weddings to attend these days. Mostly it's baby showers, and even then those are few and far between. It's so hard coming up with good gifts these days, whether it be for a wedding, anniversary or new baby. Enter Uncommon Goods, I love that they support artists and designers that are run by the designer themselves and over 50% of what they sell are handmade. I love when I can support someone doing what they love.
Now for the ladies. Finding an anniversary gift for me is crazy repetitive. I always like clothes and shoes, but one can only buy that so many times? Sometimes it's nice to get something you didn't know you wanted. For me I'm sentimental and like cheesy things like this. Here are a few gifts ideas for the ladies.
And then there are the things that you just want to get for yourself, like this and this. I might have one of those things coming my way. I'll let you know what I think of it, thanks Uncommon Goods for sending it to me!
There are also so many great gifts for hostess gifts for all of those holiday parties coming up! What would you pick out for yourself? |
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='snipper',
version=__import__('snipper').__version__,
url='https://github.com/mesuutt/snipper',
author='Mesut Tasci',
author_email='[email protected]',
description=('A command-line tool to manage Bitbucket snippets.'),
license='MIT',
test_suite='tests',
keywords="bitbucket snippet gist command-line cli",
long_description=read('README.rst'),
entry_points={
'console_scripts': [
'snipper = snipper.snipper:cli',
]
},
packages=['snipper'],
install_requires=[
'requests>=2.12',
'click>=6.7',
'prompt_toolkit>=1.0',
'pyperclip>=1.5',
],
classifiers=[
"Environment :: Console",
'License :: OSI Approved :: MIT License',
'Development Status :: 4 - Beta',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Intended Audience :: Developers',
'Operating System :: POSIX',
'Operating System :: MacOS :: MacOS X',
],
)
|
If you are interested in our research, please email me.
A recent numerical result which won a UK-Fluid network video competion.
Some of other numerical results (videos) can be found in Research & Gallery.
Physics of Fluids, 29, 121611 (2017).
Journal of Scientific Computing, 72, 1146-1168 (2017).
Int. J. Comput. Methods, 14, 1750010 (2017).
Int. J. Numer. Methods Fluids, 82, 493 (2016).
Int. J. Comput. Methods, 13, 1641004 (2016).
J. Comput. Phys., 278, 221 (2014).
J. Comput. Phys., 232, 252 (2013).
Soft Matter, 7, 5120 (2011).
J. Sci. Comput., 46, 166 (2011).
Phys. Fluids, 21, 072102 (2009).
Comput. Phys. Commun., 180, 1145 (2009).
J. Sci. Comput., 35, 372 (2008).
J. Comput. Phys., 226, 1985 (2007), (Source codes available).
Phys. Rev. E, 72, 046713 (2005).
J. Comput. Phys., 202, 1 (2005).
Phys. Rev. E, 67, 045701(R) (2003).
Phys. Rev. E, 65, 055701(R) (2002), Errata, 65, 069903(E) (2002).
Physica D, 161, 202 (2002), Erratum, 165, 251 (2002).
CFD Journal, 10, 771 (2001).
Phys. Rev. E, 61, R1016 (2000).
Prog. Theor. Phys. Suppl. 138, 708 (2000).
Phys. Lett. A, 257, 153 (1999). |
# Author Ken Celenza <[email protected]>
# Author Jason Edelman <[email protected]>
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError, AnsibleFilterError
def cast_list_to_dict(data, key):
new_obj = {}
if not isinstance(data, list):
raise AnsibleFilterError("Type is not a valid list")
for item in data:
if not isinstance(item, dict):
raise AnsibleFilterError("List item is not a valid dict")
try:
key_elem = item.get(key)
except Exception as e:
raise AnsibleFilterError(str(e))
if new_obj.get(key_elem):
raise AnsibleFilterError("Key {0} is not unique, cannot correctly turn into dict".format(key_elem))
elif not key_elem:
raise AnsibleFilterError("Key {0} was not found".format(key))
else:
new_obj[key_elem] = item
return new_obj
def cast_dict_to_list(data, key_name):
new_obj = []
if not isinstance(data, dict):
raise AnsibleFilterError("Type is not a valid dict")
for key, value in data.items():
if not isinstance(value, dict):
raise AnsibleFilterError("Type of key {0} value {1} is not a valid dict".format(key, value))
if value.get(key_name):
raise AnsibleFilterError("Key name {0} is already in use, cannot correctly turn into dict".format(key_name))
value[key_name] = key
new_obj.append(value)
return new_obj
class FilterModule(object):
'''Convert a list to a dictionary provided a key that exists in all dicts.
If it does not, that dict is omitted
'''
def filters(self):
return {
'cast_list_to_dict': cast_list_to_dict,
'cast_dict_to_list': cast_dict_to_list,
}
if __name__ == "__main__":
list_data = [{"proto": "eigrp", "state": "enabled"}, {"proto": "ospf", "state": "enabled"}]
print(cast_list_to_dict(list_data, 'proto'))
dict_data = {'eigrp': {'state': 'enabled', 'as': '1'}, 'ospf': {'state': 'enabled', 'as': '2'}}
print(cast_dict_to_list(dict_data, 'proto'))
|
This time my dog and I are Eastward bound. First a stop yesterday in Cleveland to hang out with the illustrious Steve Brown , and today we’re in Leonia NJ staying with Cousin Scott and family. The purpose of this trip is to go to the opening of Lenore’s first solo NY art show tomorrow night in Manhattan. It should be great. We both have a number of friends in the area, so I’m hoping that it will end up to be a little reunion of all our East Coast pals. We’ll see who can make it. Then after the show I get to go to the weekly post-juggling-practice meal with the NY juggling club. Good Chinese food, and always good times.
It’ll be a short visit here; on Friday we’ll take off again back to the good ol’ Midwest. After another stop at Steve Brown’s house, we’ll be home again for a couple of days before heading up to Milwaukee for a gig (in Chicago), and for me to fly out to California for my brother’s wedding. Vader will hang out in his “vacation home” with Lenore’s mother in Milwaukee. After that I’ll be home for a few days, then back up to Milwaukee for the Shorewood juggling festival where I will be MC for the big show.
March is a big month for traveling but April won’t be so bad.
Minnesota States [yo-yo contest] is on March 31st, we’d love to have you there boss!
Oooo… unfortunately that’s not gonna work out. I’ll be on my way up to Milwaukee to MC the juggling festival show.
Mark Hayward Is My Hero is powered by WordPress 5.1.1 and delivered to you in 0.497 seconds using 36 queries. |
# -*- coding: utf-8 -*-
from itertools import count
from mahjong.hand_calculating.yaku_list import (
AkaDora,
Chankan,
Chantai,
Chiitoitsu,
Chinitsu,
Chun,
DaburuOpenRiichi,
DaburuRiichi,
Dora,
Haitei,
Haku,
Hatsu,
Honitsu,
Honroto,
Houtei,
Iipeiko,
Ippatsu,
Ittsu,
Junchan,
NagashiMangan,
OpenRiichi,
Pinfu,
Renhou,
Riichi,
Rinshan,
Ryanpeikou,
Sanankou,
SanKantsu,
Sanshoku,
SanshokuDoukou,
Shosangen,
Tanyao,
Toitoi,
Tsumo,
YakuhaiEast,
YakuhaiNorth,
YakuhaiOfPlace,
YakuhaiOfRound,
YakuhaiSouth,
YakuhaiWest,
)
from mahjong.hand_calculating.yaku_list.yakuman import (
Chiihou,
Chinroutou,
ChuurenPoutou,
DaburuChuurenPoutou,
DaburuKokushiMusou,
Daichisei,
Daisangen,
Daisharin,
DaiSuushii,
KokushiMusou,
Paarenchan,
RenhouYakuman,
Ryuuiisou,
Sashikomi,
Shousuushii,
Suuankou,
SuuankouTanki,
Suukantsu,
Tenhou,
Tsuuiisou,
)
class YakuConfig(object):
def __init__(self):
id = count(0)
# Yaku situations
self.tsumo = Tsumo(next(id))
self.riichi = Riichi(next(id))
self.open_riichi = OpenRiichi(next(id))
self.ippatsu = Ippatsu(next(id))
self.chankan = Chankan(next(id))
self.rinshan = Rinshan(next(id))
self.haitei = Haitei(next(id))
self.houtei = Houtei(next(id))
self.daburu_riichi = DaburuRiichi(next(id))
self.daburu_open_riichi = DaburuOpenRiichi(next(id))
self.nagashi_mangan = NagashiMangan(next(id))
self.renhou = Renhou(next(id))
# Yaku 1 Han
self.pinfu = Pinfu(next(id))
self.tanyao = Tanyao(next(id))
self.iipeiko = Iipeiko(next(id))
self.haku = Haku(next(id))
self.hatsu = Hatsu(next(id))
self.chun = Chun(next(id))
self.east = YakuhaiEast(next(id))
self.south = YakuhaiSouth(next(id))
self.west = YakuhaiWest(next(id))
self.north = YakuhaiNorth(next(id))
self.yakuhai_place = YakuhaiOfPlace(next(id))
self.yakuhai_round = YakuhaiOfRound(next(id))
# Yaku 2 Hans
self.sanshoku = Sanshoku(next(id))
self.ittsu = Ittsu(next(id))
self.chantai = Chantai(next(id))
self.honroto = Honroto(next(id))
self.toitoi = Toitoi(next(id))
self.sanankou = Sanankou(next(id))
self.sankantsu = SanKantsu(next(id))
self.sanshoku_douko = SanshokuDoukou(next(id))
self.chiitoitsu = Chiitoitsu(next(id))
self.shosangen = Shosangen(next(id))
# Yaku 3 Hans
self.honitsu = Honitsu(next(id))
self.junchan = Junchan(next(id))
self.ryanpeiko = Ryanpeikou(next(id))
# Yaku 6 Hans
self.chinitsu = Chinitsu(next(id))
# Yakuman list
self.kokushi = KokushiMusou(next(id))
self.chuuren_poutou = ChuurenPoutou(next(id))
self.suuankou = Suuankou(next(id))
self.daisangen = Daisangen(next(id))
self.shosuushi = Shousuushii(next(id))
self.ryuisou = Ryuuiisou(next(id))
self.suukantsu = Suukantsu(next(id))
self.tsuisou = Tsuuiisou(next(id))
self.chinroto = Chinroutou(next(id))
self.daisharin = Daisharin(next(id))
self.daichisei = Daichisei(next(id))
# Double yakuman
self.daisuushi = DaiSuushii(next(id))
self.daburu_kokushi = DaburuKokushiMusou(next(id))
self.suuankou_tanki = SuuankouTanki(next(id))
self.daburu_chuuren_poutou = DaburuChuurenPoutou(next(id))
# Yakuman situations
self.tenhou = Tenhou(next(id))
self.chiihou = Chiihou(next(id))
self.renhou_yakuman = RenhouYakuman(next(id))
self.sashikomi = Sashikomi(next(id))
self.paarenchan = Paarenchan(next(id))
# Other
self.dora = Dora(next(id))
self.aka_dora = AkaDora(next(id))
|
PacificSource gives a wide range of individual and group medical insurance options throughout Oregon, Idaho, and Montana. Blue Cross NC offers Wholesome Outcomes applications as a convenience to aid you in bettering your well being; results are usually not assured. Blue Cross NC contracts with Optum, an impartial third occasion vendor, for the provision of certain features of Wholesome Outcomes programs and is not liable in any manner for goods or companies obtained from Optum. Optum does not provide Blue Cross and Blue Defend products or services. Blue Cross NC reserves the right to discontinue or change Healthy Outcomes packages at any time. The programs are educational in nature, and are meant that can assist you make informed selections about your health, and that can assist you comply together with your physician’s plan of care.
You can avail well being Checkup for yourself and your spouse (if insured below the policy) yearly so that you live a healthier and happier life. That method, with every paycheck you’ll be able to accumulate funds that can sooner or later be used to cover prescriptions, procedures, copays or other medical bills. Primarily it is a fixed amount that you simply choose on the time of shopping for medical insurance and you must pay as a part of the total hospital bill in time of a declare.
Policy exclusions – We regularly have a behavior of trying into what’s being provided, and overlook the things that are not covered. To reap the benefits of a medical health insurance coverage, the policyholder has to pay premium regularly. In case your sickness or damage is roofed beneath the medical insurance coverage, the insured will get the advantages acknowledged within the terms and conditions of the policy. Call Blue Defend at (888) 626-6780 for more details about these plans or go to Lined CA Well being Plans website.
It’s also possible to select to pay a $500 extra & benefit from decrease premiums.
We’re greater than just a medical health insurance firm. One other factor to contemplate is the community hospital protection, as you’d require medical insurance whenever you journey to other cities in India. Every time you’re planning to buy a medical health insurance coverage it is best to at all times look for this characteristic. Take into consideration your budget in addition to your health care wants, and learn how much it’s going to cost you in insurance premiums and out-of-pocket costs for every plan you take into account.
The good news is that we have now medical health insurance plans that can assist us get our lives back on monitor after any medical emergency. You may cover partner, dependent kids, and oldsters under this , the sum assured is floated amongst members of the family named in the policy. Yes, maternity is covered beneath medical insurance plans. These plans are typically uniform in nature, providing the identical benefits to all workers or members of the group.
So it’s essential that you understand the insurance coverage coverage is details and also verify the protection. Now Well being International offers innovative products and is an award winning global medical health insurance firm, serving to guarantee you’ll be able to supply your purchasers the best coverage, the most effective care and the very best customer service, helping you to grow your small business.
We may also help you determine what type of plan you need, the right way to discover a steadiness of price and protection, and what different advantages you must consider. |
import json
import uuid
from app.models import ServiceDataRetention
from tests import create_authorization_header
from tests.app.db import create_service_data_retention
def test_get_service_data_retention(client, sample_service):
sms_data_retention = create_service_data_retention(service=sample_service)
email_data_retention = create_service_data_retention(service=sample_service, notification_type='email',
days_of_retention=10)
letter_data_retention = create_service_data_retention(service=sample_service, notification_type='letter',
days_of_retention=30)
response = client.get(
'/service/{}/data-retention'.format(str(sample_service.id)),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
)
assert response.status_code == 200
json_response = json.loads(response.get_data(as_text=True))
assert len(json_response) == 3
assert json_response[0] == email_data_retention.serialize()
assert json_response[1] == sms_data_retention.serialize()
assert json_response[2] == letter_data_retention.serialize()
def test_get_service_data_retention_returns_empty_list(client, sample_service):
response = client.get(
'/service/{}/data-retention'.format(str(sample_service.id)),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
)
assert response.status_code == 200
assert len(json.loads(response.get_data(as_text=True))) == 0
def test_get_data_retention_for_service_notification_type(client, sample_service):
data_retention = create_service_data_retention(service=sample_service)
response = client.get('/service/{}/data-retention/notification-type/{}'.format(sample_service.id, 'sms'),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
)
assert response.status_code == 200
assert json.loads(response.get_data(as_text=True)) == data_retention.serialize()
def test_get_service_data_retention_by_id(client, sample_service):
sms_data_retention = create_service_data_retention(service=sample_service)
create_service_data_retention(service=sample_service, notification_type='email',
days_of_retention=10)
create_service_data_retention(service=sample_service, notification_type='letter',
days_of_retention=30)
response = client.get(
'/service/{}/data-retention/{}'.format(str(sample_service.id), sms_data_retention.id),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
)
assert response.status_code == 200
assert json.loads(response.get_data(as_text=True)) == sms_data_retention.serialize()
def test_get_service_data_retention_by_id_returns_none_when_no_data_retention_exists(client, sample_service):
response = client.get(
'/service/{}/data-retention/{}'.format(str(sample_service.id), uuid.uuid4()),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
)
assert response.status_code == 200
assert json.loads(response.get_data(as_text=True)) == {}
def test_create_service_data_retention(client, sample_service):
data = {
"notification_type": 'sms',
"days_of_retention": 3
}
response = client.post(
'/service/{}/data-retention'.format(str(sample_service.id)),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
data=json.dumps(data)
)
assert response.status_code == 201
json_resp = json.loads(response.get_data(as_text=True))['result']
results = ServiceDataRetention.query.all()
assert len(results) == 1
data_retention = results[0]
assert json_resp == data_retention.serialize()
def test_create_service_data_retention_returns_400_when_notification_type_is_invalid(client):
data = {
"notification_type": 'unknown',
"days_of_retention": 3
}
response = client.post(
'/service/{}/data-retention'.format(str(uuid.uuid4())),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
data=json.dumps(data)
)
json_resp = json.loads(response.get_data(as_text=True))
assert response.status_code == 400
assert json_resp['errors'][0]['error'] == 'ValidationError'
assert json_resp['errors'][0]['message'] == 'notification_type unknown is not one of [sms, letter, email]'
def test_create_service_data_retention_returns_400_when_data_retention_for_notification_type_already_exists(
client, sample_service
):
create_service_data_retention(service=sample_service)
data = {
"notification_type": "sms",
"days_of_retention": 3
}
response = client.post(
'/service/{}/data-retention'.format(str(uuid.uuid4())),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
data=json.dumps(data)
)
assert response.status_code == 400
json_resp = json.loads(response.get_data(as_text=True))
assert json_resp['result'] == 'error'
assert json_resp['message'] == 'Service already has data retention for sms notification type'
def test_modify_service_data_retention(client, sample_service):
data_retention = create_service_data_retention(service=sample_service)
data = {
"days_of_retention": 3
}
response = client.post(
'/service/{}/data-retention/{}'.format(sample_service.id, data_retention.id),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
data=json.dumps(data)
)
assert response.status_code == 204
assert response.get_data(as_text=True) == ''
def test_modify_service_data_retention_returns_400_when_data_retention_does_not_exist(client, sample_service):
data = {
"days_of_retention": 3
}
response = client.post(
'/service/{}/data-retention/{}'.format(sample_service.id, uuid.uuid4()),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
data=json.dumps(data)
)
assert response.status_code == 404
def test_modify_service_data_retention_returns_400_when_data_is_invalid(client):
data = {
"bad_key": 3
}
response = client.post(
'/service/{}/data-retention/{}'.format(uuid.uuid4(), uuid.uuid4()),
headers=[('Content-Type', 'application/json'), create_authorization_header()],
data=json.dumps(data)
)
assert response.status_code == 400
|
1.Goods can be exchanged within 3 days of delivery provided that they are returned undamaged, unused with all tags attached and in their original packaging. However, if the packaging has been damaged and the items as a consequence are not resaleable, we will decline the claim. Contact MUST be made directly with us for approval prior to returning. Freight charges are NOT refundable, and the item will need to be shipped back at your cost.
2.Our goods have 30 day warranty against manufacturing defects, and in the unlikely event of a major defect arising, our Company sells under the terms of the Consumer Guarantees Act. The warranty does not cover accident damage, wear and tear, abuse, neglect or careless storage. At our option, we will repair, replace or refund.
3.We do not have to provide a refund if you have changed your mind about a particular purchase, so please choose carefully. |
import os
from contextlib import suppress
import time
from importlib import import_module
import pygame
with suppress(ImportError):
import pygame._view # sometimes necessary. If it isn't this will cause an error
#! UPDATE: this might only be necessary for py2exe to work, so if you can
# compile without it, then there's no need to import pygame_view whatsoever
import psutil
from pygametemplate import load_image
from pygametemplate.system import System
from pygametemplate.console import Console
from pygametemplate.userinput import Input
from pygametemplate.hotkey import Hotkey
from pygametemplate.text_input import TextInput
pygame.init()
class Game:
VIEW_MODULE = "lib.views"
def __init__(self, StartingView, resolution=(1280, 720), mode="windowed",
*, caption="Insert name here v0.1.0", icon=None,
max_allowed_ram=1 * 2**30):
"""Create a new Game object.
`icon` should be the name of an image file.
"""
self.pygame = pygame
self.system = System(self)
self.width, self.height = resolution
self.mode = mode
self.initialise_screen()
pygame.display.set_caption(caption)
if icon is not None:
pygame.display.set_icon(load_image(icon))
self.max_allowed_ram = max_allowed_ram
self.previous_views = []
self.current_view = StartingView(self)
self.fps = 60
self.frame = 0 # The current frame the game is on (since the game was opened)
self.input = Input(self)
self.console = Console(self)
self.quit_condition = Hotkey(self, "f4", alt=True).pressed
def set_view(self, view_name: str):
"""Set the current view to the View class with the given name."""
self.previous_views.append(self.current_view)
View = self.get_view_class(view_name) # pylint: disable=invalid-name
for view in reversed(self.previous_views):
if isinstance(view, View):
self.current_view = view
self.previous_views.remove(view)
break
else:
self.current_view = View(self)
while self.previous_views and self.get_memory_use() > self.max_allowed_ram:
oldest_view = self.previous_views.pop(0)
oldest_view.unload()
def get_view_class(self, view_name: str):
"""Return the View class with the given view_name."""
return getattr(import_module(self.VIEW_MODULE), view_name)
def logic(self):
raise NotImplementedError
def draw(self):
raise NotImplementedError
def on_quit(self):
pass
def quit(self):
"""Signal the game to quit."""
self.running = False
def _logic(self):
self._check_quit()
self.console.logic()
self.current_view.logic()
self.logic()
def _draw(self):
self.screen.fill((0, 0, 0))
self.current_view.draw()
self.draw()
self.console.draw()
def _quit(self):
self.on_quit()
pygame.quit()
@staticmethod
def get_memory_use():
"""Return the current memory usage of the game (RSS) in bytes."""
return psutil.Process(os.getpid()).memory_info()[0]
def initialise_screen(self, resolution=None, mode=None):
"""(Re)initialise the screen using the given resolution and mode."""
if resolution is None:
resolution = (self.width, self.height)
if mode is None:
mode = self.mode
flags = pygame.HWSURFACE | pygame.DOUBLEBUF
if mode == "fullscreen":
flags |= pygame.FULLSCREEN
elif mode == "windowed":
os.environ["SDL_VIDEO_CENTERED"] = "1"
elif mode == "borderless":
os.environ["SDL_VIDEO_WINDOW_POS"] = "0,0"
flags |= pygame.NOFRAME
else:
raise ValueError("Unknown mode for reinitialise_screen(): '{}'".format(mode))
self.screen = pygame.display.set_mode(resolution, flags)
self.width, self.height = resolution
self.mode = mode
def display(self, image, coordinates, area=None, special_flags=0):
"""Display the given image at the given coordinates.
Coordinates and area should be givenas if they were for a 1920x1080 window.
"""
x_scale = self.width/1920.0
y_scale = self.height/1080.0
coordinates = (coordinates[0]*x_scale, coordinates[1]*y_scale)
if area is not None:
area = (area[0]*x_scale, area[1]*y_scale,
area[2]*x_scale, area[3]*y_scale)
self.screen.blit(image, coordinates, area, special_flags)
def _inputs(self):
self.input.reset()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
elif event.type == pygame.MOUSEMOTION:
self.input.mouse_pos = event.pos
elif event.type == pygame.MOUSEBUTTONDOWN:
self.input.buttondown(event)
elif event.type == pygame.MOUSEBUTTONUP:
self.input.buttonup(event.button)
elif event.type == pygame.KEYDOWN:
self.input.buttondown(event)
TextInput.receive_single_characters(event)
elif event.type == pygame.KEYUP:
self.input.buttonup(event.key)
TextInput.receive_multiple_characters()
def _update(self):
self.frame += 1
pygame.display.flip() # Updating the screen
self.clock.tick(self.fps) # [fps] times per second
def runtime(self) -> float:
"""Return the amount of time the game has been running for in seconds."""
return time.time() - self.start_time
def _check_quit(self):
if self.quit_condition():
self.quit()
def run(self):
"""Run the game."""
self.running = True
self.clock = pygame.time.Clock()
self.start_time = time.time()
while self.running:
self._inputs()
self._logic()
self._draw()
self._update()
self._quit()
|
Sometimes we carry our biggest dreams in the plainest packages. Victor Morgado sat in an armchair at the back of a Barnes & Noble bookstore on Monday and held his dream on his lap, wrapped in a white plastic bag.
The bag contained two hardcover books. One was titled “Crock Pot: The Original Slow Cooker,” and the other was “The Paleo Slow Cooker.” At age 62, Morgado spent decades eating stir-fried meat for dinner, and now he has a chunky torso and high blood pressure. His daughter is 15, and her parents’ divorce in 2011 left her estranged and angry.
When will she forgive him? Morgado doesn’t know. Maybe it will take years, he said. This is why he went to The Shops at Riverside mall the day after Christmas to buy books on slow, healthy cooking.
Someday his daughter will love him back. Morgado is preparing to wait.
Many gifts are uncomplicated, devoid of meaning or portent. We give a pair of gloves for Christmas, we receive a gift card for Hanukkah, and we smile and soon forget it. Other things are so tied to personal taste they rarely work as holiday presents.
“People don’t really give comfortable shoes as Christmas gifts,” said Andrew Green, manager of the Aetrex shoe store in downtown Englewood, which was open but quiet Monday morning.
Other gifts carry deeper purpose. As they visited shops in quiet historic downtowns or battled for parking spaces in busy suburban shopping malls, some people in North Jersey found the day after Christmas to be the perfect time for buying gifts that align with their highest aspirations.
Many of those gifts were small and informally wrapped, if they were wrapped at all.
Others came packaged exquisitely. Cory Nieves aspires someday to be rich. He is the founder and CEO of Mr. Cory’s Cookies, a cookie baking company he started when he was 6 years old. Now, at age 12, he appears to be reasonably well on his way, walking down Dean Street in Englewood on Monday wearing brown wingtip boots, tight-fitting blue jeans, a belt buckle shaped like a lobster claw, a blue mock turtleneck, a blue blazer with a white kerchief tucked into the breast pocket, eyeglass frames with no glass inside, and his hair picked into a high, round Afro.
In his right hand he carried two bracelets from a Pandora jewelry store.
Cory hopes his circle of friends soon will include Howard Schultz, the longtime CEO of Starbucks. So he had a little stunt planned. He walked into Englewood’s Starbucks store carrying a Starbucks teddy bear in his left hand. After some quick consultations between his mother and the store’s manager, five Starbucks employees walked around the counter and posed around Cory for a photo, which Howard snapped with her iPhone.
Cory and his mother hope their relationship with Starbucks will grow. They’ve already sent Schultz a number of letters, they said, with no response. This year, with a teddy bear in hand and the gift of a photo from a perfectly dressed kid, they hope to get Schultz’s attention.
“I would like him to be my mentor,” Cory said.
Back at the Barnes & Noble in Hackensack, Bondette Tangen held gifts she hoped would help bring her angry, suffering family back together. Her daughter suffers from scoliosis and arthritis, and needs surgery to correct a twisted vertebra. Her son is in a tempestuous marriage, which grew even rockier when he supported Donald Trump for president and his wife voted for Hillary Clinton.
To help her 11-year-old granddaughters take a break from all the stress, Tangen took them shopping. One, Charlotte, has been so down from all the arguments at home that she’s stopped doing her homework and paying attention in class, Tangen said, which leaves her in danger of failing some subjects. Her other granddaughter, Gianna, just needed a break from the house.
“My aspirations are just for my family to be happier next year,” said Tangen, of Garfield.
So Tangen sat at Barnes & Noble holding gifts the girls had picked out, including a Batman figurine and a package of nonstick Playfoam balls. For Christmas she gave each girl a camera that instantly prints small photos, and she carried a small metal tin with some of the prints inside.
“It’s to help them take pictures, and hopefully have fun together,” Tangen said.
Many important gifts were left at home on Monday. Morgado’s daughter is an artist and a budding punk rocker, he said, with hair dyed bright pink and an image of the Buddha tattooed on the back of her hand. To support her, Morgado bought her a pair of maroon Dr. Martens boots. He wrapped them in Christmas paper and positioned the box just inside her bedroom at Morgado’s house in Bergenfield, just in case. |
#!/usr/bin/env python3
# Based on gathertags, this goes further by identifying owners and
# sorting files by genre.
import csv, os, sys
from collections import Counter
import numpy as np
import pandas as pd
# import utils
currentdir = os.path.dirname(__file__)
libpath = os.path.join(currentdir, '../lib')
sys.path.append(libpath)
import SonicScrewdriver as utils
readers = ['donofrio', 'erickson', 'alvarez', 'flynn', 'rubio', 'barajas', 'koh', 'trondson', 'lin', 'buck', 'fleming']
sourcedir = '/Volumes/TARDIS/work/readers/'
subobjects = os.listdir(sourcedir)
subdirs = [x for x in subobjects if os.path.isdir(os.path.join(sourcedir, x))]
tagset = set()
taglist = []
paths = dict()
readerowners = dict()
for subdir in subdirs:
thisreader = 'none'
for reader in readers:
if reader in subdir.lower():
thisreader = reader
break
if thisreader == 'none':
print(subdir + ' lacks a recognized reader.')
sys.exit(0)
wholepath = os.path.join(sourcedir, subdir, 'tags')
if os.path.isdir(wholepath):
tagfiles = [x for x in os.listdir(wholepath) if x.endswith('.csv')]
for f in tagfiles:
thispath = os.path.join(wholepath, f)
okaytoadd = True
with open(thispath, encoding = 'utf-8') as file:
reader = csv.DictReader(file)
for row in reader:
if 'tag' not in row or len(row['tag']) < 3:
okaytoadd = False
break
if okaytoadd:
tagset.add(f)
if f not in readerowners:
readerowners[f] = []
paths[f] = []
if thisreader not in readerowners[f]:
readerowners[f].append(thisreader)
paths[f].append(thispath)
print(len(tagset))
multipleowners = []
for filename, owners in readerowners.items():
if len(owners) > 1:
multipleowners.append(filename)
print(len(multipleowners))
sumpages = 0
sumdiffs = 0
disagreements = Counter()
for filename in multipleowners:
print()
print(filename)
print(len(paths[filename]))
existing = dict()
allcounts = 0
differences = 0
for p in paths[filename]:
with open(p, encoding = 'utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
if 'tag' not in row:
print(p)
break
allcounts += 1
page = row['page']
tag = row['tag']
if page not in existing:
existing[page] = tag
else:
if tag != existing[page]:
differences += 1
thistuple = (tag, existing[page])
if thistuple not in disagreements:
thistuple = (existing[page], tag)
disagreements[thistuple] += 1
print(differences/allcounts)
sumpages += allcounts
sumdiffs += differences
if (differences / allcounts) > 0.1:
print(paths[filename])
print()
print(sumdiffs / sumpages)
for key, value in disagreements.items():
print(key, value)
allfiles = tagset
train1 = pd.read_csv('bzipmeta.csv', dtype = 'object', index_col = 'docid')
tidx = set(train1.index.values)
for filename in allfiles:
docid = filename.replace('.csv', '')
if utils.dirty_pairtree(docid) not in tidx:
print(docid)
ficlist = []
nonficlist = []
errorlist = []
for filename, owners in readerowners.items():
path = paths[filename][0]
if 'metadat' in filename:
print(filename)
continue
docid = utils.dirty_pairtree(filename.replace('.csv', ''))
genre = train1.loc[docid, 'sampledas']
with open(path, encoding = 'utf-8') as f:
reader = csv.DictReader(f)
ficct = 0
allct = 0
for row in reader:
allct += 1
if row['tag'].lower() == 'fic':
ficct += 1
ficpct = ficct / allct
if genre == 'fic' and ficpct < 0.7:
print('ERROR', genre, docid)
errorlist.append((docid, ficpct))
if ficpct < 0.4:
nonficlist.append(docid)
elif genre == 'fic':
ficlist.append(docid)
elif genre != 'fic' and ficpct > 0.3:
print('ERROR', genre, docid)
errorlist.append((docid, ficpct))
if ficpct > 0.8:
ficlist.append(docid)
else:
nonficlist.append(docid)
fiction = train1.loc[ficlist, :]
nonfiction = train1.loc[nonficlist, :]
fiction.loc[ :, 'class'] = pd.Series([1] * len(ficlist), index = fiction.index)
nonfiction.loc[ :, 'class'] = pd.Series([0] * len(nonficlist), index = nonfiction.index)
forclassification = pd.concat([fiction, nonfiction])
forclassification.to_csv('firsttrainingset.csv')
errorids = [x[0] for x in errorlist]
errors = [x[1] for x in errorlist]
errors = pd.Series(errors, index = errorids)
errordf = train1.loc[errorids, :]
errordf.loc[ : , 'ficpct'] = errors
errordf.to_csv('errorlist.csv')
|
Every person in life has to cook. Some order food at home, others go to restaurants, but most often we cook ourselves. Someone likes to do it, someone cooks out of need, and someone connects their work with cooking. Anyway, how to prepare the dish, we learn from the recipes. Experienced housewives have learned to cook without scalloped potatoes and ham recipe for memory. But one way or another, you always want to make a difference in your diet. Recipes will help you save time on how to remake a dish, if it suddenly failed. And you can not think of which of the ingredients you forgot to put.
Where to find the scalloped potatoes and ham recipe?
Now the most common option is to find a scalloped potatoes and ham recipe on the Internet. There are recipes with step-by-step descriptions, there are videos in which you will be shown and told how to prepare the dish. Also in the bookstore or in the stall with magazines you can purchase a recipe book. There are special magazines with scalloped potatoes and ham recipe for which you can subscribe and receive them once a week or once a month. Now on TV show a lot of TV shows, in which the chefs are gradually telling how to cook this or that dish. So you can write a scalloped potatoes and ham recipe, or cook in parallel with the chef. Previously, women started special notebooks and recorded there recipes that they heard on TV, or learned from friends.
What scalloped potatoes and ham recipe is in the books?
Books can specialize in scalloped potatoes and ham recipe from a particular country. For example, there are books of European, Japanese, Italian, Mexican, French cuisine. There are collected recipes from the most simple to the most complex. Accordingly, the products for such dishes are sometimes very difficult to find and they can cost not cheap. Therefore, if you prefer to diversify your diet for each day, you can safely write magazines. There, scalloped potatoes and ham recipe is not printed by chefs, but by people who share their recipes, or they can point out the shortcomings of a classic scalloped potatoes and ham recipe of a dish and give advice on how to improve it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.