text
stringlengths 29
850k
|
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015, Fabrice Laporte
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
"""Uses the `keroaek` program to add tag fields to lyrics
"""
import io
import argparse
import sys
from keroaek.editor import Editor
def main(argv=None):
if argv is None:
argv = sys.argv
parser = argparse.ArgumentParser(
description='Lrc files creator'
'See https://github.com/Kraymer/keroaek for more infos.')
parser.add_argument('audio', metavar='MP3_FILE',
help='Music file', default='')
parser.add_argument('-l', '--lyrics', dest='src',
help='src lyrics'
'DEFAULT: consider audio embedded lyrics', default='')
parser.add_argument('-o', '--output', dest='dest',
help='output filename. '
'DEFAULT: edit input file in-place', default='')
args = vars(parser.parse_args())
if not args['dest']:
args['dest'] = args['src']
if not args['src']:
pass
else:
with io.open(args['src'], 'r', encoding='utf-8') as f:
lyrics = f.read()
lrc = Editor().sync(args['audio'], lyrics)
with io.open(args['dest'], 'w', encoding='utf-8') as f:
f.write(lrc)
if __name__ == "__main__":
sys.exit(main())
|
plane trees over 400 years old that are unique specimens of the plant in Europe.
There is no need to cross the Narrow Sea to reach Essos.
Games of Thrones is not the only series to choose Croatia as a set, however. In 2015 the popular series "Crossing Lines", starring Donald Sutherland, filmed scenes for the third season in the stunning coastal towns of Opatija, Rijeka and Rovinj, that are all worth more than a visit!
you can retrace the footsteps of the Native American hero Winnetou of the cult 1960s films. The filming of a new trilogy about the character, created by Karl May, was begun in the area in 2015, as well as in the regions of Istria, Lika and Gorski Kotar.
Orson Wells shot his adaptation of Franz Kafka's "The Trial" in Zagreb.
Jules Verne set the plot of his novel "Mathias Sandorf" in the town of Pazin.
Lord Byron christened the city of Dubrovnik “The Pearl of the Adriatic”.
George Bernard Shaw claimed that “If you want to see heaven on earth, come to Dubrovnik”.
Shaw also wrote: "On the last day of the Creation, God desired to crown his work, and thus created the Kornati Islands out of tears, stars and breath".
Vladimir Nabokov described his summers as a youth in Opatija as "perfect".
|
from intelmq.lib.bot import Bot, sys
from intelmq.lib.message import Event
from intelmq.bots import utils
import redis
import json
class HPFeedsBot(Bot):
def process(self):
report = self.receive_message()
self.logger.info(report)
if report:
#m = json.loads(report)
m = report
event = Event()
for k in m.keys():
event.add(k, m.value(k))
event.add('feed', 'hpfeed')
event.add('feed_url', m.value("sensorname"))
event = utils.generate_source_time(event, "source_time")
event = utils.generate_observation_time(event, "observation_time")
event = utils.generate_reported_fields(event)
self.send_message(event)
self.acknowledge_message()
if __name__ == "__main__":
bot = HPFeedsBot(sys.argv[1])
bot.start()
|
With years of experience and hundreds of completed projects under our belt, Portland’s premiere roofing company is also the area’s go to contractor for residential exterior painting jobs.
Does the idea of painting the outside of your home fill you with anxiety? Are you looking for exterior house painters who do a great job, are reliable, and will get the job done on time? If you want to get the best results with minimal trouble, call Giron Roofing: your first choice when you need expert painting contractors. We will measure your exterior walls and trim, calculate the amount of paint and labor that it will require to paint your house, and provide you with an accurate cost and time estimate for job completion free of charge. We pride ourselves on delivering a clean, finished product, on time and without cost overruns.
Sherwin Williams recommends flat/matte sheens for the surface areas of walls and siding as it does a better job of hiding stains and blemishes. On the other hand, satin finishes work better for trim, window frames, exterior shutters, and other areas that require more frequent cleaning. Choosing the right paint textures can keep your freshly-painted home looking new for much longer, so consider sticking with these tried and true tips.
Sherwin Williams, the paint we most often recommend, has over 1,500 colors, so you’re free to mix and match your trim with your walls. Whether you’re trying to make a statement with commanding bold wall colors or you’d prefer a more conservative look for the exterior of your home, we can match the paint to your vision.
Some homes are restricted by a color pallet that’s been approved by their HOA board. At Giron Roofing, we’re able to match the color that you select from your association’s approved color scheme.
When Giron Roofing takes a contract, we leave our work area the same as we found it—other than the improvements we were hired for, of course. When we arrive to paint your home, we will have the quantity of paint that’s required: the brushes, tarps, and other equipment that we require; and we will go to work prepping your house. This includes pressure cleaning the walls, leaves, and trim; priming stained surfaces; protecting doors, exterior light fixtures, window panes, et cetera.
When the last coat of paint has dried, we will remove our discarded cans, brushes, and tarps, and leave your home in good order.
Nothing can boost the curb appeal of a home like a fresh coat of paint. With the passage of time, all paint jobs need to be redone. Old paint tends to discolor and fade, while colors that were all the rage a decade ago will now appear dated. Your busy schedule allows you no time to take on this job yourself. Book our team of painting professionals and leave all the stress to us.
Why Sherwin Williams? We recognize that our work is reflected in the materials we use, and our experience tells us that Sherwin Williams paints are the best for exterior residential painting jobs. With over 1,500 paint colors, it’s always easy to find just the right shade to improve the look of your house. Their wide range of colors will give you a nearly infinite list of options for the exterior walls of your home.
Giron Roofing has a reputation for excellence. We offer free estimates for Portland-area residents who are seeking to repaint the exteriors of their entire homes.
|
import os
from .errors import Missing
from .types import FieldType
class Field:
def __init__(
self, type_, desc=None, name=None,
optional=False, default=None):
self.name = name
self.desc = desc
self.optional = optional
self.default = default
self._cache = None
if isinstance(type_, type):
if issubclass(type_, FieldType):
self.type_ = type_()
else:
raise TypeError("Invalid field type for {}.".format(self.name))
elif isinstance(type_, FieldType):
self.type_ = type_
else:
raise TypeError("Invalid value for {}.".format(self.name))
def resolve(self, env):
if self._cache is not None:
return self._cache
value = env.get(self.name)
if value is None:
if self.default is not None:
return self.default
elif self.optional:
return None
else:
raise Missing("Required variable {} not set".format(self.name))
self._cache = self.type_.parse(value)
return self._cache
def __get__(self, instance, owner):
if instance is None:
return self
return self.resolve(instance.env)
def __str__(self):
return "<Field(name={}, type={})>".format(self.name, self.type_)
def __repr__(self):
return str(self)
class ProviderMeta(type):
def __new__(mcs, name, bases, attrs):
fields = []
for key, value in attrs.items():
if isinstance(value, Field):
if value.name is None:
value.name = key
fields.append(value)
attrs['fields'] = tuple(fields)
return super().__new__(mcs, name, bases, attrs)
class EnvProvider(metaclass=ProviderMeta):
def __init__(self, eager=True):
if eager:
self.load()
@property
def env(self):
return os.environ
def load(self):
for i in self.fields: # pylint: disable=no-member
i.resolve(self.env)
def __str__(self):
frags = []
for i in self.fields: # pylint: disable=no-member
item = '{}={}'.format(i.name, repr(i.resolve(self.env)))
frags.append(item)
return '<Env({})>'.format(', '.join(frags))
|
There are numerous the reason why you are searching for details about unique colorful wedding dresses green, but certainly, you are researching for new suggestions for your needs. We determined this on the net sources and we believe this can be one of several awesome content for reference. And you know, when I first found it, we liked it, hopefully you're too. We believe, we might own diverse thoughts, but, what we do just like to support you in finding more suggestions about Fresh Unique Colorful Wedding Dresses Green Or Blue And Green Wedding Dresses Photo 1 55.
2016 wedding collection dresses jolies nicole colored,green wedding dresses bride 18 non for traditional,light mint green gown ball wedding colored sparkly h1485 princess, bavarian colors wedding dresses great for,accents bridal gown gowns colorful color,puffy flowers wedding sheer handmade crew neck colorful dresses, dresses green wedding colorful unique,fairy is020 white mint tulle princess dress off shoulder wedding,designers dresses ideas sea party for modern green girls outfits,lace new with and colored flower 2017 organza spring wedding dress.
Listed below are some of top rated Fresh Unique Colorful Wedding Dresses Green Or Blue And images on the internet. We discovered it from reliable source. It is tagged and published by poetrymag in Poetrymag Property field. We believe this kind of Fresh Unique Colorful Wedding Dresses Green Or Blue And image could possibly be the most trending topic when we distribute it in google plus or facebook on August 31, 2018.
We attempt to presented in this posting since this can be one of wonderful resource for any Fresh Unique Colorful Wedding Dresses Green Or Blue And options. Dont you come here to know some new unique Fresh Unique Colorful Wedding Dresses Green Or Blue And ideas? We really hope you can easily recognize it as one of the reference and many thanks for your effort for viewing our website. Make sure you show this image for your precious friends, families, community via your social websites such as facebook, google plus, twitter, pinterest, or some other social bookmarking sites.
|
from django.core.mail import mail_managers
from django.dispatch import receiver
from django.utils.translation import ugettext_noop, ugettext_lazy as _
from comments.signals import comment_created
from gallery.signals import image_created
@receiver(comment_created)
def somebody_commented_your_fruit(comment, comment_type, object_id, **kwargs):
"""
Notify users that there is a new comment under their marker.
"""
if comment_type.model == 'fruit':
fruit = comment_type.get_object_for_this_type(pk=object_id)
if fruit.user != comment.author:
if not comment.complaint:
msg_template = ugettext_noop(
'User <a href="{user_url}">{user_name}</a> '
'posted a <a href="{comment_url}">comment</a> '
'under your <a href="{fruit_url}">marker</a>.'
)
else:
msg_template = ugettext_noop(
'User <a href="{user_url}">{user_name}</a> '
'<strong>posted a <a href="{comment_url}">complaint</a></strong> '
'under your <a href="{fruit_url}">marker</a>.'
)
context = dict(
user_name=comment.author.username,
user_url=comment.author.get_absolute_url(),
comment_url=comment.get_absolute_url(),
fruit_url=fruit.get_absolute_url(),
)
fruit.user.send_message(msg_template, context=context, system=True)
@receiver(comment_created)
def complaint_notification(comment, *args, **kwargs):
"""
Notify manages that complaint has been sent.
"""
if comment.complaint:
subject = _('A complaint has been made.')
body = _('Please review the situation: https://na-ovoce.cz{url}').format(
url=comment.get_absolute_url(),
)
mail_managers(subject, body)
@receiver(image_created)
def somebody_added_image_to_your_fruit(image, gallery_ct, gallery_id, **kwargs):
"""
Notify users that somebody added an image to their marker.
"""
if gallery_ct.model == 'fruit':
fruit = gallery_ct.get_object_for_this_type(pk=gallery_id)
if fruit.user != image.author:
msg_template = ugettext_noop(
'User <a href="{user_url}">{user_name}</a> '
'added a <a href="{image_url}">photo</a> '
'under your <a href="{fruit_url}">marker</a>.'
)
context = dict(
user_name=image.author.username,
user_url=image.author.get_absolute_url(),
image_url=image.get_absolute_url(),
fruit_url=fruit.get_absolute_url(),
)
fruit.user.send_message(msg_template, context=context, system=True)
|
As Canada’s leading addictive substance, alcohol has had an impact on people around the country. What was known as ‘alcoholism’ and ‘alcohol abuse’ have been redefined as an Alcohol Use Disorder (AUD). An AUD classifies someone’s consumption of alcohol in three different stages: mild, moderate, and severe. Simply put, it is a pattern of alcohol use that negatively affects someone’s life and creates health and safety risks.
The American Psychiatric Association published a manual classifying Diagnostic and Statistical Mental Disorders. The newest edition (DSM-5) features a list of eleven symptoms that categorize the criteria of an AUD.
1. Alcohol is consumed in large amounts for a longer period than was intended.
2. An incapability to cut back on the amount of alcohol consumed.
3. Spending a lot of time drinking and being sick as a result of alcohol consumption.
4. The inability to focus on anything due to intense alcohol cravings.
5. An inability to care for family members, focus on school, or complete tasks for a job.
6. Continuing to drink despite social and interpersonal relationship issues.
7. Giving up activities that were once important or that you enjoyed due to alcohol.
8. Being involved in dangerous situations as a direct result of drinking.
9. Continuing to drink after alcohol has caused health issues, depression, or symptoms of anxiety.
10. Drinking more due to an increased tolerance of alcohol.
If you are experiencing at least two of these, it is an indication of an AUD. The severity is recognized by the number of symptoms that someone encounters. It varies between mild (2 to 3 symptoms), moderate (4 to 5 symptoms), and severe (6 or more symptoms) levels. If this is the case, we recommend that you reach out for help. The 11 drinking behaviours could harm someone’s life if the consumption continues and may lead to potential health and social issues. Intoxication impairs a person’s mental state and can alter behavioural patterns. It is important to regulate these issues as an increased consumption of alcohol leads to serious impacts. That being said, 70% of patients at Cedars seek treatment for alcohol-related addiction.
Keep in mind that alcohol consumption is individual: it is easy to hide behind comparisons to others when denial comes into play. It is important to keep updated on ways to prevent AUD development and gain an understanding of when to seek help. Rehabilitation and recovery is meant to restore a fulfilling life driven by purpose. Yes, we all have good days and bad ones, but alcohol should not be a factor that helps determine our happiness.
An AUD does not only impact your mental, behavioural, and emotional state but it also affects the nervous system. What’s more is that liquor influences your coping skills and habits, also known as brain maps. Because an AUD alters the normal functioning of the brain, the condition is classified as a Mental Disorder. The brain is a neural network that associates people’s actions with their behaviours and constructs systems that control the body’s main functions. The process is simple; consuming more liquor than your liver can metabolize permits the ethyl alcohol chemicals to disrupt the electro-chemical signaling process. As a result, a prolonged exposure to such substances changes brain structure and functioning.
How does Cedars treat AUD?
Here at Cedars, we focus on being in touch with different cognitive and dialectical therapies and applying them using individual treatment plans. You deserve to live a confident and positive life, so make it happen! If you need help or are concerned about your well-being, feel free to contact Cedars and we will be more than happy to guide you in the right direction.
Why is providing online counselling and therapy for addiction recovery important?
|
import json
class ReplyMarkup(object):
def dict(self):
raise NotImplementedError()
def json(self):
return json.dumps(self.dict())
def __str__(self):
return str(self.dict())
class ReplyKeyboardMarkup(ReplyMarkup):
def __init__(self, buttons = [], resize_keyboard = False, one_time_keyboard = False, selective = False):
self.buttons = buttons
self.resize_keyboard = resize_keyboard
self.one_time_keyboard = one_time_keyboard
self.selective = selective
def dict(self):
return {
"keyboard": [[button.dict() for button in row] for row in self.buttons],
"resize_keyboard": self.resize_keyboard,
"one_time_keyboard": self.one_time_keyboard,
"selective": self.selective
}
class KeyboardButton(object):
def __init__(self, text = "", request_contact = False, request_location = False):
self.text = text
self.request_contact = request_contact
self.request_location = request_location
def dict(self):
return {
"text": self.text,
"request_contact": self.request_contact,
"request_location": self.request_location
}
class ReplyKeyboardHide(ReplyMarkup):
def __init__(self, selective = False):
self.selective = selective
def dict(self):
return {
"hide_keyboard": True,
"selective": self.selective
}
class InlineKeyboardMarkup(ReplyMarkup):
def __init__(self, buttons = []):
self.buttons = buttons
def dict(self):
return {
"inline_keyboard": [[button.dict() for button in row] for row in self.buttons]
}
class InlineKeyboardButton(object):
def __init__(self, text = "", url = None, callback_data = None, switch_inline_query = None):
self.text = text
self.url = url
self.callback_data = callback_data
self.switch_inline_query = switch_inline_query
def dict(self):
obj = {
"text": self.text
}
if self.url == None and self.callback_data == None and self.switch_inline_query == None:
raise Exception("At least one of url, callback_data or switch_inline_query should be set")
if self.url != None: obj["url"] = self.url
if self.callback_data != None: obj["callback_data"] = self.callback_data
if self.switch_inline_query != None: obj["switch_inline_query"] = self.switch_inline_query
return obj
class ForceReply(ReplyMarkup):
def __init__(self, selective = False):
self.selective = selective
def dict(self):
return {
"force_reply": True,
"selective": self.selective
}
|
What I’m reading right now: The Fear Cure — Lissa Rankin MD Fabulous tools for understanding what and why we might be holding ourselves back, knowing the difference between real fear and false fears that we create!
I would almost not believe it’s halfway through January…unless my skin did not remind me daily. Anyone else now in the the throws of tight crawl-out-of-your-skin-itchies? Here are some ABC’s for winter hydration!
Eating your feelings this holiday season?
Non-toxic cleaning ideas to prevent the flu (influenza)!
Sick to your stomach? Nip your nausea in the bud!
|
from __future__ import absolute_import
import json
import requests
try:
import polling
except ImportError:
raise ImportError(
"Please install the python module 'polling' via pip or download it from "
"https://github.com/justiniso/polling/"
)
from ..exceptions import (
reCaptchaException,
reCaptchaServiceUnavailable,
reCaptchaAccountError,
reCaptchaTimeout,
reCaptchaParameter,
reCaptchaBadJobID,
reCaptchaReportError
)
from . import reCaptcha
class captchaSolver(reCaptcha):
def __init__(self):
super(captchaSolver, self).__init__('deathbycaptcha')
self.host = 'http://api.dbcapi.me/api'
self.session = requests.Session()
# ------------------------------------------------------------------------------- #
@staticmethod
def checkErrorStatus(response):
errors = dict(
[
(400, "DeathByCaptcha: 400 Bad Request"),
(403, "DeathByCaptcha: 403 Forbidden - Invalid credentails or insufficient credits."),
# (500, "DeathByCaptcha: 500 Internal Server Error."),
(503, "DeathByCaptcha: 503 Service Temporarily Unavailable.")
]
)
if response.status_code in errors:
raise reCaptchaServiceUnavailable(errors.get(response.status_code))
# ------------------------------------------------------------------------------- #
def login(self, username, password):
self.username = username
self.password = password
def _checkRequest(response):
if response.ok:
if response.json().get('is_banned'):
raise reCaptchaAccountError('DeathByCaptcha: Your account is banned.')
if response.json().get('balanace') == 0:
raise reCaptchaAccountError('DeathByCaptcha: insufficient credits.')
return response
self.checkErrorStatus(response)
return None
response = polling.poll(
lambda: self.session.post(
'{}/user'.format(self.host),
headers={'Accept': 'application/json'},
data={
'username': self.username,
'password': self.password
}
),
check_success=_checkRequest,
step=10,
timeout=120
)
self.debugRequest(response)
# ------------------------------------------------------------------------------- #
def reportJob(self, jobID):
if not jobID:
raise reCaptchaBadJobID(
"DeathByCaptcha: Error bad job id to report failed reCaptcha."
)
def _checkRequest(response):
if response.status_code == 200:
return response
self.checkErrorStatus(response)
return None
response = polling.poll(
lambda: self.session.post(
'{}/captcha/{}/report'.format(self.host, jobID),
headers={'Accept': 'application/json'},
data={
'username': self.username,
'password': self.password
}
),
check_success=_checkRequest,
step=10,
timeout=180
)
if response:
return True
else:
raise reCaptchaReportError(
"DeathByCaptcha: Error report failed reCaptcha."
)
# ------------------------------------------------------------------------------- #
def requestJob(self, jobID):
if not jobID:
raise reCaptchaBadJobID(
"DeathByCaptcha: Error bad job id to request reCaptcha."
)
def _checkRequest(response):
if response.ok and response.json().get('text'):
return response
self.checkErrorStatus(response)
return None
response = polling.poll(
lambda: self.session.get(
'{}/captcha/{}'.format(self.host, jobID),
headers={'Accept': 'application/json'}
),
check_success=_checkRequest,
step=10,
timeout=180
)
if response:
return response.json().get('text')
else:
raise reCaptchaTimeout(
"DeathByCaptcha: Error failed to solve reCaptcha."
)
# ------------------------------------------------------------------------------- #
def requestSolve(self, url, siteKey):
def _checkRequest(response):
if response.ok and response.json().get("is_correct") and response.json().get('captcha'):
return response
self.checkErrorStatus(response)
return None
response = polling.poll(
lambda: self.session.post(
'{}/captcha'.format(self.host),
headers={'Accept': 'application/json'},
data={
'username': self.username,
'password': self.password,
'type': '4',
'token_params': json.dumps({
'googlekey': siteKey,
'pageurl': url
})
},
allow_redirects=False
),
check_success=_checkRequest,
step=10,
timeout=180
)
if response:
return response.json().get('captcha')
else:
raise reCaptchaBadJobID(
'DeathByCaptcha: Error no job id was returned.'
)
# ------------------------------------------------------------------------------- #
def getCaptchaAnswer(self, captchaType, url, siteKey, reCaptchaParams):
jobID = None
for param in ['username', 'password']:
if not reCaptchaParams.get(param):
raise reCaptchaParameter(
"DeathByCaptcha: Missing '{}' parameter.".format(param)
)
setattr(self, param, reCaptchaParams.get(param))
if captchaType == 'hCaptcha':
raise reCaptchaException(
'Provider does not support hCaptcha.'
)
if reCaptchaParams.get('proxy'):
self.session.proxies = reCaptchaParams.get('proxies')
try:
jobID = self.requestSolve(url, siteKey)
return self.requestJob(jobID)
except polling.TimeoutException:
try:
if jobID:
self.reportJob(jobID)
except polling.TimeoutException:
raise reCaptchaTimeout(
"DeathByCaptcha: reCaptcha solve took to long and also failed reporting the job id {}.".format(jobID)
)
raise reCaptchaTimeout(
"DeathByCaptcha: reCaptcha solve took to long to execute job id {}, aborting.".format(jobID)
)
# ------------------------------------------------------------------------------- #
captchaSolver()
|
How do I obtain a copy of a folio and/or map?
A plain copy of a folio can be viewed and printed on our online service delivery channel landdirect.ie. This costs €5 per folio. A certified copy of the folio can also be ordered on landdirect.ie and the fee for this is €40. Certified copy folios with maps (title plans) can be ordered by the same method and the fee for this is also €40.
If you do not have access to landdirect.ie, then you can inspect or order these documents at our public offices or by lodging an application by post.
Please see the Contact section of this website for the relevant postal address.
← How do I obtain a copy of a folio and/or map?
|
# coding: utf-8
#
# Copyright 2019 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Feature detection utilities for Python 2 and Python 3."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import print_function # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
import inspect
import io
import itertools
import os
import sys
_THIRD_PARTY_PATH = os.path.join(os.getcwd(), 'third_party', 'python_libs')
sys.path.insert(0, _THIRD_PARTY_PATH)
_YAML_PATH = os.path.join(os.getcwd(), '..', 'oppia_tools', 'pyyaml-5.1.2')
sys.path.insert(0, _YAML_PATH)
_CERTIFI_PATH = os.path.join(
os.getcwd(), '..', 'oppia_tools', 'certifi-2020.12.5')
sys.path.insert(0, _CERTIFI_PATH)
import yaml # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import builtins # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import future.utils # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import past.builtins # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import past.utils # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import six # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import certifi # isort:skip pylint: disable=wrong-import-position, wrong-import-order
import ssl # isort:skip pylint: disable=wrong-import-position, wrong-import-order
BASESTRING = past.builtins.basestring
INPUT = builtins.input
MAP = builtins.map
NEXT = builtins.next
OBJECT = builtins.object
PRINT = print
RANGE = builtins.range
ROUND = builtins.round
UNICODE = builtins.str
ZIP = builtins.zip
def SimpleXMLRPCServer( # pylint: disable=invalid-name
addr, requestHandler=None, logRequests=True, allow_none=False,
encoding=None, bind_and_activate=True):
"""Returns SimpleXMLRPCServer from SimpleXMLRPCServer module if run under
Python 2 and from xmlrpc module if run under Python 3.
Args:
addr: tuple(str, int). The host and port of the server.
requestHandler: callable. A factory for request handler instances.
Defaults to SimpleXMLRPCRequestHandler.
logRequests: bool. Whether to log the requests sent to the server.
allow_none: bool. Permits None in the XML-RPC responses that will be
returned from the server.
encoding: str|None. The encoding used by the XML-RPC responses that will
be returned from the server.
bind_and_activate: bool. Whether server_bind() and server_activate() are
called immediately by the constructor; defaults to true. Setting it
to false allows code to manipulate the allow_reuse_address class
variable before the address is bound.
Returns:
SimpleXMLRPCServer. The SimpleXMLRPCServer object.
"""
try:
from xmlrpc.server import SimpleXMLRPCServer as impl # pylint: disable=import-only-modules
except ImportError:
from SimpleXMLRPCServer import SimpleXMLRPCServer as impl # pylint: disable=import-only-modules
if requestHandler is None:
try:
from xmlrpc.server import SimpleXMLRPCRequestHandler # pylint: disable=import-only-modules
except ImportError:
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler # pylint: disable=import-only-modules
requestHandler = SimpleXMLRPCRequestHandler
return impl(
addr, requestHandler=requestHandler, logRequests=logRequests,
allow_none=allow_none, encoding=encoding,
bind_and_activate=bind_and_activate)
def redirect_stdout(new_target):
"""Returns redirect_stdout from contextlib2 if run under Python 2 and from
contextlib if run under Python 3.
Args:
new_target: FileLike. The file-like object all messages printed to
stdout will be redirected to.
Returns:
contextlib.redirect_stdout or contextlib2.redirect_stdout. The
redirect_stdout object.
"""
try:
from contextlib import redirect_stdout as impl # pylint: disable=import-only-modules
except ImportError:
from contextlib2 import redirect_stdout as impl # pylint: disable=import-only-modules
return impl(new_target)
def nullcontext(enter_result=None):
"""Returns nullcontext from contextlib2 if run under Python 2 and from
contextlib if run under Python 3.
Args:
enter_result: *. The object returned by the nullcontext when entered.
Returns:
contextlib.nullcontext or contextlib2.nullcontext. The nullcontext
object.
"""
try:
from contextlib import nullcontext as impl # pylint: disable=import-only-modules
except ImportError:
from contextlib2 import nullcontext as impl # pylint: disable=import-only-modules
return impl(enter_result=enter_result)
def ExitStack(): # pylint: disable=invalid-name
"""Returns ExitStack from contextlib2 if run under Python 2 and from
contextlib if run under Python 3.
Returns:
contextlib.ExitStack or contextlib2.ExitStack. The ExitStack object.
"""
try:
from contextlib import ExitStack as impl # pylint: disable=import-only-modules
except ImportError:
from contextlib2 import ExitStack as impl # pylint: disable=import-only-modules
return impl()
def string_io(buffer_value=b''):
"""Returns StringIO from StringIO module if run under Python 2 and from io
module if run under Python 3.
Args:
buffer_value: str. A string that is to be converted to in-memory text
stream.
Returns:
StringIO.StringIO or io.StringIO. The StringIO object.
"""
try:
from StringIO import StringIO # pylint: disable=import-only-modules
except ImportError:
from io import StringIO # pylint: disable=import-only-modules
return StringIO(buffer_value) # pylint: disable=disallowed-function-calls
def get_args_of_function_node(function_node, args_to_ignore):
"""Extracts the arguments from a function definition.
Args:
function_node: ast.FunctionDef. Represents a function.
args_to_ignore: list(str). Ignore these arguments in a function
definition.
Returns:
list(str). The args for a function as listed in the function
definition.
"""
try:
return [
a.arg
for a in function_node.args.args
if a.arg not in args_to_ignore
]
except AttributeError:
return [
a.id for a in function_node.args.args if a.id not in args_to_ignore
]
def open_file(filename, mode, encoding='utf-8', newline=None):
"""Open file and return a corresponding file object.
Args:
filename: str. The file to be opened.
mode: str. Mode in which the file is opened.
encoding: str. Encoding in which the file is opened.
newline: None|str. Controls how universal newlines work.
Returns:
_io.TextIOWrapper. The file object.
Raises:
IOError. The file cannot be opened.
"""
# The try/except is needed here to unify the errors because io.open in
# Python 3 throws FileNotFoundError while in Python 2 it throws an IOError.
# This should be removed after we fully migrate to Python 3.
try:
return io.open(filename, mode, encoding=encoding, newline=newline)
except:
raise IOError('Unable to open file: %s' % filename)
def url_join(base_url, relative_url):
"""Construct a full URL by combining a 'base URL' with another URL using
urlparse.urljoin if run under Python 2 and urllib.parse.urljoin if run under
Python 3.
Args:
base_url: str. The base URL.
relative_url: str. The other URL.
Returns:
str. The full URL.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
return urlparse.urljoin(base_url, relative_url) # pylint: disable=disallowed-function-calls
def url_split(urlstring):
"""Splits a URL using urlparse.urlsplit if run under Python 2 and
urllib.parse.urlsplit if run under Python 3.
Args:
urlstring: str. The URL.
Returns:
tuple(str). The components of a URL.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
return urlparse.urlsplit(urlstring) # pylint: disable=disallowed-function-calls
def url_parse(urlstring):
"""Parse a URL into six components using urlparse.urlparse if run under
Python 2 and urllib.parse.urlparse if run under Python 3. This corresponds
to the general structure of a URL:
scheme://netloc/path;parameters?query#fragment.
Args:
urlstring: str. The URL.
Returns:
tuple(str). The components of a URL.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
return urlparse.urlparse(urlstring) # pylint: disable=disallowed-function-calls
def url_unsplit(url_parts):
"""Combine the elements of a tuple as returned by urlsplit() into a complete
URL as a string using urlparse.urlunsplit if run under Python 2 and
urllib.parse.urlunsplit if run under Python 3.
Args:
url_parts: tuple(str). The components of a URL.
Returns:
str. The complete URL.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
return urlparse.urlunsplit(url_parts) # pylint: disable=disallowed-function-calls
def parse_query_string(query_string):
"""Parse a query string given as a string argument
(data of type application/x-www-form-urlencoded) using urlparse.parse_qs if
run under Python 2 and urllib.parse.parse_qs if run under Python 3.
Args:
query_string: str. The query string.
Returns:
dict. The keys are the unique query variable names and the values are
lists of values for each name.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
return urlparse.parse_qs(query_string) # pylint: disable=disallowed-function-calls
def urllib_unquote(content):
"""Replace %xx escapes by their single-character equivalent using
urllib.unquote if run under Python 2 and urllib.parse.unquote if run under
Python 3.
Args:
content: str. The string to be unquoted.
Returns:
str. The unquoted string.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urllib as urlparse
return urlparse.unquote(content)
def url_quote(content):
"""Quotes a string using urllib.quote if run under Python 2 and
urllib.parse.quote if run under Python 3.
Args:
content: str. The string to be quoted.
Returns:
str. The quoted string.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urllib as urlparse
return urlparse.quote(content)
def url_unquote_plus(content):
"""Unquotes a string and replace plus signs by spaces, as required for
unquoting HTML form values using urllib.unquote_plus if run under Python 2
and urllib.parse.unquote_plus if run under Python 3.
Args:
content: str. The string to be unquoted.
Returns:
str. The unquoted string.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urllib as urlparse
return urlparse.unquote_plus(content)
def url_encode(query, doseq=False):
"""Convert a mapping object or a sequence of two-element tuples to a
'url-encoded' string using urllib.urlencode if run under Python 2 and
urllib.parse.urlencode if run under Python 3.
Args:
query: dict or tuple. The query to be encoded.
doseq: bool. If true, individual key=value pairs separated by '&' are
generated for each element of the value sequence for the key.
Returns:
str. The 'url-encoded' string.
"""
try:
import urllib.parse as urlparse
except ImportError:
import urllib as urlparse
return urlparse.urlencode(query, doseq)
def url_retrieve(source_url, filename=None):
"""Copy a network object denoted by a URL to a local file using
urllib.urlretrieve if run under Python 2 and urllib.request.urlretrieve if
run under Python 3.
Args:
source_url: str. The URL.
filename: str. The file location to copy to.
Returns:
urlretrieve. The 'urlretrieve' object.
"""
context = ssl.create_default_context(cafile=certifi.where())
try:
import urllib.request as urlrequest
except ImportError:
import urllib as urlrequest
# Change the User-Agent to prevent servers from blocking requests.
# See https://support.cloudflare.com/hc/en-us/articles/360029779472-Troubleshooting-Cloudflare-1XXX-errors#error1010. # pylint: disable=line-too-long
urlrequest.URLopener.version = (
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) '
'Gecko/20100101 Firefox/47.0'
)
return urlrequest.urlretrieve(
source_url, filename=filename, context=context)
def url_open(source_url):
"""Open a network object denoted by a URL for reading using
urllib2.urlopen if run under Python 2 and urllib.request.urlopen if
run under Python 3.
Args:
source_url: str. The URL.
Returns:
urlopen. The 'urlopen' object.
"""
context = ssl.create_default_context(cafile=certifi.where())
try:
import urllib.request as urlrequest
except ImportError:
import urllib2 as urlrequest
return urlrequest.urlopen(source_url, context=context)
def url_request(source_url, data, headers):
"""This function provides an abstraction of a URL request. It uses
urllib2.Request if run under Python 2 and urllib.request.Request if
run under Python 3.
Args:
source_url: str. The URL.
data: str. Additional data to send to the server.
headers: dict. The request headers.
Returns:
Request. The 'Request' object.
"""
try:
import urllib.request as urlrequest
except ImportError:
import urllib2 as urlrequest
return urlrequest.Request(source_url, data, headers)
def divide(number1, number2):
"""This function divides number1 by number2 in the Python 2 way, i.e it
performs an integer division.
Args:
number1: int. The dividend.
number2: int. The divisor.
Returns:
int. The quotent.
"""
return past.utils.old_div(number1, number2)
def with_metaclass(meta, *bases):
"""Python 2 & 3 helper for installing metaclasses.
Example:
class BaseForm(python_utils.OBJECT):
pass
class FormType(type):
pass
class Form(with_metaclass(FormType, BaseForm)):
pass
Args:
meta: type. The metaclass to install on the derived class.
*bases: tuple(class). The base classes to install on the derived class.
When empty, `object` will be the sole base class.
Returns:
class. A proxy class that mutates the classes which inherit from it to
install the input meta class and inherit from the input base classes.
The proxy class itself does not actually become one of the base classes.
"""
if not bases:
bases = (OBJECT,)
return future.utils.with_metaclass(meta, *bases)
def convert_to_bytes(string_to_convert):
"""Converts the string to bytes.
Args:
string_to_convert: unicode|str. Required string to be converted into
bytes.
Returns:
bytes. The encoded string.
"""
if isinstance(string_to_convert, UNICODE):
return string_to_convert.encode('utf-8')
return bytes(string_to_convert)
def _recursively_convert_to_str(value):
"""Convert all builtins.bytes and builtins.str elements in a data structure
to bytes and unicode respectively. This is required for the
yaml.safe_dump() function to work as it only works for unicode and bytes and
not builtins.bytes nor builtins.str(UNICODE). See:
https://stackoverflow.com/a/1950399/11755830
Args:
value: list|dict|BASESTRING. The data structure to convert.
Returns:
list|dict|bytes|unicode. The data structure in bytes and unicode.
"""
if isinstance(value, list):
return [_recursively_convert_to_str(e) for e in value]
elif isinstance(value, dict):
return {
_recursively_convert_to_str(k): _recursively_convert_to_str(v)
for k, v in value.items()
}
# We are using 'type' here instead of 'isinstance' because we need to
# clearly distinguish the builtins.str and builtins.bytes strings.
elif type(value) == future.types.newstr: # pylint: disable=unidiomatic-typecheck
temp = str(value.encode('utf-8')) # pylint: disable=disallowed-function-calls
# Remove the b'' prefix from the string.
return temp[2:-1].decode('utf-8')
elif type(value) == future.types.newbytes: # pylint: disable=unidiomatic-typecheck
temp = bytes(value)
# Remove the b'' prefix from the string.
return temp[2:-1]
else:
return value
def yaml_from_dict(dictionary, width=80):
"""Gets the YAML representation of a dict.
Args:
dictionary: dict. Dictionary for conversion into yaml.
width: int. Width for the yaml representation, default value
is set to be of 80.
Returns:
str. Converted yaml of the passed dictionary.
"""
dictionary = _recursively_convert_to_str(dictionary)
return yaml.safe_dump(dictionary, default_flow_style=False, width=width)
def reraise_exception():
"""Reraise exception with complete stacktrace."""
# TODO(#11547): This method can be replace by 'raise e' after we migrate
# to Python 3.
# This code is needed in order to reraise the error properly with
# the stacktrace. See https://stackoverflow.com/a/18188660/3688189.
exec_info = sys.exc_info()
six.reraise(exec_info[0], exec_info[1], tb=exec_info[2])
def is_string(value):
"""Returns whether value has a string type."""
return isinstance(value, six.string_types)
def get_args_of_function(func):
"""Returns the argument names of the function.
Args:
func: function. The function to inspect.
Returns:
list(str). The names of the function's arguments.
Raises:
TypeError. The input argument is not a function.
"""
try:
# Python 3.
return [p.name for p in inspect.signature(func).parameters
if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)]
except AttributeError:
# Python 2.
return inspect.getargspec(func).args
def create_enum(*sequential):
"""Creates a enumerated constant.
Args:
*sequential: *. Sequence List to generate the enumerations.
Returns:
dict. Dictionary containing the enumerated constants.
"""
enum_values = dict(ZIP(sequential, sequential))
try:
from enum import Enum # pylint: disable=import-only-modules
# The type() of argument 1 in Enum must be str, not unicode.
return Enum(str('Enum'), enum_values) # pylint: disable=disallowed-function-calls
except ImportError:
_enums = {}
for name, value in enum_values.items():
_value = {
'name': name,
'value': value
}
_enums[name] = type(b'Enum', (), _value)
return type(b'Enum', (), _enums)
def zip_longest(*args, **kwargs):
"""Creates an iterator that aggregates elements from each of the iterables.
If the iterables are of uneven length, missing values are
filled-in with fillvalue.
Args:
*args: list(*). Iterables that needs to be aggregated into an iterable.
**kwargs: dict. It contains fillvalue.
Returns:
iterable(iterable). A sequence of aggregates elements
from each of the iterables.
"""
fillvalue = kwargs.get('fillvalue')
try:
return itertools.zip_longest(*args, fillvalue=fillvalue)
except AttributeError:
return itertools.izip_longest(*args, fillvalue=fillvalue)
|
Members met February 6 at Janda’s in Ellisville. Prior to the meeting, we worked on a calendar picture activity to be donated to local senior centers.
There was an election of officers, with the following results: President Al Ledvina, Vice-President Jan Janowski, Secretary Pete Janowski, Treasurer Mary Jo Shefchik, and Correspondent Judy Kraynik.
The Home Office documentation relating to the National Convention was reviewed. The delegates will have to be elected by April 1.
Five members were present at the district II planning meeting on January 27, at Machut’s, Two Rivers. The District II Bingo Meeting is March 24 at Suster’s in Denmark at noon. The District II Bowling Social is at CZ’s in Luxemburg at noon on March 31. We will bowl, eat, and socialize. The District II Meeting is May 5 at Machut’s in Two Rivers at noon.
Al Ledvina and Joe Kuffel will be 50-year members.
Condolences go out to the family of Vickie Retrum of Green Bay.
It was noted that our lodge now has 246 adult and 65 juvenile members. Our secretary reviewed points earned for 2018, and noted that we were awarded with 99 points, which is a 5-star rating.
Five members attended the meeting on November 19 at the home of Al and Barb Ledvina. We did a paper plate lollipop project, which was donated to Oak Creek Assisted Living, Luxemburg.
It was noted that the last quarterly payment was received from the Home Office.
A thank-you was received from Oak Park Place for the owl cans that were donated to them.
We discussed an Easter project with the Pilsen 4-H Club, and also a winter project.
Members met November 7. We worked the morning of November 7 at St. Vincent de Paul. An appreciation meal and meeting followed at the China Buffet in Green Bay.
The secretary reviewed correspondence from the Home Office relating to the National Convention. It was noted that we will be eligible to have two delegates and two alternatives. Delegate elections will take place at a future meeting.
The Luxemburg Emergency and Rescue sent a thank-you note to our lodge for the sizable donation we gave. The money came from a recent brat fry we hosted and Matching Funds from the Home Office. It enabled them to purchase an Air Chair, equipment used to rescue victims from tight spaces.
Lodge President Al Ledvina handing check to Dan Opicka of Luxemburg Emergency and Rescue.
The families of Lillian Ledvina and Marion Mleziva also sent a thank-you note for memorials sent by our lodge.
Our next meeting will be at 11:30 a.m. on January 23 at Janda’s, Ellisville. Members will also be doing a calendar project, to be donated to local nursing facilities.
Members attended a meeting on October 17 at CZ’s. Those who attended the State Meeting reported events that took place.
The owl can project was done with the Pilsen 4-H Club on September 20. Pens received from agent Rudy Kolarik and small notebooks from the Home Office were put into the cans before donating to Oak Creek Home and Oak Park Place.
Owl can project members did with 4-H Club.
Members worked at the Pilsen blood drive on October 2.
The Halloween youth party was held at Montpelier Community Center on October 27 at 1 p.m. with No. 365 joining. Both lodges shared in bringing the food, milk, soda, treats, and Bingo game. Prizes were a bike and two scooters. The bike was won by Emmett Brodtke, and the scooters were won by Eva Oshefsky and Jenah Krueger.
Our meeting was held September 3 at Montpelier Community Center. Following the meeting, we had our annual Labor Day picnic. Members brought a dish to pass and the lodge furnished chicken, refreshments, and ice cream. Member, Father Milton Suess, gave an interesting talk.
Mary Jo Shefchik sent stamps to Stamps for the Wounded as a lodge project.
Our quarterly deposit was received from the Home Office.
Upcoming events are the youth Halloween party on October 27 in conjunction with No. 365 at the Montpelier Community Center. There will be a bike and two scooters for prize giveaways.
Members will work at St. Vincent de Paul on November 7 from 9 until 11:30 a.m. with a meeting afterwards.
We will have an adult holiday party at Suster’s in Denmark on November 9 at 6:30 p.m. RSVP to Judy (468-5932) by November 2 if attending. Food donations for Kewaunee County Pantry would be appreciated.
Members met on July 25 at CZ’s. We sponsored a brat fry that was held at Festival East on June 29. It was a successful fundraiser that allowed the Luxemburg Rescue Department to purchase an air chair to be used in patient rescues.
We discussed the State Meeting. It was decided to make a can tab donation to the Ronald McDonald House.
The Czech and Kolache Festival, the largest in northeastern WI, was held at the Agricultural Heritage Farm on August 4-5. Six-thousand kolache were made for the occasion. There was a Czech kroje style show, Czech food, music, and exhibits. Members participated in various areas.
The secretary arranged to get together with the Pilsen 4-H Club on September 20 at the Montpelier Community Center for an “owl can” project. Items will be donated to residents of assisted living.
Members will be working at St. Vincent de Paul on November 7, 9-11:30 a.m. with meeting to follow.
Members met June 20 at CZ’s. Agent Rudy Kolarik attended the meeting.
Secretary Pete Janowski discussed the State Meeting to be held on October 6 in Black River Falls. Delegates will be Al and Barb Ledvina, Ken and Pearl Schlies, and Pete Janowski. Our lodge will be bringing items for the state scholarship raffle.
An owl project, with the Pilsen 4-H members, will be scheduled in August at a date convenient with the club. A turkey project, to benefit the local nursing homes, will be scheduled at our November meeting with date to be determined.
A thank-you note was received from East Shore Industries, for our donation of $100 worth of credit cards.
Members met May 22 at CZ’s. We discussed the State Meeting on October 6 in Black River Falls. Meeting starts at 10 a.m. and ends with an evening dinner and entertainment. We will wait for more information from Black River Falls and make delegate nominations at our meeting.
Our secretary reported that we have one new member, Carlos Castillo. Condolences go out to the family of lodge member Marion Mleziva.
Members met April 11 at the China Buffet in Green Bay. We had worked earlier that morning at the St. Vincent de Paul store, helping where needed. An appreciation lunch was sponsored by the lodge for those who worked, followed by a meeting.
Five members attended the District 2 membership/Bingo rally at Gill’s, on April 8. Approximately 75 District 2 members were in attendance.
An “owl can” project is in the planning stages, and will be discussed with the Pilsen 4-H Club. There was also discussion on a turkey pine cone project tentatively scheduled for the November meeting.
Members will be working at the Festival East Brat Barn, Bellevue, on June 29, from 10 a.m.-5:30 p.m. Funds will be donated to the Luxemburg Rescue Department for the purchase of an “air chair” to be used in victim rescues. A request goes out to support this worthy cause.
Members met March 21 at CZ’s in Luxemburg, WI.
A blood pressure check was done at St. Therese Church, Pilsen, on March 10 after the 4 p.m. mass. Member Julie Thoreson R.N., conducted the testing, with the help of other members.
There was discussion about the prizes that would be donated to the District 2 membership rally at Gill’s, Whitelaw, on April 8.
Thank-you letters were received from the CP Telethon and the veterans at King, WI, for the valentines we sent.
It was decided that funds received from the Brat Fry on June 29, at Festival’s Brat Barn, will be donated to the Luxemburg Rescue Department. The money will go towards an air chair, which would be used in victim rescues.
We welcome new member Zachary Barlament.
Members met at Janda’s in Ellisville on February 21 for a noon luncheon and meeting. Afterwards, everyone participated in a project creating calendar picture books, utilizing pictures from old calendars. Five books were made and were donated to local nursing homes.
The secretary noted that the festival food brat barn is reserved for June 29. More details will come later.
We have two 50-year members for 2018: Betty Mastalir and Patricia Rolf.
Members met on January 31. We had the election of officers with the following results: President Al Ledvina, Vice President Jan Janowski, Secretary Pete Janowski, Treasurer Mary Jo Shefchik, and Correspondent Judy Kraynik.
Plastic caps were collected for St. Paul Lutheran Church in Ellisville.
The secretary passed out the summary of points received for the 2017 lodge projects. We achieved our top reward. Possible projects and activities for 2018 were discussed.
Members met at the home of Mary Jo Shefchik on February 7 to make valentines for the veteran’s home in King, WI. Cash donations will be made to the Cerebral Palsy Green Bay Chapter and East Shore Industries as well.
Join us at noon on March 18 for the District 2 Big Brothers Big Sisters bowling at CZ’s. April 8 at noon is the District 2 Bingo/dinner at Gill’s in Whitelaw, with $14 cost. On April 11, we work at St. Vincent de Paul in Green Bay from 9 to 11:30 a.m. Mark your calendar for May 5 Join Hands Day roadside garbage pick up with Pilsen 4-H Club at St. Therese Church, Pilsen, 9 a.m.
|
# Copyright 2014 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.
''' TraceEventImporter imports TraceEvent-formatted data
into the provided model.
This is a port of the trace event importer from
https://code.google.com/p/trace-viewer/
'''
import copy
import json
import re
import telemetry.timeline.async_slice as tracing_async_slice
import telemetry.timeline.flow_event as tracing_flow_event
from telemetry.timeline import importer
from telemetry.timeline import tracing_timeline_data
class TraceBufferOverflowException(Exception):
pass
class TraceEventTimelineImporter(importer.TimelineImporter):
def __init__(self, model, timeline_data):
super(TraceEventTimelineImporter, self).__init__(
model, timeline_data, import_priority=1)
event_data = timeline_data.EventData()
self._events_were_from_string = False
self._all_async_events = []
self._all_object_events = []
self._all_flow_events = []
if type(event_data) is str:
# If the event data begins with a [, then we know it should end with a ].
# The reason we check for this is because some tracing implementations
# cannot guarantee that a ']' gets written to the trace file. So, we are
# forgiving and if this is obviously the case, we fix it up before
# throwing the string at JSON.parse.
if event_data[0] == '[':
event_data = re.sub(r'[\r|\n]*$', '', event_data)
event_data = re.sub(r'\s*,\s*$', '', event_data)
if event_data[-1] != ']':
event_data = event_data + ']'
self._events = json.loads(event_data)
self._events_were_from_string = True
else:
self._events = event_data
# Some trace_event implementations put the actual trace events
# inside a container. E.g { ... , traceEvents: [ ] }
# If we see that, just pull out the trace events.
if 'traceEvents' in self._events:
container = self._events
self._events = self._events['traceEvents']
for field_name in container:
if field_name == 'traceEvents':
continue
# Any other fields in the container should be treated as metadata.
self._model.metadata.append({
'name' : field_name,
'value' : container[field_name]})
@staticmethod
def CanImport(timeline_data):
''' Returns whether obj is a TraceEvent array. '''
if not isinstance(timeline_data,
tracing_timeline_data.TracingTimelineData):
return False
event_data = timeline_data.EventData()
# May be encoded JSON. But we dont want to parse it fully yet.
# Use a simple heuristic:
# - event_data that starts with [ are probably trace_event
# - event_data that starts with { are probably trace_event
# May be encoded JSON. Treat files that start with { as importable by us.
if isinstance(event_data, str):
return len(event_data) > 0 and (event_data[0] == '{'
or event_data[0] == '[')
# Might just be an array of events
if (isinstance(event_data, list) and len(event_data)
and 'ph' in event_data[0]):
return True
# Might be an object with a traceEvents field in it.
if 'traceEvents' in event_data:
trace_events = event_data.get('traceEvents', None)
return (type(trace_events) is list and
len(trace_events) > 0 and 'ph' in trace_events[0])
return False
def _GetOrCreateProcess(self, pid):
return self._model.GetOrCreateProcess(pid)
def _DeepCopyIfNeeded(self, obj):
if self._events_were_from_string:
return obj
return copy.deepcopy(obj)
def _ProcessAsyncEvent(self, event):
'''Helper to process an 'async finish' event, which will close an
open slice.
'''
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
self._all_async_events.append({
'event': event,
'thread': thread})
def _ProcessCounterEvent(self, event):
'''Helper that creates and adds samples to a Counter object based on
'C' phase events.
'''
if 'id' in event:
ctr_name = event['name'] + '[' + str(event['id']) + ']'
else:
ctr_name = event['name']
ctr = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateCounter(event['cat'], ctr_name))
# Initialize the counter's series fields if needed.
if len(ctr.series_names) == 0:
#TODO: implement counter object
for series_name in event['args']:
ctr.series_names.append(series_name)
if len(ctr.series_names) == 0:
self._model.import_errors.append('Expected counter ' + event['name'] +
' to have at least one argument to use as a value.')
# Drop the counter.
del ctr.parent.counters[ctr.full_name]
return
# Add the sample values.
ctr.timestamps.append(event['ts'] / 1000.0)
for series_name in ctr.series_names:
if series_name not in event['args']:
ctr.samples.append(0)
continue
ctr.samples.append(event['args'][series_name])
def _ProcessObjectEvent(self, event):
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
self._all_object_events.append({
'event': event,
'thread': thread})
def _ProcessDurationEvent(self, event):
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
if not thread.IsTimestampValidForBeginOrEnd(event['ts'] / 1000.0):
self._model.import_errors.append(
'Timestamps are moving backward.')
return
if event['ph'] == 'B':
thread.BeginSlice(event['cat'],
event['name'],
event['ts'] / 1000.0,
event['tts'] / 1000.0 if 'tts' in event else None,
event['args'])
elif event['ph'] == 'E':
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
if not thread.IsTimestampValidForBeginOrEnd(event['ts'] / 1000.0):
self._model.import_errors.append(
'Timestamps are moving backward.')
return
if not thread.open_slice_count:
self._model.import_errors.append(
'E phase event without a matching B phase event.')
return
new_slice = thread.EndSlice(
event['ts'] / 1000.0,
event['tts'] / 1000.0 if 'tts' in event else None)
for arg_name, arg_value in event.get('args', {}).iteritems():
if arg_name in new_slice.args:
self._model.import_errors.append(
'Both the B and E phases of ' + new_slice.name +
' provided values for argument ' + arg_name + '. ' +
'The value of the E phase event will be used.')
new_slice.args[arg_name] = arg_value
def _ProcessCompleteEvent(self, event):
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
thread.PushCompleteSlice(
event['cat'],
event['name'],
event['ts'] / 1000.0,
event['dur'] / 1000.0 if 'dur' in event else None,
event['tts'] / 1000.0 if 'tts' in event else None,
event['tdur'] / 1000.0 if 'tdur' in event else None,
event['args'])
def _ProcessMetadataEvent(self, event):
if event['name'] == 'thread_name':
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
thread.name = event['args']['name']
elif event['name'] == 'process_name':
process = self._GetOrCreateProcess(event['pid'])
process.name = event['args']['name']
elif event['name'] == 'trace_buffer_overflowed':
process = self._GetOrCreateProcess(event['pid'])
process.SetTraceBufferOverflowTimestamp(event['args']['overflowed_at_ts'])
else:
self._model.import_errors.append(
'Unrecognized metadata name: ' + event['name'])
def _ProcessInstantEvent(self, event):
# Treat an Instant event as a duration 0 slice.
# SliceTrack's redraw() knows how to handle this.
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
thread.BeginSlice(event['cat'],
event['name'],
event['ts'] / 1000.0,
args=event.get('args'))
thread.EndSlice(event['ts'] / 1000.0)
def _ProcessSampleEvent(self, event):
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
thread.AddSample(event['cat'],
event['name'],
event['ts'] / 1000.0,
event.get('args'))
def _ProcessFlowEvent(self, event):
thread = (self._GetOrCreateProcess(event['pid'])
.GetOrCreateThread(event['tid']))
self._all_flow_events.append({
'event': event,
'thread': thread})
def ImportEvents(self):
''' Walks through the events_ list and outputs the structures discovered to
model_.
'''
for event in self._events:
phase = event.get('ph', None)
if phase == 'B' or phase == 'E':
self._ProcessDurationEvent(event)
elif phase == 'X':
self._ProcessCompleteEvent(event)
elif phase == 'S' or phase == 'F' or phase == 'T':
self._ProcessAsyncEvent(event)
# Note, I is historic. The instant event marker got changed, but we
# want to support loading old trace files so we have both I and i.
elif phase == 'I' or phase == 'i':
self._ProcessInstantEvent(event)
elif phase == 'P':
self._ProcessSampleEvent(event)
elif phase == 'C':
self._ProcessCounterEvent(event)
elif phase == 'M':
self._ProcessMetadataEvent(event)
elif phase == 'N' or phase == 'D' or phase == 'O':
self._ProcessObjectEvent(event)
elif phase == 's' or phase == 't' or phase == 'f':
self._ProcessFlowEvent(event)
else:
self._model.import_errors.append('Unrecognized event phase: ' +
phase + '(' + event['name'] + ')')
return self._model
def FinalizeImport(self):
'''Called by the Model after all other importers have imported their
events.'''
self._model.UpdateBounds()
# We need to reupdate the bounds in case the minimum start time changes
self._model.UpdateBounds()
self._CreateAsyncSlices()
self._CreateFlowSlices()
self._SetBrowserProcess()
self._CreateExplicitObjects()
self._CreateImplicitObjects()
self._CreateTabIdsToThreadsMap()
def _CreateAsyncSlices(self):
if len(self._all_async_events) == 0:
return
self._all_async_events.sort(
cmp=lambda x, y: int(x['event']['ts'] - y['event']['ts']))
async_event_states_by_name_then_id = {}
all_async_events = self._all_async_events
for async_event_state in all_async_events:
event = async_event_state['event']
name = event.get('name', None)
if name is None:
self._model.import_errors.append(
'Async events (ph: S, T or F) require an name parameter.')
continue
event_id = event.get('id')
if event_id is None:
self._model.import_errors.append(
'Async events (ph: S, T or F) require an id parameter.')
continue
# TODO(simonjam): Add a synchronous tick on the appropriate thread.
if event['ph'] == 'S':
if not name in async_event_states_by_name_then_id:
async_event_states_by_name_then_id[name] = {}
if event_id in async_event_states_by_name_then_id[name]:
self._model.import_errors.append(
'At %d, a slice of the same id %s was already open.' % (
event['ts'], event_id))
continue
async_event_states_by_name_then_id[name][event_id] = []
async_event_states_by_name_then_id[name][event_id].append(
async_event_state)
else:
if name not in async_event_states_by_name_then_id:
self._model.import_errors.append(
'At %d, no slice named %s was open.' % (event['ts'], name,))
continue
if event_id not in async_event_states_by_name_then_id[name]:
self._model.import_errors.append(
'At %d, no slice named %s with id=%s was open.' % (
event['ts'], name, event_id))
continue
events = async_event_states_by_name_then_id[name][event_id]
events.append(async_event_state)
if event['ph'] == 'F':
# Create a slice from start to end.
async_slice = tracing_async_slice.AsyncSlice(
events[0]['event']['cat'],
name,
events[0]['event']['ts'] / 1000.0)
async_slice.duration = ((event['ts'] / 1000.0)
- (events[0]['event']['ts'] / 1000.0))
async_slice.start_thread = events[0]['thread']
async_slice.end_thread = async_event_state['thread']
if async_slice.start_thread == async_slice.end_thread:
if 'tts' in event and 'tts' in events[0]['event']:
async_slice.thread_start = events[0]['event']['tts'] / 1000.0
async_slice.thread_duration = ((event['tts'] / 1000.0)
- (events[0]['event']['tts'] / 1000.0))
async_slice.id = event_id
async_slice.args = events[0]['event']['args']
# Create sub_slices for each step.
for j in xrange(1, len(events)):
sub_name = name
if events[j - 1]['event']['ph'] == 'T':
sub_name = name + ':' + events[j - 1]['event']['args']['step']
sub_slice = tracing_async_slice.AsyncSlice(
events[0]['event']['cat'],
sub_name,
events[j - 1]['event']['ts'] / 1000.0)
sub_slice.parent_slice = async_slice
sub_slice.duration = ((events[j]['event']['ts'] / 1000.0)
- (events[j - 1]['event']['ts'] / 1000.0))
sub_slice.start_thread = events[j - 1]['thread']
sub_slice.end_thread = events[j]['thread']
if sub_slice.start_thread == sub_slice.end_thread:
if 'tts' in events[j]['event'] and \
'tts' in events[j - 1]['event']:
sub_slice.thread_duration = \
((events[j]['event']['tts'] / 1000.0)
- (events[j - 1]['event']['tts'] / 1000.0))
sub_slice.id = event_id
sub_slice.args = events[j - 1]['event']['args']
async_slice.AddSubSlice(sub_slice)
# The args for the finish event go in the last sub_slice.
last_slice = async_slice.sub_slices[-1]
for arg_name, arg_value in event['args'].iteritems():
last_slice.args[arg_name] = arg_value
# Add |async_slice| to the start-thread's async_slices.
async_slice.start_thread.AddAsyncSlice(async_slice)
del async_event_states_by_name_then_id[name][event_id]
def _CreateExplicitObjects(self):
# TODO(tengs): Implement object instance parsing
pass
def _CreateImplicitObjects(self):
# TODO(tengs): Implement object instance parsing
pass
def _CreateFlowSlices(self):
if len(self._all_flow_events) == 0:
return
self._all_flow_events.sort(
cmp=lambda x, y: int(x['event']['ts'] - y['event']['ts']))
flow_id_to_event = {}
for data in self._all_flow_events:
event = data['event']
thread = data['thread']
if 'name' not in event:
self._model.import_errors.append(
'Flow events (ph: s, t or f) require a name parameter.')
continue
if 'id' not in event:
self._model.import_errors.append(
'Flow events (ph: s, t or f) require an id parameter.')
continue
flow_event = tracing_flow_event.FlowEvent(
event['cat'],
event['id'],
event['name'],
event['ts'] / 1000.0,
event['args'])
thread.AddFlowEvent(flow_event)
if event['ph'] == 's':
if event['id'] in flow_id_to_event:
self._model.import_errors.append(
'event id %s already seen when encountering start of'
'flow event.' % event['id'])
continue
flow_id_to_event[event['id']] = flow_event
elif event['ph'] == 't' or event['ph'] == 'f':
if not event['id'] in flow_id_to_event:
self._model.import_errors.append(
'Found flow phase %s for id: %s but no flow start found.' % (
event['ph'], event['id']))
continue
flow_position = flow_id_to_event[event['id']]
self._model.flow_events.append([flow_position, flow_event])
if event['ph'] == 'f':
del flow_id_to_event[event['id']]
else:
# Make this event the next start event in this flow.
flow_id_to_event[event['id']] = flow_event
def _SetBrowserProcess(self):
for thread in self._model.GetAllThreads():
if thread.name == 'CrBrowserMain':
self._model.browser_process = thread.parent
def _CheckTraceBufferOverflow(self):
for process in self._model.GetAllProcesses():
if process.trace_buffer_did_overflow:
raise TraceBufferOverflowException(
'Trace buffer of process with pid=%d overflowed at timestamp %d. '
'Raw trace data:\n%s' %
(process.pid, process.trace_buffer_overflow_event.start,
repr(self._events)))
def _CreateTabIdsToThreadsMap(self):
# Since _CreateTabIdsToThreadsMap() relies on markers output on timeline
# tracing data, it maynot work in case we have trace events dropped due to
# trace buffer overflow.
self._CheckTraceBufferOverflow()
tab_ids_list = []
for metadata in self._model.metadata:
if metadata['name'] == 'tabIds':
tab_ids_list = metadata['value']
break
for tab_id in tab_ids_list:
timeline_markers = self._model.FindTimelineMarkers(tab_id)
assert(len(timeline_markers) == 1)
assert(timeline_markers[0].start_thread ==
timeline_markers[0].end_thread)
self._model.AddMappingFromTabIdToRendererThread(
tab_id, timeline_markers[0].start_thread)
|
RAUCH's company history starts in the gastronomy sector of 1919. The first product was apple juice. It was delivered in 1 liter bottles to nearby gastronomers. 100 years later we have become an indispensable partner for the gastronomy in the field of non-alcoholic beverages. Along with countless brands, we offer all kinds of packaging solutions, too.
According to the new mega trend of “VEGANISM“, in collaboration with the vegan society, RAUCH has made certificates and herewith guarantees that no raw materials derived from animals are used throughout the whole production process. From now on, the European V label will be on ALL 0.2 l varieties in the glass bottle exclusively for gastronomy.
Looking for a convenient solution for your breakfast buffet? Our bag-in-box dispenser offers the highest flexibility and the best quality.
The Rauch POSTMIX serving system is ideal in case of a high fruit juice demand. With one click, it prepares the desired beverages from concentrate and fresh water and guarantees a prompt, clean and powerful way of serving beverages for up to 200 liters. With flexible usage: different serving heights for glasses and carafes provide multiple uses. A number of dispenser models allow for the use of 2 or, respectively, 5 varieties.
The bag-in-box PREMIX two-chamber dispenser provides pure fruit pleasure. With powerful cooling, 2-3 different products may be served simultaneously in traditional Rauch quality. The assortment includes 100% organic juices, high-grade 100% fruit juices with no addition of sugar as well as the most favorite nectars. Its handling by the staff is very easy - guests take their beverages quickly and smoothly.
|
from __init__ import *
def comp(nameplot):
if nameplot == 'DS_Store':
return
nameplot = nameplot[:-4]
print 'comp() working on ' + nameplot + '...'
cmnd = 'mkdir -p ' + pathimag + 'comprtag/' + nameplot + '/'
#print cmnd
os.system(cmnd)
#print
strgplot = nameplot.split('/')[-1]
cmndconv = 'convert -density 300'
for line in listline:
namedest = pathimag + 'comprtag/' + nameplot + '/' + strgplot + '_' + line + '.pdf'
if not os.path.isfile(namedest):
strgorig = '%s' % pathimag + line + '/' + nameplot + '.pdf'
cmnd = 'cp %s %s' % (strgorig, namedest)
#print cmnd
os.system(cmnd)
#print
else:
pass
print 'File already exists...'
#print
cmndconv += ' ' + namedest
cmndconv += ' ' + pathimag + 'comprtag/' + nameplot + '/merg.pdf'
os.system(cmndconv)
#print
print 'comp_rtag() initialized...'
pathimag = os.environ["PCAT_DATA_PATH"] + '/imag/'
cmnd = 'mkdir -p %s' % (os.environ["PCAT_DATA_PATH"] + '/imag/comprtag')
os.system(cmnd)
print 'Listing the available runs...'
cmnd = 'ls %s | xargs -n 1 basename > %s/listrtag.txt' % (pathimag, pathimag)
print cmnd
os.system(cmnd)
pathlist = pathimag + 'listrtag.txt'
with open(pathlist) as thisfile:
listline = thisfile.readlines()
listline = [x.strip() for x in listline]
if len(sys.argv) > 2:
listline = sys.argv[1:]
else:
strgsrch = sys.argv[1]
listline = fnmatch.filter(listline, strgsrch)
print 'listline'
for line in listline:
print line
namerefr = listline[0]
pathrefr = os.environ["PCAT_DATA_PATH"] + '/imag/' + namerefr + '/'
print 'Iterating over folders of the reference run...'
for namefrst in os.listdir(pathrefr):
namefrstprim = os.path.join(pathrefr, namefrst)
if os.path.isdir(namefrstprim):
for nameseco in os.listdir(namefrstprim):
if nameseco == 'fram':
continue
namesecoprim = os.path.join(namefrstprim, nameseco)
if os.path.isdir(namesecoprim):
for namethrd in os.listdir(namesecoprim):
namethrdprim = os.path.join(namesecoprim, namethrd)
if os.path.isdir(namethrdprim):
for namefrth in os.listdir(namethrdprim):
namefrthprim = os.path.join(namethrdprim, namefrth)
comp(namefrthprim.split(pathrefr)[-1])
else:
comp(namethrdprim.split(pathrefr)[-1])
elif nameseco.endswith('pdf') or nameseco.endswith('gif'):
comp(namesecoprim.split(pathrefr)[-1])
elif namefrst.endswith('pdf') or namefrst.endswith('gif'):
comp(namefrstprim.split(pathrefr)[-1])
|
Notes on server implementations and fixes for VMware, Microsoft, and other fun projects.
The partition number should automatically be selected, and press enter twice to accept the beginning and ending blocks on the free space.
Press w to write the changes.
This was written using VMware's KB article on the subject as a reference.
No warranty or guarantee is expressed or implied on anything that is posted here. You assume all risk for anything that you do to your servers, software, equipment. Everything posted here is for reference only.
All posts are copyrighted by the author and cannot be reused without expressed permission of the owner.
|
# sync file generator for lightshowpi
# run usage
#
# python sync_file_generator.py
#
# Enter y to confirm that you wish to run this
# Enter the path to the folder containing your audio files
# along with the sync files it will also generate a playlist file
# enter the path to this playlist file in your overrides.cfg and
# lightshowpi will use this as your new playlist
import decoder
import glob
import mutagen
import numpy as np
import os
import sys
import wave
HOME_DIR = os.getenv("SYNCHRONIZED_LIGHTS_HOME")
if not HOME_DIR:
print("Need to setup SYNCHRONIZED_LIGHTS_HOME environment variable, "
"see readme")
sys.exit()
# hack to get the configuration_manager and fft modules to load
# from a different directory
path = list(sys.path)
# insert script location and configuration_manager location into path
sys.path.insert(0, HOME_DIR + "/py")
# import the configuration_manager and fft now that we can
import fft
import configuration_manager as cm
#### reusing code from synchronized_lights.py
#### no need to reinvent the wheel
_CONFIG = cm.CONFIG
GPIOLEN = len([int(pin) for pin in _CONFIG.get('hardware',
'gpio_pins').split(',')])
_MIN_FREQUENCY = _CONFIG.getfloat('audio_processing', 'min_frequency')
_MAX_FREQUENCY = _CONFIG.getfloat('audio_processing', 'max_frequency')
try:
_CUSTOM_CHANNEL_MAPPING = \
[int(channel) for channel in _CONFIG.get('audio_processing',\
'custom_channel_mapping').split(',')]
except:
_CUSTOM_CHANNEL_MAPPING = 0
try:
_CUSTOM_CHANNEL_FREQUENCIES = [int(channel) for channel in
_CONFIG.get('audio_processing',
'custom_channel_frequencies').split(',')]
except:
_CUSTOM_CHANNEL_FREQUENCIES = 0
CHUNK_SIZE = 2048 # Use a multiple of 8 (move this to config)
def calculate_channel_frequency(min_frequency,
max_frequency,
custom_channel_mapping,
custom_channel_frequencies):
"""
Calculate frequency values
Calculate frequency values for each channel,
taking into account custom settings.
"""
# How many channels do we need to calculate the frequency for
if custom_channel_mapping != 0 and len(custom_channel_mapping) == GPIOLEN:
channel_length = max(custom_channel_mapping)
else:
channel_length = GPIOLEN
octaves = (np.log(max_frequency / min_frequency)) / np.log(2)
octaves_per_channel = octaves / channel_length
frequency_limits = []
frequency_store = []
frequency_limits.append(min_frequency)
if custom_channel_frequencies != 0 and (len(custom_channel_frequencies)
>= channel_length + 1):
frequency_limits = custom_channel_frequencies
else:
for i in range(1, GPIOLEN + 1):
frequency_limits.append(frequency_limits[-1]
* 10 ** (3 /
(10 * (1 / octaves_per_channel))))
for i in range(0, channel_length):
frequency_store.append((frequency_limits[i], frequency_limits[i + 1]))
# we have the frequencies now lets map them if custom mapping is defined
if custom_channel_mapping != 0 and len(custom_channel_mapping) == GPIOLEN:
frequency_map = []
for i in range(0, GPIOLEN):
mapped_channel = custom_channel_mapping[i] - 1
mapped_frequency_set = frequency_store[mapped_channel]
mapped_frequency_set_low = mapped_frequency_set[0]
mapped_frequency_set_high = mapped_frequency_set[1]
frequency_map.append(mapped_frequency_set)
return frequency_map
else:
return frequency_store
def cache_song(song_filename):
"""Play the next song from the play list (or --file argument)."""
# Initialize FFT stats
matrix = [0 for _ in range(GPIOLEN)] # get length of gpio and assign it to a variable
# Set up audio
if song_filename.endswith('.wav'):
musicfile = wave.open(song_filename, 'r')
else:
musicfile = decoder.open(song_filename)
sample_rate = musicfile.getframerate()
num_channels = musicfile.getnchannels()
song_filename = os.path.abspath(song_filename)
# create empty array for the cache_matrix
cache_matrix = np.empty(shape=[0, GPIOLEN])
cache_filename = \
os.path.dirname(song_filename) + "/." + os.path.basename(song_filename) + ".sync"
# The values 12 and 1.5 are good estimates for first time playing back
# (i.e. before we have the actual mean and standard deviations
# calculated for each channel).
mean = [12.0 for _ in range(GPIOLEN)]
std = [1.5 for _ in range(GPIOLEN)]
# Process audio song_filename
row = 0
data = musicfile.readframes(CHUNK_SIZE) # move chunk_size to configuration_manager
frequency_limits = calculate_channel_frequency(_MIN_FREQUENCY,
_MAX_FREQUENCY,
_CUSTOM_CHANNEL_MAPPING,
_CUSTOM_CHANNEL_FREQUENCIES)
while data != '':
# No cache - Compute FFT in this chunk, and cache results
matrix = fft.calculate_levels(data, CHUNK_SIZE, sample_rate, frequency_limits, GPIOLEN)
# Add the matrix to the end of the cache
cache_matrix = np.vstack([cache_matrix, matrix])
# Read next chunk of data from music song_filename
data = musicfile.readframes(CHUNK_SIZE)
row = row + 1
# Compute the standard deviation and mean values for the cache
for i in range(0, GPIOLEN):
std[i] = np.std([item for item in cache_matrix[:, i] if item > 0])
mean[i] = np.mean([item for item in cache_matrix[:, i] if item > 0])
# Add mean and std to the top of the cache
cache_matrix = np.vstack([mean, cache_matrix])
cache_matrix = np.vstack([std, cache_matrix])
# Save the cache using numpy savetxt
np.savetxt(cache_filename, cache_matrix)
#### end reuse
def main():
print "Do you want to generating sync files"
print
print "This could take a while if you have a lot of songs"
question = raw_input("Would you like to proceed? (Y to continue) :")
if not question in ["y", "Y"]:
sys.exit(0)
location = raw_input("Enter the path to the folder of songs:")
location += "/"
sync_list = list()
audio_file_types = ["*.mp3", "*.mp4",
"*.m4a", "*.m4b",
"*.aac", "*.ogg",
"*.flac", "*.oga",
"*.wma", "*.wav"]
for file_type in audio_file_types:
sync_list.extend(glob.glob(location + file_type))
playlistFile = open(location + "playlist", "w")
for song in sync_list:
print "Generating sync file for",song
cache_song(song)
print "cached"
metadata = mutagen.File(song, easy=True)
if "title" in metadata:
title = metadata["title"][0]
else:
title = os.path.splitext(os.path.basename(song))[0].strip()
title = title.replace("_", " ")
title = title.replace("-", " - ")
playlistFile.write(title + "\t" + song + "\n")
playlistFile.close()
print "All Finished."
print "A playlist was also generated"
print location + "playlist"
sys.path[:] = path
if __name__ == "__main__":
main()
|
Apart from her, other Bollywood actors who have lent their voices for the film – which is based on Rudyard Kipling’s classic The Jungle Book stories – include Anil Kapoor, Madhuri Dixit, Abhishek Bachchan, and Jackie Shroff.
Kareena, in length, talked about her character and why she decided to say yes to it.
“Everybody has grown up watching The Jungle Book. Our whole youth has been about Mowgli, Bagheera, Baloo and other characters. These characters have actually lived with us. I think it’s amazing that now we are getting to see them on a global platform like Netflix,” she said at the red carpet of the film’s world premiere on Sunday.
Talking about the character that she likes the most, the ‘Veere Di Wedding’ star said that Kaa, one of the oldest characters in The Jungle Book, has been her favourite always.
So, is she open to doing web series as well?
“Of course!”, replied the ‘Takht’ star and added that it is great to see how well ‘Sacred Games’ – the crime thriller for which husband Saif has been gaining accolades – has been received.
“Wherever I go, people keep asking me when the second season is coming out,” she signed off.
Meanwhile, the timeless classic will be dubbed in different languages including Tamil and Telugu, owing to which fans will be able to see it in whatever language they prefer.
|
# -*- coding: utf-8 -*-
import types
import AID
try:
import json
except ImportError:
import simplejson as json
class Envelope:
"""
FIPA envelope
"""
def __init__(self, to=None, _from=None, comments=None, aclRepresentation=None, payloadLength=None, payloadEncoding=None, date=None, encrypted=None, intendedReceiver=None, received=None, transportBehaviour=None, userDefinedProperties=None, jsonstring=None):
self.to = list()
if to is not None:
for i in to:
if isinstance(i, AID.aid):
self.to.append(i) # aid
self._from = None
if _from is not None and isinstance(_from, AID.aid):
self._from = _from # aid
if comments is not None:
self.comments = comments # str
else:
self.comments = None
if aclRepresentation is not None:
self.aclRepresentation = aclRepresentation # str
else:
self.aclRepresentation = None
if payloadLength is not None:
self.payloadLength = payloadLength # int
else:
self.payloadLength = None
if payloadEncoding is not None:
self.payloadEncoding = payloadEncoding # str
else:
self.payloadEncoding = None
if date is not None:
self.date = date # list(datetime)
else:
self.date = None
if encrypted is not None:
self.encrypted = encrypted # list(str)
else:
self.encrypted = list()
if intendedReceiver is not None:
self.intendedReceiver = intendedReceiver # list(aid)
else:
self.intendedReceiver = list()
if received is not None:
self.received = received # list(ReceivedObject)
else:
self.received = None
if transportBehaviour is not None:
self.transportBehaviour = transportBehaviour # list(?)
else:
self.transportBehaviour = list()
if userDefinedProperties is not None:
self.userDefinedProperties = userDefinedProperties # list(properties)
else:
self.userDefinedProperties = list()
if jsonstring:
self.loadJSON(jsonstring)
def getTo(self):
return self.to
def addTo(self, to):
self.to.append(to)
self.addIntendedReceiver(to)
def getFrom(self):
return self._from
def setFrom(self, _from):
self._from = _from
def getComments(self):
return self.comments
def setComments(self, comments):
self.comments = comments
def getAclRepresentation(self):
return self.aclRepresentation
def setAclRepresentation(self, acl):
self.aclRepresentation = acl
def getPayloadLength(self):
return self.payloadLength
def setPayloadLength(self, pl):
self.payloadLength = pl
def getPayloadEncoding(self):
return self.payloadEncoding
def setPayloadEncoding(self, pe):
self.payloadEncoding = pe
def getDate(self):
return self.date
def setDate(self, date):
self.date = date
def getEncryted(self):
return self.encrypted
def setEncryted(self, encrypted):
self.encrypted = encrypted
def getIntendedReceiver(self):
return self.intendedReceiver
def addIntendedReceiver(self, intended):
if not intended in self.intendedReceiver:
self.intendedReceiver.append(intended)
def getReceived(self):
return self.received
def setReceived(self, received):
self.received = received
def __str__(self):
return self.asXML()
def asXML(self):
"""
returns a printable version of the envelope in XML
"""
r = '<?xml version="1.0"?>' + "\n"
r = r + "\t\t<envelope> \n"
r = r + '\t\t\t<params index="1">' + "\n"
r = r + "\t\t\t\t<to>\n"
for aid in self.to:
r = r + "\t\t\t\t\t<agent-identifier> \n"
r = r + "\t\t\t\t\t\t<name>" + aid.getName() + "</name> \n"
r = r + "\t\t\t\t\t\t<addresses>\n"
for addr in aid.getAddresses():
r = r + "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
r = r + "\t\t\t\t\t\t</addresses> \n"
r = r + "\t\t\t\t\t</agent-identifier>\n"
r = r + "\t\t\t\t</to> \n"
if self._from:
r = r + "\t\t\t\t<from> \n"
r = r + "\t\t\t\t\t<agent-identifier> \n"
r = r + "\t\t\t\t\t\t<name>" + self._from.getName() + "</name> \n"
r = r + "\t\t\t\t\t\t<addresses>\n"
for addr in self._from.getAddresses():
r = r + "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
r = r + "\t\t\t\t\t\t</addresses> \n"
r = r + "\t\t\t\t\t</agent-identifier> \n"
r = r + "\t\t\t\t</from>\n"
if self.aclRepresentation:
r = r + "\t\t\t\t<acl-representation>" + self.aclRepresentation + "</acl-representation>\n"
if self.payloadLength:
r = r + "\t\t\t\t<payload-length>" + str(self.payloadLength) + "</payload-length>\n"
if self.payloadEncoding:
r = r + "\t\t\t\t<payload-encoding>" + self.payloadEncoding + "</payload-encoding>\n"
if self.date:
r = r + "\t\t\t\t<date>" + str(self.date) + "</date>\n"
if self.intendedReceiver:
r = r + "\t\t\t\t<intended-receiver>\n"
for aid in self.intendedReceiver:
r = r + "\t\t\t\t\t<agent-identifier> \n"
r = r + "\t\t\t\t\t\t<name>" + aid.getName() + "</name> \n"
r = r + "\t\t\t\t\t\t<addresses>\n"
for addr in aid.getAddresses():
r = r + "\t\t\t\t\t\t\t<url>" + addr + "</url>\n"
r = r + "\t\t\t\t\t\t</addresses> \n"
r = r + "\t\t\t\t\t</agent-identifier>\n"
r = r + "\t\t\t\t</intended-receiver> \n"
if self.received:
r = r + "\t\t\t\t<received>\n"
if self.received.getBy():
r = r + '\t\t\t\t\t<received-by value="' + self.received.getBy() + '"/>\n'
if self.received.getDate():
r = r + '\t\t\t\t\t<received-date value="' + str(self.received.getDate()) + '"/>\n'
if self.received.getId():
r = r + '\t\t\t\t\t<received-id value="' + self.received.getId() + '"/>\n'
r = r + "\t\t\t\t</received>\n"
r = r + "\t\t\t</params> \n"
r = r + "\t\t</envelope>\n"
return r
def asJSON(self):
"""
returns a printable version of the envelope in JSON
"""
r = "{"
r = r + '"to":['
for aid in self.to:
r = r + '{'
r = r + '"name":"' + aid.getName() + '",'
r = r + '"addresses":['
for addr in aid.getAddresses():
r = r + '"' + addr + '",'
if r[-1:] == ",": r = r[:-1]
r = r + "]"
r = r + "},"
if r[-1:] == ",": r = r[:-1]
r = r + "],"
if self._from:
r = r + '"from":{'
r = r + '"name":"' + self._from.getName() + '",'
r = r + '"addresses":['
for addr in self._from.getAddresses():
r = r + '"' + addr + '",'
if r[-1:] == ",": r = r[:-1]
r = r + "]},"
if self.aclRepresentation:
r = r + '"acl-representation":"' + self.aclRepresentation + '",'
if self.payloadLength:
r = r + '"payload-length":"' + str(self.payloadLength) + '",'
if self.payloadEncoding:
r = r + '"payload-encoding":"' + self.payloadEncoding + '",'
if self.date:
r = r + '"date":"' + str(self.date) + '",'
if self.intendedReceiver:
r = r + '"intended-receiver":['
for aid in self.intendedReceiver:
r = r + "{"
r = r + '"name":"' + aid.getName() + '",'
r = r + '"addresses":['
for addr in aid.getAddresses():
r = r + '"' + addr + '",'
if r[-1:] == ",": r = r[:-1]
r = r + "],"
if r[-1:] == ",": r = r[:-1]
r = r + "},"
if r[-1:] == ",": r = r[:-1]
r = r + "],"
if self.received:
r = r + '"received":{'
if self.received.getBy():
r = r + '"received-by":"' + self.received.getBy() + '",'
if self.received.getDate():
r = r + '"received-date":"' + str(self.received.getDate()) + '",'
if self.received.getId():
r = r + '"received-id":"' + self.received.getId() + '"'
if r[-1:] == ",": r = r[:-1]
r = r + "}"
if r[-1:] == ",": r = r[:-1]
r = r + "}"
return r
def loadJSON(self, jsonstring):
"""
loads a JSON string in the envelope
"""
r = json.loads(jsonstring)
if "to" in r:
for a in r["to"]:
aid = AID.aid()
aid.setName(a["name"])
for addr in a["addresses"]:
aid.addAddress(addr)
self.addTo(aid)
if "from" in r:
aid = AID.aid()
aid.setName(r["from"]["name"])
for addr in r["from"]["addresses"]:
aid.addAddress(addr)
self.setFrom(aid)
if "acl-representation" in r:
self.setAclRepresentation(r["acl-representation"])
if "payload-length" in r:
self.setPayloadLength(r["payload-length"])
if "payload-encoding" in r:
self.setPayloadEncoding(r["payload-encoding"])
if "date" in r:
self.setDate(r["date"])
if "intended-receiver" in r:
for ag in r["intended-receiver"]:
aid = AID.aid()
aid.setName(ag["name"])
for addr in ag["addresses"]:
aid.addAddress(addr)
self.addIntendedReceiver(aid)
|
New Delhi: In order to promote Make in India initiative, ships built in the country will now get priority in chartering under a new policy, the government said Monday.
Shipping Minister Nitin Gadkari will launch the revised guidelines in this direction on Tuesday.
"In a big step to promote Make in India initiative and incentivise ship-building activity in the country, Ministry of Shipping has revised its guidelines for chartering of ships by providing Right of First Refusal( RoFR) to ships built in India," the shipping ministry said in a statement.
Henceforth, whenever a tendering process is undertaken to charter a vessel, a bidder offering an indigenously-built ship will be given the first priority to match the lowest bidder quote, it said.
The statement said it is expected that the priority given to ships built in India will raise the demand for such vessels, providing them with additional market access and business support.
A policy in this regard will be launched by Gadkari in Mumbai on Tuesday during the inauguration of the two-day Regional Maritime Safety Conference.
Prior to the revision of the guidelines, the RoFR was reserved for Indian flag vessels as per the relevant provisions of Merchant Shipping Act, 1958.
The existing licensing conditions have been reviewed in consonance with India's policy of promoting Make in India initiative, the statement said.
The review is also in line with the need to give a long term strategic boost to the domestic shipbuilding industry.
The shipping ministry has also laid down eligibility conditions and rules for exercise of the RoFR.
One of the rules says: "The RoFR would be exercised only in case the vessel being offered for charter by the lowest bidder has been built outside India."
The government has taken several steps to promote shipbuilding in India, especially by providing long-term subsidy under the Shipbuilding Financial Assistance Policy (2016-2026).
Budgetary provision of Rs 30 crore was earmarked in 2018-19 for providing financial assistance to all Indian shipyards, excluding Defence Shipyards.
An amount of Rs 11.89 crore has already been disbursed to three shipyards.
|
import aiohttp
import asyncio
import discord
import functools
import re
from io import BytesIO
import numpy as np
import os
from PIL import Image
from redbot.core import Config, checks, commands
from redbot.core.utils.chat_formatting import box, pagify
from redbot.core.data_manager import cog_data_path
from wordcloud import WordCloud as WCloud
from wordcloud import ImageColorGenerator
# Special thanks to co-author aikaterna for pressing onward
# with this cog when I had lost motivation!
URL_RE = re.compile(
r"([\w+]+\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#]?[\w-]+)*\/?", flags=re.I
)
# https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
class WordClouds(commands.Cog):
"""Word Clouds"""
def __init__(self, bot):
self.bot = bot
self.session = aiohttp.ClientSession()
self.conf = Config.get_conf(self, identifier=3271169074)
default_guild_settings = {
"bg_color": "black",
"maxwords": 200,
"excluded": [],
"mask": None,
"colormask": False,
}
self.conf.register_guild(**default_guild_settings)
self.mask_folder = str(cog_data_path(raw_name="WordClouds")) + "/masks"
if not os.path.exists(self.mask_folder):
os.mkdir(self.mask_folder)
# Clouds can really just be stored in memory at some point
def cog_unload(self):
self.bot.loop.create_task(self.session.close())
async def red_delete_data_for_user(self, **kwargs):
"""Nothing to delete."""
return
async def _list_masks(self, ctx):
masks = sorted(os.listdir(self.mask_folder))
if len(masks) == 0:
return await ctx.send(
"No masks found. Place masks in the bot's data folder for WordClouds or add one with `{}wcset maskfile`.".format(
ctx.prefix
)
)
msg = "Here are the image masks you have installed:\n"
for mask in masks:
msg += f"{mask}\n"
for page in pagify(msg, delims=["\n"]):
await ctx.send(box(page, lang="ini"))
@commands.guild_only()
@commands.command(name="wordcloud", aliases=["wc"])
@commands.cooldown(1, 15, commands.BucketType.guild)
async def wordcloud(self, ctx, *argv):
"""Generate a wordcloud. Optional arguments are channel, user, and
message limit (capped at 10,000)."""
author = ctx.author
channel = ctx.channel
user = None
limit = 10000
# a bit clunky, see if Red has already implemented converters
channel_converter = commands.TextChannelConverter()
member_converter = commands.MemberConverter()
for arg in argv:
try:
channel = await channel_converter.convert(ctx, arg)
continue
except discord.ext.commands.BadArgument:
pass
try:
user = await member_converter.convert(ctx, arg)
continue
except discord.ext.commands.BadArgument:
pass
if arg.isdecimal() and int(arg) <= 10000:
limit = int(arg)
guild = channel.guild
# Verify that wordcloud requester is not being a sneaky snek
if not channel.permissions_for(author).read_messages or guild != ctx.guild:
await ctx.send("\N{SMIRKING FACE} Nice try.")
return
# Default settings
mask = None
coloring = None
width = 800
height = 600
mode = "RGB"
bg_color = await self.conf.guild(guild).bgcolor()
if bg_color == "clear":
mode += "A"
bg_color = None
max_words = await self.conf.guild(guild).maxwords()
if max_words == 0:
max_words = 200
excluded = await self.conf.guild(guild).excluded()
if not excluded:
excluded = None
mask_name = await self.conf.guild(guild).mask()
if mask_name is not None:
mask_file = f"{self.mask_folder}/{mask_name}"
try:
mask = np.array(Image.open(mask_file))
except FileNotFoundError:
await ctx.send(
"I could not load your mask file. It may "
"have been deleted. `{}wcset clearmask` "
"may resolve this.".format(ctx.prefix)
)
return
if await self.conf.guild(guild).colormask():
coloring = ImageColorGenerator(mask)
kwargs = {
"mask": mask,
"color_func": coloring,
"mode": mode,
"background_color": bg_color,
"max_words": max_words,
"stopwords": excluded,
"width": width,
"height": height,
}
msg = "Generating wordcloud for **" + guild.name + "/" + channel.name
if user is not None:
msg += "/" + user.display_name
msg += "** using the last {} messages. (this might take a while)".format(limit)
await ctx.send(msg)
text = ""
try:
async for message in channel.history(limit=limit):
if not message.author.bot:
if user is None or user == message.author:
text += message.clean_content + " "
text = URL_RE.sub("", text)
except discord.errors.Forbidden:
await ctx.send("Wordcloud creation failed. I can't see that channel!")
return
if not text or text.isspace():
await ctx.send(
"Wordcloud creation failed. I couldn't find "
"any words. You may have entered a very small "
"message limit, or I may not have permission "
"to view message history in that channel."
)
return
task = functools.partial(self.generate, text, **kwargs)
task = self.bot.loop.run_in_executor(None, task)
try:
image = await asyncio.wait_for(task, timeout=45)
except asyncio.TimeoutError:
await ctx.send("Wordcloud creation timed out.")
return
await ctx.send(file=discord.File(image))
@staticmethod
def generate(text, **kwargs):
# Designed to be run in executor to avoid blocking
wc = WCloud(**kwargs)
wc.generate(text)
file = BytesIO()
file.name = "wordcloud.png"
wc.to_file(file)
file.seek(0)
return file
@commands.guild_only()
@commands.group(name="wcset")
@checks.mod_or_permissions(administrator=True)
async def wcset(self, ctx):
"""WordCloud image settings"""
pass
@wcset.command(name="listmask")
async def _wcset_listmask(self, ctx):
"""List image files available for masking"""
await self._list_masks(ctx)
@wcset.command(name="maskfile")
async def _wcset_maskfile(self, ctx, filename: str):
"""Set local image file for masking
- place masks in the cog's data folder/masks/"""
guild = ctx.guild
mask_path = f"{self.mask_folder}/{filename}"
if not os.path.isfile(mask_path):
print(mask_path)
await ctx.send("That's not a valid filename.")
return await self._list_masks(ctx)
await self.conf.guild(guild).mask.set(filename)
await ctx.send("Mask set to {}.".format(filename))
@wcset.command(name="upload")
@checks.is_owner()
async def _wcset_upload(self, ctx, url: str = None):
"""Upload an image mask through Discord"""
user = ctx.author
guild = ctx.guild
attachments = ctx.message.attachments
emoji = ("\N{WHITE HEAVY CHECK MARK}", "\N{CROSS MARK}")
if len(attachments) > 1 or (attachments and url):
await ctx.send("Please add one image at a time.")
return
if attachments:
filename = attachments[0].filename
filepath = f"{self.mask_folder}/{filename}"
try:
await attachments[0].save(filepath)
except:
ctx.send("Saving attachment failed.")
return
elif url:
filename = url.split("/")[-1].replace("%20", "_")
filepath = f"{self.mask_folder}/{filename}"
async with self.session.get(url) as new_image:
# Overwrite file if it exists
f = open(str(filepath), "wb")
f.write(await new_image.read())
f.close()
else:
await ctx.send(
"You must provide either a Discord attachment " "or a direct link to an image"
)
return
msg = await ctx.send(
"Mask {} added. Set as current mask for this server?".format(filename)
)
await msg.add_reaction(emoji[0])
await asyncio.sleep(0.5)
await msg.add_reaction(emoji[1])
def check(r, u):
return u == user and r.message.id == msg.id and r.emoji == emoji[0]
try:
await self.bot.wait_for("reaction_add", timeout=60.0, check=check)
await self.conf.guild(guild).mask.set(filename)
await ctx.send("Mask for this server set to uploaded file.")
except asyncio.TimeoutError:
# Can add an timeout message, but not really necessary
# as clearing the reactions is sufficient feedback
pass
finally:
await msg.clear_reactions()
@wcset.command(name="clearmask")
async def _wcset_clearmask(self, ctx):
"""Clear image file for masking"""
guild = ctx.guild
await self.conf.guild(guild).mask.set(None)
await ctx.send("Mask set to None.")
@wcset.command(name="colormask")
async def _wcset_colormask(self, ctx, on_off: bool = None):
"""Turn color masking on/off"""
guild = ctx.guild
if await self.conf.guild(guild).colormask():
await self.conf.guild(guild).colormask.set(False)
await ctx.send("Color masking turned off.")
else:
await self.conf.guild(guild).colormask.set(True)
await ctx.send("Color masking turned on.")
@wcset.command(name="bgcolor")
async def _wcset_bgcolor(self, ctx, color: str):
"""Set background color. Use 'clear' for transparent."""
# No checks for bad colors yet
guild = ctx.guild
await self.conf.guild(guild).bgcolor.set(color)
await ctx.send("Background color set to {}.".format(color))
@wcset.command(name="maxwords")
async def _wcset_maxwords(self, ctx, count: int):
"""Set maximum number of words to appear in the word cloud
Set to 0 for default (4000)."""
# No checks for bad values yet
guild = ctx.guild
await self.conf.guild(guild).maxwords.set(count)
await ctx.send("Max words set to {}.".format(str(count)))
@wcset.command(name="exclude")
async def _wcset_exclude(self, ctx, word: str):
"""Add a word to the excluded list.
This overrides the default excluded list!"""
guild = ctx.guild
excluded = await self.conf.guild(guild).excluded()
if word in excluded:
await ctx.send("'{}' is already in the excluded words.".format(word))
return
excluded.append(word)
await self.conf.guild(guild).excluded.set(excluded)
await ctx.send("'{}' added to excluded words.".format(word))
@wcset.command(name="clearwords")
async def _wcset_clearwords(self, ctx):
"""Clear the excluded word list.
Default excluded list will be used."""
guild = ctx.guild
await self.conf.guild(guild).excluded.set([])
await ctx.send("Cleared the excluded word list.")
|
Michael Archuleta is a cutting-edge, innovative, visionary leader who possesses strong leadership skills with extensive experience and a proven track record of driving increased levels of productivity, profits, high integrity customer relationship skills & expert problem-solving approaches.
He offers expert skills in team building, working across cross-functional organizations and program management skills. Michael currently serves on the board of directors for The Neural Network, a CXO advisory board facilitated by NetApp, a Healthcare Ambassador for Fujitsu of America & a past Board of Director for Colorado HIMSS Chapter. He is also an active member of CHIME, a cybersecurity advisor to a healthcare startup company & an active speaker in the field of HIT.
The results of this close collaboration between the hospital & ITS can be astonishing: In his current role, Michael oversees all aspects of ITS and has led major organizational transformations. During Michael’s time serving as CIO, he led and designed the first data center while then adding virtualization efforts that reduced costs 56 percent & improved uptime from 59 to 99 percent which increased business productivity, operating efficiencies and enhanced services while reducing operating expenses. This direct collaboration allows the ITS team to innovate pragmatically & remain a leader and disruptor in Health IT.
Under Michael’s guidance and leadership, Mt. San Rafael Hospital became one of the leading community hospitals in Colorado for leveraging advanced technology to enhance the patient and provider experience.
In the healthcare, cyberterrorism can appear in a variety of forms. It can bring down a hospital computer system or publicly reveal private medical records. Whatever shape it takes, the general effects are the same: patient care is compromised, and trust in the health system is diminished.
Evidence suggests that cyber threats are increasing and that much of the U.S. healthcare system is ill equipped to deal with them.
Securing cyberspace is not an easy proposition as the threats are constantly changing, but it’s critical to recognize that cyberterrorism should be part of a broader information technology risk management strategy.
In this session, Michael Archuleta, recently recognized as a Top Hospital and Health System CIO, reviews case studies and the tremendous negative effects a cyber-attack could have on a healthcare organization. It’s scary stuff, but Michael will also share his thoughts on the best practices healthcare organizations can adopt to protect themselves – and their patients – from such attacks.
|
import matplotlib.pyplot as plt
import numpy as np
import time
import pickle
from matplotlib.path import Path
from dirac_sheet import dirac_sheet
def main():
fig = plt.figure()
filename='E:/pyDirac/collimator_output_full_absorb
# make these smaller to increase the resolution
dx = .25
dt = 0.1
Ngrid = int(1802)
X_offset=112.5
# generate 2 2d grids for the x & y bounds
#y, x = np.ogrid[slice(-5, 5 + dy, dy),
# slice(-3, 3 + dx, dx)]
#y, x = np.mgrid[slice((0-round(Ngrid/2))*dy,(Ngrid-round(Ngrid/2))*dy,dy),
# slice((0-round(Ngrid/2))*dx+112.25,(Ngrid-round(Ngrid/2))*dx+112.25,dx)]
plt.ion()
plt.clf()
ax = plt.plot()
# tic = time.time()
myDirac=dirac_sheet(0,901,dt,dx,X_offset,0)
myDirac.set_p(.5,np.pi/4.0)
# x, y = myDirac.get_pos_mat()
# NoPropMat = np.zeros(x.shape,dtype=np.uint8)
# print myDirac.p0
#define part of injector shape
#poly_verts = np.array([[0,37],[70,12.5],[70,1001],[0,1001],[0,37]])
#NoPropMat[inPolygon(poly_verts,x,y)]=1
# mirror across x-axis and make CCW
# poly_verts[:,1]*=-1
# poly_verts[:,1]-=.125
# poly_verts[:,:]=poly_verts[::-1,:]
# NoPropMat[inPolygon(poly_verts,x,y)]=1
# NoPropMat[((x<140.26)&(x>140)&(y>12.5))]=1
# NoPropMat[((x<140.26)&(x>140)&(y<-12.5))]=1
# AbsMat = np.zeros(x.shape)
# AbsMat[x>205]=.99
# AbsMat[(x>70)&(x<141)&(y>40)]=.99
# AbsMat[(x>70)&(x<141)&(y<-40)]=.99
# DriveMat=np.zeros(x.shape)
# DriveMat[(x>0)&(x<1)&(y>-36)&(y<36)]=1
# myDirac.set_No_prop_mat(NoPropMat)
# myDirac.set_Absorb_mat(AbsMat)
# myDirac.set_Drive_mat(DriveMat)
data=np.load(filename)
u1=data['u1']
# u2=data['u2']
v1=data['v1']
# v2=data['v2']
# plt.clf()
#z limits
z_min, z_max = -0.3, 0.3 #np.min(np.real(myDirac.u1)), np.max(np.real(myDirac.u1))
print np.max(np.real((myDirac.u10*np.conj(myDirac.v10))+(myDirac.v10*np.conj(myDirac.u10))).T)
print np.max(np.imag((myDirac.u10*np.conj(myDirac.v10))-(myDirac.v10*np.conj(myDirac.u10))).T)
print myDirac.theta
plt.imshow(np.real(u1),cmap='RdBu', vmin=z_min, vmax=z_max,
#plt.imshow(np.real(v1*np.conj(v1)).T+np.real(u2*np.conj(u2)).T+0*np.real(v1*np.conj(v1)).T+0*np.real(v2*np.conj(v2)).T, cmap='hot', vmin=z_min, vmax=z_max,
#plt.imshow(np.imag((myDirac.u10*np.conj(myDirac.v10))-(myDirac.v10*np.conj(myDirac.u10))).T, cmap='RdBu', vmin=z_min, vmax=z_max,
#plt.imshow(np.real(((u1+u2)*np.conj(v1+v2))+((v1+v2)*np.conj(u1+u2))).T, cmap='RdBu', vmin=z_min, vmax=z_max,
#plt.imshow(np.imag(np.gradient(u2)[1]*(np.conj(u2))-u2*np.gradient(np.conj(u2))[1]).T, cmap='RdBu', vmin=z_min, vmax=z_max,
#extent=[x.min(), x.max(), y.min(), y.max()],
interpolation='nearest', origin='lower')
#plt.quiver(np.imag(np.gradient(u2)[0]*(np.conj(u2))-u2*np.gradient(np.conj(u2))[0]).T,np.imag(np.gradient(u2)[1]*(np.conj(u2))-u2*np.gradient(np.conj(u2))[1]).T)
#plt.title('image (interp. nearest)')
#plt.colorbar()
fig.canvas.draw()
plt.ioff()
# This line was moved up <----
plt.draw()
plt.show()
def inPolygon(poly_verts,x,y):
ss=x.shape
x1, y1 = x.flatten(), y.flatten()
points = np.vstack((x1,y1)).T
path = Path(poly_verts)
grid = path.contains_points(points, radius=.01)
grid = grid.reshape(ss)
return grid
if __name__ == '__main__':
main()
|
Every homeowner wants the best for their home, but they often find themselves in need of professional roofing and plumbing companies for repairs, installation and maintenance. While you can perform a few minor repairs by yourself, there are roofing and plumbing problems that only skilled contractors can do.
If you want to plan in advance, you can get the job done with no hassle if you choose your roofing and plumbing company well. Here are some questions you should ask before hiring one.
What’s Your Complete Company Name And Business Address?
Don’t forget to ask for the roofing company’s full name and address. By doing this, you’ll be able to check whether they are a legitimate roofing contractor or not. For example, you might doubt they are legitimate if a roofing company doesn’t have a physical business address. Try to see whether they are located in your area. That way, you can visit the place to ensure that they are an authentic roofing provider.
Of course, roofing work is considered a tough job, which is why only skilled and professional roofers can perform the task flawlessly. Inquire whether the roofing contractors carry workman’s compensation and liability insurance. The rationale of this is that you want to make sure that in the event of an accident, you will not be liable for any injuries. It’s important to remember that without insurance coverage, you may be held responsible for the medical bills and other associated costs if a roofing company’s employee is injured while doing the work.
Be firm in asking whether the roofing company works with subcontractors. If they do, you should ask a follow-up question regarding their insurance coverage. Doing so will give you peace of mind that all people working on your roofing are insured from the moment they start.
Are You A Licensed Roofing Company?
It’s essential to ask whether your potential roofing company is licensed or not. While licensing requirements vary from one state to the other, you should still verify that they have the license that is required in the place where you reside. If it’s needed, you may ask help from the local licensing offices to look for companies that are licensed to do roofing works. Furthermore, make sure that the license is up-to-date and not expired.
Do You Provide Warranties On Your Roofing Services?
If you want to make the most out of the money you spend on roofing work, don’t hesitate to ask the roofing company what warranty they can offer you. Check how long they can guarantee their work. Also, make sure you understand the coverage and the length of the warranty they’re giving you.
Do You Have A Plumbing Contractor License?
Like other types of contractors, a plumbing company may also require a license. Remember, a licensed plumbing contractor means that the business is registered with the government and authorized to perform plumbing works in the area or region. Always ask about this at the beginning of your conversation. Don’t ever forget to open up this topic. This info will play a big part in your decision in hiring the best plumbing company.
Asking about the charges can help you in hiring a plumbing company. You can inquire whether they provide free estimates to their customers. Once you have received a quotation from them, be wary of the estimated costs they offer you. Check whether the materials, labor and even contingency fees are included or not. When it comes to labor costs, be wary on the computation. Clarify if they will be paid hourly or with a flat amount. Be cautious with these topics as they can impact your financial health in the run. Make sure that what you’ll be paying for will be a good job.
Who Will Do The Plumbing Works?
Try to be particular with the people who will be working on your plumbing tasks. Check whether the company you’re dealing with will be the one doing the job or if they will hire subcontractors to do the work. Once you have asked this question, the next thing to do is verify the qualifications of the workers who will be assigned to perform the work for you. Lastly, don’t forget to ask about their insurance coverage, so you’re protected the moment there’s an accident.
Do You Provide Cleanup After The Completion Of Work?
Try to be clear in asking about the cleanup services provided for by the plumbing company. Verify whether it’s already included in the quotation or if you’re going to pay an additional amount for it. Remember, discussions about cleanup are essential when completing a job.
While hiring a roofing and plumbing company can be a challenging task, applying and asking these key questions can help you get someone who is honest, professional, and trustworthy. Finding a quality contractor like Crockett Home Improvement to carefully handle your roofing and plumbing tasks will be much easier if you follow the guidelines presented in this article. In the end, don’t ever hire someone who may leave you with a poor and unfinished project.
|
# Problem Set 2 - Problem 3
# Author: Felipo Soranz
# Time: ~ 30 Minutes
# For the Diophantine equation (i.e. a, b, c, n are all positive integers):
# a * 6 + b * 9 + c * 20 = n
# Try to find the larges possible value for n where the equation is false
count_possibles = 0
max_impossible = 0
for i in range(1,150):
c = 0
impossible = True
while c * 20 <= i and impossible:
b = 0
while b * 9 <= i and impossible:
a = 0
while a * 6 <= i and impossible:
total = a * 6 + b * 9 + c * 20
if total == i:
impossible = False
a += 1
b += 1
c += 1
if impossible:
max_impossible = i
count_possibles = 0
else:
count_possibles += 1
# After 6 possible consecutive solutions,
# the equation is always solvable, since x + 5 + 1 = x + 6
# Ex: x = 50, x + 5 = 55, x + 6 = x + 5 + 1 = 56
if count_possibles == 6:
break
print("Largest number of McNuggest that cannot be bought in exact quantity:",
max_impossible)
|
A big thanks to our 250 volunteers, including 40 school children from the Sunshine Academy who – deployed as 15 garbage busting teams, throughly sweeped the Tada stream and removed 2 full tractor loads of garbage and got a public commitment from the AP Chief Conservator of Forests in front of the local media to make Tada a zero-plastic and alcohol freezone. The CCF and other forest officials greatly appreciated our initiative and invited us to organize a similar environmental awareness event in their home-base Tirupati in the near future.
Tada could be considered as the birthplace of CTC – it’s the place where we did many of our initial treks, got our initial exposure to beautiful, untouched nature, it’s the place were we first left the known trail and climbed into the mountains above to explore the unexplored which has become the signature of CTC’s treks. Tada is part of the Nagalapuram range which is CTC’s 2nd home and has given us so much over the past years. It was highly time for us to return something back to this troubled spot – it was time to expose, create awareness and preserve. We will not rest until the place we love so much is protected from any unwanted pollution and anti-social elements and preserved for future generations. As someone truly said it – we are not inheriting the nature and forests from our parents, we are borrowing it from our children.
A big thanks to many, many volunteers who contributed to the organization and coordination of the event including Neetha, Thilak, Zeba, Ela, the assembly point coordinators – Balaji, Hari, Rajnith, Neetha, Sudhir, Thilak, Biju, Anand, to all the team leads – Alex, Karmu, Meena, Manoj, Ranjith, Balaji, Prital, Ravi, Bala, Hari, Biju, Arul, Marie, Ansar, Sudir, to all our photographers – Karthik, Hari, Lokesh, Nikil, Vishnu, Aswin, Vishnu, Jagadish, Shyam, Samudhiram and videographers Ram, Ramesh, Ramanujam.
A big thanks to Aravind with his Ham Radio team to provide us with an essential communication backbone during the cleanup operation, to Sailaja, Kirubha, Ramya and Nitya for coordinating the distribution of garbage bags, snacks and gloves, to Arul, Thilak and other warriors (forgot the names) to walk back all the way to the parking under the hot son and supplied the volunteers with lunch deep inside the forest, to Javed and Guru for managing the parking logistics.
A big thanks to the many other volunteers whose name I might not recollect but whose faces I will always remember.
A big thanks to our sponsor SriCity (www.sricity.in) – Vishman, Reshma, Arthi and many, many others who arranged yummy breakfast for us, tasty biryani and curd rice, gifted us with beautiful t-shirts and provided significant visibility to our awareness campaign through posters, banners, media and forest officials. All breakfast and lunch plates/packings provided were eco-friendly.
A big thanks to our long-time sponsor BioTec (www.biotec.com) who provided us with proper bio-degradable garbage bags. Thank you Shankker for your ongoing support to our preservation campaigns.
This is a great job and project done.There should be more efforts to try to save the nature from further deterioration.
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) Toto Azéro, 2011-2015
#
# Distribué sous licence GNU GPLv3
# Distributed under the terms of the GNU GPLv3 license
# http://www.gnu.org/licenses/gpl.html
#
import pywikibot, ip
from pywikibot import pagegenerators
import os, datetime, shutil, locale, codecs
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
site = pywikibot.Site()
#lesMois = {
#1 : u"janvier",
#2 : u"février",
#3 : u"mars",
#4 : u"avril",
#5 : u"mai",
#6 : u"juin",
#7 : u"juillet",
#8 : u"août",
#9 : u"septembre",
#10 : u"octobre",
#11 : u"novembre",
#12 : u"décembre"
#}
dateDuJour = datetime.date.today()
## Date d'il y a un an et un jour
dateFichierDuJour = dateDuJour + datetime.timedelta(days=-366)
#annee = int(dateFichierDuJour.strftime("%Y"))
#mois = int(dateFichierDuJour.strftime("%B"))
#jour = int(dateFichierDuJour.strftime("%d"))
cwd = os.getcwd()
os.chdir('/data/project/totoazero/pywikibot')
nomFichierDuJour = u"Dates messages IP/%s/%i" % (dateFichierDuJour.strftime("%Y/%m").decode('utf-8'), int(dateFichierDuJour.strftime('%d')))
if nomFichierDuJour[-1] == 1:
nomFichierDuJour += u"er"
## Copie du fichier pour être sûr de ne pas le perdre
## en ne traitant pas l'original
#nomFichierSauvegarde = u"%s - sauvegarde" % nomFichierDuJour
#os.chdir('/home/totoazero/')
#shutil.copy(nomFichierDuJour, nomFichierSauvegarde)
fichierDuJour = codecs.open(nomFichierDuJour, 'r')
listeIP = fichierDuJour.read().split()
fichierDuJour.close()
os.chdir(cwd)
listePdDIP = []
for num_ip in listeIP:
listePdDIP.append(pywikibot.Page(site, u"Discussion utilisateur:%s" % num_ip))
#print listePdDIP
pywikibot.output(u"Nombre de pages à traiter : %i" % len(listePdDIP))
gen = pagegenerators.PreloadingGenerator(listePdDIP)
IPBot = ip.IPBot(gen, False)
IPBot.run()
|
Alma Mary Speck was the daughter of Frank Speck and Elisabeth Linneman Speck and would have been the younger sister of my grandmother, Agnes Speck. Alma was born in Monessen, Pennsylvania and died just one day later. The cause of death was “premature infant” and she was buried that same day at Grandview Cemetery in Monessen.
I never knew of Alma until the Pennsylvania death certificates from 1906-1964 were made available on Ancestry.com. As most of us did when these records were released, I searched for surnames of family that had lived in Pennsylvania to see if I could find death certificates for collateral relatives or ancestors whose date of death was unknown. Through these searches I have found several children that died young between census years, and had no other records of their short lives.
I asked my father about Alma and he was not aware that Frank and Elizabeth had another child. We visited Grandview Cemetery in 2007 and found the tombstone for Alma’s father, Frank Speck, but did not see anything for Alma. She man have been buried in another location or did not have a headstone.
Besides finding another ancestor, I was able to learn a few more things about the Speck family from this record. They were living at 223 Alliquipa Street at the time of her death.
In addition, the name Alma Mary may provide some clues for family names. Their other children seem to have been named after family members … Agnes(Frank’s mother) Elizabeth (Elizabeth and her mother Elizabeth Barbara) and Frank (Frank) Rudolph(Elizabeth’s two brothers who died as children). I know the names of Elizabeth’s siblings and parents, so Mary may be from her side (Maria was Elizabeth’s middle name and her grandmother’s name). Alma could possibly be from Frank’s side of the family, as I do not know much about his family or where they were from in Germany. Maybe Alma was Frank’s sister or grandmother?? Another possible clue to add to the mysterious Speck family.
Pennsylvania, Pennsylvania Death Certificates, 1906-1963, No. 73103, Alma Mary Speck, 1 July 1916; digital image, Ancestry.com (http://www.ancestry.com : accessed 30 March 2015); citing Pennsylvania (state). Death certificates, 1906-1963. Series 11.90 (1,905 cartons). Records of the Pennsylvania Department of Health, Record Group 11. Pennsylvania Historical and Museum Commission, Harrisburg, Pennsylvania.
|
#!/usr/bin/env python
"""
@package nilib
@file niforward.py
@brief CL-independent NetInf routing module
@version Copyright (C) 2013 SICS Swedish ICT AB
This is an adjunct to the NI URI library developed as
part of the SAIL project. (http://sail-project.eu)
Specification(s) - note, versions may change
- http://tools.ietf.org/html/draft-farrell-decade-ni-10
- http://tools.ietf.org/html/draft-hallambaker-decade-ni-params-03
- http://tools.ietf.org/html/draft-kutscher-icnrg-netinf-proto-00
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.
===========================================================================
@code
Revision History
================
Version Date Author Notes
0.1 08/11/2013 Bengt Ahlgren Implemented default route as a start
@endcode
"""
#==============================================================================#
#=== Standard modules for Python 2.[567].x distributions ===
import os
import stat
import sys
import socket
import threading
#import itertools
import logging
#import shutil
import json
import random
import tempfile
#import re
#import time
#import datetime
#import textwrap
# try:
# from cStringIO import StringIO
# except ImportError:
# from StringIO import StringIO
# import cgi
import urllib
import urllib2
# import hashlib
# import xml.etree.ElementTree as ET
# import base64
import email.parser
import email.message
# import magic
# import DNS
# import qrcode
#=== Local package modules ===
from netinf_ver import NETINF_VER, NISERVER_VER
from ni import NIname, NIdigester, NIproc, NI_SCHEME, NIH_SCHEME, ni_errs, ni_errs_txt
from metadata import NetInfMetaData
DEBUG = True
def dprint(who, string):
"""
@brief Debug print function
"""
if DEBUG:
print "DEBUG({}): {}".format(who, string)
return
#==============================================================================#
# CONSTANTS
# Enumerate convergence layers (CLs) - used for NextHop.cl_type
NICLHTTP = 1
#NICLDTN = 2
#NICLUDP = 3
# Enumerate router features - used in set NetInfRouterCore.features
NIFWDNAME = 1 # ni-name-based forwarding
NIFWDLOOKUPHINTS = 2 # perform additional routing hint lookup
NIFWDHINT = 3 # hint-based forwarding
NIFWDDEFAULT = 4 # default forwarding
#==============================================================================#
# CLASSES
class NextHop:
"""
@brief Class for one nexthop entry
"""
def __init__(self, cl_type, nexthop_address):
self.cl_type = cl_type
self.cl_address = nexthop_address
# May want other info here, for example, pointers to methods
# for queuing a message for output, or a pointer to a CL class
# that has methods for the CL
return
class NextHopTable(dict):
"""
@brief Class for a table with nexthops, mapping an index to a nexthop entry
"""
# Choosing the dictionary type for now - may not be the best wrt
# performance? convert to list?
def __setitem__(self, index, entry):
"""
@brief add an entry to the nexthop table
@param index integer index of the entry to add
@param entry NextHop next hop entry to add
@return (none)
"""
if not isinstance(index, int):
raise TypeError("'index' needs to be of type 'int'")
if not isinstance(entry, NextHop):
raise TypeError("'entry' needs to be of type 'NextHop'")
if index in self:
dprint("NextHopTable.__setitem__", "Overwriting index {}".format(index))
dict.__setitem__(self, index, entry)
return
# Note: the type of a routing hint is assumed to be an ascii string
# There might be reasons to change to integer for the lookup in the
# forwarding table, but for now it seems simplest to just use the
# ASCII string from the GET message directly without any conversion
class HintForwardTable(dict):
"""
@brief Class for a routing hint forwarding table
"""
def __setitem__(self, hint, nexthop_index):
"""
@brief add a forwarding entry
@param hint string the routing hint to add
@param nexthop_index integer the index of the next hop to use
@return (none)
"""
if not isinstance(hint, str):
raise TypeError("'hint' needs to be of type 'str'")
if not isinstance(nexthop_index, int):
raise TypeError("'nexthop_index' needs to be of type 'int'")
if hint in self:
dprint("HintForwardTable.__setitem__",
"Overwriting entry for hint {}".format(str(hint)))
dict.__setitem__(self, hint, nexthop_index)
return
class NetInfRouterCore:
def __init__(self, config, logger, features):
self.logger = logger
self.features = features # Set of features
# Initialise next hop table and default
# TODO: get info from config instead of letting parent set things up
self.nh_table = NextHopTable()
self.nh_default = -1
return
# These lookup functions could instead for flexibility be
# implemented as part of separate classes that are configured as
# some sort of plug-ins.
def do_name_forward_lookup(self, message, meta, incoming_handle):
return [] # XXX
def do_lookup_hints(self, message, meta, incoming_handle):
pass # XXX
def do_hint_forward_lookup(self, message, meta, incoming_handle):
return [] # XXX
# This method has the main forwarding logic
def do_forward_nexthop(self, msgid, uri, ext, incoming_handle = None):
"""
@brief perform forwarding functions to select next hop(s) for the
@brief message and call CL to forward to the selected next hop(s)
@param msgid str message id of NetInf message
@param uri str uri format ni name for NDO
@param ext str ext field of NetInf message
@param incoming_handle object XXX - handle to the connection
@param receiving the message
@return bool success status
@return object the response to the message - to be returned to
@return the source of the message
"""
next_hops = []
# XXX - all but NIFWDDEFAULT very sketchy...
if NIFWDNAME in self.features: # if ni-name forwarding
next_hops = self.do_name_forward_lookup(uri, ext, incoming_handle)
# XXX - should extract hints from ext, and then add possible new hints
if (next_hops == []) and (NIFWDLOOKUPHINTS in self.features):
# can do_lookup_hints just add hints to the meta
# variable??? or should it add to the message itself (ext
# parameter)???
self.do_lookup_hints(uri, ext, incoming_handle)
if (next_hops == []) and (NIFWDHINT in self.features):
next_hops = self.do_hint_forward(uri, ext, incoming_handle)
if (next_hops == []) and (NIFWDDEFAULT in self.features):
if self.nh_default != -1:
next_hops = [ self.nh_table[self.nh_default] ]
if next_hops != []:
# we have some next hops - call appropriate CL to send
# outgoing message; need to go through some next hop
# structure that is initialised by niserver at startup
status, metadata, filename = do_get_fwd(self.logger, next_hops,
uri, ext)
return status, metadata, filename
else:
return False, None
#--------------------------------------------------------------------------#
# copied and adapted from nifwd.py. / bengta
#
# the actual forwarding should be independent from how the next hops
# are computed so that different schemes can be accomodated.
#
# TODO (later...):
# - next-hop state to reuse existing next-hop connection
# - composing and sending a message should be extracted to another
# library function (common to other code), also the router code
# needs some sort of output queues
#
def do_get_fwd(logger,nexthops,uri,ext):
"""
@brief fwd a request and wait for a response (with timeout)
@param nexthops list a list with next hops to try forwarding to
@param uri str the ni name from the GET message
@param ext str the ext field from the GET message
@return 3-tuple (bool - True if successful,
NetInfMetaData instance with object metadata
str - filename of file with NDO content)
"""
logger.info("Inside do_fwd");
metadata=None
fname=""
for nexthop in nexthops:
# send form along
logger.info("checking via %s" % nexthop.cl_address)
# Only http CL for now...
if nexthop.cl_type != NICLHTTP:
continue
# Generate NetInf form access URL
http_url = "http://%s/netinfproto/get" % nexthop.cl_address
try:
# Set up HTTP form data for get request
new_msgid = random.randint(1, 32000) # need new msgid!
form_data = urllib.urlencode({ "URI": uri,
"msgid": new_msgid,
"ext": ext})
except Exception, e:
logger.info("do_get_fwd: to %s form encoding exception: %s"
% (nexthop.cl_address,str(e)));
continue
# Send POST request to destination server
try:
# Set up HTTP form data for netinf fwd'd get request
http_object = urllib2.urlopen(http_url, form_data, 30)
except Exception, e:
logger.info("do_fwd: to %s http POST exception: %s" %
(nexthop.cl_address,str(e)));
continue
# Get HTTP result code
http_result = http_object.getcode()
# Get message headers - an instance of email.Message
http_info = http_object.info()
obj_length_str = http_info.getheader("Content-Length")
if (obj_length_str != None):
obj_length = int(obj_length_str)
else:
obj_length = None
# Read results into buffer
# Would be good to try and do this better...
# if the object is large we will run into problems here
payload = http_object.read()
http_object.close()
# The results may be either:
# - a single application/json MIME item carrying metadata of object
# - a two part multipart/mixed object with metadats and the content (of whatever type)
# Parse the MIME object
# Verify length and digest if HTTP result code was 200 - Success
if (http_result != 200):
logger.info("do_fwd: weird http status code %d" % http_result)
continue
if ((obj_length != None) and (len(payload) != obj_length)):
logger.info("do_fwd: weird lengths payload=%d and obj=%d" %
(len(payload),obj_length))
continue
buf_ct = "Content-Type: %s\r\n\r\n" % http_object.headers["content-type"]
buf = buf_ct + payload
msg = email.parser.Parser().parsestr(buf)
parts = msg.get_payload()
if msg.is_multipart():
if len(parts) != 2:
logger.info("do_fwd: funny number of parts: %d" % len(parts))
continue
json_msg = parts[0]
ct_msg = parts[1]
try:
temp_fd,fname=tempfile.mkstemp();
f = os.fdopen(temp_fd, "w")
f.write(ct_msg.get_payload())
f.close()
except Exception,e:
logger.info("do_fwd: file crap: %s" % str(e))
return True,metadata,fname
else:
json_msg = msg
ct_msg = None
# Extract JSON values from message
# Check the message is a application/json
if json_msg.get("Content-type") != "application/json":
logger.info("do_fwd: weird content type: %s" %
json_msg.get("Content-type"))
continue
# Extract the JSON structure
try:
json_report = json.loads(json_msg.get_payload())
except Exception, e:
logger.info("do_fwd: can't decode json: %s" % str(e));
continue
curi=NIname(uri)
curi.validate_ni_url()
metadata = NetInfMetaData(curi.get_canonical_ni_url())
logger.info("Metadata I got: %s" % str(json_report))
metadata.insert_resp_metadata(json_report) # will do json.loads again...
# removed GET_RES handling present in do_get_fwd in nifwd.py / bengta
# all good break out of loop
break
# make up stuff to return
# print "do_fwd: success"
if metadata is None:
return False, metadata, fname
return True,metadata,fname
#----------------------------------------------------------------------
#
# main program for testing
if __name__ == "__main__":
print len(sys.argv)
if len(sys.argv) > 1:
print int(sys.argv[1])
# well, doesn't do anything...
|
While a lot of drugs endeavor to restore hormone harmony, the scientific and medical communities have started looking into how natural solutions like turmeric may benefit hormone regulation without the need of synthetics. Moreover, these studies also found that men who took inflammation-reducing medicines or adopted dietary patterns that had been less likely to advertise inflammation are at lower risk of prostate cancer.
Over the long-term, anything at all that has a laxative effect interferes with the body`s natural elimination processes, causes dehydration, electrolyte imbalance and mal-absorption of vitamins and minerals. Osteoarthritis steadily develops about several several years and in the beginning is not always painful, while in the later on stages when the cartilage has disintegrated, inflammation sets in and muscle spasms may perhaps take place.
Curcumin, found in Turmeric, scavenges and neutralizes the different forms of free radicals, reduces oxidative stress and boosts the body`s individual antioxidant capacity with schedule dietary intake. Scott Haig, in which a affected person with serious hip problems and in will need of hip replacement medical procedures eschewed traditional pain relievers totally and managed his pain with turmeric. Researchers have analyzed and verified that aspects these types of as afterwards - stage perimenopause, sleep disruption, COGNITUNE current stress, and the existence of sizzling flashes are relevant to the depressive symptoms.
Again, we refer to turmeric curcumin`s anti - oxidant and anti - inflammatory properties in preventing and even reversing age - relevant degenerative diseases, which includes people affecting the eyes. Turmeric and depression have not been researched on a long - term basis, but in week trials, participants demonstrated improved symptoms when taking turmeric alongside their antidepressant, Majumdar states.
Studies have shown that, when compared to a placebo group, those people who included turmeric in their diet observed a sizeable reduction in physical, behavioral, and emotional premenstrual symptoms. In a single study, patients who were being going through coronary artery bypass surgical treatment were being randomized to either placebo or grams of curcumin for every day, a handful of days ahead of and right after the surgical procedures. Choosing the appropriate turmeric or curcumin supplement can get complicated because of complications including quality regulate issues and nebulous terminology such as turmeric curcumin supplements.
When these radicals sign up for with LDL negative cholesterol particles through oxidation, the LDL particles turn into more virulent and can conveniently penetrate the artery-cell and accumulate there. In addition to common side effects like abnormal bleeding and hemorrhage, the risks associated with anticoagulants abound and include everything from again pain to headaches to trouble respiratory. Since turmeric is understood to scale back again ache and discomfort, it`s not surprising that it`s commonly made use of as a complementary cure for every single osteoarthritis and rheumatoid arthritis.
Curcumin is not easily absorbed into the blood stream, so generating it challenging for its anti - inflammatory properties to be effective on inflammation that happens outside the digestive system. Eight months soon after she began taking the supplements, a blood take a look at unveiled that she experienced elevated levels of liver enzymes, which usually advise that there`s a problem with the liver.
Oftentimes, people with digestive and stomach issues develop into intolerant to medical interventions because the stomach flora is by now compromised, and drugs can practically tear up the mucosal lining. A handful of months in the past, I go through an article that concentrated on the herbal therapies for osteo arthritis and gouty arthritis that relieve joint areas having difficulties and distress.
|
from django.test import TestCase
from django.conf import settings
from location_field.apps import DefaultConfig
from tests.models import Place
from tests.forms import LocationForm
from pyquery import PyQuery as pq
import json
import location_field
class LocationFieldTest(TestCase):
def test_plain(self):
vals = {
'city': 'Bauru',
'location': '-22.2878573,-49.0905487',
}
obj = Place.objects.create(**vals)
self.assertEqual(obj.city, 'Bauru')
self.assertEqual(obj.location, '-22.2878573,-49.0905487')
def test_settings(self):
with self.settings(LOCATION_FIELD={'map.provider': 'foobar'}):
app_config = DefaultConfig('location_field', location_field)
app_config.patch_settings()
self.assertEqual(settings.LOCATION_FIELD.get('map.provider'),
'foobar')
def test_field_options(self):
form = LocationForm(initial={})
d = pq(str(form))
opts = json.loads(d('[data-location-field-options]').attr(
'data-location-field-options'))
location_field_opts = settings.LOCATION_FIELD
for key, value in location_field_opts.items():
self.assertEqual(value, opts[key])
def test_custom_resources(self):
form = LocationForm(initial={})
self.assertIn('form.js', str(form.media))
with self.settings(LOCATION_FIELD={
'resources.media': {'js': ['foo.js', 'bar.js']}}):
self.assertIn('foo.js', str(form.media))
self.assertIn('bar.js', str(form.media))
if settings.TEST_SPATIAL:
from . import spatial_test
|
A quality Terra Alta AC Repair AC contractor is able to install, repair and maintain a wide variety of systems, such as ductless mini splits, package units, water source heat pumps, split systems and VRV mini split multi systems. They should also have the ability to perform various types of work on a home's HVAC system, such as preventative maintenance that helps the system remain energy efficient, repairing or replacing duct work, cleaning and sanitizing ducts and installing new thermostats.
This will depend on a variety of factors. Homeowners need to consider how old their current system is and what condition it currently is in, plus the nature of the repairs to be performed. Other factors to keep in consideration is how long one is planning to stay in their current home, how energy efficient the current system is and what their budget is. An honest AC contractor in Terra Alta AC Repair will be happy to help the homeowner decide whether it would be better to have an existing system repaired or to simply replace it with a new one.
A central AC system distributes air through a system of ducts in the home. Ducts that are leaky will decrease the system's overall efficiency, causing wasted electricity. When a central air conditioning system is being replaced, it is recommended that the ducts be inspected to determine if cleaning or repairs are needed. Call our contractors in Terra Alta AC Repair today to get a quote for your AC repair.
|
# -*- coding: utf-8 -*-
"""This tries to do more or less the same thing as CutyCapt, but as a
python module.
This is a derived work from CutyCapt: http://cutycapt.sourceforge.net/
////////////////////////////////////////////////////////////////////
//
// CutyCapt - A Qt WebKit Web Page Rendering Capture Utility
//
// Copyright (C) 2003-2010 Bjoern Hoehrmann <bjoern@hoehrmann.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// $Id$
//
////////////////////////////////////////////////////////////////////
"""
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
class Capturer(object):
"""A class to capture webpages as images"""
def __init__(self, url, filename):
self.url = url
self.filename = filename
self.saw_initial_layout = False
self.saw_document_complete = False
def loadFinishedSlot(self):
self.saw_document_complete = True
if self.saw_initial_layout and self.saw_document_complete:
self.doCapture()
def initialLayoutSlot(self):
self.saw_initial_layout = True
if self.saw_initial_layout and self.saw_document_complete:
self.doCapture()
def capture(self):
"""Captures url as an image to the file specified"""
self.wb = QtWebKit.QWebPage()
self.wb.mainFrame().setScrollBarPolicy(
QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff)
self.wb.mainFrame().setScrollBarPolicy(
QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff)
self.wb.loadFinished.connect(self.loadFinishedSlot)
self.wb.mainFrame().initialLayoutCompleted.connect(
self.initialLayoutSlot)
self.wb.mainFrame().load(QtCore.QUrl(self.url))
def doCapture(self):
#print "Capturando"
self.wb.setViewportSize(self.wb.mainFrame().contentsSize())
img = QtGui.QImage(self.wb.viewportSize(), QtGui.QImage.Format_ARGB32)
#print self.wb.viewportSize()
painter = QtGui.QPainter(img)
self.wb.mainFrame().render(painter)
painter.end()
img.save(self.filename)
QtCore.QCoreApplication.instance().quit()
if __name__ == "__main__":
"""Run a simple capture"""
print sys.argv
app = QtGui.QApplication(sys.argv)
c = Capturer(sys.argv[1], sys.argv[2])
c.capture()
app.exec_()
|
I have never been to Piers Point. I would love to go. I won't be there for this event this year. But maybe next year.
Would love to hear if anyone goes and how it turns out.
I have to say I enjoyed the evening we spent down in Enderby a couple of years ago.
|
#!/usr/bin/env python
# Description = RNA related CDD domain
import re
class RnaRelatedCDDSelection(object):
'''classification of data'''
def __init__(self, keywords_file,
cdd_whole_data_file,
interpro_mapped_cdd,
domain_data_path):
self._keywords_file = keywords_file
self._cdd_whole_data_file = cdd_whole_data_file
self._interpro_mapped_cdd = interpro_mapped_cdd
self._domain_data_path = domain_data_path
self.cdd_whole_data_list = []
self._cdd_dict = {}
self._mapped_cdd_members = {}
def select_cdd_domains(self):
''''''
self.read_keyword_file()
self.read_interpro_mapped_cdd_file()
self.read_cdd_whole_data_file()
self.create_rna_related_domain_file()
def read_keyword_file(self):
'''reads keywords for domain selection'''
self._keyword_list = [rna_keyword.strip()
for rna_keyword in open(
self._keywords_file, 'r')]
return self._keyword_list
def read_interpro_mapped_cdd_file(self):
'''Parses interpro cdd mapped file to extract common information'''
with open(self._interpro_mapped_cdd, 'r') as in_fh:
for entry in in_fh:
ipr_id = entry.strip().split('\t')[0]
ipr_members = entry.strip().split('\t')[1]
cdd_id = entry.strip().split('\t')[2]
cdd_member = entry.strip().split('\t')[3]
domain_length = entry.strip().split('\t')[4]
self._mapped_cdd_members[cdd_member] = ipr_members
self._mapped_cdd_members
def read_cdd_whole_data_file(self):
'''Parses CDD annotation data from table'''
with open(self._cdd_whole_data_file, 'r') as cdd_data_fh:
for cdd_entry in cdd_data_fh:
if 'smart' in cdd_entry.split('\t')[1]:
cdd_entry = cdd_entry.replace(
cdd_entry.split('\t')[1], 'SM'+cdd_entry.split(
'\t')[1].split('smart')[-1])
elif 'pfam' in cdd_entry.split('\t')[1]:
cdd_entry = cdd_entry.replace(
cdd_entry.split('\t')[1], 'PF'+cdd_entry.split(
'\t')[1].split('pfam')[-1])
cdd_domain = cdd_entry.split('\t')[1]
if cdd_domain in self._mapped_cdd_members.keys():
members = self._mapped_cdd_members[cdd_domain]
else:
members = 'NA'
self.cdd_whole_data_list.append(
cdd_entry.strip())
self._cdd_dict[cdd_entry.strip()] = cdd_entry.strip(
).split('\t')[3]
return self.cdd_whole_data_list, self._cdd_dict
def create_rna_related_domain_file(self):
'''Creates RNA related domain list'''
self._keyword_annotation_dict = {}
self._rna_related_domain = []
for cdd_entry in self.cdd_whole_data_list:
for keyword in self._keyword_list:
if ' ' in keyword:
key_list = []
for each_key in keyword.split(' '):
key_list.append(each_key)
match = re.search(r'\b%s*|\W%s\b'%(key_list[0].lower(),
key_list[1].lower()),
self._cdd_dict[cdd_entry])
if match:
self._keyword_annotation_dict.setdefault(
keyword, []).append(cdd_entry)
else:
match = re.search(r'\b%s\b'%keyword, self._cdd_dict[cdd_entry])
if match:
self._keyword_annotation_dict.setdefault(
keyword, []).append(cdd_entry)
for fkeyword in self._keyword_list:
fkeyword = fkeyword.replace(' ', '_')
with open(self._domain_data_path+'/'+fkeyword+'_related_cdd_ids.tab',
'w') as keyword_specific_domain:
if self._keyword_annotation_dict.get(fkeyword):
for each_entry in self._keyword_annotation_dict[fkeyword]:
each_entry = each_entry.replace(
each_entry.split('\t')[3], " ".join(
each_entry.split('\t')[3].split())).replace(';', ',')
cdd_domain = each_entry.split('\t')[1]
if cdd_domain in set(self._mapped_cdd_members.keys()):
members = self._mapped_cdd_members[cdd_domain]
else:
members = 'NA'
keyword_specific_domain.write('%s\t%s\t%s\n'%(
'\t'.join(each_entry.split('\t')[0:-1]), members,
each_entry.split('\t')[-1]))
self._rna_related_domain.append(('%s\t%s\t%s'%(
'\t'.join(each_entry.split('\t')[0:-1]), members,
each_entry.split('\t')[-1])))
uniq_rna_related_domains = list(set(self._rna_related_domain))
with open(self._domain_data_path+'/all_rna_related_cdd_data.tab',
'w') as rna_related_domain_file:
for domain_entry in uniq_rna_related_domains:
rna_related_domain_file.write('%s\n'%str(domain_entry))
|
The Illinois Supreme Court restored Rahm Emanuel’s name to Chicago’s mayoral ballot, at least for now.
CHICAGO — The Illinois Supreme Court puffed life back into Rahm Emanuel’s mayoral campaign on Tuesday when it restored his name to the city’s ballots, at least for now, and agreed to decide whether he should be allowed to run for mayor.
The decisions arrived at a dizzying pace, only a day after a panel of the Illinois Appellate Court had ordered Mr. Emanuel’s name stricken from the ballot, saying his time in Washington as White House chief of staff meant that he failed to meet a requirement of residing in Chicago for a year before the Feb. 22 election.
The Supreme Court’s orders were seen as a positive sign for Mr. Emanuel (the court could have chosen to skip the case altogether), but the justices still have to consider the merits of the case itself, and so Chicago — already suffering from political whiplash — will have to wait a bit more.
The Supreme Court will study briefs already submitted to the lower court, rather than wait for new ones, and will entertain no oral arguments. It is uncertain exactly how quickly a decision will emerge, but deadlines are looming; early voting, for instance, begins Monday.
While Mr. Emanuel seemed to defiantly march on Tuesday with a local Teamsters’ endorsement, a fund-raising event, a meeting with teachers, as if nothing much was going on, his five opponents were left trying to sort out whether the top polling candidate was in or out, and just who, then, to criticize.
City elections officials, too, found themselves trapped in the tangle of the legal fight. With absentee ballots due to be mailed out as early as Friday, the officials had begun printing ballots — without Mr. Emanuel’s name, per the appellate court’s Monday ruling — at 7 a.m. Tuesday.
By noon, with 300,000 ballots done, the Supreme Court said no ballots should be printed without Mr. Emanuel’s name. “We absolutely called the printers and said, ‘Stop the presses,’ ” Jim Allen, a spokesman for Chicago’s Board of Election Commissioners, recounted not long after.
Legal experts cautioned against reading too much into the State Supreme Court’s decision to bar printing of ballots without Mr. Emanuel’s name even before it decides the case. In cases of someone seeking a stay, courts often take into account the possibility of irreparable harm.
“In this case, Emanuel would suffer great harm in the event that his name was left off the ballot and the State Supreme Court reverses” later in the process, said Richard L. Hasen, a visiting professor of law at the University of California, Irvine.
For months, even as Mr. Emanuel became the clear front-runner in the race to replace Mayor Richard M. Daley, who will retire this spring, challenges have been simmering over whether he lived here long enough to qualify for the ballot. Such challenges fit into a broader landscape strewn, experts said, with narrow readings of statutory language and broad principles of election law.
In essence, in finding on Monday that Mr. Emanuel did not qualify to run for mayor, the appellate panel relied on a distinction in Illinois’s code between the residency qualifications to cast a vote and the requirements for those running for office. Running for local office, the appellate judges said, actually required a person to physically live in a given city, not just to own property there or pay taxes there, as Mr. Emanuel always had.
Other legal experts pointed to a broader concern in the realm of such election questions.
Professor Rosen pointed, for example, to the circumstances in 2010 of Senator Lisa Murkowski, Republican of Alaska, who ran for re-election as a write-in candidate and for whom election officials allowed poorly spelled versions of her name.
Still, residency has tripped up candidates before. In 1974, Charles Ravenel was heavily favored to win a race for governor of South Carolina, but was knocked out by a lawsuit that cited a State Constitution requirement that candidates have lived in the state for five years.
Chicago voters, meanwhile, were reeling. At lunch spots downtown on Tuesday, they had questions: Was Mr. Emanuel in? Was he out? Could he ultimately launch a write-in campaign? (Perhaps, though that would likely create new challenges.) Would the election be stopped altogether?
Langdon D. Neal, chairman of the Chicago Board of Election Commissioners, seemed to empathize, even encouraging voters with lingering questions to consider waiting beyond the start of early voting — to see what happens to all of this — before casting their ballots.
Mr. Emanuel’s top opponents — Carol Moseley Braun, a former United States senator, and Gery Chico, a former mayoral chief of staff to Mr. Daley — seemed uncertain about how best to proceed as well. In the past, most of Mr. Emanuel’s opponents have focused squarely on him, but on Tuesday Ms. Braun issued a news release condemning Mr. Chico’s stance (misunderstood, Mr. Chico’s aides say) on whether city workers should live within the city limits.
Still, the effort seemed to draw little notice. And efforts to woo away Mr. Emanuel’s supporters and donors had not worked so far, some from his campaign said; campaign donations have not dropped off.
And while nearly everyone — including the local Teamsters who decided to announce their endorsement of Mr. Emanuel on Tuesday morning in part because they were angry at the prospect that he might be removed from the ballot — debated his fate, Mr. Emanuel himself seemed intent on talking about anything but.
Inside a fruit warehouse on the Southwest Side, he grinned and high-fived members of the Teamsters and spoke of the city’s struggling economy. He talked about safety on the streets, his tax plan, a comprehensive wellness plan for city workers and the minimum wage.
Finally, pressed by reporters to discuss his ballot woes, he said he intended to go full force ahead. Perhaps he would double up now, he said, adding even more campaign stops, more handshaking visits to trains, more sojourns to bowling alleys.
|
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import filecmp
import logging
import os
import shutil
from pants.base.deprecated import deprecated_conditional
from pants.base.exceptions import TaskError
from pants.binaries.binary_tool import NativeTool
from pants.option.custom_types import dir_option, file_option
from pants.util.dirutil import safe_mkdir, safe_rmtree
from pants.util.memo import memoized_method, memoized_property
from pants.contrib.node.subsystems.command import command_gen
from pants.contrib.node.subsystems.package_managers import (PACKAGE_MANAGER_NPM,
PACKAGE_MANAGER_YARNPKG,
PACKAGE_MANAGER_YARNPKG_ALIAS,
VALID_PACKAGE_MANAGERS,
PackageManagerNpm,
PackageManagerYarnpkg)
from pants.contrib.node.subsystems.yarnpkg_distribution import YarnpkgDistribution
logger = logging.getLogger(__name__)
class NodeDistribution(NativeTool):
"""Represents a self-bootstrapping Node distribution."""
options_scope = 'node-distribution'
name = 'node'
default_version = 'v6.9.1'
archive_type = 'tgz'
@classmethod
def subsystem_dependencies(cls):
# Note that we use a YarnpkgDistribution scoped to the NodeDistribution, which may itself
# be scoped to a task.
return (super(NodeDistribution, cls).subsystem_dependencies() +
(YarnpkgDistribution.scoped(cls), ))
@classmethod
def register_options(cls, register):
super(NodeDistribution, cls).register_options(register)
register('--package-manager', advanced=True, default='npm', fingerprint=True,
choices=VALID_PACKAGE_MANAGERS,
help='Default package manager config for repo. Should be one of {}'.format(
VALID_PACKAGE_MANAGERS))
register('--eslint-setupdir', advanced=True, type=dir_option, fingerprint=True,
help='Find the package.json and yarn.lock under this dir '
'for installing eslint and plugins.')
register('--eslint-config', advanced=True, type=file_option, fingerprint=True,
help='The path to the global eslint configuration file specifying all the rules')
register('--eslint-ignore', advanced=True, type=file_option, fingerprint=True,
help='The path to the global eslint ignore path')
register('--eslint-version', default='4.15.0', fingerprint=True,
help='Use this ESLint version.')
@memoized_method
def _get_package_managers(self):
npm = PackageManagerNpm([self._install_node])
yarnpkg = PackageManagerYarnpkg([self._install_node, self._install_yarnpkg])
return {
PACKAGE_MANAGER_NPM: npm,
PACKAGE_MANAGER_YARNPKG: yarnpkg,
PACKAGE_MANAGER_YARNPKG_ALIAS: yarnpkg, # Allow yarn to be used as an alias for yarnpkg
}
def get_package_manager(self, package_manager=None):
package_manager = package_manager or self.get_options().package_manager
package_manager_obj = self._get_package_managers().get(package_manager)
if not package_manager_obj:
raise TaskError(
'Unknown package manager: {}.\nValid values are {}.'.format(
package_manager, list(NodeDistribution.VALID_PACKAGE_MANAGER_LIST.keys())
))
return package_manager_obj
@memoized_method
def version(self, context=None):
# The versions reported by node and embedded in distribution package names are 'vX.Y.Z'.
# TODO: After the deprecation cycle is over we'll expect the values of the version option
# to already include the 'v' prefix, so there will be no need to normalize, and we can
# delete this entire method override.
version = super(NodeDistribution, self).version(context)
deprecated_conditional(
lambda: not version.startswith('v'), entity_description='', removal_version='1.7.0.dev0',
hint_message='value of --version in scope {} must be of the form '
'vX.Y.Z'.format(self.options_scope))
return version if version.startswith('v') else 'v' + version
@classmethod
def _normalize_version(cls, version):
# The versions reported by node and embedded in distribution package names are 'vX.Y.Z' and not
# 'X.Y.Z'.
return version if version.startswith('v') else 'v' + version
@memoized_property
def eslint_setupdir(self):
return self.get_options().eslint_setupdir
@memoized_property
def eslint_version(self):
return self.get_options().eslint_version
@memoized_property
def eslint_config(self):
return self.get_options().eslint_config
@memoized_property
def eslint_ignore(self):
return self.get_options().eslint_ignore
@memoized_method
def _install_node(self):
"""Install the Node distribution from pants support binaries.
:returns: The Node distribution bin path.
:rtype: string
"""
node_package_path = self.select()
# Todo: https://github.com/pantsbuild/pants/issues/4431
# This line depends on repacked node distribution.
# Should change it from 'node/bin' to 'dist/bin'
node_bin_path = os.path.join(node_package_path, 'node', 'bin')
return node_bin_path
@memoized_method
def _install_yarnpkg(self):
"""Install the Yarnpkg distribution from pants support binaries.
:returns: The Yarnpkg distribution bin path.
:rtype: string
"""
yarnpkg_package_path = YarnpkgDistribution.scoped_instance(self).select()
yarnpkg_bin_path = os.path.join(yarnpkg_package_path, 'dist', 'bin')
return yarnpkg_bin_path
def node_command(self, args=None, node_paths=None):
"""Creates a command that can run `node`, passing the given args to it.
:param list args: An optional list of arguments to pass to `node`.
:param list node_paths: An optional list of paths to node_modules.
:returns: A `node` command that can be run later.
:rtype: :class:`NodeDistribution.Command`
"""
# NB: We explicitly allow no args for the `node` command unlike the `npm` command since running
# `node` with no arguments is useful, it launches a REPL.
return command_gen([self._install_node], 'node', args=args, node_paths=node_paths)
def _configure_eslinter(self, bootstrapped_support_path):
logger.debug('Copying {setupdir} to bootstrapped dir: {support_path}'
.format(setupdir=self.eslint_setupdir,
support_path=bootstrapped_support_path))
safe_rmtree(bootstrapped_support_path)
shutil.copytree(self.eslint_setupdir, bootstrapped_support_path)
return True
_eslint_required_files = ['yarn.lock', 'package.json']
def eslint_supportdir(self, task_workdir):
""" Returns the path where the ESLint is bootstrapped.
:param string task_workdir: The task's working directory
:returns: The path where ESLint is bootstrapped and whether or not it is configured
:rtype: (string, bool)
"""
bootstrapped_support_path = os.path.join(task_workdir, 'eslint')
# TODO(nsaechao): Should only have to check if the "eslint" dir exists in the task_workdir
# assuming fingerprinting works as intended.
# If the eslint_setupdir is not provided or missing required files, then
# clean up the directory so that Pants can install a pre-defined eslint version later on.
# Otherwise, if there is no configurations changes, rely on the cache.
# If there is a config change detected, use the new configuration.
if self.eslint_setupdir:
configured = all(os.path.exists(os.path.join(self.eslint_setupdir, f))
for f in self._eslint_required_files)
else:
configured = False
if not configured:
safe_mkdir(bootstrapped_support_path, clean=True)
else:
try:
installed = all(filecmp.cmp(
os.path.join(self.eslint_setupdir, f), os.path.join(bootstrapped_support_path, f))
for f in self._eslint_required_files)
except OSError:
installed = False
if not installed:
self._configure_eslinter(bootstrapped_support_path)
return bootstrapped_support_path, configured
|
FiiO X series music players X1II, X1, X3II, X3 Mark III, X5II, X5III, X7, X7 Mark II and the DAC/amp E17K utilize a 11-pin micro USB port, and may realize exclusive docking expansion functions such as amplification and charging.... Buy. Fiio has been around for roughly 9 years now, and have made very steady progress with their products. Their latest release, the ‘ALL NEW X1’ is an updated version of their best-selling player, the original X1.
The K5 from Fiio is a high quality headphone amplifier and DAC with an integrated dock for Fiio audio players, such as the X1, X3II, X5II, X7, and E17K.... FiiO K5 Dock. The K5 is the latest docking station from FiiO. It is compatible with the X1, X3ii, X5ii and X7, as well as the E17K. With an 11pin micro USB port this allows you facilitate exclusive docking expansion functions such as amplifications and charging.
I have KEF 300 USB digital speakers. They will not play sound when connected through the USB 3.0 Dock. I have to have them directly connected to the laptop, X1 Carbon, or they will work through a USB hub that is directly connected.
|
import nose
from nose.tools import *
from tempfile import mkdtemp
import shutil, os, sys
from os.path import join, split
#Make sure we test the local source code rather than the installed copy
test_dir = os.path.dirname(__file__)
src_dir = os.path.normpath(os.path.join(test_dir, '..'))
sys.path.insert(0, src_dir)
import pathmap
class TestMakeRegexRule():
known_results = {'.+':
{'hello': ['hello'],
'something.txt': ['something.txt'],
'': pathmap.NoMatch,
},
'(.+)\.(.+)':
{'something.txt': ['something.txt',
'something',
'txt'
],
'image_001.dcm': ['image_001.dcm',
'image_001',
'dcm'
],
'something': pathmap.NoMatch,
},
'image_([0-9]+)\.dcm':
{'image_001.dcm': ['image_001.dcm',
'001'
],
'image_1.dcm': ['image_1.dcm',
'1'
],
'image_one.dcm': pathmap.NoMatch,
'image_001.dc': pathmap.NoMatch,
}
}
def test_known_results(self):
for match_regex, tests in self.known_results.iteritems():
match_rule = pathmap.make_regex_rule(match_regex)
for input_str, results in tests.iteritems():
assert(match_rule(input_str, None) == results)
def build_dir(base_dir, paths_at_level):
for level in paths_at_level:
for path in level:
if split(path)[1].split('-')[-1].startswith('dir'):
os.mkdir(join(base_dir, path))
else:
tmpfile = open(join(base_dir, path), 'a')
tmpfile.close()
class TestSimpleRules():
paths_at_level = [['level0-dir'],
[join('level0-dir', 'level1-file1'),
join('level0-dir', 'level1-file2'),
join('level0-dir', 'level1-dir1'),
join('level0-dir', 'level1-dir2'),
],
[join('level0-dir', 'level1-dir1', 'level2-file1'),
join('level0-dir', 'level1-dir1', 'level2-file2'),
join('level0-dir', 'level1-dir1', 'level2-dir1'),
join('level0-dir', 'level1-dir2', 'level2-dir2'),
join('level0-dir', 'level1-dir2', 'level2-file3')
],
[join('level0-dir', 'level1-dir1', 'level2-dir1',
'level3-file1'),
join('level0-dir', 'level1-dir1', 'level2-dir1',
'level3-dir1'),
],
[join('level0-dir', 'level1-dir1', 'level2-dir1',
'level3-dir1', 'level4-file1'),
],
]
def setup(self):
self.init_dir = os.getcwd()
self.test_dir = mkdtemp()
build_dir(self.test_dir, self.paths_at_level)
os.chdir(self.test_dir)
def tearDown(self):
os.chdir(self.init_dir)
shutil.rmtree(self.test_dir)
def test_min_depth(self):
for i in range(len(self.paths_at_level)):
pm = pathmap.PathMap(depth=(i, None))
matches = list(pm.matches('level0-dir'))
total_paths = 0
for j in range(i, len(self.paths_at_level)):
total_paths += len(self.paths_at_level[j])
for path in self.paths_at_level[j]:
assert(any(path == m.path for m in matches))
if len(matches) != total_paths:
print i
print [m.path for m in matches]
assert(len(matches) == total_paths)
def test_max_depth(self):
for i in range(len(self.paths_at_level)):
pm = pathmap.PathMap(depth=(0, i))
matches = list(pm.matches('level0-dir'))
total_paths = 0
for j in range(0, i+1):
total_paths += len(self.paths_at_level[j])
for path in self.paths_at_level[j]:
assert(any(path == m.path for m in matches))
assert(len(matches) == total_paths)
def test_match_regex(self):
for i in range(len(self.paths_at_level)):
pm = pathmap.PathMap('level' + str(i))
matches = list(pm.matches('level0-dir'))
for j in range(i, len(self.paths_at_level)):
for path in self.paths_at_level[j]:
path = os.path.normpath(path)
assert(any(['level' + str(i)] == m.match_info
for m in matches)
)
def test_ignore_regex(self):
pm = pathmap.PathMap(ignore_rules=['level0'])
matches = list(pm.matches('level0-dir'))
assert(len(matches) == 0)
for i in range(1, len(self.paths_at_level)):
pm = pathmap.PathMap(ignore_rules=['level' + str(i)])
matches = list(pm.matches('level0-dir'))
for j in range(0, i):
for path in self.paths_at_level[j]:
path = os.path.normpath(path)
assert(any(path == m.path for m in matches))
def test_ignore_regexes(self):
ignore_rules = ['level2-file1', '.+'+os.sep+'level3-dir1$']
pm = pathmap.PathMap(ignore_rules=ignore_rules)
for match_result in pm.matches('level0-dir'):
assert(not os.path.basename(match_result.path) in
['level2-file1', 'level3-dir1'])
def test_prune_regex(self):
pm = pathmap.PathMap(prune_rules=['level0-dir'])
matches = list(pm.matches('level0-dir'))
assert(len(matches) == 1)
assert(matches[0].path == 'level0-dir')
prune_rule = 'level2-dir1'
pm = pathmap.PathMap(prune_rules=[prune_rule])
for match_result in pm.matches('level0-dir'):
idx = match_result.path.find(prune_rule)
if idx != -1:
assert(all(x != os.sep for x in match_result.path[idx:]))
def test_prune_regexes(self):
prune_rules = ['level1-dir2', 'level3-dir1']
pm = pathmap.PathMap(prune_rules=prune_rules)
for match_result in pm.matches('level0-dir'):
for rule in prune_rules:
idx = match_result.path.find(rule)
if idx != -1:
assert(all(x != os.sep for x in match_result.path[idx:]))
class TestSorting():
paths_at_level = [['c-dir', 'a-dir', 'd-file', 'b-file'],
[join('c-dir', 'g-file'),
join('c-dir', 'f-file'),
join('a-dir', 'y-file'),
join('a-dir', 'x-file'),
],
]
dfs_sorted = ['.',
join('.', 'a-dir'),
join('.', 'b-file'),
join('.', 'c-dir'),
join('.', 'd-file'),
join('.', 'a-dir', 'x-file'),
join('.', 'a-dir', 'y-file'),
join('.', 'c-dir', 'f-file'),
join('.', 'c-dir', 'g-file'),
]
def setup(self):
self.init_dir = os.getcwd()
self.test_dir = mkdtemp()
build_dir(self.test_dir, self.paths_at_level)
os.chdir(self.test_dir)
def tearDown(self):
os.chdir(self.init_dir)
shutil.rmtree(self.test_dir)
def test_sorting(self):
pm = pathmap.PathMap(sort=True)
matched_paths = [m.path for m in pm.matches('.')]
assert matched_paths == self.dfs_sorted
|
The Volvo S60 is the first model to come out since Ford sold the company to Chinese-owned Geely.
Engine: Turbocharged, in-line six-cylinder with 300 horsepower and 325 pound-feet of torque.
Speed: 0 to 60 mph in 5.5 seconds.
Gas mileage per gallon: 18 city; 26 highway.
Best feature: Romping ride in subdued package.
Worst feature: Where are the behind-the-wheel paddles?
Target buyer: The sports sedan seeker who wants a BMW and Audi alternative.
Until I drove the S60 sport sedan, the only fun I've ever had in a Volvo was behind the wheel of a careening double-decker bus.
More than a decade ago I drove Volvo's entire line at its Gothenburg, Sweden, headquarters. It was a sleepy, torpid affair, as you might expect from the world's most boring (yet safe -- really, really safe!) automobiles.
Finally someone asked if I wanted a crack at the "big toys" -- Volvo's heavy equipment division -- which sent me around a test track in my own version of the movie "Speed."
Awesomeness that nearly made up for the lackluster cars.
Lately, though, colleagues have been insisting that the updated S60 sports sedan is different -- a fun Volvo. I filed that phrase between "friendly fire" and "jumbo shrimp."
Only they're right. The S60 T6 sport sedan is a sleeper agent, a 300-hp, BMW-challenging sports car camouflaged by geeky frame glasses and Volvo duds Clark Kent might like.
Underneath the exterior, the T6 model has an "S" emblazoned on its chest, courtesy of a turbocharged, inline six-cylinder. This thing was made to run.
Pounce on the gas and -- whammo! -- 60 mph (96kph) comes on in 5.5 seconds, leaving BMW 3-series drivers scratching their heads. Who saw that coming?
Audi was once the European manufacturer most identified with superhero sports cars with hidden identities. The brand's bravura redesign made its products a lot more interesting, but had some fans feeling left behind.
The sedan is crisp and handsome, with a stance that leans forward. It has a particularly good-looking rear, a mix of sharp lines and concave hollows that looks hand-crafted. Dynamic, but not shriekingly so.
It's good timing, as the Swedish car industry has had a hard ride lately. Saab was sold off by General Motors Co. in a last-minute deal to Spyker Cars NV, and has seen production delays due to unpaid bills.
A recent drive in the updated 9-5 sedan left me disappointed in the flimsy-feeling interior, a hallmark of GM from a few years ago.
The S60, meanwhile, is the first model to come out since Ford sold Volvo to Chinese-owned Geely. Nonetheless, the design and engineering departments remain in Sweden, just as they had underneath Ford.
The T6 model starts at 44,900 euros in Europe. It gets the six-cylinder engine and all-wheel drive. The front-wheel-drive, five-cylinder T5 has 250 hp and starts at 33,950 euros.
The awd makes a big difference. You can feel the S60 push and pull you simultaneously and relentlessly down the road. It stays perfectly flat on big sweeping curves.
I'll admit to my surprise. After 100 miles I wanted to drive 100 more. Quite unlike the Saab, which left me feeling a little blue for a model I once liked.
The Volvo would benefit from a swifter transmission, as the six-speed automatic takes a heartbeat to kick down when you suddenly need a spurt to burst through traffic. Behind-the-wheel paddles would be nice, too.
The steering-wheel effort can be adjusted electronically -- I put it on the heaviest setting. The on-center feel is a bit hazy and takes some getting used to.
My tester was a burnt-orange color (vibrant copper metallic, according to the company), with a nice brown-leather interior that seems like a 1970s throwback, but in a cool way. I would totally order it in the combination.
The S60 has an adequate navigation system that's well integrated into the console. The instrument cluster is a bit dull, but the controls only take a moment to master.
There's a lane-departure warning, adaptive cruise control and a distance alert. Those can also be turned off with a button on the console, as simply paying attention to the road does wonders.
As carmakers change hands among corporate (and international) owners, it's nice to discover that the final result doesn't always yield products that are watered down. In Volvo's case, I find it more potent.
|
#!/usr/bin/env python
"""Module with GRRWorker implementation."""
import pdb
import time
import traceback
import logging
from grr.lib import aff4
from grr.lib import config_lib
from grr.lib import flags
from grr.lib import flow
from grr.lib import master
from grr.lib import queue_manager as queue_manager_lib
from grr.lib import queues as queues_config
from grr.lib import rdfvalue
from grr.lib import registry
# pylint: disable=unused-import
from grr.lib import server_stubs
# pylint: enable=unused-import
from grr.lib import stats
from grr.lib import threadpool
from grr.lib import utils
class Error(Exception):
"""Base error class."""
class FlowProcessingError(Error):
"""Raised when flow requests/responses can't be processed."""
class GRRWorker(object):
"""A GRR worker."""
# time to wait before polling when no jobs are currently in the
# task scheduler (sec)
POLLING_INTERVAL = 2
SHORT_POLLING_INTERVAL = 0.3
SHORT_POLL_TIME = 30
# target maximum time to spend on RunOnce
RUN_ONCE_MAX_SECONDS = 300
# A class global threadpool to be used for all workers.
thread_pool = None
# This is a timed cache of locked flows. If this worker encounters a lock
# failure on a flow, it will not attempt to grab this flow until the timeout.
queued_flows = None
def __init__(self, queues=queues_config.WORKER_LIST,
threadpool_prefix="grr_threadpool",
threadpool_size=None, token=None):
"""Constructor.
Args:
queues: The queues we use to fetch new messages from.
threadpool_prefix: A name for the thread pool used by this worker.
threadpool_size: The number of workers to start in this thread pool.
token: The token to use for the worker.
Raises:
RuntimeError: If the token is not provided.
"""
logging.info("started worker with queues: " + str(queues))
self.queues = queues
self.queued_flows = utils.TimeBasedCache(max_size=10, max_age=60)
if token is None:
raise RuntimeError("A valid ACLToken is required.")
# Make the thread pool a global so it can be reused for all workers.
if GRRWorker.thread_pool is None:
if threadpool_size is None:
threadpool_size = config_lib.CONFIG["Threadpool.size"]
GRRWorker.thread_pool = threadpool.ThreadPool.Factory(
threadpool_prefix, min_threads=2, max_threads=threadpool_size)
GRRWorker.thread_pool.Start()
self.token = token
self.last_active = 0
# Well known flows are just instantiated.
self.well_known_flows = flow.WellKnownFlow.GetAllWellKnownFlows(token=token)
self.flow_lease_time = config_lib.CONFIG["Worker.flow_lease_time"]
self.well_known_flow_lease_time = config_lib.CONFIG[
"Worker.well_known_flow_lease_time"]
def Run(self):
"""Event loop."""
try:
while 1:
if master.MASTER_WATCHER.IsMaster():
processed = self.RunOnce()
else:
processed = 0
if processed == 0:
if time.time() - self.last_active > self.SHORT_POLL_TIME:
interval = self.POLLING_INTERVAL
else:
interval = self.SHORT_POLLING_INTERVAL
time.sleep(interval)
else:
self.last_active = time.time()
except KeyboardInterrupt:
logging.info("Caught interrupt, exiting.")
self.thread_pool.Join()
def RunOnce(self):
"""Processes one set of messages from Task Scheduler.
The worker processes new jobs from the task master. For each job
we retrieve the session from the Task Scheduler.
Returns:
Total number of messages processed by this call.
"""
start_time = time.time()
processed = 0
queue_manager = queue_manager_lib.QueueManager(token=self.token)
for _ in range(0, queue_manager.num_notification_shards):
for queue in self.queues:
# Freezeing the timestamp used by queue manager to query/delete
# notifications to avoid possible race conditions.
queue_manager.FreezeTimestamp()
fetch_messages_start = time.time()
notifications_by_priority = queue_manager.GetNotificationsByPriority(
queue)
stats.STATS.RecordEvent("worker_time_to_retrieve_notifications",
time.time() - fetch_messages_start)
# Process stuck flows first
stuck_flows = notifications_by_priority.pop(
queue_manager.STUCK_PRIORITY, [])
if stuck_flows:
self.ProcessStuckFlows(stuck_flows, queue_manager)
notifications_available = []
for priority in sorted(notifications_by_priority, reverse=True):
for notification in notifications_by_priority[priority]:
# Filter out session ids we already tried to lock but failed.
if notification.session_id not in self.queued_flows:
notifications_available.append(notification)
try:
# If we spent too much time processing what we have so far, the
# active_sessions list might not be current. We therefore break here
# so we can re-fetch a more up to date version of the list, and try
# again later. The risk with running with an old active_sessions list
# is that another worker could have already processed this message,
# and when we try to process it, there is nothing to do - costing us a
# lot of processing time. This is a tradeoff between checking the data
# store for current information and processing out of date
# information.
processed += self.ProcessMessages(notifications_available,
queue_manager,
self.RUN_ONCE_MAX_SECONDS -
(time.time() - start_time))
# We need to keep going no matter what.
except Exception as e: # pylint: disable=broad-except
logging.error("Error processing message %s. %s.", e,
traceback.format_exc())
stats.STATS.IncrementCounter("grr_worker_exceptions")
if flags.FLAGS.debug:
pdb.post_mortem()
queue_manager.UnfreezeTimestamp()
# If we have spent too much time, stop.
if (time.time() - start_time) > self.RUN_ONCE_MAX_SECONDS:
return processed
return processed
def ProcessStuckFlows(self, stuck_flows, queue_manager):
stats.STATS.IncrementCounter("grr_flows_stuck", len(stuck_flows))
for stuck_flow in stuck_flows:
try:
flow.GRRFlow.TerminateFlow(
stuck_flow.session_id, reason="Stuck in the worker",
status=rdfvalue.GrrStatus.ReturnedStatus.WORKER_STUCK,
force=True, token=self.token)
except Exception: # pylint: disable=broad-except
logging.exception("Error terminating stuck flow: %s", stuck_flow)
finally:
# Remove notifications for this flow. This will also remove the
# "stuck flow" notification itself.
queue_manager.DeleteNotification(stuck_flow.session_id)
def ProcessMessages(self, active_notifications, queue_manager, time_limit=0):
"""Processes all the flows in the messages.
Precondition: All tasks come from the same queue.
Note that the server actually completes the requests in the
flow when receiving the messages from the client. We do not really
look at the messages here at all any more - we just work from the
completed messages in the flow RDFValue.
Args:
active_notifications: The list of notifications.
queue_manager: QueueManager object used to manage notifications,
requests and responses.
time_limit: If set return as soon as possible after this many seconds.
Returns:
The number of processed flows.
"""
now = time.time()
processed = 0
for notification in active_notifications:
if notification.session_id not in self.queued_flows:
if time_limit and time.time() - now > time_limit:
break
processed += 1
self.queued_flows.Put(notification.session_id, 1)
self.thread_pool.AddTask(target=self._ProcessMessages,
args=(notification,
queue_manager.Copy()),
name=self.__class__.__name__)
return processed
def _ProcessRegularFlowMessages(self, flow_obj, notification):
"""Processes messages for a given flow."""
session_id = notification.session_id
if not isinstance(flow_obj, flow.GRRFlow):
logging.warn("%s is not a proper flow object (got %s)", session_id,
type(flow_obj))
stats.STATS.IncrementCounter("worker_bad_flow_objects",
fields=[str(type(flow_obj))])
raise FlowProcessingError("Not a GRRFlow.")
runner = flow_obj.GetRunner()
if runner.schedule_kill_notifications:
# Create a notification for the flow in the future that
# indicates that this flow is in progess. We'll delete this
# notification when we're done with processing completed
# requests. If we're stuck for some reason, the notification
# will be delivered later and the stuck flow will get
# terminated.
stuck_flows_timeout = rdfvalue.Duration(
config_lib.CONFIG["Worker.stuck_flows_timeout"])
kill_timestamp = (rdfvalue.RDFDatetime().Now() +
stuck_flows_timeout)
with queue_manager_lib.QueueManager(token=self.token) as manager:
manager.QueueNotification(session_id=session_id,
in_progress=True,
timestamp=kill_timestamp)
# kill_timestamp may get updated via flow.HeartBeat() calls, so we
# have to store it in the runner context.
runner.context.kill_timestamp = kill_timestamp
try:
runner.ProcessCompletedRequests(notification, self.thread_pool)
# Something went wrong - log it in the flow.
except Exception as e: # pylint: disable=broad-except
runner.context.state = rdfvalue.Flow.State.ERROR
runner.context.backtrace = traceback.format_exc()
logging.error("Flow %s: %s", flow_obj, e)
raise FlowProcessingError(e)
finally:
# Delete kill notification as the flow got processed and is not
# stuck.
with queue_manager_lib.QueueManager(token=self.token) as manager:
if runner.schedule_kill_notifications:
manager.DeleteNotification(
session_id, start=runner.context.kill_timestamp,
end=runner.context.kill_timestamp)
runner.context.kill_timestamp = None
if (runner.process_requests_in_order and
notification.last_status and
(runner.context.next_processed_request <=
notification.last_status)):
# We are processing requests in order and have received a
# notification for a specific request but could not process
# that request. This might be a race condition in the data
# store so we reschedule the notification in the future.
delay = config_lib.CONFIG[
"Worker.notification_retry_interval"]
manager.QueueNotification(
notification, timestamp=notification.timestamp + delay)
def _ProcessMessages(self, notification, queue_manager):
"""Does the real work with a single flow."""
flow_obj = None
session_id = notification.session_id
try:
# Take a lease on the flow:
flow_name = session_id.FlowName()
if flow_name in self.well_known_flows:
# Well known flows are not necessarily present in the data store so
# we need to create them instead of opening.
expected_flow = self.well_known_flows[flow_name].__class__.__name__
flow_obj = aff4.FACTORY.CreateWithLock(
session_id, expected_flow,
lease_time=self.well_known_flow_lease_time,
blocking=False, token=self.token)
else:
flow_obj = aff4.FACTORY.OpenWithLock(
session_id, lease_time=self.flow_lease_time,
blocking=False, token=self.token)
now = time.time()
logging.debug("Got lock on %s", session_id)
# If we get here, we now own the flow. We can delete the notifications
# we just retrieved but we need to make sure we don't delete any that
# came in later.
queue_manager.DeleteNotification(session_id, end=notification.timestamp)
if flow_name in self.well_known_flows:
stats.STATS.IncrementCounter("well_known_flow_requests",
fields=[str(session_id)])
# We remove requests first and then process them in the thread pool.
# On one hand this approach increases the risk of losing requests in
# case the worker process dies. On the other hand, it doesn't hold
# the lock while requests are processed, so other workers can
# process well known flows requests as well.
with flow_obj:
responses = flow_obj.FetchAndRemoveRequestsAndResponses(session_id)
flow_obj.ProcessResponses(responses, self.thread_pool)
else:
with flow_obj:
self._ProcessRegularFlowMessages(flow_obj, notification)
elapsed = time.time() - now
logging.debug("Done processing %s: %s sec", session_id, elapsed)
stats.STATS.RecordEvent("worker_flow_processing_time", elapsed,
fields=[flow_obj.Name()])
# Everything went well -> session can be run again.
self.queued_flows.ExpireObject(session_id)
except aff4.LockError:
# Another worker is dealing with this flow right now, we just skip it.
# We expect lots of these when there are few messages (the system isn't
# highly loaded) but it is interesting when the system is under load to
# know if we are pulling the optimal number of messages off the queue.
# A high number of lock fails when there is plenty of work to do would
# indicate we are wasting time trying to process work that has already
# been completed by other workers.
stats.STATS.IncrementCounter("worker_flow_lock_error")
except FlowProcessingError:
# Do nothing as we expect the error to be correctly logged and accounted
# already.
pass
except Exception as e: # pylint: disable=broad-except
# Something went wrong when processing this session. In order not to spin
# here, we just remove the notification.
logging.exception("Error processing session %s: %s", session_id, e)
stats.STATS.IncrementCounter("worker_session_errors",
fields=[str(type(e))])
queue_manager.DeleteNotification(session_id)
class WorkerInit(registry.InitHook):
"""Registers worker stats variables."""
pre = ["StatsInit"]
def RunOnce(self):
"""Exports the vars.."""
stats.STATS.RegisterCounterMetric("grr_flows_stuck")
stats.STATS.RegisterCounterMetric("worker_bad_flow_objects",
fields=[("type", str)])
stats.STATS.RegisterCounterMetric("worker_session_errors",
fields=[("type", str)])
stats.STATS.RegisterCounterMetric(
"worker_flow_lock_error", docstring=("Worker lock failures. We expect "
"these to be high when the system"
"is idle."))
stats.STATS.RegisterEventMetric("worker_flow_processing_time",
fields=[("flow", str)])
stats.STATS.RegisterEventMetric("worker_time_to_retrieve_notifications")
|
1 & 2. It took volunteers several months to cut down and clear the tall gorse and tobacco weed.
3. Piles of dead gorse and weeds removed from the reserve.
4. A batch of native trees and shrubs grown by volunteers at Kerikeri Shadehouse nursery.
5 - 8. Local volunteers planting the southern ridge of the reserve.
9. Planted southern ridge. Some of the plants needed tree guard protection from gnawing rabbits.
10. Planted northern ridge, with rabbit protection for species that rabbits like to graze on. Larger trees will be inserted between the plants this month.
|
# -*- encoding: utf-8 -*-
from django.core.urlresolvers import reverse
from django import template
from private_messages.models import Message
from django.utils.translation import ugettext_lazy as _
register = template.Library()
@register.filter('unread_messages')
def get_unread_messages(user):
if user is None:
unread_messages = 0
else:
unread_messages = Message.objects.get_inbox_for_user(user)\
.filter(unread=True).count()
return unread_messages
@register.simple_tag
def get_header(request):
if reverse('private_messages_inbox') in request.path:
return _('Bandeja de entrada')
elif reverse('private_messages_outbox') in request.path:
return _('Enviados')
else:
return ''
@register.simple_tag
def is_sent_url(request):
if reverse('private_messages_outbox') == request.path:
return True
else:
return False
@register.tag('match_url')
def do_match_url(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, page_url, _as_, var_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument"\
% token.contents.split()[0])
if not (page_url[0] == page_url[-1] and page_url[0] in ('"', "'")):
raise template.TemplateSyntaxError("%r tag's argument should be\
in quotes" % tag_name)
return MatchUrl(page_url[1:-1], var_name)
class MatchUrl(template.Node):
def __init__(self, page_url, var_name):
self.page_url = page_url
self.var_name = var_name
def render(self, context):
request = context['request']
context[self.var_name] = reverse(self.page_url) == request.path
return ''
@register.tag('match_referer')
def do_match_referer(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, page_url, _as_, var_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument"\
% token.contents.split()[0])
if not (page_url[0] == page_url[-1] and page_url[0] in ('"', "'")):
raise template.TemplateSyntaxError("%r tag's argument should be\
in quotes" % tag_name)
return MatchReferer(page_url[1:-1], var_name)
class MatchReferer(template.Node):
def __init__(self, referer_name, var_name):
self.referer_name = referer_name
self.var_name = var_name
def render(self, context):
request = context['request']
referer_url = request.META.get('HTTP_REFERER')
context[self.var_name] = self.referer_name in referer_url
return ''
|
widgets that provide standard GUI functionality.
when multiple versions like 4 and 5 are installed or local Qt builds are to be used.
It is commonly used via a symlink from an executable_name like qmake.
symlinked to qtchooser will be executed without additional parameters.
qtchooser was written by Thiago Macieira from Intel.
|
# -*- coding: utf-8 -*-
from amoco.arch.core import Formatter
def pfx(i):
if i.misc['pfx'] is None: return ''
pfxgrp0 = i.misc['pfx'][0]
if pfxgrp0 is None: return ''
return '%s '%pfxgrp0
def mnemo(i):
mnemo = i.mnemonic.replace('cc','')
if hasattr(i,'cond'): mnemo += i.cond[0].split('/')[0]
return '{: <12}'.format(mnemo.lower())
def deref(op):
if not op._is_mem: return str(op)
d = '%+d'%op.a.disp if op.a.disp else ''
s = {8:'byte ptr ',16:'word ptr ',32:'dword ptr ', 128:'xmmword ptr '}.get(op.size,'')
s += '%s:'%op.a.seg if op.a.seg is not '' else ''
s += '[%s%s]'%(op.a.base,d)
return s
def opers(i):
s = []
for op in i.operands:
if op._is_mem:
s.append(deref(op))
continue
elif op._is_cst:
if i.misc['imm_ref'] is not None:
s.append(str(i.misc['imm_ref']))
continue
elif op.sf:
s.append('%+d'%op.value)
continue
# default:
s.append(str(op))
return ', '.join(s)
def oprel(i):
to = i.misc['to']
if to is not None: return '*'+str(to)
if (i.address is not None) and i.operands[0]._is_cst:
v = i.address + i.operands[0].signextend(64) + i.length
i.misc['to'] = v
return '*'+str(v)
return '.%+d'%i.operands[0].value
# main intel formats:
format_intel_default = (mnemo,opers)
format_intel_ptr = (mnemo,opers)
format_intel_str = (pfx,mnemo,opers)
format_intel_rel = (mnemo,oprel)
# formats:
IA32e_Intel_formats = {
'ia32_strings' : format_intel_str,
'ia32_mov_adr' : format_intel_ptr,
'ia32_ptr_ib' : format_intel_ptr,
'ia32_ptr_iwd' : format_intel_ptr,
'ia32_rm8' : format_intel_ptr,
'ia32_rm32' : format_intel_ptr,
'ia32_imm_rel' : format_intel_rel,
}
IA32e_Intel = Formatter(IA32e_Intel_formats)
IA32e_Intel.default = format_intel_default
|
There are 4 desktop wallpapers listed below. The files are sorted by the date they were posted to the site, beginning with the most recent content.
A beautiful sunset at the Grand Canyon, seen from the Desert View Watchtower.
SNS HDR & Adobe Lightroom 5.
An early morning in May at Grand Teton National Park rewarded us with this amazing panorama.
The water was so calm that it produced an almost perfect reflection of the mountains.
The approaching dusk colors the area in a beautiful purple tone.
Taken near the Grand Canyon Desert View Watchtower, Arizona on March 2, 2013. HDR composed of 5 frames with +-2 and +-4 EV respectively. SNS-HDR & Adobe Lightroom 4.
|
import abilities
from combat import targets
from combat.attacks.base import Attack
from combat.enums import DamageType
from echo import functions
from stats.enums import StatsEnum
from util import check_roller, dice
class Punch(Attack):
name = "Punch"
target_type = targets.Single
description = "Basic unarmed attack."
actor_message = "You swing your fist at {defender}"
observer_message = "{attacker} swings {attacker_his} fist at {defender}"
@classmethod
def can_execute(cls, attack_context):
attacker = attack_context.attacker
if attack_context.distance_to <= 1:
attacker_body = attacker.body
if attacker_body:
return bool(attacker_body.get_ability(abilities.Punch))
return False
@classmethod
def execute(cls, attack_context):
attacker = attack_context.attacker
defender = attack_context.defender
hit_modifier = attacker.stats.strength.modifier
attack_result = cls.make_hit_roll(attack_context, hit_modifier)
attack_result.attack_message = cls.get_message(attacker, defender)
attack_result.context.attacker_weapon = "fist"
cls.make_damage_roll(attack_result, hit_modifier)
return attack_result,
@classmethod
def make_damage_roll(cls, attack_result, str_modifier):
melee_damage_dice = cls.get_melee_damage_dice(attack_result.context.attacker)
total_damage = check_roller.roll_damage(
dice_stacks=(melee_damage_dice,),
modifiers=str_modifier,
critical=attack_result.critical
)
attack_result.total_damage = total_damage
attack_result.separated_damage = [(total_damage, DamageType.Blunt)]
return attack_result
@classmethod
def get_melee_damage_dice(cls, actor):
return dice.DiceStack(1, dice.D1)
@classmethod
def get_message(cls, actor, target):
if actor.is_player:
return cls.actor_message.format(defender=target.name)
else:
return cls.observer_message.format(
attacker=actor.name,
attacker_his=functions.his_her_it(actor),
defender=functions.name_or_you(target)
)
|
Senegal visit of Princess Mary, which was in the official program of the Princess was cancelled due to security reasons, but Princess Mary made a two-day humanitarian aid visit to Mali together with Minister of Development and Cooperation, Ulla Tornaes between the dates of October 23-24. Because of that visit, she couldn't attend the concert at Fredensborg Palace.
During the visit to Mali, at the meetings held with UNFPA, subjects like rights of women and girls, and strategies to be developed especially for the purpose of preventing child marriage were dealt with.
Princess Mary also visited Danish soldiers performing duty at UN peace mission MINUSMA deployed in Mali and talked to those soldiers. The Princess then visited Danish C-130 cargo airplanes at MINUSMA base. Crown Princess Mary is a member of Home Guard since 2008 and currently carries the title of First Lieutenant.
I like these dresses on Mary especially the blue flowery dress with matching blue shoes. I'm glad that she is working on this cause. No girls should be allowed to marry in such a very young age.
Mary always dresses appropriately and attractively. That is why I always click on her photos. She never makes me wince or groan "oh no!"
She looks great in all these photos. When I saw she wasn't at that concert with the other royals I assumed that she was out of town - she certainly was! A lot of events for 2 days.
|
# Copyright 2014 Rustici Software
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
if __name__ == '__main__':
from main import setup_tincan_path
setup_tincan_path()
from tincan import (
ActivityDefinition,
LanguageMap,
InteractionComponentList,
)
class ActivityDefinitionTest(unittest.TestCase):
def test_InitEmpty(self):
adef = ActivityDefinition()
self.assertEqual(vars(adef), {
'_choices': None,
'_correct_responses_pattern': None,
'_description': None,
'_extensions': None,
'_interaction_type': None,
'_more_info': None,
'_name': None,
'_scale': None,
'_source': None,
'_steps': None,
'_target': None,
'_type': None
})
self.assertIsInstance(adef, ActivityDefinition)
def test_InitAll(self):
adef = ActivityDefinition({
'name': {'en-US': 'test'},
'description': {'en-US': 'test'},
'type': 'test',
'more_info': 'test',
'interaction_type': 'choice',
'correct_responses_pattern': ['test'],
'choices': InteractionComponentList(),
'scale': InteractionComponentList(),
'source': InteractionComponentList(),
'target': InteractionComponentList(),
'steps': InteractionComponentList(),
'extensions': {'test': 'test'}
})
self.definitionVerificationHelper(adef)
def test_InitExceptionType(self):
with self.assertRaises(ValueError):
ActivityDefinition(type='')
def test_InitExceptionMoreInfo(self):
with self.assertRaises(ValueError):
ActivityDefinition(more_info='')
def test_InitExceptionInteractionType(self):
with self.assertRaises(ValueError):
ActivityDefinition(interaction_type='notvalidinteraction')
def test_InitExceptionCorrectResponsesPattern(self):
with self.assertRaises(TypeError):
ActivityDefinition(correct_responses_pattern='notlist')
def test_InitExceptionChoices(self):
with self.assertRaises(TypeError):
ActivityDefinition(choices='notlist')
def test_InitExceptionChoicesNotComponentList(self):
with self.assertRaises(TypeError):
ActivityDefinition(choices=['not component'])
def test_InitExceptionScale(self):
with self.assertRaises(TypeError):
ActivityDefinition(scale='notlist')
def test_InitExceptionScaleNotComponentList(self):
with self.assertRaises(TypeError):
ActivityDefinition(scale=['not component'])
def test_InitExceptionSource(self):
with self.assertRaises(TypeError):
ActivityDefinition(source='notlist')
def test_InitExceptionSourceNotComponentList(self):
with self.assertRaises(TypeError):
ActivityDefinition(source=['not component'])
def test_InitExceptionTarget(self):
with self.assertRaises(TypeError):
ActivityDefinition(target='notlist')
def test_InitExceptionTargetNotComponentList(self):
with self.assertRaises(TypeError):
ActivityDefinition(target=['not component'])
def test_InitExceptionSteps(self):
with self.assertRaises(TypeError):
ActivityDefinition(steps='notlist')
def test_InitExceptionStepsNotComponentList(self):
with self.assertRaises(TypeError):
ActivityDefinition(steps=['not component'])
def test_InitUnpack(self):
obj = {
'name': {'en-US': 'test'},
'description': {'en-US': 'test'},
'type': 'test',
'more_info': 'test',
'interaction_type': 'choice',
'correct_responses_pattern': ['test'],
'choices': InteractionComponentList(),
'scale': InteractionComponentList(),
'source': InteractionComponentList(),
'target': InteractionComponentList(),
'steps': InteractionComponentList(),
'extensions': {'test': 'test'}
}
adef = ActivityDefinition(**obj)
self.definitionVerificationHelper(adef)
def test_FromJSONExceptionBadJSON(self):
with self.assertRaises(ValueError):
ActivityDefinition.from_json('{"bad JSON"}')
def test_FromJSONExceptionMalformedJSON(self):
with self.assertRaises(AttributeError):
ActivityDefinition.from_json('{"test": "invalid property"}')
def test_FromJSONExceptionPartiallyMalformedJSON(self):
with self.assertRaises(AttributeError):
ActivityDefinition.from_json('{"test": "invalid property", "id": \
"valid property"}')
def test_FromJSONExceptionEmpty(self):
with self.assertRaises(ValueError):
ActivityDefinition.from_json('')
def test_FromJSON(self):
json_str = '{"name":{"en-US":"test"},\
"description":{"en-US":"test"},\
"type":"test",\
"more_info":"test",\
"interaction_type":"choice",\
"correct_responses_pattern": ["test"],\
"choices": [], "scale": [], "source": [], "target": [], "steps": [],\
"extensions": {"test": "test"}}'
adef = ActivityDefinition.from_json(json_str)
self.definitionVerificationHelper(adef)
def test_AsVersionEmpty(self):
adef = ActivityDefinition()
adef2 = adef.as_version()
self.assertEqual(adef2, {})
def test_AsVersion(self):
adef = ActivityDefinition({
'description': {'en-US': 'test'},
'name': {'en-US': 'test'},
'type': 'test',
'more_info': 'test',
'interaction_type': 'choice',
'correct_responses_pattern': ['test'],
'choices': InteractionComponentList(),
'scale': InteractionComponentList(),
'source': InteractionComponentList(),
'target': InteractionComponentList(),
'steps': InteractionComponentList(),
'extensions': {'test': 'test'}
})
adef2 = adef.as_version()
self.assertEqual(adef2, {
"name": {"en-US": "test"},
"correctResponsesPattern": ["test"],
"scale": [],
"description": {"en-US": "test"},
"choices": [],
"source": [],
"steps": [],
"moreInfo": "test",
"extensions": {"test": "test"},
"interactionType": "choice",
"target": [],
"type": "test",
})
def test_AsVersionIgnoreNone(self):
adef = ActivityDefinition({
'description': {'en-US': 'test'},
'more_info': None
})
self.assertEqual(adef.description, {'en-US': 'test'})
self.assertIsNone(adef.more_info)
adef2 = adef.as_version()
self.assertEqual(adef2, {'description': {'en-US': 'test'}})
def test_ToJSONIgnoreNone(self):
adef = ActivityDefinition({
'description': {'en-US': 'test'},
'more_info': None
})
self.assertEqual(adef.to_json(), '{"description": {"en-US": "test"}}')
def test_ToJSONEmpty(self):
adef = ActivityDefinition()
self.assertEqual(adef.to_json(), '{}')
def definitionVerificationHelper(self, definition):
check_map = LanguageMap({'en-US': 'test'})
check_string = 'test'
self.assertIsInstance(definition.name, LanguageMap)
self.assertEqual(definition.name, check_map)
self.assertIsInstance(definition.description, LanguageMap)
self.assertEqual(definition.description, check_map)
self.assertEqual(definition.type, check_string)
self.assertEqual(definition.more_info, check_string)
self.assertEqual(definition.interaction_type, 'choice')
self.assertIn(definition.interaction_type, ActivityDefinition._interaction_types)
self.assertEqual(definition.correct_responses_pattern, ['test'])
self.assertEqual(definition.choices, [])
self.assertIsInstance(definition.choices, InteractionComponentList)
self.assertEqual(definition.scale, [])
self.assertIsInstance(definition.scale, InteractionComponentList)
self.assertEqual(definition.source, [])
self.assertIsInstance(definition.source, InteractionComponentList)
self.assertEqual(definition.target, [])
self.assertIsInstance(definition.target, InteractionComponentList)
self.assertEqual(definition.steps, [])
self.assertIsInstance(definition.steps, InteractionComponentList)
self.assertEqual(definition.extensions, {"test": "test"})
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(ActivityDefinitionTest)
unittest.TextTestRunner(verbosity=2).run(suite)
|
Obviously, it has actually ended up being popular for numerous after hours oral centers to use more specific services besides those that are generally categorized as emergency situations. In reality, some cosmetic services can be both an emergency situation and regular, depending upon your circumstance. For instance, an emergency situation oral workplace in Sutter, IL might have the ability to seal back on your caps and crowns that have actually ended up being loose after consuming, playing sports, or other regular activities. Also, the dental practitioner on call with this practice might accept take molds for oral implants if you have actually knocked out a tooth that ultimately has to be changed. If you use dentures, you can likewise bask in understanding that an emergency situation oral area in Sutter is on hire case you have to have actually these components fixed, even if on a short-term basis. These issues are essential to your health and capability to take pleasure in the rest of your day off.
When you feel the very first tints of a tooth pain or feel the discomfort of a damaged tooth in the back of your mouth, your very first idea might be, “Where am I going to discover an after oral workplace near me in Sutter, IL?”. In truth, this idea might be affordable if you have actually never ever needed to utilize the services of a dental professional who is open late for such emergency situations. When your main oral experiences have actually been relegated to the annual check-ups and exams advised for all clients, you might be uninformed that some dental professionals in Sutter make it a routine to remain open Friday nights or perhaps open Saturday for individuals who require very same day preventative services after the close of the routine service day. In reality, some dental experts in Sutter, IL who use basic care throughout the week likewise devote a particular quantity of time throughout the night hours and weekends to deal with walk-in clients who otherwise would need to go without oral care completely, either since of absence of time throughout the work week or since of an emergency situation. When you have to discover a dental practitioner in Sutter who is open early throughout the week or open Sunday, in addition to throughout the night hours, you can utilize this service in IL to obtain evaluations and get in touch with the oral workplace that would best match your requirements.
When you require a dental professional that is open on Saturday and you understand exactly what to do, you do exactly what anybody would do, you begin browsing online. At 24 Hour Dental, as soon as you call our toll-free directory site you will be gotten in touch with a operator and get gotten in touch with a dental practitioner in Sutter who can see you right away. You might be needed to inform this operator what type of concerns you are dealing with. For instance, if you have actually a broken tooth that is breaking and triggering you discomfort, you might have to be matched with an emergency situation oral cosmetic surgeon who can either put caps or crowns on it or eliminate it from your mouth completely. If you have teeth that are contaminated and exuding pus or blood, you might have to be seen by an emergency situation periodontist in Sutter, IL who can recommend an antibiotic and scrape away a few of the contaminated tissue around the base of your teeth. This info can be essential in ensuring you are provided the perfect contact information for a dental practitioner in Sutter, IL who can look after your oral problem this Saturday. It can be a matter of safeguarding your health and avoiding more issues from your oral problem when you call 24 Hour Dental in Sutter and asked to be matched with a dental professional open Saturday in Sutter, IL .
24 Hr Dental IL oral network has actually collaborate with regional dental practitioners to assist you in your discover a Sunday dental professional in Sutter. Now you that you have actually discovered the dental professional you have actually been trying to find its now time to consider how your going to pay. A lot of weekend or after hour care might not be covered by insurance coverage. It is something you have to take under factor to consider. Your dental practitioner might need payment at the time of the go to and your out-of-pocket expenditure might be qualified for repayment later on by your insurance company. It holds true that numerous dental experts who use weekend care hesitate to provide exact same day billing services. Their accountant might be off work or they might not have the computer systems operating to send billing for you. Nevertheless, when you call, the operator can assist you discover a Sunday oral workplace in Sutter that can use payment choices that satisfy your requirements the exact same time. Make certain to inform the operator if you have insurance coverage and exactly what your strategy is. They can assist link you to a in-network dental professional and conserve you cash.
Oral emergency situations take place when you least anticipate them to take place. You might be great on a Friday night, however then fall or suffer a mishap on Saturday that leaves your teeth painfully broke or broken. Instead of handle the discomfort and nurse your injury with moderate nonprescription pain relievers till the next service day, you can get quick and expert care by developing a relationship with a 24 hour dental professional in Sutter, IL. If you are not sure of where in IL to discover oral center open 24 hours, you can get the details that you require today by calling this totally free and personal Sutter 24 hour dental professional directory site. The Sutter dental expert directory site can offer you with the contact information to assist you establish an immediate dental practitioner visit with a 24 hour oral surgery service provider who might have the ability to provide sedation services or a minimum of offer you a prescription antibiotic till you can arrange a time for the expert repair work of your teeth in Sutter, IL.
By phoning our 24 hour dental expert directory site, you likewise might discover a 24 hour emergency situation dental practitioner in Sutter, IL who provides late hours and runs an oral center open on Sunday. While numerous companies in IL and beyond take Sundays off, others recognize that customers often require an emergency situation dental professional open late who can use them the assistance and convenience they require today. Instead of handle an unpleasant, frightening, and potentially dangerous oral circumstance till Monday early morning, you can rather utilize this 24/7 totally free oral directory site that runs in Sutter and in IL to find a 24 hour emergency situation dental practitioner near me who can treat you without delay without you needing to wait till the work week to begin once again.
|
import copy
import numpy as np
from matplotlib import pyplot as plt
try:
from mpld3 import plugins
except:
plugins = None
import param
from ...core import NdOverlay, Overlay
from ...element import HeatMap, Raster, Scatter, Curve, Points, Bars, Histogram
from . import CurvePlot, PointPlot, OverlayPlot, RasterPlot, HistogramPlot, BarPlot
class PlottingHook(param.ParameterizedFunction):
"""
PlottingHooks can be used to extend the default functionality
of HoloViews. Each ElementPlot type can be provided with a list of
hooks to apply at the end of plotting. The PlottingHook is provided
with ElementPlot instance, which gives access to the figure, axis
and artists via the handles, and the Element currently displayed
by the Plot. Since each Plot can be associated with multiple
Element plot types the Element types are validated against the
Elements in the types parameter.
"""
types = param.List([], doc="""List of types processed by the hook.""")
__abstract = True
def _applies(self, plot, view):
return type(view) in self.types
class MplD3Plugin(PlottingHook):
"""
The mpld3 library available as an optional backend
for HoloViews provides the option of adding
interactivity to the plot through various plugins.
Subclasses of this PlottingHook can enable
"""
css = param.String(doc="""CSS applied to HTML mpld3 Plugins.""", default="""
table {border-collapse: collapse;}
th {color: #ffffff; background-color: #000000;}
td {background-color: #cccccc;}
table, th, td {font-family:Arial, Helvetica, sans-serif;
border: 1px solid black; text-align: right;}""")
hoffset = param.Integer(default=10, doc="Vertical offset of the labels.")
voffset = param.Integer(default=10, doc="Horizontal offset of the labels.")
__abstract = True
def _applies(self, plot, view):
from ..ipython.magics import OutputMagic
types_match = super(MplD3Plugin, self)._applies(plot, view)
axes3d = plot.projection == '3d'
mpld3_backend = OutputMagic.options['backend'] == 'd3'
return types_match and mpld3_backend and not axes3d
class PointPlugin(MplD3Plugin):
"Labels each point with a table of its values."
types = param.List([Points, Scatter])
def __call__(self, plot, view):
if not self._applies(plot, view): return
fig = plot.handles['fig']
df = view.dframe()
labels = []
for i in range(len(df)):
label = df.ix[[i], :].T
label.columns = [view.label]
labels.append(str(label.to_html(header=len(view.label)>0)))
tooltip = plugins.PointHTMLTooltip(plot.handles['paths'], labels,
voffset=self.voffset, hoffset=self.hoffset,
css=self.css)
plugins.connect(fig, tooltip)
class CurvePlugin(MplD3Plugin):
"Labels each line with the Curve objects label"
format_string = param.String(default='<h4>{label}</h4>', doc="""
Defines the HTML representation of the Element label""")
types = param.List([Curve])
def __call__(self, plot, view):
if not self._applies(plot, view): return
fig = plot.handles['fig']
labels = [self.format_string.format(label=view.label)]
tooltip = plugins.LineHTMLTooltip(plot.handles['line_segment'], labels,
voffset=self.voffset, hoffset=self.hoffset,
css=self.css)
plugins.connect(fig, tooltip)
class BarPlugin(MplD3Plugin):
types = param.List([Bars])
def __call__(self, plot, view):
if not self._applies(plot, view): return
fig = plot.handles['fig']
for key, bar in plot.handles['bars'].items():
handle = bar.get_children()[0]
selection = [(d.name,{k}) for d, k in zip(plot.bar_dimensions, key)
if d is not None]
label_data = view.select(**dict(selection)).dframe().ix[0].to_frame()
label = str(label_data.to_html(header=len(view.label)>0))
tooltip = plugins.LineHTMLTooltip(handle, label, voffset=self.voffset,
hoffset=self.hoffset, css=self.css)
plugins.connect(fig, tooltip)
class HistogramPlugin(MplD3Plugin):
"Labels each bar with a table of its values."
types = param.List([Histogram])
def __call__(self, plot, view):
if not self._applies(plot, view): return
fig = plot.handles['fig']
df = view.dframe()
labels = []
for i in range(len(df)):
label = df.ix[[i], :].T
label.columns = [view.label]
labels.append(str(label.to_html(header=len(view.label)>0)))
for i, (bar, label) in enumerate(zip(plot.handles['bars'].get_children(), labels)):
tooltip = plugins.LineHTMLTooltip(bar, label, voffset=self.voffset,
hoffset=self.hoffset, css=self.css)
plugins.connect(fig, tooltip)
class RasterPlugin(MplD3Plugin):
"""
Replaces the imshow based Raster image with a
pcolormesh, allowing each pixel to be labelled.
"""
types = param.List(default=[Raster, HeatMap])
def __call__(self, plot, view):
if not self._applies(plot, view): return
fig = plot.handles['fig']
ax = plot.handles['axis']
valid_opts = ['cmap']
opts = {k:v for k,v, in plot.style.options.items()
if k in valid_opts}
data = view.data
rows, cols = view.data.shape
if isinstance(view, HeatMap):
data = np.ma.array(data, mask=np.isnan(data))
cmap = copy.copy(plt.cm.get_cmap(opts.get('cmap', 'gray')))
cmap.set_bad('w', 1.)
opts['cmap'] = cmap
df = view.dframe(True).fillna(0)
df = df.sort([d.name for d in view.dimensions()[1:2]])[::-1]
l, b, r, t = (0, 0, 1, 1)
data = np.flipud(data)
else:
df = view.dframe().sort(['y','x'], ascending=(1,1))[::-1]
l, b, r, t = (0, 0, cols, rows)
for k, ann in plot.handles.get('annotations', {}).items():
ann.remove()
plot.handles['annotations'].pop(k)
# Generate color mesh to label each point
cols+=1; rows+=1
cmin, cmax = view.range(2)
x, y = np.meshgrid(np.linspace(l, r, cols), np.linspace(b, t, rows))
plot.handles['im'].set_visible(False)
mesh = ax.pcolormesh(x, y, data, vmin=cmin, vmax=cmax, **opts)
ax.invert_yaxis() # Doesn't work uninverted
df.index = range(len(df))
labels = []
for i in range(len(df)):
label = df.ix[[i], :].T
label.columns = [' '.join([view.label, view.group])]
labels.append(str(label.to_html(header=len(view.label)>0)))
tooltip = plugins.PointHTMLTooltip(mesh, labels[::-1], hoffset=self.hoffset,
voffset=self.voffset, css=self.css)
plugins.connect(fig, tooltip)
class LegendPlugin(MplD3Plugin):
"""
Provides an interactive legend allowing selecting
and unselecting of different elements.
"""
alpha_unsel = param.Number(default=0.2, doc="""
The alpha level of the unselected elements""")
alpha_sel = param.Number(default=2.0, doc="""
The alpha level of the unselected elements""")
types = param.List([Overlay, NdOverlay])
def __call__(self, plot, view):
if not self._applies(plot, view): return
fig = plot.handles['fig']
if 'legend' in plot.handles:
plot.handles['legend'].set_visible(False)
line_segments, labels = [], []
keys = view.keys()
for idx, subplot in enumerate(plot.subplots.values()):
if isinstance(subplot, PointPlot):
line_segments.append(subplot.handles['paths'])
if isinstance(view, NdOverlay):
labels.append(str(keys[idx]))
else:
labels.append(subplot.hmap.last.label)
elif isinstance(subplot, CurvePlot):
line_segments.append(subplot.handles['line_segment'])
if isinstance(view, NdOverlay):
labels.append(str(keys[idx]))
else:
labels.append(subplot.hmap.last.label)
tooltip = plugins.InteractiveLegendPlugin(line_segments, labels,
alpha_sel=self.alpha_sel,
alpha_unsel=self.alpha_unsel)
plugins.connect(fig, tooltip)
if plugins is not None:
OverlayPlot.finalize_hooks = [LegendPlugin]
RasterPlot.finalize_hooks = [RasterPlugin]
CurvePlot.finalize_hooks = [CurvePlugin]
PointPlot.finalize_hooks = [PointPlugin]
HistogramPlot.finalize_hooks = [HistogramPlugin]
BarPlot.finalize_hooks = [BarPlugin]
|
For Ringette Associations looking to give all their goalies a day (or weekend) of goalie attention. *Limited weekends available, first come, first served. Beginner goalies up to AA/AAA caliber.
We have limited weekends available to book Goalie Clinics so the earlier you reserve a weekend, the better. Contact Keely or Heather if your Association is interested in booking us for this coming season. We can talk with your Association’s board and are prepared to discuss options that will work for your teams and your goalies.
|
# -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2018 CERN.
#
# CERN Analysis Preservation Framework 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.
#
# CERN Analysis Preservation Framework 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 CERN Analysis Preservation Framework; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Util methods for fixtures."""
import json
import uuid
from elasticsearch import helpers
from elasticsearch_dsl import Q
from flask import current_app
from invenio_access.models import Role
from invenio_db import db
from invenio_pidstore.errors import PIDDoesNotExistError
from invenio_pidstore.models import PersistentIdentifier
from invenio_search import RecordsSearch
from invenio_search.proxies import current_search_client as es
from cap.modules.deposit.api import CAPDeposit
from cap.modules.deposit.errors import DepositDoesNotExist
from cap.modules.deposit.fetchers import cap_deposit_fetcher
from cap.modules.deposit.minters import cap_deposit_minter
from cap.modules.user.utils import get_existing_or_register_user
def construct_draft_obj(schema, data):
"""Contructs a draft object."""
entry = {
'$schema': 'https://{}/schemas/deposits/records/{}.json'.format(
current_app.config.get('JSONSCHEMAS_HOST'),
schema)
}
entry.update(data)
return entry
def get_entry_uuid_by_unique_field(index, dict_unique_field_value):
"""Return record by uuid."""
rs = RecordsSearch(index=index)
res = rs.query(Q('match',
**dict_unique_field_value)).execute().hits.hits
if not res:
raise DepositDoesNotExist
else:
return res[0]['_id']
def add_read_permission_for_egroup(deposit, egroup):
"""Add read permission for egroup."""
role = Role.query.filter_by(name=egroup).one()
deposit._add_egroup_permissions(role,
['deposit-read'],
db.session)
deposit.commit()
db.session.commit()
def add_drafts_from_file(file_path, schema,
egroup=None, usermail=None, limit=None):
"""Add drafts from a specified file.
Drafts with specified pid will be registered under those.
For drafts without pid, new pids will be minted.
"""
if usermail:
user = get_existing_or_register_user(usermail)
else:
user = None
with open(file_path, 'r') as fp:
entries = json.load(fp)
for entry in entries[0:limit]:
data = construct_draft_obj(schema, entry)
pid = cap_deposit_fetcher(None, data)
pid_value = pid.pid_value if pid else None
try:
PersistentIdentifier.get('depid', pid_value)
print('Draft with id {} already exist!'.format(pid_value))
except PIDDoesNotExistError:
record_uuid = uuid.uuid4()
pid = cap_deposit_minter(record_uuid, data)
deposit = CAPDeposit.create(data, record_uuid, user)
deposit.commit()
if egroup:
add_read_permission_for_egroup(deposit, egroup)
print('Draft {} added.'.format(pid.pid_value))
db.session.commit()
def bulk_index_from_source(index_name, doc_type, source):
"""Indexes from source."""
actions = [{
"_index": index_name,
"_type": doc_type,
"_id": idx,
"_source": obj
} for idx, obj in enumerate(source)]
helpers.bulk(es, actions)
|
With minutes left to play and the biggest game in club football once again in his hands, Arjen Robben made sure he didn't miss this time.
Robben found redemption at Wembley Stadium on Saturday, scoring the winner in the 89th minute of the Champions League final to give Bayern a 2-1 victory over German rival Borussia Dortmund – ending four years of frustration for his team in Europe's biggest tournament and erasing some of the painful memories of his penalty miss in last year's final.
"I don't know how many times I dreamed about it," Robben said. "Everybody I spoke to before the game I said, 'Today is going to be the night and we're going to do it.' To do it in the end is an unbelievable feeling."
This was a win that was long in the making for both Robben and Bayern, not only because of the stubborn challenge from a Dortmund side that refused to accept its status as underdog in the club's biggest game in 16 years. Bayern had lost two of the last three Champions League finals, including the gut-wrenching defeat in a penalty shootout to Chelsea last year in its own stadium in Munich.
Robben missed a penalty in extra time in that game, a mistake that stung the Bayern fans so much that many temporarily turned against him. This time, when he carried the European Cup toward the thousands of celebrating red-and-white fans and raised it over his head, there was nothing but undivided adulation in return.
"There are so many emotions, especially after where we came from. Last year was such a disappointment," Robben said. "We've spoken about it. The last four years, we've been in the final three times. It needed to happen but you still have to do it."
In a game that featured a slew of chances for both teams, Mario Mandzukic put Bayern ahead in the 60th minute at Wembley Stadium before Ilkay Gundogan levelled from the penalty spot eight minutes later, after defender Dante fouled Marco Reus in the area.
Robben had missed two great chances in the first half, reviving memories of last year and even of the 2010 World Cup final, when the winger missed the Netherlands' best chance when he came one-on-one with Spain goalkeeper Iker Casillas and missed.
Even Bayern great Franz Beckenbauer, the club's honorary president, said on TV during halftime that "evidently in the big games he just can't score."
Robben ran onto Franck Ribery's backheeled flick-on in the area and calmly slotted the ball past goalkeeper Roman Weidenfeller to give Bayern its first Champions League victory since 2001. Bayern lost to Inter Milan in the 2010 final.
"That's three finals and of course you don't want the stamp of a loser, you don't want that tag," Robben said. "It was a sense of 'finally.' It was unbelievable, I can't describe what's going through my mind."
Robben also set up the first goal for Bayern, taking a pass from Ribery and drawing Weidenfeller out toward the touchline before squaring for Mandzukic, who could hardly miss from a few yards out.
But the lead didn't last long. Dante clumsily clattered into Reus in the area, and Italian referee Nicola Rizzoli pointed to the spot. Gundogan sent Manuel Neuer the wrong way before calmly slotting his spot kick into the right side of the net.
But Dortmund seemed to tire toward the end, and Bayern had a couple of good chances before Robben's late winner.
"It's hard to deal with the disappointment right now, especially if you concede the goal in the 89th minute," Dortmund defender Mats Hummels said. "In the end we had become a little tired and Bayern took advantage."
The European Cup title caps a spectacular season for Bayern, which broke a host of Bundesliga records in running away with the German league title – finishing an unprecedented 25 points ahead of second-place Dortmund.
It can still complete a treble, as it faces Stuttgart in the German Cup final next Saturday.
Regardless of that result, coach Jupp Heynckes will leave the German powerhouse in perfect style. Heynckes, who is stepping down at the end of the season, won his second Champions League trophy after leading Real Madrid to the title in 1998. He will be replaced by Pep Guardiola next season, but the former Barcelona coach will have a hard time improving on this Bayern side – which dismantled the Spanish giants 7-0 on aggregate in the semifinals.
"It's incredible what the team had achieved in the last few years. And today we were finally rewarded. We had to overcome a lot of setbacks," Bayern captain Philipp Lahm said. "There was so much pressure, it was enormous. After you lose two finals, if you lose again you don't know if you'll get another chance. The pressure was so great, I've never felt so much pressure before. The international titles were missing, we never won a big international title for this generation."
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#
# This file is part of the NNGT project to generate and analyze
# neuronal networks and their activity.
# Copyright (C) 2015-2019 Tanguy Fardet
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" Analyze the activity of a network """
from collections import namedtuple
from copy import deepcopy
import weakref
import nest
import numpy as np
from nngt.lib import InvalidArgument, nonstring_container
from .nest_utils import nest_version, _get_nest_gids
__all__ = [
"ActivityRecord",
"activity_types",
"analyze_raster",
"get_recording",
]
# ------------------------------ #
# Finding the various activities #
# ------------------------------ #
class ActivityRecord:
'''
Class to record the properties of the simulated activity.
'''
def __init__(self, spike_data, phases, properties, parameters=None):
'''
Initialize the instance using `spike_data` (store proxy to an optional
`network`) and compute the properties of provided data.
Parameters
----------
spike_data : 2D array
Array of shape (num_spikes, 2), containing the senders on the 1st
row and the times on the 2nd row.
phases : dict
Limits of the different phases in the simulated period.
properties : dict
Values of the different properties of the activity (e.g.
"firing_rate", "IBI"...).
parameters : dict, optional (default: None)
Parameters used to compute the phases.
Note
----
The firing rate is computed as num_spikes / total simulation time,
the period is the sum of an IBI and a bursting period.
'''
self._data = spike_data
self._phases = phases.copy()
self._properties = properties.copy()
self.parameters = parameters
def simplify():
raise NotImplementedError("Will be implemented soon.")
@property
def data(self):
'''
Returns the (N, 2) array of (senders, spike times).
'''
return self._data
@property
def phases(self):
'''
Return the phases detected:
- "bursting" for periods of high activity where a large fraction
of the network is recruited.
- "quiescent" for periods of low activity
- "mixed" for firing rate in between "quiescent" and "bursting".
- "localized" for periods of high activity but where only a small
fraction of the network is recruited.
Note
----
See `parameters` for details on the conditions used to
differenciate these phases.
'''
return self._phases
@property
def properties(self):
'''
Returns the properties of the activity.
Contains the following entries:
- "firing_rate": average value in Hz for 1 neuron in the network.
- "bursting": True if there were bursts of activity detected.
- "burst_duration", "IBI", "ISI", and "period" in ms, if
"bursting" is True.
- "SpB" (Spikes per Burst): average number of spikes per neuron
during a burst.
'''
return self._properties
# ---------------- #
# Analyse activity #
# ---------------- #
def get_recording(network, record, recorder=None, nodes=None):
'''
Return the evolution of some recorded values for each neuron.
Parameters
----------
network : :class:`nngt.Network`
Network for which the activity was simulated.
record : str or list
Name of the record(s) to obtain.
recorder : tuple of ints, optional (default: all multimeters)
GID of the "spike_detector" objects recording the network activity.
nodes : array-like, optional (default: all nodes)
NNGT ids of the nodes for which the recording should be returned.
Returns
-------
values : dict of dict of arrays
Dictionary containing, for each `record`, an M array with the
recorded values for n-th neuron is stored under entry `n` (integer).
A `times` entry is also added; it should be the same size for all
records, otherwise an error will be raised.
Examples
--------
After the creation of a :class:`~nngt.Network` called ``net``, use the
following code: ::
import nest
rec, _ = monitor_nodes(
net.nest_gids, "multimeter", {"record_from": ["V_m"]}, net)
nest.Simulate(100.)
recording = nngt.simulation.get_recording(net, "V_m")
# access the membrane potential of first neuron + the times
V_m = recording["V_m"][0]
times = recording["times"]
'''
if nodes is None:
nodes = [network.id_from_nest_gid(n) for n in network.nest_gids]
gids = _get_nest_gids([network.nest_gids[n] for n in nodes])
if not nonstring_container(record):
record = [record]
values = {rec: {} for rec in record}
if recorder is None:
if nest_version == 3:
recorder = nest.GetNodes(properties={'model': 'multimeter'})
else:
recorder = nest.GetNodes((0,), properties={'model': 'multimeter'})
times = None
for rec in recorder:
events = nest.GetStatus(rec, "events")[0]
senders = events["senders"]
if times is not None:
assert times == events["times"], "Different times between the " +\
"recorders; check the params."
times = events["times"]
values["times"] = times[senders == senders[0]]
for rec_name in record:
for idx, gid in zip(nodes, gids):
ids = (senders == senders[gid])
values[rec_name][idx] = events[rec_name][ids]
return values
def activity_types(spike_detector, limits, network=None,
phase_coeff=(0.5, 10.), mbis=0.5, mfb=0.2, mflb=0.05,
skip_bursts=0, simplify=False, fignums=[], show=False):
'''
Analyze the spiking pattern of a neural network.
@todo:
think about inserting t=0. and t=simtime at the beginning and at the
end of ``times``.
Parameters
----------
spike_detector : NEST node(s) (tuple or list of tuples)
The recording device that monitored the network's spikes.
limits : tuple of floats
Time limits of the simulation region which should be studied (in ms).
network : :class:`~nngt.Network`, optional (default: None)
Neural network that was analyzed
phase_coeff : tuple of floats, optional (default: (0.2, 5.))
A phase is considered 'bursting' when the interspike between all spikes
that compose it is smaller than ``phase_coeff[0] / avg_rate`` (where
``avg_rate`` is the average firing rate), 'quiescent' when it is
greater that ``phase_coeff[1] / avg_rate``, 'mixed' otherwise.
mbis : float, optional (default: 0.5)
Maximum interspike interval allowed for two spikes to be considered in
the same burst (in ms).
mfb : float, optional (default: 0.2)
Minimal fraction of the neurons that should participate for a burst to
be validated (i.e. if the interspike is smaller that the limit BUT the
number of participating neurons is too small, the phase will be
considered as 'localized').
mflb : float, optional (default: 0.05)
Minimal fraction of the neurons that should participate for a local
burst to be validated (i.e. if the interspike is smaller that the limit
BUT the number of participating neurons is too small, the phase will be
considered as 'mixed').
skip_bursts : int, optional (default: 0)
Skip the `skip_bursts` first bursts to consider only the permanent
regime.
simplify: bool, optional (default: False)
If ``True``, 'mixed' phases that are contiguous to a burst are
incorporated to it.
return_steps : bool, optional (default: False)
If ``True``, a second dictionary, `phases_steps` will also be returned.
@todo: not implemented yet
fignums : list, optional (default: [])
Indices of figures on which the periods can be drawn.
show : bool, optional (default: False)
Whether the figures should be displayed.
Note
----
Effects of `skip_bursts` and `limits[0]` are cumulative: the `limits[0]`
first milliseconds are ignored, then the `skip_bursts` first bursts of the
remaining activity are ignored.
Returns
-------
phases : dict
Dictionary containing the time intervals (in ms) for all four phases
(`bursting', `quiescent', `mixed', and `localized`) as lists.
E.g: ``phases["bursting"]`` could give ``[[123.5,334.2],
[857.1,1000.6]]``.
'''
# check if there are several recorders
senders, times = [], []
if True in nest.GetStatus(spike_detector, "to_file"):
for fpath in nest.GetStatus(spike_detector, "record_to"):
data = _get_data(fpath)
times.extend(data[:, 1])
senders.extend(data[:, 0])
else:
for events in nest.GetStatus(spike_detector, "events"):
times.extend(events["times"])
senders.extend(events["senders"])
idx_sort = np.argsort(times)
times = np.array(times)[idx_sort]
senders = np.array(senders)[idx_sort]
# compute phases and properties
data = np.array((senders, times))
phases, fr = _analysis(times, senders, limits, network=network,
phase_coeff=phase_coeff, mbis=mbis, mfb=mfb, mflb=mflb,
simplify=simplify)
properties = _compute_properties(data, phases, fr, skip_bursts)
kwargs = {
"limits": limits,
"phase_coeff": phase_coeff,
"mbis": mbis,
"mfb": mfb,
"mflb": mflb,
"simplify": simplify
}
# plot if required
if show:
_plot_phases(phases, fignums)
return ActivityRecord(data, phases, properties, kwargs)
def analyze_raster(raster=None, limits=None, network=None,
phase_coeff=(0.5, 10.), mbis=0.5, mfb=0.2, mflb=0.05,
skip_bursts=0, skip_ms=0., simplify=False, fignums=[],
show=False):
'''
Return the activity types for a given raster.
Parameters
----------
raster : array-like (N, 2) or str
Either an array containing the ids of the spiking neurons on the first
column, then the corresponding times on the second column, or the path
to a NEST .gdf recording.
limits : tuple of floats
Time limits of the simulation regrion which should be studied (in ms).
network : :class:`~nngt.Network`, optional (default: None)
Network on which the recorded activity was simulated.
phase_coeff : tuple of floats, optional (default: (0.2, 5.))
A phase is considered 'bursting' when the interspike between all spikes
that compose it is smaller than ``phase_coeff[0] / avg_rate`` (where
``avg_rate`` is the average firing rate), 'quiescent' when it is
greater that ``phase_coeff[1] / avg_rate``, 'mixed' otherwise.
mbis : float, optional (default: 0.5)
Maximum interspike interval allowed for two spikes to be considered in
the same burst (in ms).
mfb : float, optional (default: 0.2)
Minimal fraction of the neurons that should participate for a burst to
be validated (i.e. if the interspike is smaller that the limit BUT the
number of participating neurons is too small, the phase will be
considered as 'localized').
mflb : float, optional (default: 0.05)
Minimal fraction of the neurons that should participate for a local
burst to be validated (i.e. if the interspike is smaller that the limit
BUT the number of participating neurons is too small, the phase will be
considered as 'mixed').
skip_bursts : int, optional (default: 0)
Skip the `skip_bursts` first bursts to consider only the permanent
regime.
simplify: bool, optional (default: False)
If ``True``, 'mixed' phases that are contiguous to a burst are
incorporated to it.
fignums : list, optional (default: [])
Indices of figures on which the periods can be drawn.
show : bool, optional (default: False)
Whether the figures should be displayed.
Note
----
Effects of `skip_bursts` and `limits[0]` are cumulative: the
`limits[0]` first milliseconds are ignored, then the `skip_bursts`
first bursts of the remaining activity are ignored.
Returns
-------
activity : ActivityRecord
Object containing the phases and the properties of the activity
from these phases.
'''
data = _get_data(raster) if isinstance(raster, str) else raster
if data.any():
if limits is None:
limits = [np.min(data[:, 1]), np.max(data[:, 1])]
kwargs = {
"limits": limits,
"phase_coeff": phase_coeff,
"mbis": mbis,
"mfb": mfb,
"mflb": mflb,
"simplify": simplify
}
# compute phases and properties
phases, fr = _analysis(data[:, 1], data[:, 0], limits, network=network,
phase_coeff=phase_coeff, mbis=mbis, mfb=mfb, mflb=mflb,
simplify=simplify)
properties = _compute_properties(data.T, phases, fr, skip_bursts)
# plot if required
if show:
import matplotlib.pyplot as plt
if fignums:
_plot_phases(phases, fignums)
else:
fig, ax = plt.subplots()
ax.scatter(data[:, 1], data[:, 0])
_plot_phases(phases, [fig.number])
return ActivityRecord(data, phases, properties, kwargs)
return ActivityRecord(data, {}, {})
# ----- #
# Tools #
# ----- #
def _get_data(source):
'''
Returns the (times, senders) array.
Parameters
----------
source : list or str
Indices of spike detectors or path to the .gdf files.
Returns
-------
data : 2D array of shape (N, 2)
'''
data = [[],[]]
is_string = isinstance(source, str)
if is_string:
source = [source]
elif nonstring_container(source) and isinstance(source[0], str):
is_string = True
if is_string:
for path in source:
tmp = np.loadtxt(path)
data[0].extend(tmp[:, 0])
data[1].extend(tmp[:, 1])
else:
source_shape = np.shape(np.squeeze(source))
if len(source_shape) == 2:
# source is directly the data
if source_shape[0] == 2 and source_shape[1] != 2:
return np.array(source).T
else:
return np.array(source)
else:
# source contains gids
source = _get_nest_gids(source)
events = None
if nonstring_container(source[0]):
events = [nest.GetStatus(gid, "events")[0] for gid in source]
else:
events = nest.GetStatus(source, "events")
for ev in events:
data[0].extend(ev["senders"])
data[1].extend(ev["times"])
idx_sort = np.argsort(data[1])
return np.array(data)[:, idx_sort].T
def _find_phases(times, phases, lim_burst, lim_quiet, simplify):
'''
Find the time limits of the different phases.
'''
diff = np.diff(times).tolist()[::-1]
i = 0
previous = {"bursting": -2, "mixed": -2, "quiescent": -2}
while diff:
tau = diff.pop()
while True:
if tau < lim_burst: # bursting phase
if previous["bursting"] == i-1:
phases["bursting"][-1][1] = times[i+1]
else:
if simplify and previous["mixed"] == i-1:
start_mixed = phases["mixed"][-1][0]
phases["bursting"].append([start_mixed, times[i+1]])
del phases["mixed"][-1]
else:
phases["bursting"].append([times[i], times[i+1]])
previous["bursting"] = i
i+=1
break
elif tau > lim_quiet:
if previous["quiescent"] == i-1:
phases["quiescent"][-1][1] = times[i+1]
else:
phases["quiescent"].append([times[i], times[i+1]])
previous["quiescent"] = i
i+=1
break
else:
if previous["mixed"] == i-1:
phases["mixed"][-1][1] = times[i+1]
previous["mixed"] = i
else:
if simplify and previous["bursting"] == i-1:
phases["bursting"][-1][1] = times[i+1]
previous["bursting"] = i
else:
phases["mixed"].append([times[i], times[i+1]])
previous["mixed"] = i
i+=1
break
def _check_burst_size(phases, senders, times, network, mflb, mfb):
'''
Check that bursting periods involve at least a fraction mfb of the neurons.
'''
transfer, destination = [], {}
n = len(set(senders)) if network is None else network.node_nb()
for i,burst in enumerate(phases["bursting"]):
idx_start = np.where(times==burst[0])[0][0]
idx_end = np.where(times==burst[1])[0][0]
participating_frac = len(set(senders[idx_start:idx_end])) / float(n)
if participating_frac < mflb:
transfer.append(i)
destination[i] = "mixed"
elif participating_frac < mfb:
transfer.append(i)
destination[i] = "localized"
for i in transfer[::-1]:
phase = phases["bursting"].pop(i)
phases[destination[i]].insert(0, phase)
remove = []
i = 0
while i < len(phases['mixed']):
mixed = phases['mixed'][i]
j=i+1
for span in phases['mixed'][i+1:]:
if span[0] == mixed[1]:
mixed[1] = span[1]
remove.append(j)
elif span[1] == mixed[0]:
mixed[0] = span[0]
remove.append(j)
j+=1
i+=1
remove = list(set(remove))
remove.sort()
for i in remove[::-1]:
del phases["mixed"][i]
def _analysis(times, senders, limits, network=None,
phase_coeff=(0.5, 10.), mbis=0.5, mfb=0.2, mflb=0.05,
simplify=False):
# prepare the phases and check the validity of the data
phases = {
"bursting": [],
"mixed": [],
"quiescent": [],
"localized": []
}
num_spikes, avg_rate = len(times), 0.
if num_spikes:
num_neurons = (len(np.unique(senders)) if network is None
else network.node_nb())
# set the studied region
if limits[0] >= times[0]:
idx_start = np.where(times >= limits[0])[0][0]
times = times[idx_start:]
senders = senders[idx_start:]
if limits[1] <= times[-1]:
idx_end = np.where(times <= limits[1])[0][-1]
times = times[:idx_end]
senders = senders[:idx_end]
# get the average firing rate to differenciate the phases
simtime = limits[1] - limits[0]
lim_burst, lim_quiet = 0., 0.
avg_rate = num_spikes / float(simtime)
lim_burst = max(phase_coeff[0] / avg_rate, mbis)
lim_quiet = min(phase_coeff[1] / avg_rate, 10.)
# find the phases
_find_phases(times, phases, lim_burst, lim_quiet, simplify)
_check_burst_size(phases, senders, times, network, mflb, mfb)
avg_rate *= 1000. / float(num_neurons)
return phases, avg_rate
def _compute_properties(data, phases, fr, skip_bursts):
'''
Compute the properties from the spike times and phases.
Parameters
----------
data : 2D array, shape (N, 2)
Spike times and senders.
phases : dict
The phases.
fr : double
Firing rate.
Returns
-------
prop : dict
Properties of the activity. Contains the following pairs:
- "firing_rate": average value in Hz for 1 neuron in the network.
- "bursting": True if there were bursts of activity detected.
- "burst_duration", "ISI", and "IBI" in ms, if "bursting" is True.
- "SpB": average number of spikes per burst for one neuron.
'''
prop = {}
times = data[1, :]
# firing rate (in Hz, normalized for 1 neuron)
prop["firing_rate"] = fr
num_bursts = len(phases["bursting"])
init_val = 0. if num_bursts > skip_bursts else np.NaN
if num_bursts:
prop["bursting"] = True
prop.update({
"burst_duration": init_val,
"IBI": init_val,
"ISI": init_val,
"SpB": init_val,
"period": init_val})
else:
prop["bursting"] = False
for i, burst in enumerate(phases["bursting"]):
if i >= skip_bursts:
# burst_duration
prop["burst_duration"] += burst[1] - burst[0]
# IBI
if i > 0:
end_older_burst = phases["bursting"][i-1][1]
prop["IBI"] += burst[0]-end_older_burst
# get num_spikes inside the burst, divide by num_neurons
idxs = np.where((times >= burst[0])*(times <= burst[1]))[0]
num_spikes = len(times[idxs])
num_neurons = len(set(data[0, :][idxs]))
if num_neurons:
prop["SpB"] += num_spikes / float(num_neurons)
# ISI
if num_spikes:
prop["ISI"] += num_neurons * (burst[1] - burst[0])\
/ float(num_spikes)
for key in prop.keys():
if key not in ("bursting", "firing_rate") and num_bursts > skip_bursts:
prop[key] /= float(num_bursts - skip_bursts)
if num_bursts > skip_bursts:
prop["period"] = prop["IBI"] + prop["burst_duration"]
if num_bursts and prop["SpB"] < 2.:
prop["ISI"] = np.NaN
return prop
def _plot_phases(phases, fignums):
import matplotlib.pyplot as plt
colors = ('r', 'orange', 'g', 'b')
names = ('bursting', 'mixed', 'localized', 'quiescent')
for fignum in fignums:
fig = plt.figure(fignum)
for ax in fig.axes:
for phase, color in zip(names, colors):
for span in phases[phase]:
ax.axvspan(span[0], span[1], facecolor=color,
alpha=0.2)
plt.show()
|
Choosing the ideal stuff for your own shower curtains. At this time it’s necessary for you to understand that shower curtains are all created by several substances. Vinyl and material would be the common material you are able to choose. In addition, they are on flexible cost. Eventually, all those are typical some hints you may choose from the vanities by depth great for narrow bathrooms home.
Oval sink with trendy look of vainness may assist the cabinet to offer wider impression. Apart from that, egg-shaped spout lets you have more distances compared to this sq sink. Washstand along with the drawers pub will function as the next factor. You do not have to present added distance to hang the towel while in the end. Specific brands will provide you magnificent urban or industrial look for your own cabinet.
Are you on the lookout for some ideas for your futuristic cabinet theme to be full of suitable furniture? Then, mini chandelier for cabinet can eventually become your best solution with this circumstance. They aren’t just in a position to increase your cabinet look into more tranquility looking however they are also very useful yet stylish! Following are a few selections of vanities by depth great for narrow bathrooms home.
People are able to just go to the store and they will be able to discover different choices of cabinet counter that could be set up in their house. Some people may be tempted together with the cabinet counter that resembles something that can make the luxury cabinet for instance. But, individuals must see the cabinet counter that looks perfect for other cabinets does not always give exactly the same effect to his or her cabinet. Measurement which includes vanities by depth great for narrow bathrooms home needs to be one of the absolute most essential things to think about when folks would like to acquire the cabinet counter with the optimal/optimally look and work inside their cabinet. This usually means they have to focus on the accessible space in the cabinet also.
The Color of Luxury. Really, all of the shades can spell out that the luxurious. However, I really put a focus on gray, black and white since they are going to encourage your cabinet components seem greater than others. So, whenever you want to get the accessories, do not neglect to select them to fulfill your vanities by depth great for narrow bathrooms home!
vanities by depth great for narrow bathrooms home will encourage the cabinet design. Until this period, you can find lots of materials which contain the vinyl like ceramic, marble, porcelain, and glass. The correct tile which people choose may determine that our cabinet looks additionally the use of the tile way too. Now’s article will criticism in regards to the cabinet tile layout and these ideas.
This Vanities By Depth Great For Narrow Bathrooms Home the gallery form Narrow Depth Base Cabinets. Hopefully you can find the best inspiration from our gallery here.
|
# -*- coding: utf-8 -*-
"""
RED Plugin
Copyright (C) 2014 Olaf Lüke <olaf@tinkerforge.com>
Copyright (C) 2014 Ishraq Ibne Ashraf <ishraq@tinkerforge.com>
config_parser.py: Parses key=value configs from RED Brick
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
"""
from io import StringIO
import configparser
def parse(data):
if isinstance(data, list):
string = bytes(data).decode('utf-8')
elif isinstance(data, str):
string = data
else:
return None
config = configparser.ConfigParser()
config.read_file(['[fake_section]'] + [l for l in string.splitlines() if not l.find('=') < 0])
try:
config = dict(config.items('fake_section'))
except:
return None
return config
def parse_no_fake(data):
if isinstance(data, list):
string = bytes(data).decode('utf-8')
elif isinstance(data, str):
string = data
else:
return None
config = configparser.ConfigParser()
config.read_string(string)
return config
def to_string(data):
config = configparser.ConfigParser()
config.add_section('fake_section')
for key, value in data.items():
config.set('fake_section', key, value)
s = StringIO()
config.write(s)
return s.getvalue().replace('[fake_section]\n', '')
def to_string_no_fake(data):
s = StringIO()
data.write(s)
return s.getvalue()
|
At Marstudio we are strategic branding experts. Through our comprehensive research process, we create unique visual brands for each of our clients. We provide you a visually pleasing and recognizable foundation to build your company’s image on and use across your multiple marketing initiatives. We invest ample time identifying your target demographic in order to create logos that resonate with them, hence helping distinguish your business from your competition.
A&S was looking to rebrand with a stronger focus on their two divisions, Home and Commercial. Both have stone and tile offerings, but to two different customer groups, using two different sales methods. A&S Home provides stone and tile as well as additional home design services and products directly to the consumers, while A&S Commercial primarily works with contractors. We created two different logos that worked together visually but still had clear distinctions for each division. We were able to associate the two brands without creating confusion online, within the company, and overall.
Celestial Fire Glass was looking for a brand that was as eye-catching as their products. We explored how we could create concepts that embody the product and its associated name, focusing on the concept of celestial bodies. The product itself also gave us a lot of visual cues to work with. The colors represent the range of colors available for the product. Overall, this is a very fresh and sophisticated concept with multiple layers that can easily be used for marketing down the road.
Alstom is a French developer of integrated railway systems, and manufacturer of Acela trains. Alstom asked Marstudio to develop a brand that would give them prominence in their field and ensure they would stand out among the competition. We simplified the existing concept to its core strengths and designed a logo that could exist with and compliment the Amtrak and Acela brands while having the necessary presence to stand alone.
Ayoub N&H is a family owned and operated floor covering company. Marstudio created a custom logo which takes cues from Ayoub N&H’s heritage yet still appears modern and powerful. The complex nature of the shape is based on the embroidery and rug patterns. The letter A, representing Ayoub, is present in the shape and it is woven into the icon. The color palette is precise, sophisticated and portrays Ayoub N&H as an elite business that is competent and professional yet rooted in history and family heritage.
Brian Shefferman Law, a criminal defense law firm, came to Marstudio looking to build a firm from the brand up. The letters “S” and “L” are intertwined in the icon, and the angles speak to the process of covering all possible angles when it comes to criminal defense. The three-dimensional nature of the icon presents stability and confidence, representing building a strong case to defend clients. The ultimate shape is very strong and cohesive which emulates Shefferman Law’s services.
CPeople, a leading provider of healthcare information technology consulting services, came to Marstudio for a brand refresh. We refined the existing concept to make it more modern, current, and sophisticated by fine-tuning the curves of the logo. The result is a more symmetrical and balanced look. The new typeface is custom-made and compliments the curves of the logo. Choosing an uppercase typeface conceptually conveys a sense of strength, authority, and stability, since consulting is all about competency and credibility. Small changes make the biggest impacts; this brand refresh is all about the details.
DC Spiritual Director’s core services set Marstudio on a path to create a design that not only had inherent meaning but also conveyed a certain feeling and perception right from the onset. Marstudio designed a logo that showcases DC Spiritual Director’s goal of “Sparking Hope, Igniting Change.” The flame represents passion, light, strength, and energy. It capitalizes on the energy that that DC Spiritual Director provides with his talks and how he helps spark lasting change in the people he engages with. The play of dark and light colors in the palette metaphorically represents spiritual guidance.
Digital Mobilizations, Inc. is an Engineering Services corporation who came to Marstudio for a branding refresh and logo redesign. We focused on combining three conceptual elements in order to create a unique icon that represents the essence of the company. The strong lines of the icon speak volumes to the strength that Digital Mobilizations portrays. The stark lettering creates a strong contrast and gives the overall design a unique depth and sophistication. We then topped off the design with our selected tagline. Overall, this is a very strong brand that has great marketing potential with a good elevator pitch built in.
FitRec, a new social fitness app, was looking to create a strong brand with a focus on making bold fitness choices. A bold, visible logo and app icon were paramount in order to break from the clutter on phones riddled with other apps. One of the main concepts in the logo design was the idea of one person helping another and the sense of community associated with the FitRec app. The logo is essentially two interlocking hands grasping at each other’s forearms, forming a bond. We have coupled the bold icon with a short and catchy name, FitRec.
Gelberg Signs was looking to celebrate the company’s 75th anniversary in a big way. Marstudio refreshed Gelberg Signs’ logo and designed a 75th-anniversary logo component to complement it. The refreshed logo features clean lines and a new font, giving the logo a sophisticated look. Gelberg Signs’ 75th-anniversary logo provides a modern look for an old concept, by bringing a nostalgic element from the 1940’s to the forefront. Coupled together, the logos present Gelberg Signs as both professional and experienced.
Marstudio embarked on a redesign initiative to introduce completely new concepts that would represent Growing Innovations in a whole new way. Growing Innovations is an advocacy firm dedicated to supporting and educating new solutions to maintaining natural grass playing fields. The bidirectional triangles represent the exchange of information and a creative play on the educational concept. The color gradation reinforces the idea of growth from blue (sky) to brown (earth) and ultimately green (grass). This abstract design represents not only the landscaping industry, but the education that sets Growing Innovations apart.
The Natural Grass Advisory Group was launched by Growing Innovations, a client of Marstudio. With this concept, we attempted to present the educational aspect of this new endeavor. The letter “G” is highlighted to represent growth through the process of education. The main colors selected are the dark brown representing the earth and the green representing the grass and growth.
|
# Traffique: live visitor statistics on App Engine
# Copyright (C) 2011 Jean Joskin <jeanjoskin.com>
#
# Traffique 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.
#
# Traffique 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 Traffique. If not, see <http://www.gnu.org/licenses/>.
import model
from datetime import datetime, timedelta
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import channel
from google.appengine.api import memcache
PIXEL_GIF = "GIF87a\x01\x00\x01\x00\x80\x00\x00\x0A\x00\x00\x00\x00\x00\x21\xF9" + \
"\x04\x01\x00\x00\x01\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02" + \
"\x02\x4C\x01\x00\x3B"
class Tracker(webapp.RequestHandler):
@staticmethod
def get_active_channel_tokens():
# Fetch active clients
channel_tokens = memcache.get("channel_tokens")
if channel_tokens is None:
q = model.Session.all()
q.filter("last_activity > ", datetime.utcnow() - timedelta(minutes = 5))
q.order("-last_activity")
clients = q.fetch(limit = 20)
channel_tokens = []
for client in clients:
channel_tokens.append(client.key().name())
memcache.set("channel_tokens", channel_tokens, 3600)
return channel_tokens
def get(self):
try:
# Notify all sessions
tokens = Tracker.get_active_channel_tokens()
msg = '{"i":"' + self.request.remote_addr + '"}';
for token in tokens:
channel.send_message(token, msg)
finally:
# Return pixel to user
self.response.headers["Content-Type"] = "image/gif"
self.response.out.write(PIXEL_GIF)
application = webapp.WSGIApplication(
[
("/t.gif", Tracker)
],
debug=False)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
The City of Bradford has hosted many celebrations during the years, including our finest veterans from Pennsylvania. The three medals above were given to those veterans who attended these conventions. The National Guard Association medal is from the estate of Pennsylvania Governor Edward Martin (1879-1967). In addition to being governor and a US Senator, Martin had a distinguished military career through four wars.
Arrival of the delegates and registration. Convention opened by a banquet held Wednesday, June 22 at 6 P.M. at the Hotel Holley, with the representative of the Mayor of Bradford Charles F. Schwab and other prominent speakers addressing the Convention in joint session.
Banquet at the Hotel Holley at 6:00 P.M.
|
#!/usr/bin/env python
# coding: utf-8
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
# A chapter of the story
from linux_story.step_helper_functions import unblock_cd_commands
from linux_story.story.terminals.terminal_mkdir import TerminalMkdir
from linux_story.helper_functions import play_sound
from linux_story.story.challenges.challenge_23 import Step1 as NextStep
class StepTemplateMkdir(TerminalMkdir):
challenge_number = 22
class Step1(StepTemplateMkdir):
story = [
"{{gb:Bravo, sembra che ci siano tutti!}}",
"\nRomina: {{Bb:Grazie davvero!}}",
"{{Bb:Staremo qui al sicuro. Ti sono così grata per tutto quello "
"che hai fatto.}}",
"\nUsa {{lb:cat}} per controllare se gli animali stanno "
"bene qui dentro"
]
start_dir = "~/fattoria/fienile/.riparo"
end_dir = "~/fattoria/fienile/.riparo"
commands = [
"cat Violetta",
"cat Trogolo",
"cat Gelsomino"
]
hints = [
"{{rb:Usa}} {{lb:cat}} {{rb:per controlare un animale, tipo}} "
"{{yb:cat Violetta}}{{rb:.}}"
]
# Remove all the food
deleted_items = [
"~/paese/.riparo-nascosto/basket",
"~/paese/.riparo-nascosto/apple"
]
def next(self):
play_sound("bell")
Step2()
class Step2(StepTemplateMkdir):
story = [
"{{pb:Ding. Dong.}}",
"Romina: {{Bb:Cosa?? Ho sentito la campanella! Che significa?}}",
"\nSvelto! {{lb:Guarda attorno}} per controllare se manca qualcuno."
]
start_dir = "~/fattoria/fienile/.riparo"
end_dir = "~/fattoria/fienile/.riparo"
commands = [
"ls",
"ls -a"
]
hints = [
"{{rb:guarda attorno con}} {{yb:ls}}{{rb:.}}"
]
# Remove Edith
deleted_items = [
"~/paese/.riparo-nascosto/Edith"
]
def next(self):
play_sound("bell")
Step3()
class Step3(StepTemplateMkdir):
story = [
"Sembra che qui ci siano tutti...",
"\n{{pb:Ding. Dong.}}",
"\nRomina: {{Bb:Ancora! L'ho sentita! Ma è questa che hai sentito quando "
"è sparito il mio marito?}}",
"Dai un'altra {{lb:occhiata}} veloce."
]
start_dir = "~/fattoria/fienile/.riparo"
end_dir = "~/fattoria/fienile/.riparo"
commands = [
"ls",
"ls -a"
]
hints = [
"{{rb:Guardati attorno con}} {{yb:ls}}{{rb:.}}"
]
# Remove Edoardo
deleted_items = [
"~/paese/.riparo-nascosto/Edoardo"
]
def next(self):
play_sound("bell")
Step4()
# TODO: FIX THIS STEP
class Step4(StepTemplateMkdir):
story = [
"Romina: {{Bb:Meno male. Siamo al sicuro, qui ci sono tutti. "
"Ma perché suona?}}",
"\nForse dovremmo indagare su queste ultime suonate. Chi altro "
"si conosceva?",
"Si potrebbe rincontrollare quella famiglia rimpiattata nel "
"{{lb:.riparo-nascosto}} e parlare loro, ora che hai la voce.",
"\nInizia a tornare indietro per andare al {{lb:.riparo-nascosto}} con {{lb:cd}}"
]
start_dir = "~/fattoria/fienile/.riparo"
end_dir = "~/paese/.riparo-nascosto"
hints = [
"{{rb:Possiamo andare direttamente al}} {{lb:.riparo-nascosto}} "
"{{rb:usando}} {{yb:cd ~/paese/.riparo-nascosto/}}"
]
# Remove the cane
deleted_items = [
"~/paese/.riparo-nascosto/cane"
]
def block_command(self):
return unblock_cd_commands(self.last_user_input)
def check_command(self):
# If the command passes, then print a nice hint.
if self.last_user_input.startswith("cd") and \
not self.get_command_blocked() and \
not self.current_path == self.end_dir:
hint = "\n{{gb:Ottimo! Continua così!}}"
self.send_text(hint)
else:
return StepTemplateMkdir.check_command(self)
def next(self):
Step5()
class Step5(StepTemplateMkdir):
story = [
"Guarda {{lb:attorno}}."
]
start_dir = "~/paese/.riparo-nascosto"
end_dir = "~/paese/.riparo-nascosto"
commands = [
"ls",
"ls -a"
]
hints = [
"{{rb:Usa}} {{yb:ls}} {{rb:per guardare attorno.}}"
]
last_step = True
def next(self):
NextStep(self.xp)
|
We are a wholesale nursery open to the public with large quantities and competitive pricing of palms, plants and trees with delivery available.
Having started back in 1988 on a small lot in Pico Rivera and officially becoming a business in 1990 we now have over 80 acres of land where we grow our stock.
We welcome you to visit our locations where you can view and pick our stock in person!
Please call or visit for availability, price, and delivery quotes or for further information.
We provide a wide variety of 1, 5, 15, and 25 gallon container palms, plants, and trees as well as 24" box and 36" box container palms and trees.
- Delivery charges vary depending on quantity and by time and distance from the shipping location.
*PLEASE NOTE THAT OUR FILLMORE LOCATIONS ARE GROWING GROUNDS AND DO NOT OFFER THE SAME CUSTOMER ASSISTANCE AS OUR OTHER LOCATIONS.
|
from django import template
register = template.Library()
@register.filter
def length (value, length=2):
"""
Truncates `value` to `length`
:type value: float
:type length: int
:rtype: str
"""
if value:
_length = int(length)
_string = str(value).split('.')
if len(_string[1]) == 1:
_string[1] += '0'.rjust(_length - 1, '0')
return _string[0] + '.' + _string[1][:_length]
else:
return '0.{}'.format('0' * int(length))
@register.filter
def storage_fee_total (item_list, stored = True):
"""
Sums the storage fees of a given item list
:param item_list: List of items to process
:param stored: Whether to consider only items still in storage (default True)
:return: Storage fee sum
"""
_sum = float(0)
for item in item_list:
if stored:
if item.status != '4':
_sum += item.storage_fees
else:
_sum += item.storage_fees
return length(_sum, 2)
@register.filter
def stored_count (unit_list):
"""
Returns count of items (Inventory or Shipment) that are still in storage (status < 4)
:param unit_list: Set of items to filter
:type unit_list: QuerySet
:return: Number of shipments with status < 4
:rtype: Int
"""
_count = int(0)
for unit in unit_list:
if int(unit.status) < 4:
_count += 1
return _count
|
New Zealand is a beautiful island nation in the Pacific Ocean. It is not only known for its beautiful landscape and nature, but also for its open-minded people and nice villages. On our homepage we will introduce you to facts on seafood from New Zealand, as well as inform you on recent news related to New Zealand’s seafood. Enjoy!
New Zealand’s cuisine is usually seasonal, local, and as natural as possible. Since many villages and towns are close to the sea, seafood is naturally a main ingredient in New Zealand cuisine. Maori Hangi is a typical food which is cooked in a hangi, consisting usually of pork, chicken, or mutton with vegetables. Other typical foods are fish and chips, sweet potatoes, roast lamb and the famous ‘Kiwi Burger’. A burger with beetroot, egg, and meat or cheese.
There is nothing more relaxing than sitting by the seaside in one of New Zealand’s cosiest places and eating their famous seafood, with such delicacies as crayfish or lobster readily available. Many fishermen in New Zealand fish this specialty themselves, and for visitors it is an absolute must. Another tasty seafood is the Kina, a special kind of sea urchin which apparently tastes fabulously good. To try the dish called Whitebait Fritters you need to be brave. These immature fish look like small spaghetti with eyes, and are a delicacy on the West Coast of New Zealand. The sea snail Paua is another seafood which is considered tasty and healthy.
Underwater Slot Machines: Is That Even Possible?
|
#!/usr/bin/python3
import collections
import sys
Conn = collections.namedtuple('Conn', ['node', 'weight'])
def info(*tt):
print(*tt, file=sys.stderr)
class Node:
finf = float('inf')
def __init__(self):
self.connected = []
self.origin = None
self.dist = self.finf
info("Created node")
def wipe_dists(self):
info("Wiping own distance")
if self.dist != self.finf:
self.dist = self.finf
for node in connected:
node.wipe_dists()
def connect_to(self, node, path_weight):
info("Connecting up")
self.connected.append(Conn(node, path_weight))
node.connected.append(Conn(self, path_weight))
def set_origin(self):
info("Setting origin")
self.wipe_dists()
self.build_dist(0, self)
def build_dist(self, dd, obj):
info("Building distance")
self.origin = obj
self.dist = dd
needs_build = []
for conn in self.connected:
if conn.node.dist > self.dist + conn.weight:
conn.node.build_dist(self.dist + conn.weight, obj)
def shortest_path_to(self, nodes):
self.set_origin()
return [node.dist for node in nodes]
def __repr__(self):
return 'Node(dist={}, conn={})'.format(
repr(self.dist), repr(self.connected))
|
Sammy fulfilled his childhood dream when he took up painting later in life.
Receive a 12 x 16 fine art limited edition giclee print of The Color of Jazz (painted by Sammy). Museum-quality, frame-ready, on canvas, signed AND numbered by Sammy. A true collectible. Shipped to arrive in pristine condition.
© 2019 Copyright. All Rights Reserved. DOCdance Productions. Designed by Brixme.
|
import utm
import yaml
import numpy as np
from map_coords import MapCoords
def coord_in_poly(point, limits):
x=point.easting
y=point.northing
n = len(limits)
inside = False
#
p1x = limits[0].easting
p1y = limits[0].northing
for i in range(n+1):
p2x = limits[i % n].easting
p2y = limits[i % n].northing
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
class TopoNode(object):
def __init__(self, name, coord, ind):
self.name = name #Node Name
self.coord = coord #Node coordinates
self.ind = ind #Grid Indexes
self.visited = False
def __repr__(self):
a = dir(self)
b = []
s = ''
for i in a:
if not i.startswith('_'):
b.append(str(i))
for i in b:
s = s + str(i) + ': ' + str(self.__getattribute__(i)) + '\n'
return s
class TopoMap(object):
def __init__(self, grid):
self.waypoints=[]
self._calculate_waypoints(grid)
def _calculate_waypoints(self, grid):
ind = 0
for i in range(0, len(grid.cells)):
for j in range(0, len(grid.cells[0])):
if coord_in_poly(grid.cells[i][j], grid.limits):
name = "WayPoint%03d" %ind
d = TopoNode(name, grid.cells[i][j], (i, j))
self.waypoints.append(d)
ind+=1
#print name
#print len(self.waypoints)
|
When President Clinton Said It, It Was Okay; What Happens When President Trump Says It?
Are The “Psychoses” Of The United Nations and French President Macron Revealed?
Is Mass Immigration About Establishing a World Without Borders?
|
#!/usr/bin/env python
# vim: expandtab:tabstop=4:shiftwidth=4
"""
This is a script that snapshots all volumes in a given account.
The volumes must be tagged like so:
snapshot: daily
snapshot: weekly
This assumes that your AWS credentials are loaded in the ENV variables:
AWS_ACCESS_KEY_ID=xxxx
AWS_SECRET_ACCESS_KEY=xxxx
Usage:
ops-ec2-snapshot-ebs-volumes.py --with-schedule weekly
"""
# Ignoring module name
# pylint: disable=invalid-name,import-error
import os
import argparse
from openshift_tools.cloud.aws import ebs_snapshotter
# Reason: disable pylint import-error because our libs aren't loaded on jenkins.
# Status: temporary until we start testing in a container where our stuff is installed.
# pylint: disable=import-error
from openshift_tools.monitoring.metric_sender import MetricSender
EXPIRED_SNAPSHOTS_KEY = 'aws.ebs.snapshotter.expired_snapshots'
DELETED_SNAPSHOTS_KEY = 'aws.ebs.snapshotter.deleted_snapshots'
DELETION_ERRORS_KEY = 'aws.ebs.snapshotter.deletion_errors'
class TrimmerCli(object):
""" Responsible for parsing cli args and running the trimmer. """
def __init__(self):
""" initialize the class """
self.args = None
self.parse_args()
def parse_args(self):
""" parse the args from the cli """
parser = argparse.ArgumentParser(description='EBS Snapshot Trimmer')
parser.add_argument('--keep-hourly', required=True, type=int,
help='The number of hourly snapshots to keep. 0 is infinite.')
parser.add_argument('--keep-daily', required=True, type=int,
help='The number of daily snapshots to keep. 0 is infinite.')
parser.add_argument('--keep-weekly', required=True, type=int,
help='The number of weekly snapshots to keep. 0 is infinite.')
parser.add_argument('--keep-monthly', required=True, type=int,
help='The number of monthly snapshots to keep. 0 is infinite.')
parser.add_argument('--aws-creds-profile', required=False,
help='The AWS credentials profile to use.')
parser.add_argument('--dry-run', action='store_true', default=False,
help='Say what would have been done, but don\'t actually do it.')
self.args = parser.parse_args()
def main(self):
""" main function """
total_expired_snapshots = 0
total_deleted_snapshots = 0
total_deletion_errors = 0
if self.args.aws_creds_profile:
os.environ['AWS_PROFILE'] = self.args.aws_creds_profile
regions = ebs_snapshotter.EbsSnapshotter.get_supported_regions()
for region in regions:
print "Region: %s:" % region
ss = ebs_snapshotter.EbsSnapshotter(region.name, verbose=True)
expired_snapshots, deleted_snapshots, snapshot_deletion_errors = \
ss.trim_snapshots(hourly_backups=self.args.keep_hourly, \
daily_backups=self.args.keep_daily, \
weekly_backups=self.args.keep_weekly, \
monthly_backups=self.args.keep_monthly, \
dry_run=self.args.dry_run)
num_deletion_errors = len(snapshot_deletion_errors)
total_expired_snapshots += len(expired_snapshots)
total_deleted_snapshots += len(deleted_snapshots)
total_deletion_errors += num_deletion_errors
if num_deletion_errors > 0:
print " Snapshot Deletion errors (%d):" % num_deletion_errors
for cur_err in snapshot_deletion_errors:
print " %s" % cur_err
print
print " Total number of expired snapshots: %d" % total_expired_snapshots
print " Total number of deleted snapshots: %d" % total_deleted_snapshots
print "Total number of snapshot deletion errors: %d" % total_deletion_errors
print
print "Sending results to Zabbix:"
if self.args.dry_run:
print " *** DRY RUN, NO ACTION TAKEN ***"
else:
TrimmerCli.report_to_zabbix(total_expired_snapshots, total_deleted_snapshots, total_deletion_errors)
@staticmethod
def report_to_zabbix(total_expired_snapshots, total_deleted_snapshots, total_deletion_errors):
""" Sends the commands exit code to zabbix. """
mts = MetricSender(verbose=True)
mts.add_metric({
EXPIRED_SNAPSHOTS_KEY: total_expired_snapshots,
DELETED_SNAPSHOTS_KEY: total_deleted_snapshots,
DELETION_ERRORS_KEY: total_deletion_errors
})
mts.send_metrics()
if __name__ == "__main__":
TrimmerCli().main()
|
One of Australia’s favourite performers, Jonathan Biggins, is Paul Keating - visionary, reformer and rabble-rouser. With an abundance of intelligence and wit, The Gospel According to Paul is a new and anticipated comedy about a critical time in Australian history and the man who shaped it.
Share The Gospel According to Paul with friends.
|
# Generated by Django 2.2.3 on 2019-07-28 13:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [('testproject', '0001_initial')]
operations = [
migrations.CreateModel(
name='ForeignModelWithoutUrl',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=128)),
],
),
migrations.CreateModel(
name='ForeignModelWithUrl',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=128)),
],
),
migrations.AlterField(
model_name='samplemodel',
name='category',
field=models.CharField(
choices=[('blog_post', 'Blog Post'), ('foo', 'Foo'), ('bar', 'Bar')], max_length=128
),
),
migrations.AddField(
model_name='samplemodel',
name='foreign_1',
field=models.ForeignKey(
blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='testproject.ForeignModelWithUrl'
),
),
migrations.AddField(
model_name='samplemodel',
name='foreign_2',
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to='testproject.ForeignModelWithoutUrl',
),
),
]
|
307 HARVEST LN is a house for sale in Avondale, PA 19311. This 5594.00 SQFT house sits on a 0.55 acre lot and features 4 bedrooms and 3 bathrooms. Built in 2006, this house has been on the market for a total of 2 months and is currently priced at $439,900.
|
from nltk.corpus import stopwords
from itertools import chain
from nltk.corpus import wordnet
from collections import defaultdict
import pip
import csv
# combined_dataset_verbose has all the news article.
f = open('combined_dataset_verbose.csv')
csv_f = csv.reader(f)
next(csv_f)
# Set of positive, negative and neutral words.
negativeword = "downfall,down,decrease,negative,fall,JEOPARDIZED,RECALCULATE,TESTIFY,QUESTIONABLE,IMPEDED,EXACERBATE,OVERSTATEMENT,SLANDER,NONPERFORMING,UNFOUNDED,WORST,ILLICIT,RENEGOTIATE, MANIPULATE, DISTURBING, CIRCUMVENT, PREJUDICED, APPARENTLY, FRIVOLOUS, REJECT, PROTESTED, REJECTS, DOWNSIZED, GRIEVANCE, REFILE, DISSENTING, FORECLOSED, GRATUITOUS, UNPREDICTED, MISAPPLICATION, CLOSEOUT, COLLABORATES, OBLIGEE, DISSENTERS, FOREGO, WRITS, PLEDGORS, PRECIPITATED, IDLED, SUGGESTS, BAILEE, FRIENDLY, ARBITRAL, BREAKTHROUGHS, FAVORING, CERTIORARI, PERSISTS, ADJOURNMENTS, IGNORING, RECALCULATE"
negativeword = negativeword.split(',')
positiveword = "increase,growth,rise,raise,up,UNMATCHED, OUTPERFORM, VOIDED, CONFIDENT, REWARDED, PROSPERITY, DISCREPANCY, RECTIFICATION, CRITICALLY, FORFEITABLE, ARBITRARY, TURMOIL, IMBALANCE, PROGRESSES, ANTECEDENT, OVERCHARGED, DURESS, MANIPULATION, DISTRESSED, DISSOLUTIONS, HAZARD,EXPROPRIATION, UNDERSTATE, UNFIT, PLEADINGS, INVESTIGATED, SOMETIME, ENCROACHMENT, MISSTATE,MUTANDIS, DEFRAUD, UNDEFINED, DELISTING, FORFEITS, UNCOVERS, MALPRACTICE, PRESUMES, GRANTORS, COLLAPSING, FALSELY, UNSOUND, REJECTIONS, WHEREABOUTS, DAMAGING, REASSIGNMENT, DISTRACTING, DISAPPROVED, STAGNANT, PREDECEASES, SAFE"
positiveword = positiveword.split(',')
neutral = "FAVORABLE, VULNERABILITY, CLAIMS, ALTERATION, DISCONTINUING, BANKRUPTCY, DEPENDING, DEPENDING, ATTAINING, ISSIONS, CORRECTING, IMPROVES, GAIN, FLUCTUATION, DISCONTINUE, STATUTES, THEREUNTO, RISKY, RISKY, FLUCTUATES, SUBROGATION, NEGATIVELY, LOSE, ATTORNEY, REVISED, COULD, EXPOSURE, DEPENDENT, WILL, CONTRACTS, FAILURE, RISK, EASILY, PROFICIENCY, SUPERSEDES, ACCESSION, DULY, MAY, REMEDIED, VARIABLE, UNENFORCEABLE, RISKS, UNRESOLVED, VARIATIONS, COURTS, PROBLEM, VARIED, HEREBY, PREDICT"
neutral = neutral.split(',')
finalwordlist = {}
# Generating synonyms for all negative words.
negtivelist = []
for w in negativeword:
w = w.strip()
negtivelist.append(w)
synonyms = wordnet.synsets(w)
lemmas = set(chain.from_iterable([word.lemma_names() for word in synonyms]))
lists = [x.encode('UTF8') for x in lemmas]
negtivelist.extend(lists)
finalwordlist[-1] = negtivelist
# Generating synonyms for all positive words.
positivelist = []
for w in positiveword:
w = w.strip()
positivelist.append(w.lower())
synonyms = wordnet.synsets(w.lower())
lemmas = set(chain.from_iterable([word.lemma_names() for word in synonyms]))
lists = [x.encode('UTF8') for x in lemmas]
positivelist.extend(lists)
finalwordlist[1] = positivelist
# Generating synonyms for all neutral words.
neutrallist = []
for w in neutral:
w = w.strip()
neutrallist.append(w.lower())
synonyms = wordnet.synsets(w.lower())
lemmas = set(chain.from_iterable([word.lemma_names() for word in synonyms]))
lists = [x.encode('UTF8') for x in lemmas]
neutrallist.extend(lists)
finalwordlist[0] = neutrallist
stop = set(stopwords.words('english'))
# .csv output file.
fieldnames = ['publish_date', 'Date', 'sentiment_polarity', 'sentiment_subjectivity', 'Positive', 'Negative', 'Neutral',
'Class']
fp = open('final.csv', 'w')
fp1 = open('date.csv', 'w')
fieldnames1 = ['Date']
writer = csv.DictWriter(fp, fieldnames=fieldnames)
writer1 = csv.DictWriter(fp1, fieldnames=fieldnames1)
writer.writeheader()
writer1.writeheader()
# loop through all article and get sentiment score.
for row in csv_f:
broken = [i for i in row[4].lower().split() if i not in stop]
# get count for each word
pos = len(set(finalwordlist[1]) & set(broken)) + 1
neg = len(set(finalwordlist[-1]) & set(broken)) + 1
neut = len(set(finalwordlist[0]) & set(broken)) + 1
totol = pos + neg + neut
# Calculating the probability
pos = 1.0 * pos / totol
neg = 1.0 * neg / totol
neut = 1.0 * neut / totol
if row[5] > row[8]:
label = 0
else:
label = 1
writer.writerow(
{'publish_date': row[1], 'Date': row[2], 'sentiment_polarity': row[0], 'sentiment_subjectivity': row[3],
'Positive': pos, 'Negative': neg, 'Neutral': neut, 'Class': label})
writer1.writerow({'Date': row[2]})
|
At its best, Dakota Johnson’s acting reveals the restrictiveness of labels like “girlhood” and “womanhood”. Dave Crewe examines how she subverts conventional female stereotypes. This is the second essay in our special A Bigger Splash week.
As Penelope in A Bigger Splash (2015), Dakota Johnson is enigmatic yet authentic, knowing yet naïve; a daughter, a lover, a seductress, and a child all at once. The role allows Johnson to undercut the cliches of Hollywood femininity: innocent child, sexualised nymph, or idealised mother. In projects like A Bigger Splash, television sitcom Ben and Kate and, yes, Fifty Shades of Grey, she pushes against these familiar shapes, revealing nuances in characterisation often absent from the writing she’s given. At its best, Johnson’s acting reveals the restrictiveness of labels like “girlhood” and “womanhood”.
Based in Brisbane, Australia, Dave writes, teaches, watches movies, and runs ccpopculture.
|
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2017 PyMeasure Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
from pymeasure.instruments import Instrument
from pymeasure.instruments.validators import strict_discrete_set
class HP33120A(Instrument):
""" Represents the Hewlett Packard 33120A Arbitrary Waveform
Generator and provides a high-level interface for interacting
with the instrument.
"""
SHAPES = {
'sinusoid':'SIN', 'square':'SQU', 'triangle':'TRI',
'ramp':'RAMP', 'noise':'NOIS', 'dc':'DC', 'user':'USER'
}
shape = Instrument.control(
"SOUR:FUNC:SHAP?", "SOUR:FUNC:SHAP %s",
""" A string property that controls the shape of the wave,
which can take the values: sinusoid, square, triangle, ramp,
noise, dc, and user. """,
validator=strict_discrete_set,
values=SHAPES,
map_values=True
)
frequency = Instrument.control(
"SOUR:FREQ?", "SOUR:FREQ %g",
""" A floating point property that controls the frequency of the
output in Hz. The allowed range depends on the waveform shape
and can be queried with :attr:`~.max_frequency` and
:attr:`~.min_frequency`. """
)
max_frequency = Instrument.measurement(
"SOUR:FREQ? MAX",
""" Reads the maximum :attr:`~.HP33120A.frequency` in Hz for the given shape """
)
min_frequency = Instrument.measurement(
"SOUR:FREQ? MIN",
""" Reads the minimum :attr:`~.HP33120A.frequency` in Hz for the given shape """
)
amplitude = Instrument.control(
"SOUR:VOLT?", "SOUR:VOLT %g",
""" A floating point property that controls the voltage amplitude of the
output signal. The default units are in peak-to-peak Volts, but can be
controlled by :attr:`~.amplitude_units`. The allowed range depends
on the waveform shape and can be queried with :attr:`~.max_amplitude`
and :attr:`~.min_amplitude`. """
)
max_amplitude = Instrument.measurement(
"SOUR:VOLT? MAX",
""" Reads the maximum :attr:`~.amplitude` in Volts for the given shape """
)
min_amplitude = Instrument.measurement(
"SOUR:VOLT? MIN",
""" Reads the minimum :attr:`~.amplitude` in Volts for the given shape """
)
offset = Instrument.control(
"SOUR:VOLT:OFFS?", "SOUR:VOLT:OFFS %g",
""" A floating point property that controls the amplitude voltage offset
in Volts. The allowed range depends on the waveform shape and can be
queried with :attr:`~.max_offset` and :attr:`~.min_offset`. """
)
max_offset = Instrument.measurement(
"SOUR:VOLT:OFFS? MAX",
""" Reads the maximum :attr:`~.offset` in Volts for the given shape """
)
min_offset = Instrument.measurement(
"SOUR:VOLT:OFFS? MIN",
""" Reads the minimum :attr:`~.offset` in Volts for the given shape """
)
AMPLITUDE_UNITS = {'Vpp':'VPP', 'Vrms':'VRMS', 'dBm':'DBM', 'default':'DEF'}
amplitude_units = Instrument.control(
"SOUR:VOLT:UNIT?", "SOUR:VOLT:UNIT %s",
""" A string property that controls the units of the amplitude,
which can take the values Vpp, Vrms, dBm, and default.
""",
validator=strict_discrete_set,
values=AMPLITUDE_UNITS,
map_values=True
)
def __init__(self, resourceName, **kwargs):
super(HP33120A, self).__init__(
resourceName,
"Hewlett Packard 33120A Function Generator",
**kwargs
)
self.amplitude_units = 'Vpp'
def beep(self):
""" Causes a system beep. """
self.write("SYST:BEEP")
|
ARCHER, the UK's national supercomputing service, offers training in software development and high-performance computing to scientists and researchers across the UK. As part of our training service we are running a 2 day ARCHER OpenMP course at University College London on 8th - 9th September 2016.
Almost all modern computers now have a shared-memory architecture with multiple CPUs connected to the same physical memory, for example multicore laptops or large multi-processor compute servers. This course covers OpenMP, the industry standard for shared-memory programming, which enables serial programs to be parallelised easily using compiler directives. Users of desktop machines can use OpenMP on its own to improve program performance by running on multiple cores; users of parallel supercomputers can use OpenMP in conjunction with MPI to better exploit the shared-memory capabilities of the compute nodes.
This two-day course will cover an introduction to the fundamental concepts of the shared variables model, followed by the syntax and semantics of OpenMP and how it can be used to parallelise real programs. Hands-on practical programming exercises make up a significant, and integral, part of this course.
No prior HPC or parallel programming knowledge is assumed, but attendees must already be able to program in C, C++ or Fortran. It is not possible to do the exercises in Java.
All course delegates will need to bring a wireless enabled laptop computer with them on the course. If you have an EduRoam account please ensure this is set up beforehand.
Understand the concepts of threads and shared-memory programming.
Write, compile, and run parallel OpenMP programs.
Perform basic optimisations for better performance.
Course Hackpad for sharing links, resources, ideas, questions.
The course will be held in room B07, 1-19 Torrington Place, University College London.
|
# $Id$
# returns the current (if available) and next PeopleSoft semester codes with matching descriptions, as of today
import re
import xmlrpclib
Randy_Loch = '192.168.0.1'
Kim_Nguyen_G5 = '192.168.0.1'
Kim_Nguyen_Air = '192.168.0.1'
Kim_Nguyen_iMac = '192.168.0.1'
John_Hren_MBP = '192.168.0.1'
CMF2 = '192.168.0.1'
Plone1 = '192.168.0.1'
Plone3 = '192.168.0.1'
def getNextSemestersWithDescription(self):
request = self.REQUEST
RESPONSE = request.RESPONSE
remote_addr = request.REMOTE_ADDR
if remote_addr in [Plone1, CMF2, Randy_Loch, Kim_Nguyen_Air, Kim_Nguyen_G5, Kim_Nguyen_iMac, John_Hren_MBP, Plone3, '127.0.0.1', ]:
conn = getattr(self, 'Oracle_Database_Connection_NGUYEN_PRD')
connstr = conn.connection_string
try:
if not conn.connected():
conn.connect(connstr)
except:
conn.connect(connstr)
dbc = conn()
querystr = "select strm, descr from ps_term_tbl where institution = 'UWOSH' and acad_career = 'UGRD' and term_begin_dt <= sysdate and term_end_dt >= sysdate"
try:
retlist = dbc.query (querystr)
except:
# try the query a second time since it can fail to connect the first time
conn.connect(connstr)
dbc = conn()
retlist = dbc.query (querystr)
if len(retlist) == 2:
if len(retlist[1]) == 1:
if len(retlist[1][0]) == 2:
current_semester = retlist[1][0][0]
current_semester_descr = retlist[1][0][1]
if current_semester:
# now grab the next semester's code, knowing the current semester code
querystr2 = "select t1.strm, t1.descr from ps_term_tbl t1 where t1.institution = 'UWOSH' and t1.acad_career = 'UGRD' and t1.strm = (select min(strm) from ps_term_tbl t2 where t2.institution = t1.institution and t2.acad_career = t1.acad_career and t2.strm > '%s')" % current_semester
else:
# grab the next semester code, a bit differently from above because we are not currently in a semester
querystr2 = "select t1.strm, t1.descr from ps_term_tbl t1 where t1.institution = 'UWOSH' and t1.acad_career = 'UGRD' and t1.term_begin_dt = (select min(term_begin_dt) from ps_term_tbl t2 where t2.institution = t1.institution and t2.acad_career = t1.acad_career and term_begin_dt > sysdate)"
try:
retlist = dbc.query (querystr2)
except:
# try the query a second time since it can fail to connect the first time
conn.connect(connstr)
dbc = conn()
retlist = dbc.query (querystr2)
if len(retlist) == 2:
if len(retlist[1]) == 1:
if len(retlist[1][0]) == 2:
next_semester = retlist[1][0][0]
next_semester_descr = retlist[1][0][1]
myMarshaller = xmlrpclib.Marshaller()
if current_semester:
# return array of both semester data
return myMarshaller.dumps([(current_semester, current_semester_descr), (next_semester, next_semester_descr),])
#return([(current_semester, current_semester_descr), (next_semester, next_semester_descr),])
else:
if next_semester:
# return array of just next semester data
return myMarshaller.dumps([(next_semester, next_semester_descr),])
#return([(next_semester, next_semester_descr),])
else:
return "error: unable to determine the next semester code"
|
I want to spend my life at the beach.
I'm getting tired of the daily shouting.
City gets the worst of me. >Tanto ruido insoportable.
>Quiero pasar mi vida en la playa.
>Me estoy cansando del griterio cotidiano.
>La ciudad saca lo peor de mí.
>eso es todo lo que oiréis de mí.
get my head on straight.
>creo que me volveré loco.
Desert island, out in the sun, in the sun.
>Isla desierta, al sol, al sol.
>Isla desierta, al calor, al calor.
I want some real sunshine.
Can't you see I'm crying out?
and listen to me shout. >Quiero sol de verdad.
>¿No ves que estoy desesperado?
In the sand, in the light. >En la arena, a la luz.
|
import os
import sys
from urllib.parse import urlparse
import dj_database_url
# PATH vars
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def root(x):
return os.path.join(BASE_DIR, x)
# Insert the apps dir at the top of your path.
sys.path.insert(0, root('apps'))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGE THIS!!!'
# Allow all host headers
# SECURITY WARNING: don't run with this setting in production!
ALLOWED_HOSTS = ['*']
# Django applications.
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
'django.contrib.staticfiles',
]
# 3rd party apps.
THIRD_PARTY_APPS = []
# Project applications.
PROJECT_APPS = [
'{{ cookiecutter.django_app }}',
]
# Installed apps is a combination of all the apps.
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = '{{ cookiecutter.project_name }}.urls'
# Define the site admins.
# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins
ADMINS = (('{{ cookiecutter.author }}', '{{ cookiecutter.author_email }}'), )
# Define site managers.
# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers
MANAGERS = ADMINS
# Python dotted path to the WSGI application used by Django's runserver.
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = '{{ cookiecutter.project_name }}.wsgi.application'
# Internationalization.
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = root('static')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# Additional locations of static files.
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (root('assets'), )
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# Templates configuration.
# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
root('templates'),
],
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
}]
# Password validation.
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Database configuration.
# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Update database configuration with ${DATABASE_URL}.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Cache configuration.
if os.environ.get('REDIS_URL'):
redis_url = urlparse(os.environ.get('REDIS_URL'))
CACHES = {
"default": {
"BACKEND": "redis_cache.RedisCache",
"LOCATION": "{0}:{1}".format(redis_url.hostname, redis_url.port),
"OPTIONS": {
"PASSWORD": redis_url.password,
"DB": 0,
}
}
}
|
We have sinned, but God loves us and Christ died for us. God loves us and wants Jesus Christ to become the Lord in our life. If we receive Him then we are saved.
Christians seem to agree that God’s plan of salvation from the penalty of sin is a wonderful thing. However, though salvation is wonderful, the Lordship of Christ to some christians is something else, in actual fact, many do not make Christ Lord in their lives.
The difference between a Christian and a non-Christian is that in the case of a Christian, the flesh is doomed to die, but in the case of an unsaved, the flesh lives on.
Definitely, satan doesn’t want the unsaved to become Christians and neither does he want the Christian to allow Jesus Christ to be their Lord either.
Satan knows if the unsaved are not won to Christ, they will bear the penalty of sin; and if the Christian does not practice the Lordship of Christ, he will definitely not be able to have victory over the power of sin and death. He will have an ineffective testimony and therefore becoming a hindrance to bringing others to Christ. Scripture tells us that if God’s people walk right before God, having good testimony, then only the unsaved will believe and turn to Christ.
We need to invite Jesus to come into our lives, and be Lord over every aspect of our lives, then only the Holy Spirit will start to move in our lives.
Self will keep Jesus Christ from being our Lord, just as sin will keep us from going to heaven. We have to get rid of our self-centeredness and instead be Christ-centeredness. Self will lead us to sin but the Lordship of Christ will lead us to righteousness.
The difference between the Christian and the non-Christian is basically for a Christian, the flesh is doomed to die, and in the case of an unsaved, the flesh will live on. When we accepted Christ, our flesh will be nailed onto the cross.
The Spirit of God will help us to crucify our flesh. He will expose our pride, jealously, unforgiveness, wrong motives, gluttony, wrong attitudes, morals, and behavior. God lets man have a free choice on earth to say “Yes” or “No” to the Holy Spirit as He points these things out to us. If we fail to deal with our flesh here while we are still on earth , then it will be dealt with at the Judgment Seat of Christ. On Judgement Day.
To die to self, we have to agree with God, bring them to Calvary, make restitution and walk in the spirit only.
|
"""
*******************************************************************************
* Ledger Blue
* (c) 2016 Ledger
*
* 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 argparse
def auto_int(x):
return int(x, 0)
def get_argparser():
parser = argparse.ArgumentParser(description="""Load the firmware onto the MCU. The MCU must already be in
bootloader mode.""")
parser.add_argument("--targetId", help="The device's target ID", type=auto_int)
parser.add_argument("--fileName", help="The name of the firmware file to load")
parser.add_argument("--bootAddr", help="The firmware's boot address", type=auto_int)
parser.add_argument("--apdu", help="Display APDU log", action='store_true')
parser.add_argument("--reverse", help="Load HEX file in reverse from the highest address to the lowest", action='store_true')
parser.add_argument("--nocrc", help="Load HEX file without checking CRC of loaded sections", action='store_true')
return parser
if __name__ == '__main__':
from .hexParser import IntelHexParser
from .hexLoader import HexLoader
from .comm import getDongle
args = get_argparser().parse_args()
if args.targetId == None:
raise Exception("Missing targetId")
if args.fileName == None:
raise Exception("Missing fileName")
parser = IntelHexParser(args.fileName)
if args.bootAddr == None:
args.bootAddr = parser.getBootAddr()
dongle = getDongle(args.apdu)
#relative load
loader = HexLoader(dongle, 0xe0, False, None, False)
loader.validateTargetId(args.targetId)
hash = loader.load(0xFF, 0xF0, parser, reverse=args.reverse, doCRC=(not args.nocrc))
loader.run(args.bootAddr)
|
Study smarter for the bar exam with Critical Pass. All cards are color-coded, cross-referenced, and organized by subject and sub-topic, including indexes for each subject. Each card includes dedicated space for you to write your own notes or mnemonics.
Includes one year of access to the interactive Critical Pass App, which has all card content for studying on the go.
|
#!/usr/bin/env python
#
# @file CppCodeFile.py
# @brief class for generating code file for the given class
# @author Frank Bergmann
# @author Sarah Keating
#
# <!--------------------------------------------------------------------------
#
# Copyright (c) 2013-2018 by the California Institute of Technology
# (California, USA), the European Bioinformatics Institute (EMBL-EBI, UK)
# and the University of Heidelberg (Germany), with support from the National
# Institutes of Health (USA) under grant R01GM070923. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# Neither the name of the California Institute of Technology (Caltech), nor
# of the European Bioinformatics Institute (EMBL-EBI), nor of the University
# of Heidelberg, nor the names of any contributors, may be used to endorse
# or promote products derived from this software without specific prior
# written permission.
# ------------------------------------------------------------------------ -->
from ..base_files import BaseCppFile
from . cpp_functions import *
from ..util import query, strFunctions, global_variables
class CppCodeFile(BaseCppFile.BaseCppFile):
"""Class for all Cpp Code files"""
def __init__(self, class_object, represents_class=True):
self.brief_description = \
'Implementation of the {0} class.'.format(class_object['name'])
BaseCppFile.BaseCppFile.__init__(self, class_object['name'], 'cpp',
class_object['attribs'])
# members from object
if represents_class:
self.expand_class(class_object)
self.lv_info = []
if 'root' in class_object and 'lv_info' in class_object['root']:
self.lv_info = class_object['root']['lv_info']
########################################################################
# Functions for writing the class
def write_class(self):
# self.write_forward_class()
self.write_constructors()
self.write_attribute_functions()
self.write_child_element_functions()
self.write_listof_functions()
self.write_child_lo_element_functions()
self.write_concrete_functions()
self.write_general_functions()
self.write_generic_attribute_functions()
self.write_functions_to_retrieve()
if self.document:
self.write_document_error_log_functions()
self.write_protected_functions()
if self.add_impl is not None and not self.is_list_of:
self.copy_additional_file(self.add_impl)
def write_c_code(self):
self.is_cpp_api = False
if self.is_plugin:
self.write_child_lo_element_functions()
self.write_attribute_functions()
self.write_child_element_functions()
elif not self.is_list_of:
self.write_constructors()
self.write_attribute_functions()
self.write_child_element_functions()
self.write_child_lo_element_functions()
self.write_concrete_functions()
self.write_general_functions()
else:
self.write_attribute_functions()
self.write_listof_functions()
########################################################################
# Functions for writing specific includes and forward declarations
def write_forward_class(self):
if len(self.concretes) == 0:
return
for element in self.concretes:
self.write_line('class {0};'.format(element['element']))
self.skip_line()
def write_general_includes(self):
lo_name = ''
if self.has_parent_list_of:
if 'lo_class_name' in self.class_object:
lo_name = self.class_object['lo_class_name']
if len(lo_name) == 0:
lo_name = strFunctions.list_of_name(self.class_name)
if global_variables.is_package:
folder = self.language if not self.is_plugin else 'extension'
self.write_line_verbatim('#include <{0}/packages/{1}/{2}/{3}'
'.h>'.format(self.language,
self.package.lower(),
folder, self.class_name))
if self.has_parent_list_of and not self.is_list_of:
self.write_line_verbatim('#include <{0}/packages/{1}/{0}/'
'{2}'
'.h>'.format(self.language,
self.package.lower(),
lo_name))
self.write_line_verbatim('#include <{0}/packages/{1}/validator/'
'{2}{3}Error'
'.h>'.format(self.language,
self.package.lower(),
self.package,
self.cap_language))
else:
self.write_line_verbatim('#include <{0}/{1}'
'.h>'.format(self.language,
self.class_name))
if self.has_parent_list_of and not self.is_list_of:
self.write_line_verbatim('#include <{0}/{1}'
'.h>'.format(self.language,
lo_name))
self.write_line_verbatim('#include <sbml/xml/XMLInputStream.h>')
# determine whether we need to write other headers
write_element_filter = False
concrete_classes = []
write_model = False
write_validators = False
write_math = False
if len(self.child_lo_elements) > 0 and global_variables.is_package:
write_element_filter = True
elif global_variables.is_package:
# for element in self.child_elements:
# if 'concrete' in element:
# write_element_filter = True
if self.num_children > 0 and self.num_children != self.num_non_std_children:
write_element_filter = True
if self.is_plugin and not self.is_doc_plugin \
and self.language == 'sbml':
write_model = True
if self.is_doc_plugin:
write_validators = True
if self.has_math:
write_math = True
for lo in self.child_lo_elements:
if 'concrete' in lo:
child_concretes = query.get_concretes(lo['root'],
lo['concrete'])
for j in range(0, len(child_concretes)):
element = child_concretes[j]['element']
if element not in concrete_classes:
concrete_classes.append(element)
for i in range(0, len(self.concretes)):
element = self.concretes[i]['element']
if element not in concrete_classes:
concrete_classes.append(element)
for child in self.child_elements:
if 'concrete' in child:
child_concretes = query.get_concretes(child['root'],
child['concrete'])
for j in range(0, len(child_concretes)):
element = child_concretes[j]['element']
if element not in concrete_classes:
concrete_classes.append(element)
if write_element_filter:
self.write_line_verbatim('#include <{0}/util/ElementFilter.'
'h>'.format(self.language))
if write_model:
self.write_line_verbatim('#include <{0}/Model'
'.h>'.format(self.language))
if write_validators:
self.write_line_verbatim('#include <{0}/packages/{1}/validator/{2}'
'ConsistencyValidator'
'.h>'.format(self.language,
self.package.lower(),
self.package))
self.write_line_verbatim('#include <{0}/packages/{1}/validator/{2}'
'IdentifierConsistencyValidator.'
'h>'.format(self.language,
self.package.lower(),
self.package))
if write_math:
self.write_line_verbatim('#include <sbml/math/MathML.h>')
if len(concrete_classes) > 0:
self.skip_line()
for element in concrete_classes:
if global_variables.is_package:
self.write_line_verbatim('#include <{0}/packages/{1}/{0}/{2}'
'.h>'.format(self.language,
self.package.lower(),
element))
else:
self.write_line_verbatim('#include <{0}/{1}.h>'
''.format(self.language, element))
self.skip_line(2)
self.write_line('using namespace std;')
self.skip_line()
########################################################################
# function to write the data members
def write_data_members(self, attributes):
for i in range(0, len(attributes)):
if attributes[i]['attType'] != 'string':
self.write_line('{0} {1};'.format(attributes[i]['attTypeCode'],
attributes[i]['memberName']))
else:
self.write_line('std::string {0};'
.format(attributes[i]['memberName']))
if attributes[i]['isNumber'] is True \
or attributes[i]['attType'] == 'boolean':
self.write_line('bool mIsSet{0};'
.format(attributes[i]['capAttName']))
if self.overwrites_children:
self.write_line('std::string mElementName;')
########################################################################
# function to write the constructors
def write_constructors(self):
constructor = Constructors.Constructors(self.language,
self.is_cpp_api,
self.class_object)
if self.is_cpp_api and not self.is_plugin:
code = constructor.write_level_version_constructor()
self.write_function_implementation(code)
code = constructor.write_namespace_constructor()
self.write_function_implementation(code)
elif self.is_plugin:
code = constructor.write_uri_constructor()
self.write_function_implementation(code)
elif self.has_std_base:
for i in range(0, len(self.concretes)+1):
code = constructor.write_level_version_constructor(i)
self.write_function_implementation(code)
else:
code = constructor.write_level_version_constructor(-1)
self.write_function_implementation(code)
code = constructor.write_copy_constructor()
self.write_function_implementation(code)
code = constructor.write_assignment_operator()
self.write_function_implementation(code)
code = constructor.write_clone()
self.write_function_implementation(code)
code = constructor.write_destructor()
self.write_function_implementation(code)
########################################################################
# Functions for writing the attribute manipulation functions
# these are for attributes and elements that occur as a single child
# function to write the get/set/isSet/unset functions for attributes
def write_attribute_functions(self):
attrib_functions = SetGetFunctions.SetGetFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
self.class_object,
self.lv_info)
num_attributes = len(self.class_attributes)
for i in range(0, num_attributes):
code = attrib_functions.write_get(True, i)
self.write_function_implementation(code)
code = attrib_functions.write_get_string_for_enum(True, i)
self.write_function_implementation(code)
for i in range(0, num_attributes):
code = attrib_functions.write_is_set(True, i)
self.write_function_implementation(code)
code = attrib_functions.write_get_num_for_vector(True, i)
self.write_function_implementation(code)
for i in range(0, num_attributes):
code = attrib_functions.write_set(True, i)
self.write_function_implementation(code)
code = attrib_functions.write_set_string_for_enum(True, i)
self.write_function_implementation(code)
code = attrib_functions.write_add_element_for_vector(True, i)
self.write_function_implementation(code)
for i in range(0, num_attributes):
code = attrib_functions.write_unset(True, i)
self.write_function_implementation(code)
# function to write the get/set/isSet/unset functions for single
# child elements
def write_child_element_functions(self, override=None):
if override is None:
if not self.has_children:
return
attrib_functions = SetGetFunctions.\
SetGetFunctions(self.language, self.is_cpp_api,
self.is_list_of, self.class_object, self.lv_info, False, [], True)
num_elements = len(self.child_elements)
else:
attrib_functions = SetGetFunctions.SetGetFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
override)
num_elements = 1
for i in range(0, num_elements):
code = attrib_functions.write_get(False, i)
self.write_function_implementation(code)
code = attrib_functions.write_get(False, i, const=False)
self.write_function_implementation(code)
for i in range(0, num_elements):
code = attrib_functions.write_is_set(False, i)
self.write_function_implementation(code)
for i in range(0, num_elements):
code = attrib_functions.write_set(False, i)
self.write_function_implementation(code)
for i in range(0, num_elements):
code = attrib_functions.write_create(False, i)
if override is None and code is None \
and 'concrete' in self.child_elements[i]:
# need to write creates for the concrete
member = self.child_elements[i]['memberName']
concrete = self.child_elements[i]['concrete']
concretes = query.get_concretes(self.class_object['root'],
concrete)
for j in range(0, len(concretes)):
code = attrib_functions\
.write_create_concrete_child(concretes[j], member)
self.write_function_implementation(code)
else:
self.write_function_implementation(code)
for i in range(0, num_elements):
code = attrib_functions.write_unset(False, i)
self.write_function_implementation(code)
########################################################################
# Functions for writing the generic attribute manipulation functions
# these are for attributes and elements that occur as a single child
# function to write the get/set/isSet/unset functions for attributes
def write_generic_attribute_functions(self):
attrib_functions = GenericAttributeFunctions.GenericAttributeFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
self.class_object)
attributes = query.sort_attributes(self.class_attributes)
bool_atts = attributes['bool_atts']
int_atts = attributes['int_atts']
double_atts = attributes['double_atts']
uint_atts = attributes['uint_atts']
string_atts = attributes['string_atts']
code = attrib_functions.write_get(bool_atts, 'bool')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_get(int_atts, 'int')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_get(double_atts, 'double')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_get(uint_atts, 'unsigned int')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_get(string_atts, 'std::string')
self.write_function_implementation(code, exclude=True)
# code = attrib_functions.write_get(string_atts, 'const char*')
# self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_is_set(query.get_unique_attributes(self.class_attributes))
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_set(bool_atts, 'bool')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_set(int_atts, 'int')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_set(double_atts, 'double')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_set(uint_atts, 'unsigned int')
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_set(string_atts, 'const std::string&')
self.write_function_implementation(code, exclude=True)
# code = attrib_functions.write_set(string_atts, 'const char*')
# self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_unset(query.get_unique_attributes(self.class_attributes))
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_create_object()
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_add_object()
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_remove_object()
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_get_num_objects()
self.write_function_implementation(code, exclude=True)
code = attrib_functions.write_get_object()
self.write_function_implementation(code, exclude=True)
########################################################################
# Functions for writing general functions
def write_general_functions(self):
gen_functions = GeneralFunctions.GeneralFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
self.class_object,
self.lv_info)
code = gen_functions.write_rename_sidrefs()
self.write_function_implementation(code)
if not self.is_plugin:
code = gen_functions.write_get_element_name()
self.write_function_implementation(code)
code = gen_functions.write_set_element_name()
self.write_function_implementation(code, exclude=True)
if not self.is_plugin:
code = gen_functions.write_get_typecode()
self.write_function_implementation(code)
code = gen_functions.write_get_item_typecode()
self.write_function_implementation(code)
code = gen_functions.write_has_required_attributes()
self.write_function_implementation(code)
code = gen_functions.write_has_required_elements()
self.write_function_implementation(code)
code = gen_functions.write_write_elements()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_accept()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_set_document()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_write()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_connect_to_child()
self.write_function_implementation(code, exclude=True)
if self.is_plugin:
code = gen_functions.write_connect_to_parent()
self.write_function_implementation(code, exclude=True)
if global_variables.is_package:
code = gen_functions.write_enable_package()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_update_ns()
self.write_function_implementation(code, exclude=True)
if self.is_doc_plugin:
code = gen_functions.write_is_comp_flat()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_check_consistency()
self.write_function_implementation(code, exclude=True)
code = gen_functions.write_read_attributes()
self.write_function_implementation(code, exclude=True)
########################################################################
# Retrieve element functions
def write_functions_to_retrieve(self):
if not query.has_child_elements(self.attributes):
return
gen_functions = \
GlobalQueryFunctions.GlobalQueryFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
self.class_object)
code = gen_functions.write_get_by_sid()
self.write_function_implementation(code)
code = gen_functions.write_get_by_metaid()
self.write_function_implementation(code)
code = gen_functions.write_get_all_elements()
self.write_function_implementation(code)
if self.is_plugin:
code = gen_functions.write_append_from()
self.write_function_implementation(code, True)
########################################################################
# Functions for writing the attribute manipulation functions
# these are for attributes and elements that occur as a single child
# function to write additional functions on a document for another library
def write_document_error_log_functions(self):
attrib_functions = SetGetFunctions.\
SetGetFunctions(self.language, self.is_cpp_api,
self.is_list_of, self.class_object)
num_elements = len(self.child_elements)
# add error log and ns to child elements
att_tc = 'XMLNamespaces*'
if not global_variables.is_package:
att_tc = 'LIBSBML_CPP_NAMESPACE_QUALIFIER XMLNamespaces*'
element = dict({'name': 'Namespaces',
'isArray': False,
'attTypeCode': att_tc,
'capAttName': 'Namespaces',
'attType': 'element',
'memberName': 'm{0}Namespaces'.format(global_variables.prefix)})
errelement = dict({'name': '{0}ErrorLog'.format(global_variables.prefix),
'isArray': False,
'attTypeCode': '{0}ErrorLog*'.format(global_variables.prefix),
'capAttName': 'ErrorLog',
'attType': 'element',
'memberName': 'mErrorLog'})
self.child_elements.append(element)
self.child_elements.append(errelement)
code = attrib_functions.write_get(False, num_elements, True, True)
self.write_function_implementation(code)
code = attrib_functions.write_get(False, num_elements, False, True)
self.write_function_implementation(code)
code = attrib_functions.write_get(False, num_elements+1, True)
self.write_function_implementation(code)
code = attrib_functions.write_get(False, num_elements+1, False)
self.write_function_implementation(code)
self.child_elements.remove(errelement)
self.child_elements.remove(element)
# preserve existing values
existing = dict()
self.class_object['element'] = '{0}Error'.format(global_variables.prefix)
self.class_object['parent'] = dict({'name': '{0}'.format(global_variables.document_class)})
self.class_object['memberName'] = 'mErrorLog'
lo_functions = ListOfQueryFunctions\
.ListOfQueryFunctions(self.language, self.is_cpp_api,
self.is_list_of,
self.class_object)
code = lo_functions.write_get_element_by_index(is_const=False)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_index(is_const=True)
self.write_function_implementation(code)
code = lo_functions.write_get_num_element_function()
self.write_function_implementation(code)
parameter = dict({'name': 'severity',
'type': 'unsigned int'})
code = lo_functions.write_get_num_element_function(parameter)
self.write_function_implementation(code)
########################################################################
# concrete class functions
def write_concrete_functions(self):
conc_functions = \
ConcreteClassFunctions.ConcreteClassFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
self.class_object)
for i in range(0, len(self.concretes)):
code = conc_functions.write_is_foo(i)
self.write_function_implementation(code)
########################################################################
# Protected functions
def write_protected_functions(self):
protect_functions = \
ProtectedFunctions.ProtectedFunctions(self.language,
self.is_cpp_api,
self.is_list_of,
self.class_object,
self.lv_info)
exclude = True
code = protect_functions.write_create_object()
self.write_function_implementation(code, exclude)
code = protect_functions.write_add_expected_attributes()
self.write_function_implementation(code, exclude)
code = protect_functions.write_read_attributes()
self.write_function_implementation(code, exclude)
if 'num_versions' in self.class_object \
and self.class_object['num_versions'] > 1:
for i in range(0, self.class_object['num_versions']):
code = protect_functions.write_read_version_attributes(i)
self.write_function_implementation(code, exclude)
code = protect_functions.write_read_other_xml()
self.write_function_implementation(code, exclude)
code = protect_functions.write_write_attributes()
self.write_function_implementation(code, exclude)
if 'num_versions' in self.class_object \
and self.class_object['num_versions'] > 1:
for i in range(0, self.class_object['num_versions']):
code = protect_functions.write_write_version_attributes(i)
self.write_function_implementation(code, exclude)
code = protect_functions.write_write_xmlns()
self.write_function_implementation(code, exclude)
code = protect_functions.write_is_valid_type_for_list()
self.write_function_implementation(code, exclude)
code = protect_functions.write_set_element_text()
self.write_function_implementation(code, exclude)
########################################################################
# Functions for writing functions for the main ListOf class
def write_listof_functions(self):
if not self.is_list_of:
return
lo_functions = ListOfQueryFunctions\
.ListOfQueryFunctions(self.language, self.is_cpp_api,
self.is_list_of,
self.class_object)
code = lo_functions.write_get_element_by_index(is_const=False)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_index(is_const=True)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_id(is_const=False)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_id(is_const=True)
self.write_function_implementation(code)
code = lo_functions.write_remove_element_by_index()
self.write_function_implementation(code)
code = lo_functions.write_remove_element_by_id()
self.write_function_implementation(code)
if self.is_cpp_api:
code = lo_functions.write_add_element_function()
self.write_function_implementation(code)
code = lo_functions.write_get_num_element_function()
self.write_function_implementation(code)
for i in range(0, len(self.concretes)+1):
code = lo_functions.write_create_element_function(i)
self.write_function_implementation(code)
for i in range(0, len(self.sid_refs)):
code = lo_functions.write_lookup(self.sid_refs[i])
self.write_function_verbatim(code)
code = \
lo_functions.write_get_element_by_sidref(self.sid_refs[i],
const=True)
self.write_function_implementation(code)
code = \
lo_functions.write_get_element_by_sidref(self.sid_refs[i],
const=False)
self.write_function_implementation(code)
# main function to write the functions dealing with a child listOf element
def write_child_lo_element_functions(self):
num_elements = len(self.child_lo_elements)
for i in range(0, num_elements):
element = self.child_lo_elements[i]
element['std_base'] = self.std_base
element['package'] = self.package
element['is_header'] = self.is_header
element['is_plugin'] = self.is_plugin
if self.is_plugin:
element['plugin'] = self.class_name
if 'concrete' in element:
element['concretes'] = query.get_concretes(
self.class_object['root'], element['concrete'])
lo_functions = ListOfQueryFunctions\
.ListOfQueryFunctions(self.language, self.is_cpp_api,
self.is_list_of,
element)
code = lo_functions.write_get_list_of_function(is_const=True)
self.write_function_implementation(code)
code = lo_functions.write_get_list_of_function(is_const=False)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_index(is_const=False)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_index(is_const=True)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_id(is_const=False)
self.write_function_implementation(code)
code = lo_functions.write_get_element_by_id(is_const=True)
self.write_function_implementation(code)
sid_ref = query.get_sid_refs_for_class(element)
for j in range(0, len(sid_ref)):
if self.is_list_of:
code = lo_functions.write_lookup(sid_ref[j])
self.write_function_verbatim(code)
code = \
lo_functions.write_get_element_by_sidref(sid_ref[j],
const=True)
self.write_function_implementation(code)
code = \
lo_functions.write_get_element_by_sidref(sid_ref[j],
const=False)
self.write_function_implementation(code)
code = lo_functions.write_add_element_function()
self.write_function_implementation(code)
code = lo_functions.write_get_num_element_function()
self.write_function_implementation(code)
if 'concretes' in element:
for n in range(0, len(element['concretes'])):
code = lo_functions.write_create_element_function(n+1)
self.write_function_implementation(code)
else:
code = lo_functions.write_create_element_function()
self.write_function_implementation(code)
code = lo_functions.write_remove_element_by_index()
self.write_function_implementation(code)
code = lo_functions.write_remove_element_by_id()
self.write_function_implementation(code)
# this tackles the situation where a listOfFoo class also
# contains an element of another type
# eg qual:ListOfFunctionTerms contains a DefaultTerm
if not self.is_plugin:
element_children = \
query.get_other_element_children(self.class_object, element)
for j in range(0, len(element_children)):
child_class = self.create_lo_other_child_element_class(
element_children[0], self.class_name)
self.write_child_element_functions(child_class)
########################################################################
# Functions for writing definition declaration
def write_defn_begin(self):
self.skip_line(2)
self.write_line('#ifndef {0}_H__'.format(self.name))
self.write_line('#define {0}_H__'.format(self.name))
self.skip_line(2)
def write_defn_end(self):
self.skip_line(2)
self.write_line('#endif /* !{0}_H__ */'.format(self.name))
self.skip_line(2)
########################################################################
# Write file
def write_file(self):
BaseCppFile.BaseCppFile.write_file(self)
self.write_general_includes()
self.write_cppns_begin()
self.write_cpp_begin()
self.write_class()
self.write_cpp_end()
self.write_c_code()
self.write_cppns_end()
|
The overall experience of the trail was great! It was really nice that our group was very small (4 tourists).
We really enjoyed our inca trail! . The food was incredibly good (especially when considered the circumstances for cooking are not so easy along the trail). Jose, our guide, was very helpful and we also improved our spanish a great deal.
This being my very first trek, I had many new and exciting discoveries. It was a wonderful experience!
This trip will definitely remain in my memory for the rest of my life. The first day was a challenging trek up to a glacial lake and then on to the glacier itself.
The trip was excellent. The first section into the mountains was the hardest as we acclimatised to the altitude but from day two it got easier as we started to head downwards. We saw a huge tangle of micro climates from near arctic to temperate and tropical as the altitude varied through the trip.
Amazing trip, great tour guide with a fun group. From trekking next to an inspiring glacier to pisco fueled story telling the trip has been excellent.
I have to say the Salkantey hike was the best multi day trek I've been on. The views were unlike anything I've ever seen.
This was a remarkable trek with lasting memories. Trekking through the different microclimates was an amazing experience.
I thoroughly enjoyed my experience on the Salkantay trek. I could not believe how well we were taken care of from start to finish.
We booked the trekking tour in advanced and I was really looking forward to it, because I thought it to be a highlight in our trip. And it really was! I expected the track to be quite hard, but it was okay.
Before I started Salkantay Track I was a little worried because I didn't know what to expect: how hard would the hike be for me, how would the weather be, the group, the guides ect....but right from the start it turned out as an amazing adventure.
Henrry and Jimmy are amazing!!! .The trek was so beautiful and the fact that Jimmy and Henrry also shared the Andean culture with us was very special.
I had the best time with Inca Trail Reservations. Our guides Henrry and Jimmy were very professional and gave us great insight into Incan and Peruvian culture.
Jimmy is a great assistant guide. Whenever we had trouble or issues on the trek, he would be there to lend a helping hand.
I chose the Salkantay Trail because it wasn't as full and popular as the other options. It was the perfect choice, as I was going for a deeper and closer connection with the packs mama and myself.
|
# coding=utf-8
#
# Copyright 2014 Sascha Schirra
#
# This file is part of Ropper.
#
# Ropper 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.
#
# Ropper 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 ropperapp.common.abstract import *
from ropperapp.common.error import *
class RopChain(Abstract):
def __init__(self, binaries, printer):
self._binaries = binaries
self._usedBinaries = []
self._printer = printer
@abstractmethod
def create(self):
pass
@classmethod
def name(cls):
return None
@classmethod
def availableGenerators(cls):
return []
@classmethod
def archs(self):
return []
@classmethod
def get(cls, binaries, name, printer):
for subclass in cls.__subclasses__():
if binaries[0].arch in subclass.archs():
gens = subclass.availableGenerators()
for gen in gens:
if gen.name() == name:
return gen(binaries, printer)
raise RopChainError('generator %s is for arch %s not available' % (name, binaries[0].arch.__class__.__name__))
|
Wildlife in a Cambridgeshire wood is set to benefit from new habitat creation which has now been completed by the Woodland Trust.
The wood was created in the year 2000 as part of the Woodland Trust’s ‘Woods on your Doorstep’ which marked the millennium by creating hundreds of new woods across the country. The site is well used by local people and is home to many species of wildlife.
The charity’s Cow Hollow Wood near Waterbeach has benefitted from a grant of £13,859 from The Mick George Community Fund, which is managed by Grantscape, one of the UK's leading grant-makers and community benefit fund managers.
The grants have enabled the Trust to create a reed bed, providing a new home for wetland species such as dragonflies, common toads and many invertebrates, which will become a food source for birds including blackcaps, white throat and chiffchaff. The charity has also installed new benches to allow visitors to take time to enjoy the woodland and the wildlife it supports. The benches are all made from reclaimed wood and carved locally. Each bench is themed as chosen by the local community and depict carvings of nightingales, dragonflies and other wildlife.
Mick George Limited is dedicated to supporting the local community and to protecting the environment and the Mick George Community Fund helps deliver both these objectives.
In celebration of the completion of the new benches and reed bed, The Woodland Trust organised and hosted an exploration day in the wood with over 70 children from nearby Waterbeach Primary School in attendance. The children spent the day discovering nature’s secrets and learning about this special environment under the guidance of the Woodland Trust.
|
#!/usr/bin/env python
"""
Convert jupyter notebook into the markdown format. The notebook outputs will be
removed.
It is heavily adapted from https://gist.github.com/decabyte/0ed87372774cf5d34d7e
"""
import sys
import io
import os
import argparse
import nbformat
def remove_outputs(nb):
"""Removes the outputs cells for a jupyter notebook."""
for cell in nb.cells:
if cell.cell_type == 'code':
cell.outputs = []
def clear_notebook(old_ipynb, new_ipynb):
with io.open(old_ipynb, 'r') as f:
nb = nbformat.read(f, nbformat.NO_CONVERT)
remove_outputs(nb)
with io.open(new_ipynb, 'w', encoding='utf8') as f:
nbformat.write(nb, f, nbformat.NO_CONVERT)
def main():
parser = argparse.ArgumentParser(
description="Jupyter Notebooks to markdown"
)
parser.add_argument("notebook", nargs=1, help="The notebook to be converted.")
parser.add_argument("-o", "--output", help="output markdown file")
args = parser.parse_args()
old_ipynb = args.notebook[0]
new_ipynb = 'tmp.ipynb'
md_file = args.output
print md_file
if not md_file:
md_file = os.path.splitext(old_ipynb)[0] + '.md'
clear_notebook(old_ipynb, new_ipynb)
os.system('jupyter nbconvert ' + new_ipynb + ' --to markdown --output ' + md_file)
with open(md_file, 'a') as f:
f.write('<!-- INSERT SOURCE DOWNLOAD BUTTONS -->')
os.system('rm ' + new_ipynb)
if __name__ == '__main__':
main()
|
Biden has told supporters and former staff that he will run, according to one source who has knowledge of discussions. Biden and his aides also have reached out to donors and potential bundlers - people who volunteer to raise money on behalf of the candidate - to assess support, according to another source. A third source with direct knowledge of Biden's plans offered a caveat, saying the former vice president was very close to running, but "it's not 100 percent." 'We're leaning into that moment' when Biden gives the green light, the source said.
|
import unittest, time, sys, random, re
sys.path.extend(['.','..','../..','py'])
import h2o2 as h2o
import h2o_cmd, h2o_import as h2i, h2o_jobs
from h2o_test import verboseprint, dump_json, OutputObj
import h2o_test
DO_SUMMARY=False
targetList = ['red', 'mail', 'black flag', 5, 1981, 'central park',
'good', 'liquor store rooftoop', 'facebook']
lol = [
['red','orange','yellow','green','blue','indigo','violet'],
['male','female',''],
['bad brains','social distortion','the misfits','black flag',
'iggy and the stooges','the dead kennedys',
'the sex pistols','the ramones','the clash','green day'],
range(1,10),
range(1980,2013),
['central park','marin civic center','madison square garden',
'wembley arena','greenwich village',
'liquor store rooftop','"woodstock, n.y."','shea stadium'],
['good','bad'],
['expensive','cheap','free'],
['yes','no'],
['facebook','twitter','blog',''],
range(8,100),
[random.random() for i in range(20)]
]
whitespaceRegex = re.compile(r"""
^\s*$ # begin, white space or empty space, end
""", re.VERBOSE)
DO_TEN_INTEGERS = False
def random_enum(n):
# pick randomly from a list pointed at by N
if DO_TEN_INTEGERS:
# ten choices
return str(random.randint(0,9))
else:
choiceList = lol[n]
r = str(random.choice(choiceList))
if r in targetList:
t = 1
else:
t = 0
# need more randomness to get enums to be strings
r2 = random.randint(0, 10000)
return (t,"%s_%s" % (r, r2))
def write_syn_dataset(csvPathname, rowCount, colCount=1, SEED='12345678',
colSepChar=",", rowSepChar="\n"):
r1 = random.Random(SEED)
dsf = open(csvPathname, "w+")
for row in range(rowCount):
# doesn't guarantee that 10000 rows have 10000 unique enums in a column
# essentially sampling with replacement
rowData = []
lenLol = len(lol)
targetSum = 0
for col in range(colCount):
(t,ri) = random_enum(col % lenLol)
targetSum += t # sum up contributions to output choice
# print ri
# first two rows can't tolerate single/double quote randomly
# keep trying until you get one with no single or double quote in the line
if row < 2:
while True:
# can't have solely white space cols either in the first two rows
if "'" in ri or '"' in ri or whitespaceRegex.match(ri):
(t,ri) = random_enum(col % lenLol)
else:
break
rowData.append(ri)
# output column
avg = (targetSum+0.0)/colCount
# ri = r1.randint(0,1)
rowData.append(targetSum)
# use the new Hive separator
rowDataCsv = colSepChar.join(map(str,rowData)) + rowSepChar
### sys.stdout.write(rowDataCsv)
dsf.write(rowDataCsv)
dsf.close()
#*******************************
def create_file_with_seps(rowCount, colCount):
# can randomly pick the row and col cases.
### colSepCase = random.randint(0,1)
colSepCase = 1
# using the comma is nice to ensure no craziness
if (colSepCase==0):
colSepHexString = '01'
else:
colSepHexString = '2c' # comma
colSepChar = colSepHexString.decode('hex')
colSepInt = int(colSepHexString, base=16)
print "colSepChar:", colSepChar
print "colSepInt", colSepInt
rowSepCase = random.randint(0,1)
# using this instead, makes the file, 'row-readable' in an editor
if (rowSepCase==0):
rowSepHexString = '0a' # newline
else:
rowSepHexString = '0d0a' # cr + newline (windows) \r\n
rowSepChar = rowSepHexString.decode('hex')
print "rowSepChar:", rowSepChar
SEEDPERFILE = random.randint(0, sys.maxint)
if DO_TEN_INTEGERS:
csvFilename = 'syn_int10_' + str(rowCount) + 'x' + str(colCount) + '.csv'
else:
csvFilename = 'syn_enums_' + str(rowCount) + 'x' + str(colCount) + '.csv'
csvPathname = SYNDATASETS_DIR + '/' + csvFilename
print "Creating random", csvPathname
write_syn_dataset(csvPathname, rowCount, colCount, SEEDPERFILE,
colSepChar=colSepChar, rowSepChar=rowSepChar)
return csvPathname
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
global SEED
SEED = h2o.setup_random_seed()
h2o.init(1, java_heap_GB=12)
@classmethod
def tearDownClass(cls):
h2o.tear_down_cloud()
def test_w2v_basic(self):
global SYNDATASETS_DIR
SYNDATASETS_DIR = h2o.make_syn_dir()
n = 500000
tryList = [
(n, 1, 'cD', 300),
(n, 2, 'cE', 300),
(n, 3, 'cF', 300),
(n, 4, 'cG', 300),
(n, 5, 'cH', 300),
(n, 6, 'cI', 300),
(n, 7, 'cJ', 300),
(n, 9, 'cK', 300),
]
### h2b.browseTheCloud()
for (rowCount, colCount, hex_key, timeoutSecs) in tryList:
csvPathname = create_file_with_seps(rowCount, colCount)
# just parse to make sure it's good
parseResult = h2i.import_parse(path=csvPathname,
check_header=1, delete_on_done = 0, timeoutSecs=180, doSummary=False)
pA = h2o_cmd.ParseObj(parseResult)
iA = h2o_cmd.InspectObj(pA.parse_key)
cA = h2o_test.OutputObj(iA.columns[0], "inspect_column")
parse_key = pA.parse_key
numRows = iA.numRows
numCols = iA.numCols
labelList = iA.labelList
for i in range(colCount):
print cA.type, cA.missing_count
self.assertEqual(0, cA.missing_count, "Column %s Expected %s. missing: %s is incorrect" % (i, 0, cA.missing_count))
self.assertEqual('string', cA.type, "Column %s Expected %s. type: %s is incorrect" % (i, 0, cA.type))
if DO_SUMMARY:
for i in range(colCount):
co = h2o_cmd.runSummary(key=parse_key, column=i)
print co.label, co.type, co.missing, co.domain, sum(co.bins)
self.assertEqual(0, co.missing_count, "Column %s Expected %s. missing: %s is incorrect" % (i, 0, co.missing_count))
self.assertEqual('String', co.type, "Column %s Expected %s. type: %s is incorrect" % (i, 0, co.type))
# no cols ignored
labelListUsed = list(labelList)
numColsUsed = numCols
for trial in range(1):
parameters = {
'validation_frame': parse_key, # KeyIndexed False []
'ignored_columns': None, # string[] None []
'minWordFreq': 5, # int 5 []
'wordModel': 'SkipGram', # enum [u'CBOW', u'SkipGram']
'normModel': 'HSM', # enum # [u'HSM', u'NegSampling']
'negSampleCnt': 5,# int 5 []
'vecSize': 100, # int 100
'windowSize': 5, # int 5
'sentSampleRate': 0.001, # float 0.001
'initLearningRate': 0.05, # float 0.05
'epochs': 1, # int 5
}
model_key = 'benign_w2v.hex'
bmResult = h2o.n0.build_model(
algo='word2vec',
destination_key=model_key,
training_frame=parse_key,
parameters=parameters,
timeoutSecs=60)
bm = OutputObj(bmResult, 'bm')
modelResult = h2o.n0.models(key=model_key)
model = OutputObj(modelResult['models'][0]['output'], 'model')
cmmResult = h2o.n0.compute_model_metrics( model=model_key, frame=parse_key, timeoutSecs=60)
cmm = OutputObj(cmmResult, 'cmm')
mmResult = h2o.n0.model_metrics(model=model_key, frame=parse_key, timeoutSecs=60)
mm = OutputObj(mmResult['model_metrics'][0], 'mm')
# not implemented?
# prResult = h2o.n0.predict(model=model_key, frame=parse_key, timeoutSecs=60)
# pr = OutputObj(prResult['model_metrics'][0]['predictions'], 'pr')
h2o_cmd.runStoreView()
if __name__ == '__main__':
h2o.unit_main()
|
In a water distribution system in large buildings, it is required to operate four pumps in a cyclic manner and maintain the overall water pressure in the pipe for the optimum utilization of water. The water level from both upper and lower tank needs to be monitored to avoid pumps from dry running or over spillage of water.
A simple solution is to use Smart Relay Genie-Nx from GIC.
I1, I2, I3, I4 are the pressure switches for the respective pumps.
I5 and I6 for Upper level and Lower level input for monitoring the level.
I7, I8, I9, I10 are the inputs for voltage trip indication.
Q1, Q2, Q3, Q4 are the outputs for the respective pumps.
Q5 hooter for trip indication.
In order to protect the pumps from excess running, a ladder logic is developed to maneuver pumps in cyclic manner for load sharing there by increasing the operational redundancy of the system. In order to maintain the pressure of water across all the floors, the pumps are operated based on the input from the pressure switches. Whenever the water level reaches the predefined higher/lower limit pumps will be turned OFF and trip indication will be signaled by hooter to avoid dry running or over spillage of water. The pump will resume its normal operation as soon as the water level reaches to a predefined level set by the customer. The G-soft NX II software designed for Smart Relay Genie-Nx, makes it convenient for the end users to build customized ladder programs for several applications.
In a portable organic waste composting machine, it is required to monitor and control temperature, moisture level as well as proper mixing of garbage in order to produce the perfect compost manure.
Backlit LCD screen for display & modification of pre-selected parameter of functional blocks, viewing I/O status and programming on the device.
Mini PLC PL-100 along with the Temperature controller PR43 and Liquid Level Controller(LLC) from GIC are used in this application. The liquid level of the input garbage is sensed by liquid level controller and the corresponding feedback is provided to the PLC. Based on this input, PLC gives further command to regulate the temperature of heater to control the moisture level of input garbage. To ensure proper and periodic mixing of input garbage the mixer is effectively controlled by PLC for the forward and reverse operation. Interlinking LLC and temperature controller with PLC helps in achieving the highest quality of compost manure.
In a manufacturing unit, it is required to control and monitor the washing cycle of products as per the worker shift timings in order to reduce wastage of resources.
Industrial washing machines are used to wash mechanical parts with the help of petrochemical solution. Normally it is required to initiate the washing process before the worker’s shift timing in order save time and reduce process cycle time. This is achieved by using DC variant of Digital Time Switch Crono. Inbuilt RTC feature helps to automatically control the duration of washing cycle as per the shift timings. 25 on/off programs and 6 years battery reserve makes Crono indispensable for process optimization.
In high rise residential buildings, it is required to monitor and control garbage chute in order to avoid multiple handling of the system and to ensure proper segregation of dry and wet waste.
Typically, in a garbage chute application, there is a possibility of multiple individuals trying to access the garbage chute at the same time. To avoid any accidental damage to the individuals, the Mini PLC PL-100 from GIC is used to effectively monitor and control the access points of garbage chute installed at every floor of the building. Door sensors of the garbage chute at each floor are linked with the PLC and this enables to govern the operation with precise timing and provides access to single user at a time. Depending on the user selection of dry and wet waste the diversion flap at the bottom of the garbage chute is controlled to effectively segregate the waste. The wet, dry and busy conditions are indicated on the display of the garbage chute.
In the conventional cold storage application, it is required to operate two air conditioner units automatically one after the other in order to distribute load and save energy.
In order to maintain the temperature in the cold storage, high capacity air conditioners are installed so that the perishable products can be preserved and stored effectively. The digital time switch Crono from GIC is used to automatically switch ON/OFF air conditioner units as per predefined schedule in order to distribute load and save significant amount of energy. This helps to avoid the over usage of air conditioner units thereby reducing maintenance costs.
|
from detector import Detector, DetectorElement
import material
from geometry import VolumeCylinder
import math
class ECAL(DetectorElement):
def __init__(self):
volume = VolumeCylinder('ecal', 1.55, 2.25, 1.30, 2. )
mat = material.Material('ECAL', 8.9e-3, 0.) # lambda_I = 0
self.eta_crack = 1.5
self.emin = 2.
super(ECAL, self).__init__('ecal', volume, mat)
def energy_resolution(self, energy, theta=0.):
return 0.
def cluster_size(self, ptc):
pdgid = abs(ptc.pdgid)
if pdgid==22 or pdgid==11:
return 0.04
else:
return 0.07
def acceptance(self, cluster):
return True
def space_resolution(self, ptc):
pass
class HCAL(DetectorElement):
def __init__(self):
volume = VolumeCylinder('hcal', 2.9, 3.6, 1.9, 2.6 )
mat = material.Material('HCAL', None, 0.17)
super(HCAL, self).__init__('ecal', volume, mat)
def energy_resolution(self, energy, theta=0.):
return 0.
def cluster_size(self, ptc):
return 0.2
def acceptance(self, cluster):
return True
def space_resolution(self, ptc):
pass
class Tracker(DetectorElement):
#TODO acceptance and resolution depend on the particle type
def __init__(self):
volume = VolumeCylinder('tracker', 1.29, 1.99)
mat = material.void
super(Tracker, self).__init__('tracker', volume, mat)
def acceptance(self, track):
return True
def pt_resolution(self, track):
return 0.
class Field(DetectorElement):
def __init__(self, magnitude):
self.magnitude = magnitude
volume = VolumeCylinder('field', 2.9, 3.6)
mat = material.void
super(Field, self).__init__('tracker', volume, mat)
class Perfect(Detector):
'''A detector with the geometry of CMS and the same cluster size,
but without smearing, and with full acceptance (no thresholds).
Used for testing purposes.
'''
def __init__(self):
super(Perfect, self).__init__()
self.elements['tracker'] = Tracker()
self.elements['ecal'] = ECAL()
self.elements['hcal'] = HCAL()
self.elements['field'] = Field(3.8)
perfect = Perfect()
|
Hall County Fire Services welcomes feedback in regard to how our personnel are serving the citizens and visitors of Hall County. Please complete the following form for commendations or complaints to be appropriately investigated.
Hall County Fire Services requests the following information in order to provide clarification and feedback on your issue. While not required, this information will allow us the opportunity to better serve you.
|
"""License file generator module."""
from pathlib import Path
from src.license_templates import MIT_LICENSE_TEMPLATE
from src.license_templates import GPL3_LICENSE_TEMPLATE
from src.license_templates import APACHE_LICENSE_TEMPLATE
class LicenseGenerator(object):
"""License file generator class."""
@staticmethod
def generate(file_path, license_metadata):
"""Generates the LICENSE file for the project."""
content = None
if license_metadata['file'] == 'MIT':
content = MIT_LICENSE_TEMPLATE
if 'year' in license_metadata:
content = content.replace('<year>', license_metadata['year'])
if 'owner' in license_metadata:
content = content.replace('<owner>', license_metadata['owner'])
elif license_metadata['file'] == 'GPL3':
content = GPL3_LICENSE_TEMPLATE
elif license_metadata['file'] == 'Apache':
content = APACHE_LICENSE_TEMPLATE
if content:
with open(file_path, 'w') as stream:
stream.write(content)
else:
Path(file_path).touch()
|
By accessing “Axwell Forum” (hereinafter “we”, “us”, “our”, “Axwell Forum”, “https://www.axwellforum.com”), you agree to be legally bound by the following terms.
If you do not agree to be legally bound by all of the following terms then please do not access and/or use “Axwell Forum”.
We may change these at any time and we’ll do our utmost in informing you, though it would be prudent to review this regularly yourself as your continued usage of “Axwell Forum” after changes mean you agree to be legally bound by these terms as they are updated and/or amended.
You agree not to post any abusive, obscene, vulgar, slanderous, hateful, threatening, sexually-orientated or any other material that may violate any laws be it of your country, the country where “Axwell Forum” is hosted or International Law. Doing so may lead to you being immediately and permanently banned, with notification of your Internet Service Provider if deemed required by us. The IP address of all posts are recorded to aid in enforcing these conditions. You agree that “Axwell Forum” have the right to remove, edit, move or close any topic at any time should we see fit. As a user you agree to any information you have entered to being stored in a database. While this information will not be disclosed to any third party without your consent, neither “Axwell Forum” nor phpBB shall be held responsible for any hacking attempt that may lead to the data being compromised.
To comply with the GDPR you need to be made aware that your Axwell Forum account will, at a bare minimum, contain a uniquely identifiable name (hereinafter “your user name”), a personal password used for logging into your account (hereinafter “your password”) and a personal, valid email address (hereinafter “your email”). Your information for your account at Axwell Forum is protected by data-protection laws applicable in the country that hosts us. Any information beyond your user name, your password, and your email address required by Axwell Forum during the registration process is either mandatory or optional, at the discretion of Axwell Forum. In all cases, you have the option of what information in your account is publicly displayed. Furthermore, within your account, you have the option to opt-in or opt-out of automatically generated emails.
Furthermore we will store all of the IP address that you use to post with. Depending on your preferences Axwell Forum may send you emails to the email address that Axwell Forum holds in your account which will either be that you used when you registered or one that you have subsequently changed, but you are able to change these preferences from your User Control Panel (UCP) at any time should you wish to stop receiving them.
The personal details that you gave us when you signed up, or added later, will be used solely for the purposes of Axwell Forum board functionality. They will not be used for anything else and neither will they be passed on to any third party without your explicit consent. You can check, at any time, the personal details Axwell Forum is holding about you from the Profile section of your UCP.
We use files known as cookies on Axwell Forum to improve its performance and to enhance your user experience. By using Axwell Forum you agree that we can place these types of files on your device.
There are many functions that a cookie can serve. For example, a cookie will help the website, or another website, to recognise your device the next time you visit it. Axwell Forum uses the term "cookies" in this policy to refer to all files that collect information in this way.
Certain cookies contain personal information – for example, if you click on "remember me" when logging on, a cookie will store your username. Most cookies will not collect information that identifies you, but will instead collect more general information such as how users arrive at and use Axwell Forum, or a user’s general location.
What sort of cookies does Axwell Forum use?
Some cookies are essential for the operation of Axwell Forum. These cookies enable services you have specifically asked for.
Axwell Forum may also allow third parties to serve cookies that fall into any of the categories above. For example, like many sites, we may use Google Analytics to help us monitor our website traffic.
Please remember that if you do choose to disable cookies, you may find that certain sections of Axwell Forum do not work properly.
Axwell Forum may have links to social networking websites (e.g. Facebook, Twitter or YouTube). These websites may also place cookies on your device and Axwell Forum does not control how they use their cookies, therefore Axwell Forum suggests you check their website(s) to see how they are using cookies.
We will not use your Personal Data for activities where our interests are overridden by the impact on you, unless we have your consent or are otherwise required to do so by law.
|
#!/usr/bin/env python
import unittest
import datetime
from autumn.model import Model
from autumn.tests.models import Book, Author
from autumn.db.query import Query
from autumn.db import escape
from autumn import validators
class TestModels(unittest.TestCase):
def testmodel(self):
# Create tables
### MYSQL ###
#
# DROP TABLE IF EXISTS author;
# CREATE TABLE author (
# id INT(11) NOT NULL auto_increment,
# first_name VARCHAR(40) NOT NULL,
# last_name VARCHAR(40) NOT NULL,
# bio TEXT,
# PRIMARY KEY (id)
# );
# DROP TABLE IF EXISTS books;
# CREATE TABLE books (
# id INT(11) NOT NULL auto_increment,
# title VARCHAR(255),
# author_id INT(11),
# FOREIGN KEY (author_id) REFERENCES author(id),
# PRIMARY KEY (id)
# );
### SQLITE ###
#
# DROP TABLE IF EXISTS author;
# DROP TABLE IF EXISTS books;
# CREATE TABLE author (
# id INTEGER PRIMARY KEY AUTOINCREMENT,
# first_name VARCHAR(40) NOT NULL,
# last_name VARCHAR(40) NOT NULL,
# bio TEXT
# );
# CREATE TABLE books (
# id INTEGER PRIMARY KEY AUTOINCREMENT,
# title VARCHAR(255),
# author_id INT(11),
# FOREIGN KEY (author_id) REFERENCES author(id)
# );
for table in ('author', 'books'):
Query.raw_sql('DELETE FROM %s' % escape(table))
# Test Creation
james = Author(first_name='James', last_name='Joyce')
james.save()
kurt = Author(first_name='Kurt', last_name='Vonnegut')
kurt.save()
tom = Author(first_name='Tom', last_name='Robbins')
tom.save()
Book(title='Ulysses', author_id=james.id).save()
Book(title='Slaughter-House Five', author_id=kurt.id).save()
Book(title='Jitterbug Perfume', author_id=tom.id).save()
slww = Book(title='Still Life with Woodpecker', author_id=tom.id)
slww.save()
# Test ForeignKey
self.assertEqual(slww.author.first_name, 'Tom')
# Test OneToMany
self.assertEqual(len(list(tom.books)), 2)
kid = kurt.id
del(james, kurt, tom, slww)
# Test retrieval
b = Book.get(title='Ulysses')[0]
a = Author.get(id=b.author_id)[0]
self.assertEqual(a.id, b.author_id)
a = Author.get(id=b.id)[:]
self.assert_(isinstance(a, list))
# Test update
new_last_name = 'Vonnegut, Jr.'
a = Author.get(id=kid)[0]
a.last_name = new_last_name
a.save()
a = Author.get(kid)
self.assertEqual(a.last_name, new_last_name)
# Test count
self.assertEqual(Author.get().count(), 3)
self.assertEqual(len(Book.get()[1:4]), 3)
# Test delete
a.delete()
self.assertEqual(Author.get().count(), 2)
# Test validation
a = Author(first_name='', last_name='Ted')
try:
a.save()
raise Exception('Validation not caught')
except Model.ValidationError:
pass
# Test defaults
a.first_name = 'Bill and'
a.save()
self.assertEqual(a.bio, 'No bio available')
try:
Author(first_name='I am a', last_name='BadGuy!').save()
raise Exception('Validation not caught')
except Model.ValidationError:
pass
def testvalidators(self):
ev = validators.Email()
assert ev('test@example.com')
assert not ev('adsf@.asdf.asdf')
assert validators.Length()('a')
assert not validators.Length(2)('a')
assert validators.Length(max_length=10)('abcdegf')
assert not validators.Length(max_length=3)('abcdegf')
n = validators.Number(1, 5)
assert n(2)
assert not n(6)
assert validators.Number(1)(100.0)
assert not validators.Number()('rawr!')
vc = validators.ValidatorChain(validators.Length(8), validators.Email())
assert vc('test@example.com')
assert not vc('a@a.com')
assert not vc('asdfasdfasdfasdfasdf')
if __name__ == '__main__':
unittest.main()
|
The Ferrari 458 Italia is a rear mid-engined V8 sports car produced by Ferrari and is the successor to the F430.
Pininfarina designed the 458 with a lot of Formula 1 design cues, notably the deformable winglets in the front and vents next to the headlights that increase downforce. Ferrari also included a F1 influenced steering wheel with various controls placed on it.
Both the Ferrari 458 Italia and Spider ceased production in 2015, being replaced by the Ferrari 488 GTB.
|
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import json
import argparse
import time
from datetime import datetime, date as _date
from dateutil.relativedelta import relativedelta
try:
from email.Utils import formatdate
except ImportError: # py3
from email.utils import formatdate
import requests
import os.path
def logs(domain, api_key, begin=None, end=None, max_retries=None, verbose=False):
url = 'https://api.mailgun.net/v2/%s/events' % domain
params = {
'begin': begin or formatdate(),
}
if end:
params['end'] = end
init = True
while True:
count_get_page_retry = 0
if params:
response = requests.get(url=url, auth=('api', api_key), params=params)
if not response.ok:
while count_get_page_retry < max_retries:
time.sleep(2)
response = requests.get(url=url, auth=('api', api_key), params=params)
count_get_page_retry += 1
if response.ok:
break
else:
response = requests.get(url=url, auth=('api', api_key))
if not response.ok:
while count_get_page_retry < max_retries:
time.sleep(2)
response = requests.get(url=url, auth=('api', api_key), params=params)
count_get_page_retry += 1
if response.ok:
break
if not response.ok:
raise ValueError('Invalid status_code: {0}'.format(response.status_code))
if verbose:
print('# {0} {1}'.format(response.request.method, response.request.url), file=sys.stderr)
print('# STATUS CODE: {0}'.format(response.status_code), file=sys.stderr)
data = response.json()
items = data['items']
for record in items:
yield record
if not len(items):
if init:
# first iteraction, fetch first page
url = data['paging']['first']
params=None
else:
# EOF
return
else:
url = data['paging']['next']
init = False
def strdate_to_rfc2822(value=None, midnight=False, now=False):
"""Convert date in format YYYY/MM/DD to RFC2822 format.
If value is None, return current utc time.
"""
if midnight and now:
raise ValueError('Choose one of "midnight" or "now"')
strdate = value if value else datetime.utcnow().strftime('%Y/%m/%d')
datetimetuple = list(map(int, strdate.split('/')))
if midnight:
datetimetuple += (0, 0, 0)
elif now:
now = datetime.utcnow()
datetimetuple += (now.hour, now.minute, now.second)
else:
datetimetuple += (23, 59, 59)
date = datetime(*datetimetuple)
timestamp = time.mktime(date.utctimetuple())
return date.strftime('%a, %d %b %Y %H:%M:%S -0000')
def main():
parser = argparse.ArgumentParser(description='Retrieve Mailgun event logs.')
parser.add_argument('-d', '--days', help='Days ago (N)',
dest='days',
type=int,
default=None)
parser.add_argument('-b', '--begin', help='Begin date (YYYY/MM/DD)',
dest='begin',
default=None)
parser.add_argument('-e', '--end', help='End date (YYYY/MM/DD)',
dest='end',
default=None)
parser.add_argument('-j', '--json', help='Print json (original) log records',
dest='json',
action='store_true',
default=False)
parser.add_argument('-V', '--version', help='Print version to stdout and exit',
dest='version',
action='store_true',
default=False)
parser.add_argument('domain', help='Domain registered on Mailgun (or set env var MAILGUN_DOMAIN)',
metavar='domain',
type=str,
nargs='?',
default=None)
parser.add_argument('api_key', help='Mailgun API KEY (or set env var MAILGUN_API_KEY)',
metavar='api_key',
type=str,
nargs='?',
default=None)
parser.add_argument('-r', '--retries', help="Number of retries while",
dest='max_retries',
type=int,
default=100)
parser.add_argument('--file', help="Output file",
dest='filename',
type=str,
default=None)
parser.add_argument('--logstash', help="Output logstash url",
dest='logstashurl',
type=str,
default=None)
parser.add_argument('-v', '--verbose', help='Print debug messages on stderr',
dest='verbose',
action='store_true',
default=False)
args = parser.parse_args()
if args.version:
from . import __title__, __version__
print('{0}-{1}'.format(__title__, __version__))
sys.exit(0)
jsondata = {'logs': []}
# parse date interval
if args.days:
begin_day = _date.today() - relativedelta(days=args.days)
begin = strdate_to_rfc2822(begin_day.strftime('%Y/%m/%d'), midnight=True)
end_day = _date.today() - relativedelta(days=1)
end = strdate_to_rfc2822(end_day.strftime('%Y/%m/%d'))
else:
begin = strdate_to_rfc2822(args.begin, midnight=True)
end = strdate_to_rfc2822(args.end, now=False) if args.end else None
if begin:
jsondata['begin'] = begin
if end:
jsondata['end'] = end
# parse api domain and credentials
try:
if args.domain:
domain = args.domain
else:
domain = os.environ['MAILGUN_DOMAIN']
jsondata['domain'] = domain
except KeyError:
print('Missing mailgun API key')
sys.exit(1)
try:
if args.api_key:
api_key = args.api_key
else:
api_key = os.environ['MAILGUN_API_KEY']
except KeyError:
print('Missing mailgun API key')
sys.exit(1)
if args.verbose:
print('# BEGIN DATE: {}'.format(begin), file=sys.stderr)
print('# END DATE: {}'.format(end), file=sys.stderr)
sys.stderr.flush()
if args.filename:
# Check for existing file
if os.path.exists(args.filename):
while True:
answer = raw_input("File %s exists! Proceed? You will lost data in the file!: " % file)
if answer.lower() == 'yes':
break
elif answer.lower() == 'no':
sys.exit('Interrupted by user')
# Open file for write
try:
logfile = open(args.filename, 'w')
except IOError:
print('Can not open file to write')
# Main loop
time_start = datetime.now().replace(microsecond=0)
for log in logs(domain=domain, api_key=api_key, begin=begin, end=end, max_retries=args.max_retries, verbose=args.verbose):
if args.json:
line_json = json.dumps(log, indent=3)
if args.filename:
try:
logfile.write(line_json + '\n')
except IOError:
print('Can not write log to file ' + args.filename)
logfile.close()
if args.logstashurl:
try:
requests.put(args.logstashurl, data=line_json, headers={'Content-Type': 'application/json'})
except IOError:
print('Can put log to ' + args.logstashurl)
else:
status = log.get('event', '').upper()
ok = status in ['ACCEPTED', 'DELIVERED']
line = '[%s] %s <%s>' % (datetime.utcfromtimestamp(log.get('timestamp', '')), status , log.get('recipient', ''))
if not ok:
line += ' (%s)' % (log.get('delivery-status', {}).get('description', '') or log.get('delivery-status', {}).get('message', ''))
line += ': %s' % log.get('message', {}).get('headers', {}).get('subject', '')
logfile.write(line + '\n')
if args.filename:
logfile.close()
if args.verbose:
# Getting stop time and execution time
time_stop = datetime.now().replace(microsecond=0)
time_exec = time_stop - time_start
# Summary output
summary = """
Start time: %s
End time: %s
Total execution time: %s
""" % (time_start, time_stop, time_exec)
print('\n' + '!' * 79 + '\n' + summary + '!' * 79 + '\n')
if __name__ == '__main__':
main()
|
Cinegy CEO Jan Weigner said, “JET Pack has changed everything. Subscribers worldwide have found that there is no longer any need to spend precious capital to buy and maintain machinery to do the heavy lifting. JET Pack does everything, and more, that they need in a software-only environment.
Cinegy JET Pack includes Cinegy Air PRO with Cinegy Type for real-time playout and multi-channel automation, including channel branding and CG; Cinegy Capture PRO for real-time ingest; Cinegy Multiviewer, which is comprised of four channels of multi-channel video monitoring; Cinegy Live for mixing and cutting; Cinegy Convert for transcoding and batch processing as well as Cinegy Player PRO.
Although all are available on a single annual subscription basis, they can be purchased outright for an equally cost-effective outlay if desired.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.