text
stringlengths
29
850k
from blockchain import Message, Block, Blockchain, InvalidBlockchain import unittest import hashlib class TestBlockchain(unittest.TestCase): def get_block(self, msg): B = Block() B.add_message(Message(msg)) return B def get_blocks(self, *args): L = [] for arg in args: b = Block() b.add_message(Message(arg)) L.append(b) for i, block in enumerate(L): block.link(L[i-1]) if i > 0 else None block.seal() return L def test_creation(self): chain = Blockchain() self.assertEqual([], chain.blocks) def test_add_block(self): chain = Blockchain() chain.add_block(self.get_block("some message")) self.assertEqual(1, len(chain.blocks)) self.assertEqual("some message", chain.blocks[-1].messages[0].data) def test_add_multiple_blocks_sets_hashes_correctly(self): chain = Blockchain() chain.blocks = self.get_blocks("first", "second", "third") self.assertEqual(3, len(chain.blocks)) self.assertEqual("first", chain.blocks[0].messages[0].data) self.assertEqual("second", chain.blocks[1].messages[0].data) self.assertEqual("third", chain.blocks[2].messages[0].data) self.assertIsNotNone(chain.blocks[-1].hash) self.assertEqual(chain.blocks[1].prev_hash, chain.blocks[0].hash) self.assertEqual(chain.blocks[2].prev_hash, chain.blocks[1].hash) def test_invalid_block_breaks_chain(self): chain = Blockchain() chain.blocks = self.get_blocks("first", "second", "third", "fourth", "fifth") chain.blocks[1].messages[0].data = "changed" self.assertRaises(InvalidBlockchain, chain.validate) if __name__ == '__main__': unittest.main()
This brief gives a summary of HHS final rules on reinsurance, risk corridors, and risk adjustment from Wakely Consulting Group. The brief also provides a summary on how the final rules differ from the July 2011 proposed rules. This issue brief from The Commonwealth Fund estimates the rebates expected in each state if the new medical loss ratio (MLR) rules had been in effect a year earlier. According to the report, consumers would have received about $2 billion in rebates if health care reform’s new MLR requirements had been in effect in 2010. Maryland's Health Benefit Exchange has created a high level timeline to prepare the state's Level II exchange funding grant application. The deadline to apply is June 30, 2012. The North Carolina Health Benefit Exchange workgroup created a subcommittee to consider education and outreach efforts; training for nonprofits and other groups who can refer individuals to appropriate assistance; navigator training, certification, compensation and accountability; the role of agents and brokers; and how to create the “no wrong door” eligibility and enrollment process. This report gives draft recommendations from the subcommittee to the full committee. The Department of Vermont Health Access released the results of a statewide telephone survey conducted between March 17-25, 2012, to solicit views on the state's forthcoming health insurance exchange. The survey results will be used to plan the state's navigator program and marketing campaign for the exchange. This report examines the decline in state revenues and changes in Medicaid spending during the last two recessions to look more closely at what has been driving state budget deficits. Governors' Budgets for FY 2013 -- What is Proposed for Medicaid? This report provides Medicaid highlights from governors’ proposed state budgets for FY 2013, which starts July 1, 2012 for most states. These are the fourth and fifth state-specific reports in a series of 10 from the Urban Institute to track and monitor the implementation process and effects of the ACA. These reports look at the progress underway in Colorado and New York. With the help of six national health care experts, the Blue Cross Blue Shield of Massachusetts Foundation's 2011 annual report explores how to tame rising health care costs. The Foundation asked Governor Deval Patrick, Don Berwick, Deborah Enos, Jeff Levin-Scherz, Rick Lord, and Kate Walsh to talk with each other about the most promising solutions. This report addresses the potential of integrated delivery systems and effective state policy options to encourage changes in delivery systems.
# -*- encoding:utf-8 -*- import logging import jinja2 from flask import abort from flask import json mongo = None jinja_env = jinja2.Environment() def get_templates(): templates = mongo.db.templates.find({}, {'_id': 1}) return dict(templates=[t["_id"] for t in templates]) def get_template(name): template = mongo.db.templates.find_one_or_404({'_id': name}) template.pop("_id", None) return template["content"] def create_template(name, content): template = mongo.db.templates.find_one({'_id': name}) if template: abort(400) try: mongo.db.templates.insert(dict(_id=name, content=content)) except: abort(400) def update_template(name, content): mongo.db.templates.find_one_or_404({'_id': name}) try: mongo.db.templates.update({'_id': name}, {"$set": dict(content=content)}) except: abort(400) def delete_template(name): mongo.db.templates.find_one_or_404({'_id': name}) try: mongo.db.templates.remove({'_id': name}) except: abort(400)
Biggleswade Ladies did themselves proud in their first ever cup game at the weekend, with a storming win away at Towcester. The team were desperate to give a better account of themselves than they did in last week’s friendly against Chesham/Bletchley, and had worked hard at training to put right their errors. Towcester didn’t make it easy, forcing Biggleswade to defend from the off, and pinning them back in their 22. Roses scored first from a penalty, but Biggy were much better organised in defence than in previous games, rolling left and right to keep a solid line, and pressing Towcester’s attack, forcing handling errors. It was Biggleswade who got the first try: a well-executed pick and go from the back of the scrum by No 8 Amy Schiller, converted by captain and fly half Charlie Field. Flanker Sarah Ashby flew down the pitch after a pop pass from the back of the scrum, dodging Towcester players and making huge yardage, only to “*BLEEP!* up the offload” (to paraphrase coach Jimmy Caulfield). Roses built up some sustained pressure, but Biggy thwarted what looked like a certain try, defending valiantly from their own tryline, turning over the ball, and setting up a great counter-attack of their own. Biggleswade were now truly fired up and determined to take control of the game. Winger Tash Cooper was unlucky not to score after a jinking run up the touchline, stopped by a tackle into touch 5m from the line. Biggleswade increased the pressure in the second half, although it was Towcester who scored against the run of play with a breakaway try from a knock-on, taking the score to 10-7. Biggleswade didn’t flinch, working hard to rip and turnover ball in the tackle, setting up forward pods, and linking well with the back line to work the ball away to space. Lineouts and scrums were solid, backs’ moves from training were beginning to flow, and there were several quick breakaways on both wings. Biggy’s patience and hard work was rewarded by a second try from Amy, after another strong run from the back of a ruck. Sophie Earls, slotting in at loosehead prop, put in another big performance, the highlight of which was something you don’t see very often – a No 1 sprinting three-quarters of the length of the pitch to score. She caught a Roses’ restart ball and ran like the wind through their team all the way to the tryline! Holly Crawford, who started at 15 but was switched to No 9, gained yards after she picked and went from a scrum, but couldn’t break the Towcester tackle. Quick-thinking from Charlie saw her scoop up the ball, pin her ears back and run over the line to score Biggy’s fourth try, which she duly converted. There was one more score to come, when Biggy forwards sucked in Towcester to the rucks then passed out to Amy, who looped round and ran in right under the posts for another try, completing a quality hat-trick. Charlie’s successful conversion made it an impressive 5 from 5 in windy conditions. On any other occasion Amy (sponsored by CW Cakes) would have won Forward of the Match for a thunderous game including three great tries, but she was pipped at the post by Sophie Earls (sponsored by Biggleswade RUFC 3rd Team) for being the Fastest Scrum-Cap in the West. Rumours are that Sophie still hasn’t stopped running – and as this article went to press, reports were coming in of several sightings of her Forest Gumping through the Brecon Beacons. Back of the match was Teri Taylor (sponsored by Royal Images), for a great performance at No 9, then No 12, where she stopped the signature Towcester tractor move several times.
#!/usr/bin/python ########################################################## #This script has been created by #Copyright 2006 Devanshu Mehta # of http://www.scienceaddiction.com #It is released under the GNU General Public License v2 # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # This pulls information about directors of the films you have rated # from the Netflix web site. Please run getflix.pl first! # # Generates file called directors.txt # Format: DirectorName~Rating import re from mechanize import Browser import sys import urllib2 idfile=open('directors.txt','w') rat=0 id=0 tempstr='' br=Browser() for line in open('netflix.txt').xreadlines( ): arr=line.split('~') rat=int(arr.pop()) id=arr.pop(0) tempstr="http://www.netflix.com/MovieDisplay?movieid="+id br.set_handle_robots(False) f=br.open(tempstr) i=0 body=f.read() i=body.find('Director:') directorline=body[i+14:i+75] list=directorline.split('<') director=list[0].strip('. ') tempstr=director+"~"+str(rat)+"\n" idfile.write(tempstr) print tempstr idfile.flush() #br=Browser() #br.set_handle_robots(False) #f=br.open(sys.argv[1]) #body=f.read() #i=0 #i=body.find('Director') #directorline=body[i+14:i+75] #list=directorline.split('<') #director=list[0].strip('. ') #print director
My four years of undergraduate studies in CS at PSG College of Technology, Coimbatore and my exposure and penchant for research have made the choice of further study, for me, an obvious one. My goal is to pursue a career in research, either in industry or in academia. Ten years from now, I envisage myself as a full-fledged research professional in an organization, or a faculty member at one of the leading universities. The first step towards my objective would be to pursue Masters Program in Computer Science. My ultimate degree objective would however be a Ph.D. Throughout my student career I have been a top ranking student. I was in the top 0.05% of all engineering aspirants in my state, which secured me a place in PSG College of Technology- one of the premier institutions in India. I have done justice to my potential by contributing notably to the research works in our college as well as maintaining my academic rank within the top 5% of the students in my class. Over the past two years, my liking for research has burgeoned especially in the fields of security and distributed computing. I started by studying various information hiding techniques. After extensive literature survey in the fields of Steganography and Watermarking, I published my own technique for efficient information hiding in low resolution images using Newtons Forward Difference in Springer-Verlag LNCS. I have also worked with watermarking techniques especially audio watermarking and echo hiding and my paper titled “A Novel Embedding System For Efficient Watermarking In Auido In Echo” tests the fitness of the NFD Technique in this field of research. I used the NFD Technique to compress uncorrelated frames in a video file by establishing a relationship by generating a Correlation polynomial. This proposal was well acclaimed when I presented in the International Conference of Human Machine’s Interface (ICHMI 04) at Indian Institute of Science (IISc Bangalore). Two of my courses Distributed Component Architecture and Client Server Computing interested me a lot. I was very keen on doing some research work in these areas and devoted quality time towards an in-depth understanding of these subjects and tried to implement my own ideas in these fields. My urge and potential for research was identified and I was chosen to lead the team for a research project, “Code Optimisation in Middleware-based Distributed Embedded Systems”. We built a security framework for CORBA – based applications providing 6 security services, which includes authentication, authorization, non-repudiation, data integrity, auditing and security while transmission. We designed a 128-bit symmetric key crypto algorithm G- MAP to be used in all the security services. During the course of the project, I had the opportunity to design an N-tier for the distributed nature of the framework and implement them in java. Our originality and substantial work in the project was appropriately recognized and the project was given ‘The Best Project Award’, in the department. My academic pursuits have not however, prevented me from participating with interest in various co-curricular activities including organizing seminars and serving as representative of the class. These activities have led to the development of a multifaceted personality and have equipped me with strong interpersonal skills. My academic achievements, research work and inter personal skills were well acknowledged and I was given the ‘Best outgoing student’ award in our batch. I am currently working with Computer Associates and I am working on the project “Security and Device Management of Smart phones”. Apart from managing smart phones, this project deals with designing security policies for them and implementing the same using Java technologies. My work spans across all the tiers of the project, which includes building the GUI using JSTL and JSF, implementing the business logic using Enterprise Java Beans and designing the database using SQL Server. If admitted I plan to carry on with my advanced studies in the fields of security and distributed computing systems. Considering the pioneering work going on at your department labs Distributed Systems Software Lab (DSSL) and Information Systems Security Lab (MISSL), which perfectly match with the field of my interest, computer science department at University of Maryland, is the ideal choice for an exciting research career. At the same time, I am confident of contributing originally to the ongoing work at your department. By working under the guidance of distinguished faculty at your department, I am certain that I will be able to exploit my potential to the fullest. I look forward to joining University of Maryland as a graduate student at your esteemed department. 0 responses on "SOP for MS in Computer Engineering (CS)" What are the advantages and disadvantages of studying in Germany?
"""ML-ENSEMBLE :author: Sebastian Flennerhag :copyright: 2017-2018 :licence: MIT Utility functions for constructing metrics """ from __future__ import division import warnings import numpy as np from ..utils.exceptions import MetricWarning try: from collections import OrderedDict as _dict except ImportError: _dict = dict def _get_string(obj, dec): """Stringify object""" try: return '{0:.{dec}f}'.format(obj, dec=dec) except (TypeError, ValueError): return obj.__str__() def _get_partitions(obj): """Check if any entry has partitions""" for name, _ in obj: if int(name.split('.')[-2]) > 0: return True return False def _split(f, s, a_p='', a_s='', b_p='', b_s='', reverse=False): """Split string on a symbol and return two string, first possible empty""" splitted = f.split(s) if len(splitted) == 1: a, b = '', splitted[0] if reverse: b, a = a, b else: a, b = splitted if a: a = '%s%s%s' % (a_p, a, a_s) if b: b = '%s%s%s' % (b_p, b, b_s) return a, b class Data(_dict): """Wrapper class around dict to get pretty prints :class:`Data` is an ordered dictionary that implements a dedicated pretty print method for a nested dictionary. Printing a :class:`Data` dictionary provides a human-readable table. The input dictionary is expected to have two levels: the first level gives the columns and the second level the rows. Rows names are parsed as ``[OUTER]/[MIDDLE].[INNER]--[IDX]``, where IDX has to be an integer. All entries are optional. .. seealso:: :func:`assemble_data`, :func:`assemble_table` Warning ------- :class:`Data` is an internal class that expects a particular functions. This class cannot be used as a general drop-in replacement for the standard ``dict`` class. Examples -------- >>> from mlens.metrics import Data >>> d = [('row-idx-1.row-idx-2.0.0', {'column-1': 0.1, 'column-2': 0.1})] >>> data = Data(d) >>> print(data) column-a column-b row-idx-1 row-idx-2 0.10 0.20 """ def __init__(self, data=None, padding=2, decimals=2): if isinstance(data, list): data = assemble_data(data) super(Data, self).__init__(data) self.__padding__ = padding self.__decimals__ = decimals def __repr__(self): return assemble_table(self, self.__padding__, self.__decimals__) def assemble_table(data, padding=2, decimals=2): """Construct data table from input dict Given a nested dictionary formed by :func:`assemble_data`, :func:`assemble_table` returns a string that prints the contents of the input in tabular format. The input dictionary is expected to have two levels: the first level gives the columns and the second level the rows. Rows names are parsed as ``[OUTER]/[MIDDLE].[INNER]--[IDX]``, where IDX must be an integer. All entries are optional. .. seealso:: :class:`Data`, :func:`assemble_data` Examples -------- >>> from mlens.metrics import assemble_data, assemble_table >>> d = [('row-idx-1.row-idx-2.a.b', {'column-1': 0.1, 'column-2': 0.1})] >>> print(assemble_table(assemble_data(d))) column-2-m column-2-s column-1-m column-1-s row-idx-1 row-idx-2 0.10 0.00 0.10 0.00 """ buffer = 0 row_glossary = ['layer', 'case', 'est', 'part'] cols = list() rows = list() row_keys = list() max_col_len = dict() max_row_len = {r: 0 for r in row_glossary} # First, measure the maximum length of each column in table for key, val in data.items(): cols.append(key) max_col_len[key] = len(key) # dat_key is the estimators. Number of columns is not fixed so need # to assume all exist and purge empty columns for dat_key, v in sorted(val.items()): if not v: # Safety: no data continue v_ = len(_get_string(v, decimals)) if v_ > max_col_len[key]: max_col_len[key] = v_ if dat_key in row_keys: # Already mapped row entry name continue layer, k = _split(dat_key, '/') case, k = _split(k, '.') est, part = _split(k, '--', reverse=True) # Header space before column headings items = [i for i in [layer, case, est, part] if i != ''] buffer = max(buffer, len(' '.join(items))) for k, v in zip(row_glossary, [layer, case, est, part]): v_ = len(v) if v_ > max_row_len[k]: max_row_len[k] = v_ dat = _dict() dat['layer'] = layer dat['case'] = case dat['est'] = est dat['part'] = part row_keys.append(dat_key) rows.append(dat) # Check which row name columns we can drop (ex partition number) drop = list() for k, v in max_row_len.items(): if v == 0: drop.append(k) # Header out = " " * (buffer + padding) for col in cols: adj = max_col_len[col] - len(col) + padding out += " " * adj + col out += "\n" # Entries for dat_key, dat in zip(row_keys, rows): # Estimator name for key, val in dat.items(): if key in drop: continue adj = max_row_len[key] - len(val) + padding out += val + " " * adj # Data for col in cols: item = data[col][dat_key] if not item and item != 0: out += " " * (max_col_len[col] + padding) continue item_ = _get_string(item, decimals) adj = max_col_len[col] - len(item_) + padding out += " " * adj + item_ out += "\n" return out def assemble_data(data_list): """Build a data dictionary out of a list of entries and data dicts Given a list named tuples of dictionaries, :func:`assemble_data` returns a nested ordered dictionary with data keys as outer keys and tuple names as inner keys. The returned dictionary can be printed in tabular format by :func:`assemble_table`. .. seealso:: :class:`Data`, :func:`assemble_table` Examples -------- >>> from mlens.metrics import assemble_data, assemble_table >>> d = [('row-idx-1.row-idx-2.a.b', {'column-1': 0.1, 'column-2': 0.1})] >>> print(assemble_table(assemble_data(d))) column-2-m column-2-s column-1-m column-1-s row-idx-1 row-idx-2 0.10 0.00 0.10 0.00 """ data = _dict() tmp = _dict() partitions = _get_partitions(data_list) # Collect scores per preprocessing case and estimator(s) for name, data_dict in data_list: if not data_dict: continue prefix, name = _split(name, '/', a_s='/') # Names are either est.i.j or case.est.i.j splitted = name.split('.') if partitions: name = tuple(splitted[:-1]) if len(name) == 3: name = '%s.%s--%s' % name else: name = '%s--%s' % name else: name = '.'.join(splitted[:-2]) name = '%s%s' % (prefix, name) if name not in tmp: # Set up data struct for name tmp[name] = _dict() for k in data_dict.keys(): tmp[name][k] = list() if '%s-m' % k not in data: data['%s-m' % k] = _dict() data['%s-s' % k] = _dict() data['%s-m' % k][name] = list() data['%s-s' % k][name] = list() # collect all data dicts belonging to name for k, v in data_dict.items(): tmp[name][k].append(v) # Aggregate to get mean and std for name, data_dict in tmp.items(): for k, v in data_dict.items(): if not v: continue try: # Purge None values from the main est due to no predict times v = [i for i in v if i is not None] if v: data['%s-m' % k][name] = np.mean(v) data['%s-s' % k][name] = np.std(v) except Exception as exc: warnings.warn( "Aggregating data for %s failed. Raw data:\n%r\n" "Details: %r" % (k, v, exc), MetricWarning) # Check if there are empty columns discard = list() for key, data_dict in data.items(): empty = True for val in data_dict.values(): if val or val == 0: empty = False if empty: discard.append(key) for key in discard: data.pop(key) return data
The Springfield Nuclear Power Plant employee is a man who works at Sector 7G. He is friends with Homer Simpson, but laughed at him when his wife referred to him as a pig on KBBL. Episode – "Some Enchanted Evening" Episode – "Simpson and Delilah" Charles Montgomery Burns • Canary M. Burns • Executive 1 • Executive 2 • Executive 3 • Al Simmons • Waylon Smithers, Jr. Modified on October 26, 2012, at 19:24.
_Numeric=None _numpy=None try: import Numeric as _Numeric except ImportError: try: import numpy as _numpy except ImportError: pass # Test numpy #_Numeric=None #import numpy as _numpy def usingNumeric(): """Return True if we are using Numeric""" global _Numeric if _Numeric: return True return False def usingNumpy(): """Return True if we are using numpy""" global _numpy if _numpy: return True return False def isAvailable(): """Return True or False depending on whether we have linear algebra functionality""" if usingNumeric or usingNumpy: return True return False def array(object,**kw): global _Numeric, _numpy if _Numeric: return _Numeric.array(object,**kw) elif _numpy: return _numpy.array(object,**kw) else: raise AttributeError("No numeric functionality to deal with an array.") def matrixmultiply(array1,array2,**kw): global _Numeric, _numpy if _Numeric: return _Numeric.matrixmultiply(array1,array2,**kw) elif _numpy: return _numpy.dot(array1,array2,**kw) else: raise AttributeError("No numeric functionality to deal with matrixmultiply.") def reshape(array,newshape,**kw): global _Numeric, _numpy if _Numeric: return _Numeric.reshape(array,newshape,**kw) elif _numpy: return _numpy.reshape(array,newshape,**kw) else: raise AttributeError("No numeric functionality to deal with reshape.") def transpose(array,**kw): global _Numeric, _numpy if _Numeric: return _Numeric.transpose(array,**kw) elif _numpy: return _numpy.transpose(array,**kw) else: raise AttributeError("No numeric functionality to deal with transpose.") def zeros(array,**kw): global _Numeric, _numpy if _Numeric: return _Numeric.zeros(array,**kw) elif _numpy: return _numpy.zeros(array,**kw) else: raise AttributeError("No numeric functionality to zero an array.") if __name__=="__main__": import Numeric import numpy a = [ [ -121.41295785, -3.39655004, -1.22443129, 0., -35.94746644, -21.23132728 ], [ -3.39655004, -96.82243358, -0.38162982, 0., -25.73131733, -13.03766446 ], [ -1.22443129, -0.38162982, -95.95695143, 0., 0., -13.03766446 ], [ 0., 0., 0., -95.5753216, 0., 0., ], [ -35.94746644, -25.73131733, 0., 0., -70.19263086, -13.62411618 ], [ -21.23132728, -13.03766446, -13.03766446, 0., -13.62411618, -63.98948192 ], ] num_a = Numeric.array(a) npy_a = numpy.array(a) num_t = Numeric.transpose(num_a) npy_t = numpy.transpose(npy_a)
Whether it's for cereal, soup or pho, you need a good dining bowl. Lux Bowls are a necessity, for every meal of the day. Choose from bone china to porcelain, patterned to plain. Shop Habitat's range of Lux Bowls now. Whether you’re health conscious or not, Lux Bowls are just as important as plates, cutlery, glassware and mugs. They are very practical for certain food choices and there is something very satisfying about removing a knife from the equation and filling your stomach with a fork or spoon. All our Lux Bowls come in different shapes, sizes and styles to best suit your style and the type of cuisine you most regularly eat. Those who prefer something a little different will love our hand-crafted Lux Bowls, which due to the various techniques used in production, are all completely unique. Keep your kitchen looking neat and organised by investing in the matching dinner set.
# coding: utf-8 """ Deals with generating the per-page table of contents. For the sake of simplicity we use an existing markdown extension to generate an HTML table of contents, and then parse that into the underlying data. The steps we take to generate a table of contents are: * Pre-process the markdown, injecting a [TOC] marker. * Generate HTML from markdown. * Post-process the HTML, spliting the content and the table of contents. * Parse table of contents HTML into the underlying data structure. """ import re TOC_LINK_REGEX = re.compile('<a href=["]([^"]*)["]>([^<]*)</a>') class TableOfContents(object): """ Represents the table of contents for a given page. """ def __init__(self, html): self.items = _parse_html_table_of_contents(html) def __iter__(self): return iter(self.items) def __str__(self): return ''.join([str(item) for item in self]) class AnchorLink(object): """ A single entry in the table of contents. """ def __init__(self, title, url): self.title, self.url = title, url self.children = [] def __str__(self): return self._indent_print() def _indent_print(self, depth=0): indent = ' ' * depth ret = '%s%s - %s\n' % (indent, self.title, self.url) for item in self.children: ret += item._indent_print(depth + 1) return ret def _parse_html_table_of_contents(html): """ Given a table of contents string that has been automatically generated by the markdown library, parse it into a tree of AnchorLink instances. Returns a list of all the parent AnchorLink instances. """ lines = html.splitlines()[2:-2] parents = [] ret = [] for line in lines: match = TOC_LINK_REGEX.search(line) if match: href, title = match.groups() nav = AnchorLink(title, href) # Add the item to its parent if required. If it is a topmost # item then instead append it to our return value. if parents: parents[-1].children.append(nav) else: ret.append(nav) # If this item has children, store it as the current parent if line.endswith('<ul>'): parents.append(nav) elif line.startswith('</ul>'): if parents: parents.pop() # For the table of contents, always mark the first element as active if ret: ret[0].active = True return ret
Tornister Step by Step SPACE SHINY BUTTERFLY Zestaw 5 elem. SKU: 138944 Kategorie: Step by step, Tornistry Tagi: agr, space, step by step, tornister, zestaw szkolny Marka: Step by Step. Barcode: 4047443358059. Tornister Step by Step 2w1 SHINY BUTTERFLY Zestaw 4 elem.
# -*- coding: utf-8 -*- """ Created on Tue Jun 09 10:54:39 2015 @author: Paco """ from api import API class Wikipedia(API): _class_name = 'Wikipedia' _category = 'Data' _help_url = 'http://en.wikipedia.org/w/api.php?action=help&modules=query' _api_url = 'http://en.wikipedia.org/w/api.php?action=query&format=json&' def _parsing_data(self,data): keywiki = str(data['query']['pages'].keys()[0]) res = {'title':list()} for d in data['query']['pages'][keywiki]['linkshere']: res['title'].append(self._tools.key_test('title',d)) return res def _parsing_data2(self,data): keywiki = str(data['query']['pages'].keys()[0]) res = {'title':list()} for d in data['query']['pages'][keywiki]['links']: res['title'].append(self._tools.key_test('title',d)) return res def _parsing_data3(self,data): res = {'title':list()} for d in data['query']['prefixsearch']: res['title'].append(self._tools.key_test('title',d)) return res def _parsing_data4(self,data): res = {'title':list(),'timestamp':list(),'count':list()} for d in data['query']['search']: res['title'].append(self._tools.key_test('title',d)) res['timestamp'].append(self._tools.key_test('timestamp',d)) res['count'].append(self._tools.key_test('wordcount',d,'int')) return res def _parsing_data5(self,data): res = {'title':list(),'latitude':list(),'longitude':list(),'distance':list()} for d in data['query']['geosearch']: res['title'].append(self._tools.key_test('title',d)) res['latitude'].append(self._tools.key_test('lat',d,'float')) res['longitude'].append(self._tools.key_test('lon',d,'float')) res['distance'].append(self._tools.key_test('dist',d,'float')) return res def _parsing_data6(self,data): res = {'title':list(),'timestamp':list()} for d in data['query']['protectedtitles']: res['title'].append(self._tools.key_test('title',d)) res['timestamp'].append(self._tools.key_test('timestamp',d)) return res def _parsing_data7(self,data): res = {'title':list(),'timestamp':list()} for d in data['query']['recentchanges']: res['title'].append(self._tools.key_test('title',d)) res['timestamp'].append(self._tools.key_test('timestamp',d)) return res def get_linksphere(self,text='',limit=10): text = text.replace(' ','%20') url = self._api_url+'prop=linkshere&titles='+text+'&lhlimit='+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data(data) def get_links(self,text='',limit=10): text = text.replace(' ','%20') url = self._api_url+'prop=links&titles='+text+'&pllimit='+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data2(data) def search_prefix(self,text='',limit=10): text = text.replace(' ','%20') url = self._api_url+'list=prefixsearch&pssearch='+text+'&pslimit='+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data3(data) def search_text(self,text='',limit=10): text = text.replace(' ','%20') url = self._api_url+'list=search&srsearch='+text+'&srlimit='+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data4(data) def search_geo(self,lat=48.858844,lon=2.294351,radius=2,limit=10): url = self._api_url+'list=geosearch&gsradius='+str(radius*1000)+'&gscoord='+str(lat)+'|'+str(lon)+'&gslimit='+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data5(data) def get_latest_protected(self,limit=10): url = self._api_url+'list=protectedtitles&ptlimit'+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data6(data) def get_latest_changes(self,limit=10): url = self._api_url+'list=recentchanges&rclimit='+str(limit) data = self._tools.data_from_url(url) self._increment_nb_call() return self._parsing_data7(data)
With the hope of becoming more involved in the Spokane community, Crescendo formed the Crescendo Cares Club in the summer of 2018 when a board member saw an opportunity with Spokane's Meals on Wheels. On August 8th, from 10-11:30, members of the choir will participate in a pet food bagging opportunity. We'll share pictures soon! If you know of a community need that youth in our programs can be of assistance, please email us at info@CrescendoCommunityChorus.org.
''' Created on 28 Mar 2017 @author: bogdan ''' import os, sys, re, codecs # import md060graphonoLev from macpath import join class clExtractInputWd(object): ''' extracting input words from a dictionary file in glossary format refernce dictionary file has mappings for the evaluation set, but does not have the tags; *.num file has tags, but does not have mappings. --> the task: to create a file which has mappings and PoS codes --> to be used for generating input (in a trivial way) and as a reference file for checking the performance. ''' def __init__(self, SFInMap, SFInNumPoS, SFInNumPoSTgt): ''' takes the map file (from gold standard mapping) and PoS file with frequencies (output from corpus as *.num) ''' FInMap = codecs.open(SFInMap, "r", encoding='utf-8', errors='ignore') FInNumPoS = codecs.open(SFInNumPoS, "r", encoding='utf-8', errors='ignore') FInNumPoSTgt = codecs.open(SFInNumPoSTgt, "r", encoding='utf-8', errors='ignore') # FDebug = codecs.open('md010extractinputwd-debug.txt', "w", encoding='utf-8', errors='ignore') # read two dictionaries from files, then intersect them (worth within the shorter dictionary and look up the index in a larger one...) DSrc2TrgMaps = self.readDictFromFile(FInMap, 0, [1]) # temporary testing -- printing out the dictionary read # self.printDict2File(DSrc2TrgMaps) DSrc2PoS = self.readDictFromFile(FInNumPoS, 1, [2,0]) # temporary testing -- printing out the dictionary read # self.printDict2File(DSrc2PoS) DSrc2PoSTgt = self.readDictFromFile(FInNumPoSTgt, 1, [2,0]) # intersect with the target; update dictionaries; calculate Lev distance >> different kinds; save / display results (DIntersection, DDifference, DIntersectionTgt, DIntersectionDiffTgt) = self.intersectDicts(DSrc2TrgMaps, DSrc2PoS, DSrc2PoSTgt) # self.printDict2File(DIntersection) # self.printDict2File(DDifference) # print(str(len(DIntersection.keys()))) # print(str(len(DDifference.keys()))) DIntersection2 = self.optimeseDict2num(DIntersection) DIntersectionTgt2 = self.optimeseDict2num(DIntersectionTgt) ### temp ### self.printDict2num(DIntersection2) self.printDict2num(DIntersectionTgt2) ## self.printDict2File(DSrc2PoSTgt) ## self.printDict2File(DSrc2PoS) ## self.printDict2File(DIntersection2) ## self.printDict2File(DIntersectionTgt2) def intersectDicts(self, DSearch, DReference, DReferenceTgt): """ Two dictionaries: Search and Reference are intersected, and the Search dictionary is enriched with values from the reference Third dictionary is the target reference dictionary, structure медведеву [('VERB', '16'), ('INTJ', '5')] """ # dictionaries to be returned, which can be printed out DIntersection = {} DDifference = {} DIntersectionTgt = {} # intersection checked also with target DIntersectionDiffTgt = {} # there is intersection with source ref, but there is a difference with target equivalents references # counts for the number of keys in the intersection and difference sets -- to be defined as len(Keys) # IIntersection = 0 # IDifference = 0 for (SKey, LTValSearch) in DSearch.items(): # dictionary structure: # логічний [('логический',), ('логичный',)] if SKey in DReference: # dictionary structure: # медведеву [('VERB', '16'), ('INTJ', '5')] # IIntersection += 1 LTValReference = DReference[SKey] DIntersection[SKey] = (LTValReference, LTValSearch) # added test 13/04/2017 # checking if target mapping are in the target dictionary; then -- compute Lev distance --> design gold-standard eval set... try: LTRefNRefTgtWord = [] # get the list of intersecting Words for TTranslationMapped in LTValSearch: STranslationMapped = TTranslationMapped[0] # take the first element only; if STranslationMapped in DReferenceTgt: # if the target can be found # more complex task: intersection of PoS codes: # replace this: # DIntersectionTgt[SKey] = (LTValReference, LTValSearch) LTRefNRefTgtWord.append((STranslationMapped,)) # preserve the same format as LTValSearch LTValReferenceTgtPoS = DReferenceTgt[STranslationMapped] # get values (pos codes for target # get the list of intersecting PoS codes LRefNRefTgtPoS = [] for TValReferenceTgtPoS in LTValReferenceTgtPoS: # [('VERB', '16'), ('INTJ', '5')] # for each PoS in translated set : check if there exists the same PoS code and add it to the list; if the list is empty -- do not add to dictionary; SValReferenceTgtPoS = TValReferenceTgtPoS[0] # get the PoS without frequency for the target for TValReferencePoS in LTValReference: SValReferencePoS = TValReferencePoS[0] # get PoS without frequency for the original IValReferenceFrq = TValReferencePoS[1] # get frequency if SValReferenceTgtPoS == SValReferencePoS: # if Pos codes are the same LRefNRefTgtPoS.append((SValReferencePoS,IValReferenceFrq)) else: sys.stderr.write('%(STranslationMapped)s\t%(SValReferenceTgtPoS)s\t%(SValReferencePoS)s\n' % locals()) if len(LRefNRefTgtPoS) > 0: # DIntersectionTgt[SKey] = (LRefNRefTgtPoS, LTValSearch) # not the default LTValSearch, but only those which are found DIntersectionTgt[SKey] = (LRefNRefTgtPoS, LTRefNRefTgtWord) # replaced.... else: DIntersectionDiffTgt[SKey] = (LTValReference, LTValSearch) # remove also into the difference dictionary if no overlapping PoS were found else: DIntersectionDiffTgt[SKey] = (LTValReference, LTValSearch) # pos codes, translations except: sys.stderr.write('4.Mapping to target error:%(SKey)s\n' % locals()) else: # IDifference += 1 DDifference[SKey] = LTValSearch # at some point we need to print / return length of difference files --> how many were filtered out... # return dictionary structure: # логічний ([('PART', 1), ('ADJ', 500)], [('логический',), ('логичный',)]) return (DIntersection, DDifference, DIntersectionTgt, DIntersectionDiffTgt) def readDictFromFile(self, FIn, IIndexField, LIValFields): """ reads a tab separated file and creates a dictionary with a given field as an index and a list of given fields as values - creates index out of one field; - if there is a repeated index record, adds values to the list of values (then removes repetitions?) // potentially reusable in other packages... - technical solution: do not read multiword equivalents (if they contain a space) ~ addition: treat PoS as a dictionary entry -- to enable to amalgamate different meanings of the word which are within the same pos, so no double entries exist """ DIndexVals = {} # dictionary with the structure {'SIndex' : [LTValues]} (list of tuples with fields) for SLine in FIn: SLine = SLine.rstrip() try: LLine = re.split('\t', SLine) except: sys.stderr.write('0:Split Error: %(SLine)s\n' % locals()) IIdxField = int(IIndexField) try: SKey = LLine[IIdxField] except: SKey = None sys.stderr.write('1:Key Error: %(SLine)s;%(IIdxField)d\n' % locals()) LFieldsToCollect = [] for el in LIValFields: IEl = int(el) try: Val = LLine[IEl] except: Val = '' sys.stderr.write('2:Val Error: %(SLine)s;%(IEl)d\n' % locals()) # if Val == None: continue # do not add None values to the list of values # no: we need exact number of values in a tuple, even with None values # ad-hoc: not adding multiwords to reference if re.search(' ', Val): continue # to be able to run conditionally and remove.... LFieldsToCollect.append(Val) # updating the dictionary : checking if exists; if not exists TVals = tuple(LFieldsToCollect) if SKey == None: continue # do not process error lines if TVals == (): continue # do not add an empty tuple : to be able to run conditionally and remove... -- important keys ignored, e.g., торік if SKey in DIndexVals: # if the dictionary has key -- SKey LTValues = DIndexVals[SKey] else: LTValues = [] LTValues.append(TVals) # adding the tuple with values for this record DIndexVals[SKey] = LTValues # end: for Sline in FIn: return DIndexVals def printDict2File(self, DToPint): for (Key, Val) in DToPint.items(): SKey = str(Key) SVal = str(Val) print('%(SKey)s\t%(SVal)s' % locals()) def optimeseDict2num(self, DSnT2LT): """ move all structure-dependent solutions here: 1. remove empty entries 2. remove multiwords 3. join together multiple entries of the same PoS ~ prepare the dictionary for a usable format... ~ first step - remove repetitions """ DSnT2LTOut = {} for (SKey, Val) in DSnT2LT.items(): (LTPoSFrq, LTTransl) = Val DPoSFrq = {} # local dictionary for each record which may have multiple entries of the same PoS LTPoSFrqOut = [] for T2PoSFrq in LTPoSFrq: (SPoS, SFrq) = T2PoSFrq IFrq = int(SFrq) if SPoS in DPoSFrq: IFrq0 = DPoSFrq[SPoS] IFrq += IFrq0 DPoSFrq[SPoS] = IFrq for (SPoSX, IFrqX) in DPoSFrq.items(): T2PosFrqOut = (SPoSX, IFrqX) LTPoSFrqOut.append(T2PosFrqOut) DSnT2LTOut[SKey] = (LTPoSFrqOut, LTTransl) return DSnT2LTOut def printDict2num(self, DSnT2LT): # dictionary : strings mapped to 2-tuples of lists of n-tuples IItemCount = 0 IPoSCount = 0 IPoSMultiple = 0 IPoSInterjections = 0 # for (SKey, Val) in sorted(DSnT2LT.items(), reverse=True): # no sorting for (SKey, Val) in DSnT2LT.items(): IItemCount +=1 try: # unpacking 2-tuple of lists (LTPoSFrq, LTTransl) = Val except: sys.stderr.write('3.1.Wrong tuple structure %(SKey)s\n' % locals()) ILenPoS = len(LTPoSFrq) if ILenPoS > 1: IPoSMultiple += 1 if ILenPoS > 2: sys.stderr.write('%(SKey)s\t%(ILenPoS)d\n' % locals()) for T2PoSFrq in LTPoSFrq: IPoSCount +=1 (SPoS, SFrq) = T2PoSFrq if SPoS == 'INTJ' or SPoS == 'PRON': # no iterjections nor pronouns IPoSInterjections += 1 continue # print the test file: sys.stdout.write('%(SFrq)s\t%(SKey)s\t%(SPoS)s\t' % locals()) LWords = [] for TWord in LTTransl: Word = TWord[0] LWords.append(Word) SWordsTrans = '~'.join(LWords) sys.stdout.write('%(SWordsTrans)s\n' % locals()) # end: for (SKey, Val) DSnT2LT.items(): sys.stderr.write('Items:%(IItemCount)d\n' % locals()) sys.stderr.write('PoS:%(IPoSCount)d\n' % locals()) sys.stderr.write('Multi-PoS:%(IPoSMultiple)d\n' % locals()) sys.stderr.write('InterjectionsPronouns-PoS:%(IPoSInterjections)d\n' % locals()) if __name__ == '__main__': OExtractInputWd = clExtractInputWd(sys.argv[1], sys.argv[2], sys.argv[3]) # dictionary with field ; frq word list with pos codes # python3 md010extractinputwd.py ../../data/uk-ru-glossary/dict-uk-ru-uk-50k-s010-fields.txt ../../../xdata/morpho/uk.num >../../../xdata/morpho/uk2ru-cognates-pos-evalset.txt
Artomatic in the making: installation complete! I strung a five foot wide heart on the wall and, honestly, it could have been bigger. A big, big thank you to everyone who contributed a message of love for our neighbors. Artomatic opens on Friday and I can't wait to share all the messages with you. Stop in space 9203 on the ninth floor to see them in person. Everything did not work out as planned, so there's a day three in my future. Artomatic in the making: picked a space! Today I picked out my space at ARTOMATIC! A lovely, light-filled corner on the 9th floor. I need your help to fill it with messages of LOVE. Stop by my studio in Hyattsville from 3 to 6 pm TODAY to craft a message or pop one in the mail. As I think about my community, what it means to be a citizen locally, nationally and globally, and how I can use what I have to be the change I want to see, I keep coming back to love. It’s both a complex and incredibly simple thing. And one simple thing I can do is to share more love with my neighbors. I invite you to join me. This spring Artomatic, an unjuried event showcasing creative work from a variety of mediums, will be held in Crystal City, Va. I'm dedicating my space this year to messages of love. With your help, I'd like to share the message "You are loved" in as many languages, mediums and ways that we can. My hope is that anyone viewing the display will find at least one message that resonates with them. I'm collecting your messages. While the submission deadline has passed, I will do my best to have up at opening any submission received by March 15. Interested in taking part, but can't make the deadline, please reach out. Max size of 5 inches x 3 inches (this is the size of a standard index card). They can be smaller if you'd like. Submissions can be oriented vertically or horizontally. Any medium is welcome as are both 2-D and 3-D submissions. Submissions by all ages welcome. The words or imagery should convey the message that "you are loved" in a way that is culturally, linguistically, visually, artistically (in any way) relevant to you. All languages welcome. Submissions may be submitted anomalously. If you would like to be acknowledged for submitting a piece, please indicate how you would like to be credited when you make your submission (name, social media handle, etc.). I don't anticipate being able to list names next to each piece, but, for those who choose to be acknowledged, I will provide a listing of contributors in the display space and here on the website. Please mail your submissions to: Beth Hess, c/o DC GlassWorks, 5346 46th Avenue, Hyattsville, MD 20781. Please assume that your submission will NOT be returned. Artomatic is a large, public event run by volunteers. While steps are in place to ensure the security off all work, I can't guarantee the security of pieces displayed. Depending on response, I may also try to find additional ways to share submissions after Artomatic ends. I cannot provide compensation (beyond my heartfelt thanks) for submissions. I'd love to send you a personal thank you for your submission. So, if you are comfortable doing so, please include your email or mailing address with your submission (I will not share your contact information with others). This project is inspired by tiny affirmations from the You Are So Very Beautiful" Craftivism project.
''' The MIT License (MIT) Copyright (c) 2013-2017 Robert H Chase 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 inspect import logging log = logging.getLogger(__name__) class Task(object): def __init__(self, callback, cid=None): self._callback = [callback] self.cid = cid self.final = None # callable executed before callback (error or success) @property def callback(self): if len(self._callback) == 1: self.on_done() return self._callback.pop() @property def is_done(self): return len(self._callback) == 0 def on_done(self): if self.final: try: self.final() except Exception as e: log.warning('cid=%s, failure running task final: %s', self.cid, str(e)) def call(self, fn, args=None, kwargs=None, on_success=None, on_none=None, on_error=None, on_timeout=None): """ Call an async function. Allows for flexible handling of the return states of async function calls. Parameters: fn - callable async function (See Note 1) args - None, scalar, tuple or list Positional argments to be passed to fn. kwargs - None or dict Keyword argments to be passed to fn. on_success - callable called if specified and rc == 0 and if none of on_success_code, on_none and on_none_404 apply on_success(task, result) on_error - callable called if specified and rc != 0 on_error(task, result) on_none - callable called if specified and rc == 0 and result is None on_none(task, None) Notes: 1. An async function is structured like this: fn(callback, *args, **kwargs) When the function is complete, it calls callback with two parameters: rc - 0 for success, non-zero for error result - function response on success, message on error 2. If the first parameter of fn (from inspection) is named 'task', then an rhc.Task object is passed instead of a callable. Example: def on_load(task, result): pass task.call( load, args=id, on_success=on_load, ) This will call the load function, followed by on_load if the load function completes sucessfully. """ def cb(rc, result): if rc == 0: _callback(self, fn, result, on_success, on_none) else: _callback_error(self, fn, result, on_error, on_timeout) if args is None: args = () elif not isinstance(args, (tuple, list)): args = (args,) if kwargs is None: kwargs = {} has_task = inspect_parameters(fn, kwargs) if has_task: self._callback.append(cb) callback = self else: callback = cb log.debug('task.call cid=%s fn=%s %s', self.cid, fn, 'as task' if has_task else '') fn(callback, *args, **kwargs) return self def defer(self, task_cmd, partial_callback, final_fn=None): # DEPRECATED: use call ''' defer the task until partial_callback completes; then call task_cmd if partial_callback does not complete successfully, then task_cmd is not called; instead, the error is handled by calling error on the task. final_fn, if specified, is always called. Parameters: task_cmd - called with result of partial_callback on success task_cmd(task, result) partial_callback - function that takes a callback_fn callback_fn is eventually called with (rc, result) if rc != 0, partial_callback failed final_fn - a function that is called once after the partial_callback is complete. it takes no parameters. ''' def on_defer(rc, result): if final_fn: try: final_fn() except Exception as e: log.warning('failure running final_fn: %s', str(e)) if rc == 0: task_cmd(self, result) else: self.error(result) partial_callback(on_defer) return self def error(self, message): # DEPRECATED self.respond(message, 1) def respond(self, result, rc=0): # DEPRECATED: use callback if self.is_done: return if self.final: try: self.final() except Exception as e: log.warning('failure running task final: %s', str(e)) self.callback(rc, result) def unpartial(partial): """ turn a partial into a callback_fn undo the badness """ def _unpartial(cb, *args, **kwargs): return partial(*args, **kwargs)(cb) return _unpartial def inspect_parameters(fn, kwargs): task = False # get a list of function parameters args = inspect.getargspec(fn).args # is the first parameter named 'task' if len(args) and args[0] == 'task': task = True return task def catch_exceptions(message): def _catch_exceptions(task_handler): def inner(task, *args, **kwargs): try: return task_handler(task, *args, **kwargs) except Exception: log.exception(message) return inner return _catch_exceptions def _callback(task, fn, result, on_success, on_none): if on_none and result is None: try: log.debug('task.callback, cid=%s, on_none fn=%s', task.cid, on_none) return on_none(task, result) except Exception as e: return task.callback(1, 'exception during on_none: %s' % e) if on_success: try: log.debug('task.callback, cid=%s, on_success fn=%s', task.cid, on_success) return on_success(task, result) except Exception as e: return task.callback(1, 'exception during on_success: %s' % e) log.debug('task.callback, cid=%s, default success callback', task.cid) task.callback(0, result) def _callback_error(task, fn, result, on_error, on_timeout): if on_timeout and result == 'timeout': try: log.debug('task.callback, cid=%s, on_timeout fn=%s', task.cid, on_timeout) return on_timeout(task, result) except Exception as e: return task.callback(1, 'exception during on_timeout: %s' % e) if on_error: try: log.debug('task.callback, cid=%s, on_error fn=%s', task.cid, on_error) return on_error(task, result) except Exception as e: return task.callback(1, 'exception during on_error: %s' % e) log.debug('task.callback, cid=%s, default error callback', task.cid) task.callback(1, result) # # STOP USING THIS defer-able STUFF # def wrap(callback_cmd, *args, **kwargs): # DEPRECATED yucky complexity ''' helper function callback_cmd -> partially executed partial ''' return partial(callback_cmd)(*args, **kwargs) def from_callback(task_cmd): # DEPRECATED yucky complexity ''' helper function callback_cmd -> executing partial if the caller invokes the wrapped or decorated task_cmd using a standard callback syntax: task_cmd(callback, *args, **kwargs) then a task is generated from the callback, and a partial is immediately started. ''' def _wrap(callback, *args, **kwargs): return partial(task_cmd)(*args, **kwargs)(callback) return _wrap def partial(fn): # DEPRECATED yucky complexity def _args(*args, **kwargs): def _callback(callback_fn): task = Task(callback_fn) fn(task, *args, **kwargs) return task return _callback return _args
Time for a little more food photography! Yet another of those self promotion projects that always gets bumpped by other things. Well, these were two of the first experimentations with this style for a series of ads and a website. Generally, I'm pretty happy with it. It's nice to be the designer as well as the photographer. It helps get the exact image you're looking for. In addition to my local Santa Barbara images site I am in the process of doing some self promotion work for my commercial food & restaurant photography. I've always loved photography and I REALLY love food, so I guess it was only a matter of time 'til I made the connection! Ohhh I just LOVE Garlic!! We have a huge pile of peppers and tomatoes on the table from our plants in the back yard. My wife has been pointing out the cool ones to me for a couple of weeks, and I finally couldn't wait any longer it was time for a photo shoot! About three hours later this was one of my favorite shots. But I can't take all the credit, I have a great Art Director & food stylist! The cool black tray was my wife's idea. Or more specifically, "Espresso." One of the wonderful things my wife introduced me to! Mmmmm, grapes! I love the color of them. A couple of days ago you got to see the ingredients. Now we have the results! Food is a tricky thing to photograph. Especially something like chicken salad. It has the very real potential to come out looking like... well, something you really do not want to eat. In examining my favorite cookbooks, I have found that lighting and garnish both play a major role in making formless things interesting and appetizing. In the not too distant future I will be starting a new project, a cookbook, with a friend who owns a great restaurant downtown. I have to practice because his food is so good I really want to do it justice! I love Gelson's! Their produce looks like a farmer's market. They even stack everything with the stems pointing in the same direction. Particularly nice since we went there to find subjects for some still life food photography. I could have spent all day just taking pictures of their cool tea cups and tea-pots! Everything is beautifully done there, from the interior to the presentation of the food itself. You can tell they really take pride in what they do. The owners and the employees all seem like they are happy to be there. Which is very refreshing.
from django import forms from oscar.apps.payment import forms as payment_forms from oscar.apps.order.models import BillingAddress class BillingAddressForm(payment_forms.BillingAddressForm): """ Extended version of the core billing address form that adds a field so customers can choose to re-use their shipping address. """ SAME_AS_SHIPPING, NEW_ADDRESS = 'same', 'new' CHOICES = ( (SAME_AS_SHIPPING, 'Use shipping address'), (NEW_ADDRESS, 'Enter a new address'), ) same_as_shipping = forms.ChoiceField( widget=forms.RadioSelect, choices=CHOICES, initial=SAME_AS_SHIPPING) class Meta(payment_forms.BillingAddressForm): model = BillingAddress exclude = ('search_text', 'first_name', 'last_name') def __init__(self, shipping_address, data=None, *args, **kwargs): # Store a reference to the shipping address self.shipping_address = shipping_address super(BillingAddressForm, self).__init__(data, *args, **kwargs) # If no shipping address (eg a download), then force the # 'same_as_shipping' field to have a certain value. if shipping_address is None: self.fields['same_as_shipping'].choices = ( (self.NEW_ADDRESS, 'Enter a new address'),) self.fields['same_as_shipping'].initial = self.NEW_ADDRESS # If using same address as shipping, we don't need require any of the # required billing address fields. if data and data.get('same_as_shipping', None) == self.SAME_AS_SHIPPING: for field in self.fields: if field != 'same_as_shipping': self.fields[field].required = False def _post_clean(self): # Don't run model validation if using shipping address if self.cleaned_data.get('same_as_shipping') == self.SAME_AS_SHIPPING: return super(BillingAddressForm, self)._post_clean() def save(self, commit=True): if self.cleaned_data.get('same_as_shipping') == self.SAME_AS_SHIPPING: # Convert shipping address into billing address billing_addr = BillingAddress() self.shipping_address.populate_alternative_model(billing_addr) if commit: billing_addr.save() return billing_addr return super(BillingAddressForm, self).save(commit)
Aerial view of the planned conversion. Click to enlarge. While Adams Morgan is known for new market-rate residential projects, an affordable development is also on the boards. Jubilee Housing has applied to the Board of Zoning Adjustment in hopes of converting the vacant three-story commercial building at 1724 Kalorama Road NW (map) into 25 affordable units, plus office and community arts space. The PGN Architects-designed development would deliver 25 apartments across the second, third and fourth floors. Two-thirds of the units will be for households earning up to 30 percent of median family income (MFI), while the remainder will be for households earning up to 60 percent MFI. The planned conversion, seen from Kalorama Road. Click to enlarge. The ground-floor space would accommodate an expansion of the Sitar Arts Center, which also occupies space in the condo building next door. The penthouse would be used as office space for Jubilee. The application is seeking parking and lot occupancy relief, as the applicant states that the required minimum of 12 spaces (7 for residential) cannot be provided. Most of the 11 parking spaces currently at the rear of the building are not legally compliant or wouldn't be feasible for use post-conversion. Jubilee and Sitar already have parking facilities in the neighborhood and the applicant doesn't anticipate a need for residential parking. Renderings courtesy of PGN Architects.
#!/usr/bin/env python # # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Tests for protorpc.protobuf.""" __author__ = 'rafek@google.com (Rafe Kaplan)' import datetime import unittest from protorpc import message_types from protorpc import messages from protorpc import protobuf from protorpc import protorpc_test_pb2 from protorpc import test_util from protorpc import util # TODO: Add DateTimeFields to protorpc_test.proto when definition.py # supports date time fields. class HasDateTimeMessage(messages.Message): value = message_types.DateTimeField(1) class NestedDateTimeMessage(messages.Message): value = messages.MessageField(message_types.DateTimeMessage, 1) class ModuleInterfaceTest(test_util.ModuleInterfaceTest, test_util.TestCase): MODULE = protobuf class EncodeMessageTest(test_util.TestCase, test_util.ProtoConformanceTestBase): """Test message to protocol buffer encoding.""" PROTOLIB = protobuf def assertErrorIs(self, exception, message, function, *params, **kwargs): try: function(*params, **kwargs) self.fail('Expected to raise exception %s but did not.' % exception) except exception as err: self.assertEquals(message, str(err)) @property def encoded_partial(self): proto = protorpc_test_pb2.OptionalMessage() proto.double_value = 1.23 proto.int64_value = -100000000000 proto.int32_value = 1020 proto.string_value = u'a string' proto.enum_value = protorpc_test_pb2.OptionalMessage.VAL2 return proto.SerializeToString() @property def encoded_full(self): proto = protorpc_test_pb2.OptionalMessage() proto.double_value = 1.23 proto.float_value = -2.5 proto.int64_value = -100000000000 proto.uint64_value = 102020202020 proto.int32_value = 1020 proto.bool_value = True proto.string_value = u'a string\u044f' proto.bytes_value = b'a bytes\xff\xfe' proto.enum_value = protorpc_test_pb2.OptionalMessage.VAL2 return proto.SerializeToString() @property def encoded_repeated(self): proto = protorpc_test_pb2.RepeatedMessage() proto.double_value.append(1.23) proto.double_value.append(2.3) proto.float_value.append(-2.5) proto.float_value.append(0.5) proto.int64_value.append(-100000000000) proto.int64_value.append(20) proto.uint64_value.append(102020202020) proto.uint64_value.append(10) proto.int32_value.append(1020) proto.int32_value.append(718) proto.bool_value.append(True) proto.bool_value.append(False) proto.string_value.append(u'a string\u044f') proto.string_value.append(u'another string') proto.bytes_value.append(b'a bytes\xff\xfe') proto.bytes_value.append(b'another bytes') proto.enum_value.append(protorpc_test_pb2.RepeatedMessage.VAL2) proto.enum_value.append(protorpc_test_pb2.RepeatedMessage.VAL1) return proto.SerializeToString() @property def encoded_nested(self): proto = protorpc_test_pb2.HasNestedMessage() proto.nested.a_value = 'a string' return proto.SerializeToString() @property def encoded_repeated_nested(self): proto = protorpc_test_pb2.HasNestedMessage() proto.repeated_nested.add().a_value = 'a string' proto.repeated_nested.add().a_value = 'another string' return proto.SerializeToString() unexpected_tag_message = ( chr((15 << protobuf._WIRE_TYPE_BITS) | protobuf._Encoder.NUMERIC) + chr(5)) @property def encoded_default_assigned(self): proto = protorpc_test_pb2.HasDefault() proto.a_value = test_util.HasDefault.a_value.default return proto.SerializeToString() @property def encoded_nested_empty(self): proto = protorpc_test_pb2.HasOptionalNestedMessage() proto.nested.Clear() return proto.SerializeToString() @property def encoded_repeated_nested_empty(self): proto = protorpc_test_pb2.HasOptionalNestedMessage() proto.repeated_nested.add() proto.repeated_nested.add() return proto.SerializeToString() @property def encoded_extend_message(self): proto = protorpc_test_pb2.RepeatedMessage() proto.add_int64_value(400) proto.add_int64_value(50) proto.add_int64_value(6000) return proto.SerializeToString() @property def encoded_string_types(self): proto = protorpc_test_pb2.OptionalMessage() proto.string_value = u'Latin' return proto.SerializeToString() @property def encoded_invalid_enum(self): encoder = protobuf._Encoder() field_num = test_util.OptionalMessage.enum_value.number tag = (field_num << protobuf._WIRE_TYPE_BITS) | encoder.NUMERIC encoder.putVarInt32(tag) encoder.putVarInt32(1000) return encoder.buffer().tostring() def testDecodeWrongWireFormat(self): """Test what happens when wrong wire format found in protobuf.""" class ExpectedProto(messages.Message): value = messages.StringField(1) class WrongVariant(messages.Message): value = messages.IntegerField(1) original = WrongVariant() original.value = 10 self.assertErrorIs(messages.DecodeError, 'Expected wire type STRING but found NUMERIC', protobuf.decode_message, ExpectedProto, protobuf.encode_message(original)) def testDecodeBadWireType(self): """Test what happens when non-existant wire type found in protobuf.""" # Message has tag 1, type 3 which does not exist. bad_wire_type_message = chr((1 << protobuf._WIRE_TYPE_BITS) | 3) self.assertErrorIs(messages.DecodeError, 'No such wire type 3', protobuf.decode_message, test_util.OptionalMessage, bad_wire_type_message) def testUnexpectedTagBelowOne(self): """Test that completely invalid tags generate an error.""" # Message has tag 0, type NUMERIC. invalid_tag_message = chr(protobuf._Encoder.NUMERIC) self.assertErrorIs(messages.DecodeError, 'Invalid tag value 0', protobuf.decode_message, test_util.OptionalMessage, invalid_tag_message) def testProtocolBufferDecodeError(self): """Test what happens when there a ProtocolBufferDecodeError. This is what happens when the underlying ProtocolBuffer library raises it's own decode error. """ # Message has tag 1, type DOUBLE, missing value. truncated_message = ( chr((1 << protobuf._WIRE_TYPE_BITS) | protobuf._Encoder.DOUBLE)) self.assertErrorIs(messages.DecodeError, 'Decoding error: truncated', protobuf.decode_message, test_util.OptionalMessage, truncated_message) def testProtobufUnrecognizedField(self): """Test that unrecognized fields are serialized and can be accessed.""" decoded = protobuf.decode_message(test_util.OptionalMessage, self.unexpected_tag_message) self.assertEquals(1, len(decoded.all_unrecognized_fields())) self.assertEquals(15, decoded.all_unrecognized_fields()[0]) self.assertEquals((5, messages.Variant.INT64), decoded.get_unrecognized_field_info(15)) def testUnrecognizedFieldWrongFormat(self): """Test that unrecognized fields in the wrong format are skipped.""" class SimpleMessage(messages.Message): value = messages.IntegerField(1) message = SimpleMessage(value=3) message.set_unrecognized_field('from_json', 'test', messages.Variant.STRING) encoded = protobuf.encode_message(message) expected = ( chr((1 << protobuf._WIRE_TYPE_BITS) | protobuf._Encoder.NUMERIC) + chr(3)) self.assertEquals(encoded, expected) def testProtobufDecodeDateTimeMessage(self): """Test what happens when decoding a DateTimeMessage.""" nested = NestedDateTimeMessage() nested.value = message_types.DateTimeMessage(milliseconds=2500) value = protobuf.decode_message(HasDateTimeMessage, protobuf.encode_message(nested)).value self.assertEqual(datetime.datetime(1970, 1, 1, 0, 0, 2, 500000), value) def testProtobufDecodeDateTimeMessageWithTimeZone(self): """Test what happens when decoding a DateTimeMessage with a time zone.""" nested = NestedDateTimeMessage() nested.value = message_types.DateTimeMessage(milliseconds=12345678, time_zone_offset=60) value = protobuf.decode_message(HasDateTimeMessage, protobuf.encode_message(nested)).value self.assertEqual(datetime.datetime(1970, 1, 1, 3, 25, 45, 678000, tzinfo=util.TimeZoneOffset(60)), value) def testProtobufEncodeDateTimeMessage(self): """Test what happens when encoding a DateTimeField.""" mine = HasDateTimeMessage(value=datetime.datetime(1970, 1, 1)) nested = NestedDateTimeMessage() nested.value = message_types.DateTimeMessage(milliseconds=0) my_encoded = protobuf.encode_message(mine) encoded = protobuf.encode_message(nested) self.assertEquals(my_encoded, encoded) def testProtobufEncodeDateTimeMessageWithTimeZone(self): """Test what happens when encoding a DateTimeField with a time zone.""" for tz_offset in (30, -30, 8 * 60, 0): mine = HasDateTimeMessage(value=datetime.datetime( 1970, 1, 1, tzinfo=util.TimeZoneOffset(tz_offset))) nested = NestedDateTimeMessage() nested.value = message_types.DateTimeMessage( milliseconds=0, time_zone_offset=tz_offset) my_encoded = protobuf.encode_message(mine) encoded = protobuf.encode_message(nested) self.assertEquals(my_encoded, encoded) def main(): unittest.main() if __name__ == '__main__': main()
With the weather being just as beautiful on the second and last day of the festival, I had a good feeling that today was just going to be a continuation of the day before, which was nothing to complain about at all. A highlight of the entire festival for me was seeing the fearless, feisty and effervescent young man Declan Welsh take over the Tenement TV stage. His attitude and care towards the topics he sings about is very apparent within his presence on stage. His lyrics highlight important topics such as diversity, anti-conformity, and cherishing special moments. Towards the end of the set, he lost the guitar and swaggered across the stage during a song about expressing yourself. His dancing was contagious with the crowd as they all joined in and watched the band control the tent with their refreshing music. The last song was a moving and emotional tribute to the much loved and admired, late Gary Watson from Glasgow band The Lapelles, who unfortunately lost his life around this time last year. The crowd chanted his name as the band performed an excellent and fitting end to their highly enjoyable set. Declan Welsh & The Decadent West are a breath of fresh air in the music scene and showed just why they are a force to be reckoned with. On Vic Galloway's BBC Scotland Stage, an Edinburgh based 4-piece called Skjor took to the stage. They were welcomed on with a huge applause along with some praise from Galloway himself. Their dreamy, reverberated guitar riffs mixed with the funky, pounding bass and drum section created a joyous atmosphere for the whole crowd. Dressed in a white, angelic-like dress, the singer's stunning vocals and somewhat theatrical presence added to their excellent live performance, not to mention how incredibly tight and well co-ordinated the bassist and drummer were with each other. Their singles 'Self Control' and 'Living without you' had the crowd dancing and singing along as this young band displayed a mature and brilliant performance, cementing themselves as a band to keep an eye on. Grime music has been growing more and more in the music industry recently, pulling in fans from across the globe, and Shogun is Scotland's answer for it. As this young rapper vents his anger and emotion on stage with his crew and DJ behind him, the audience watch on and relish in this man's "don't care" attitude. The energy he had was incredible, and it was consistent throughout the half hour set. He electrified the crowd and had the whole tent shaking as he commanded the audience to move and jump about, screaming for noise and enthusiasm from his fans. Spotting what he believed to be his 'youngest fan ever' at the back of the tent, Shogun enthralled in the audience's joy to watch this young man's passion unveiled throughout his set. Although he seemed to be lacking some sort of hook that people could chant back, Shogun's talent was outstanding and he seemed just as proud to be up there as on-lookers were to be watching him. Fatherson were in top form as they darted onto the main stage at Electric Fields. Watching this band develop over the past few years has been something incredibly exciting to watch and their performance today showed why they've been attracting so much attention recently. Playing an array of songs from their two albums such as 'I Like Not Knowing', 'Open Book' and 'Forest' (including a brand-new song to treat the fans), their crunching guitar tones and expansive harmonies are enough to get this crowd nodding and bouncing all the way through their packed set. Although frontman Ross' guitar encountered some difficulties, he didn't let that sway his or the rest of the band's exuberant performance. Ross' vocal melodies have always been something to admire, with such range in his vocal ability it's no wonder these guys can put on such a star-studded performance. Finishing with their hit 'Lost Little Boys' the lines in the song "Cause we're just lost little boys, making a name for ourselves" seemed to have even more meaning and passion behind it on this sunny day in Dumfries. Taking over the main stage with a giant rotating Pineapple disco ball, Oxford band Glass Animals brought their hip-hop infused distinctive sound to the Dumfries crowd. The singer Dave complimented the fans on the amount of pineapples they had brought, ranging from blow-up pineapples, LED pineapples and even half eaten pineapples as they were chucked around the crowd. Their ability to entertain a crowd shone through as everyone was dancing the whole way through their hour-long set. Playing the majority of songs from their latest album such as 'Life Itself', 'Agnes' and finishing on 'Pork Soda', the band's incredible energy and talent pleased the viewers as the sun glared down. Their feel-good vibe kept the crowd on their feet and was extremely enjoyable to watch the enthusiasm the band portrayed. Having released a brand-new album this year, exactly 10 years since the band regrouped, The Jesus and Mary Chain showed the crowd watching the main stage just why they have such a status as rock legends. The chugging bass riffs and decorative guitar solos created such a huge sound, at times it was hard to hear Reid’s crushing vocals. Having lived such long careers in the music industry, these guys displayed their talent and showed they still had a lot of life left in them. Without much in-between song talking apart from a couple of ‘thank you’ nods to the crowd, also including a little bit of a ‘diva’ moment from Jim Reid as he demanded they restart a song after fumbling his words up, the Scottish rockers still managed to put on a real rock ‘n’ roll show. Playing songs from the new album like ‘Amputation’ and ‘Always Sad’, they showcased their messy, noisy sound well. Finishing on the edgy and moody ‘I Hate Rock ‘n’ Roll’, Reid gave the crowd one last moment of gratefulness before turning back into his rockstar persona, dropping the microphone and walking off stage, leaving the crowd wanting just that little bit more. Closing up the main stage with his grimey, bass-ridden sound, Dizzee Rascal bounced out to an ecstatic and applauding Electric Fields crowd. The genius behind the hit song ‘Bonkers’ released his brand new album ‘Raskit’ just a few months back. After shying away from the pop industry and mainstream chart music, the English rapper went back to his grime roots and created an album based solely on that. He presented a collection of songs from his new album which had the whole arena bouncing up and down, using what ever energy they had left from the weekend. Dizzee Rascal’s enthusiasm and movement as he spun around the stage, gave off such a good vibe to the audience it was hard not to let out a smile and move to the beat after seeing how much he himself was enjoying the set. Although some lighting failures were encountered during hit song ‘Baseline Junkie’, he thanked the fans for not letting it affect their energy and continued the show. Ending on his three biggest hits ‘Holiday’, ‘Dance Wiv Me’ and ‘Bonkers, two of which were written alongside DJ Calvin Harris who resides from Dumfries himself, Dizzee Rascal used every last bit of the crowd’s adrenaline to create a memorable performance for himself and the rest of the festival. After such an incredible lineup and a whole array of talent across the weekend, I can’t help but feel Electric Fields is going to be a festival that sticks around for a while. Situated in such a scenic location, having great weather all weekend added to such a joyous occasion. As it enters it’s fifth year, I can’t wait to see what the team behind the festival have in store for 2018.
import os,sys import traceback from os.path import abspath, basename, dirname, normpath, join, exists # from docutils import core #import publish_string, publish_file from docutils import core, io from docutils.writers import html4css1 #import em from StringIO import StringIO from textwrap import dedent from docutils.parsers.rst.directives import register_directive #from docutils.parsers.rst.directives.body import line_block #from docutils.parsers.rst import Parser #from docutils.parsers.rst.states import Inliner from docutils import nodes, statemachine ## return line_block(name, arguments, options, ## content.splitlines(), ## lineno, ## content_offset, block_text, state, state_machine, ## node_class=nodes.literal_block) ## from docutils.parsers.rst import directives ## from docutils.parsers.rst.languages import en ## registry = directives._directive_registry ## registry['script'] = ('lino.timtools.txt2html','exec_script') ## #registry['script'] = ('txt2html','exec_script') ## en.directives['script'] = 'script' class WebmanWriter(html4css1.Writer): """ adds a module-specific left (top, bottom) margin to each page. implements the exec:: directive. Note that the exec directive should rather be done by the parser, but I didn't work out how to do this... """ def __init__(self,node): html4css1.Writer.__init__(self) #self.translator_class = MyHtmlTranslator assert isinstance(node,nodes.Node) self.node = node # self.leftArea = leftArea self.namespace = dict(globals()) self.namespace['page'] = node #self.namespace['webmod'] = webmod self.namespace['writer'] = self register_directive('exec',self.exec_exec) def exec_exec(self, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if not content: error = state_machine.reporter.error( 'The "%s" directive is empty; content required.' % (name), nodes.literal_block(block_text, block_text), line=lineno) return [error] text = '\n'.join(content) text = dedent(text) _stdout = sys.stdout sys.stdout = StringIO() try: exec text in self.namespace,self.namespace except Exception,e: traceback.print_exc(None,sys.stderr) #print e stdout_text = sys.stdout.getvalue() sys.stdout = _stdout # sys.stderr.write(stdout_text) insert_lines = statemachine.string2lines(stdout_text, convert_whitespace=1) state_machine.insert_input(insert_lines, "exec") return [] exec_exec.content = 1 def translate(self): """ modified copy of superclass.translate() translate() is called by write() and must place the HTML output to self.output """ visitor = self.translator_class(self.document) self.document.walkabout(visitor) self.visitor = visitor for attr in ('head_prefix', 'stylesheet', 'head', 'body_prefix', 'body_pre_docinfo', 'docinfo', 'body', 'fragment', 'body_suffix'): setattr(self, attr, getattr(visitor, attr)) webmod = self.node.getModule() if webmod.leftArea is not None: html = webmod.leftArea(self.node) self.body_prefix.append('''<table class="mainTable"> <tr> <td valign="top" class="leftArea"> ''') self.body_prefix.append(html) self.body_prefix.append('''</td> <td class="textArea">''') self.body_suffix.insert(0,'</td></tr></table>') if webmod.bottomArea is not None: html = webmod.bottomArea(self.node) self.body_suffix.append('<div class="bottomArea">') self.body_suffix.append(html) self.body_suffix.append('</div>') if webmod.topArea is not None: raise NotImplementedError self.output = self.astext() def astext(self): return ''.join(self.head_prefix + self.head + self.stylesheet + self.body_prefix + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix) ## class WebmanInliner(Inliner): ## # no longer used since 20040922 ## # but pageref role is now broken ## def __init__(self, webmod,roles={}): ## roles['fileref'] = self.fileref_role ## roles['pageref'] = self.pageref_role ## Inliner.__init__(self,roles) ## self.webmod = webmod ## def fileref_role(self, role, rawtext, text, lineno): ## if self.webmod.filerefBase is not None: ## if text.startswith('/'): ## localfile = normpath(join(self.webmod.filerefBase,text[1:])) ## else: ## localfile = normpath(join(self.webmod.filerefBase,text)) ## #localfile = join(self.webmod.filerefBase,normpath(text)) ## if not exists(localfile): ## msg = self.reporter.error('%s : no such file' % localfile, ## line=lineno) ## prb = self.problematic(text, text, msg) ## return [prb], [msg] ## if self.webmod.filerefURL is None: ## uri = None ## else: ## uri = self.webmod.filerefURL % text ## filename = basename(text) ## return [nodes.reference(rawtext, filename, refuri=uri)], [] ## def pageref_role(self, role, rawtext, text, lineno): ## # doesn't work ## if self.webmod.filerefBase is None: ## return [rawtext],[] ## else: ## if text.startswith('/'): ## localfile = normpath(join(self.webmod.filerefBase,text[1:])) ## else: ## localfile = normpath(join(self.webmod.filerefBase,text)) ## if exists(localfile+".txt"): ## uri = localfile+".html" ## elif os.path.isdir(localfile): ## uri = localfile+"/index.html" ## else: ## msg = self.reporter.error(\ ## 'pageref to unkonwn page "%s"' % localfile, ## line=lineno) ## prb = self.problematic(text, text, msg) ## return [prb], [msg] ## return [nodes.reference(rawtext, text, refuri=uri)], [] def publish(node,srcpath): description = ('Lino WebMan publisher. ' + core.default_description) # 20040922 parser = Parser(rfc2822=0, inliner=WebmanInliner(webmod)) # pub = core.Publisher(writer=WebmanWriter(webmod), parser=parser, # destination_class=io.StringOutput) pub = core.Publisher(writer=WebmanWriter(node), destination_class=io.StringOutput) pub.set_components('standalone', 'restructuredtext', None) webmod = node.getModule() pub.process_command_line(webmod.argv, description=description, **webmod.defaults) pub.set_source(None, srcpath) # node.getSourcePath()) cwd = os.getcwd() os.chdir(webmod.getLocalPath()) r = pub.publish() #enable_exit=enable_exit) os.chdir(cwd) return r
Below you will find all inclusive prices on the vans we offer for hire. Get a quote and make a booking online anytime, we can also offer a delivery and collection service if required. Our van range offers vehicles to rent for most purposes and are all available for selfdrive hire. By clicking on the type of van you are looking to hire our website provides you with prices, a guide to the vans occupancy and capacity so you can choose which vehicle suits your needs best. If you prefer you can telephone to discuss your requirements or email us.
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. from numbers import Integral from itertools import product, groupby from collections import deque import numpy as np from numpy import pi try: from . import _siesta found_module = True except Exception as e: print(e) found_module = False from ..sile import add_sile, SileError from .sile import SileBinSiesta from sisl._internal import set_module from sisl.messages import warn, SislError from ._help import * import sisl._array as _a from sisl import Geometry, Atom, Atoms, SuperCell, Grid, SparseCSR from sisl import AtomicOrbital from sisl.sparse import _ncol_to_indptr from sisl.unit.siesta import unit_convert from sisl.physics.sparse import SparseOrbitalBZ from sisl.physics import Hamiltonian, DensityMatrix, EnergyDensityMatrix from sisl.physics.overlap import Overlap from sisl.physics.electron import EigenstateElectron __all__ = ['tshsSileSiesta', 'onlysSileSiesta', 'tsdeSileSiesta'] __all__ += ['hsxSileSiesta', 'dmSileSiesta'] __all__ += ['wfsxSileSiesta'] __all__ += ['gridSileSiesta'] __all__ += ['tsgfSileSiesta'] _Bohr2Ang = unit_convert('Bohr', 'Ang') _Ry2eV = unit_convert('Ry', 'eV') _eV2Ry = unit_convert('eV', 'Ry') def _bin_check(obj, method, message): ierr = _siesta.io_m.iostat_query() if ierr != 0: raise SileError(f'{str(obj)}.{method} {message} (ierr={ierr})') def _toF(array, dtype, scale=None): if scale is None: return array.astype(dtype, order='F', copy=False) elif array.dtype == dtype and array.flags.f_contiguous: # no need to copy since the order is correct return array * scale # We have to handle cases out = np.empty_like(array, dtype, order='F') np.multiply(array, scale, out=out) return out def _geometry_align(geom_b, geom_u, cls, method): """ Routine used to align two geometries There are a few twists in this since the fdf-reads will automatically try and pass a geometry from the output files. In cases where the *.ion* files are non-existing this will result in a twist. This routine will select and return a merged Geometry which fulfills the correct number of atoms and orbitals. However, if the input geometries have mis-matching number of atoms a SislError will be raised. Parameters ---------- geom_b : Geometry from binary file geom_u : Geometry supplied by user Raises ------ SislError : if the geometries have non-equal atom count """ if geom_b is None: return geom_u elif geom_u is None: return geom_b # Default to use the users geometry geom = geom_u is_copy = False def get_copy(geom, is_copy): if is_copy: return geom, True return geom.copy(), True if geom_b.na != geom.na: # we have no way of solving this issue... raise SileError(f"{cls.__name__}.{method} could not use the passed geometry as the " f"of atoms is not consistent, user-atoms={geom_u.na}, file-atoms={geom_b.na}.") # Try and figure out what to do if not np.allclose(geom_b.xyz, geom.xyz): warn(f"{cls.__name__}.{method} has mismatched atomic coordinates, will copy geometry and use file XYZ.") geom, is_copy = get_copy(geom, is_copy) geom.xyz[:, :] = geom_b.xyz[:, :] if not np.allclose(geom_b.sc.cell, geom.sc.cell): warn(f"{cls.__name__}.{method} has non-equal lattice vectors, will copy geometry and use file lattice.") geom, is_copy = get_copy(geom, is_copy) geom.sc.cell[:, :] = geom_b.sc.cell[:, :] if not np.array_equal(geom_b.nsc, geom.nsc): warn(f"{cls.__name__}.{method} has non-equal number of supercells, will copy geometry and use file supercell count.") geom, is_copy = get_copy(geom, is_copy) geom.set_nsc(geom_b.nsc) # Now for the difficult part. # If there is a mismatch in the number of orbitals we will # prefer to use the user-supplied atomic species, but fill with # *random* orbitals if not np.array_equal(geom_b.atoms.orbitals, geom.atoms.orbitals): warn(f"{cls.__name__}.{method} has non-equal number of orbitals per atom, will correct with *empty* orbitals.") geom, is_copy = get_copy(geom, is_copy) # Now create a new atom specie with the correct number of orbitals norbs = geom_b.atoms.orbitals[:] atoms = Atoms([geom.atoms[i].copy(orbitals=[-1.] * norbs[i]) for i in range(geom.na)]) geom._atoms = atoms return geom @set_module("sisl.io.siesta") class onlysSileSiesta(SileBinSiesta): """ Geometry and overlap matrix """ def read_supercell(self): """ Returns a SuperCell object from a TranSiesta file """ n_s = _siesta.read_tshs_sizes(self.file)[3] _bin_check(self, 'read_supercell', 'could not read sizes.') arr = _siesta.read_tshs_cell(self.file, n_s) _bin_check(self, 'read_supercell', 'could not read cell.') nsc = np.array(arr[0], np.int32) # We have to transpose since the data is read *as-is* # The cell in fortran files are (:, A1) # after reading this is still obeyed (regardless of order) # So we transpose to get it C-like # Note that care must be taken for the different data-structures # In particular not all data needs to be transposed (sparse H and S) cell = arr[1].T * _Bohr2Ang return SuperCell(cell, nsc=nsc) def read_geometry(self, geometry=None): """ Returns Geometry object from a TranSiesta file """ # Read supercell sc = self.read_supercell() na = _siesta.read_tshs_sizes(self.file)[1] _bin_check(self, 'read_geometry', 'could not read sizes.') arr = _siesta.read_tshs_geom(self.file, na) _bin_check(self, 'read_geometry', 'could not read geometry.') # see onlysSileSiesta.read_supercell for .T xyz = arr[0].T * _Bohr2Ang lasto = arr[1] # Since the TSHS file does not contain species information # and/or other stuff we *can* reuse an existing # geometry which contains the correct atomic numbers etc. orbs = np.diff(lasto) if geometry is None: # Create all different atoms... # The TSHS file does not contain the # atomic numbers, so we will just # create them individually # Get unique orbitals uorb = np.unique(orbs) # Create atoms atoms = [] for Z, orb in enumerate(uorb): atoms.append(Atom(Z+1, [-1] * orb)) def get_atom(atoms, orbs): for atom in atoms: if atom.no == orbs: return atom atom = [] for orb in orbs: atom.append(get_atom(atoms, orb)) else: # Create a new geometry with the correct atomic numbers atom = [] for ia, no in zip(geometry, orbs): a = geometry.atoms[ia] if a.no == no: atom.append(a) else: # correct atom atom.append(a.__class__(a.Z, [-1. for io in range(no)], mass=a.mass, tag=a.tag)) # Create and return geometry object return Geometry(xyz, atom, sc=sc) def read_overlap(self, **kwargs): """ Returns the overlap matrix from the TranSiesta file """ tshs_g = self.read_geometry() geom = _geometry_align(tshs_g, kwargs.get('geometry', tshs_g), self.__class__, 'read_overlap') # read the sizes used... sizes = _siesta.read_tshs_sizes(self.file) _bin_check(self, 'read_overlap', 'could not read sizes.') # see onlysSileSiesta.read_supercell for .T isc = _siesta.read_tshs_cell(self.file, sizes[3])[2].T _bin_check(self, 'read_overlap', 'could not read cell.') no = sizes[2] nnz = sizes[4] ncol, col, dS = _siesta.read_tshs_s(self.file, no, nnz) _bin_check(self, 'read_overlap', 'could not read overlap matrix.') # Create the Hamiltonian container S = Overlap(geom, nnzpr=1) # Create the new sparse matrix S._csr.ncol = ncol.astype(np.int32, copy=False) S._csr.ptr = _ncol_to_indptr(ncol) # Correct fortran indices S._csr.col = col.astype(np.int32, copy=False) - 1 S._csr._nnz = len(col) S._csr._D = _a.emptyd([nnz, 1]) S._csr._D[:, 0] = dS[:] # Convert to sisl supercell # equivalent as _csr_from_siesta with explicit isc from file _csr_from_sc_off(S.geometry, isc, S._csr) # In siesta the matrix layout is written in CSC format # due to fortran indexing, this means that we need to transpose # to get it to correct layout. return S.transpose(sort=kwargs.get("sort", True)) def read_fermi_level(self): r""" Query the Fermi-level contained in the file Returns ------- Ef : fermi-level of the system """ Ef = _siesta.read_tshs_ef(self.file) * _Ry2eV _bin_check(self, 'read_fermi_level', 'could not read fermi-level.') return Ef @set_module("sisl.io.siesta") class tshsSileSiesta(onlysSileSiesta): """ Geometry, Hamiltonian and overlap matrix file """ def read_hamiltonian(self, **kwargs): """ Returns the electronic structure from the siesta.TSHS file """ tshs_g = self.read_geometry() geom = _geometry_align(tshs_g, kwargs.get('geometry', tshs_g), self.__class__, 'read_hamiltonian') # read the sizes used... sizes = _siesta.read_tshs_sizes(self.file) _bin_check(self, 'read_hamiltonian', 'could not read sizes.') # see onlysSileSiesta.read_supercell for .T isc = _siesta.read_tshs_cell(self.file, sizes[3])[2].T _bin_check(self, 'read_hamiltonian', 'could not read cell.') spin = sizes[0] no = sizes[2] nnz = sizes[4] ncol, col, dH, dS = _siesta.read_tshs_hs(self.file, spin, no, nnz) _bin_check(self, 'read_hamiltonian', 'could not read Hamiltonian and overlap matrix.') # Check whether it is an orthogonal basis set orthogonal = np.abs(dS).sum() == geom.no # Create the Hamiltonian container H = Hamiltonian(geom, spin, nnzpr=1, orthogonal=orthogonal) # Create the new sparse matrix H._csr.ncol = ncol.astype(np.int32, copy=False) H._csr.ptr = _ncol_to_indptr(ncol) # Correct fortran indices H._csr.col = col.astype(np.int32, copy=False) - 1 H._csr._nnz = len(col) if orthogonal: H._csr._D = _a.emptyd([nnz, spin]) H._csr._D[:, :] = dH[:, :] * _Ry2eV else: H._csr._D = _a.emptyd([nnz, spin+1]) H._csr._D[:, :spin] = dH[:, :] * _Ry2eV H._csr._D[:, spin] = dS[:] _mat_spin_convert(H) # Convert to sisl supercell # equivalent as _csr_from_siesta with explicit isc from file _csr_from_sc_off(H.geometry, isc, H._csr) # Find all indices where dS == 1 (remember col is in fortran indices) idx = col[np.isclose(dS, 1.).nonzero()[0]] if np.any(idx > no): print(f'Number of orbitals: {no}') print(idx) raise SileError(str(self) + '.read_hamiltonian could not assert ' 'the supercell connections in the primary unit-cell.') # see onlysSileSiesta.read_overlap for .transpose() # For H, DM and EDM we also need to Hermitian conjugate it. return H.transpose(spin=False, sort=kwargs.get("sort", True)) def write_hamiltonian(self, H, **kwargs): """ Writes the Hamiltonian to a siesta.TSHS file """ # we sort below, so no need to do it here # see onlysSileSiesta.read_overlap for .transpose() csr = H.transpose(spin=False, sort=False)._csr if csr.nnz == 0: raise SileError(str(self) + '.write_hamiltonian cannot write ' 'a zero element sparse matrix!') # Convert to siesta CSR _csr_to_siesta(H.geometry, csr) csr.finalize(sort=kwargs.get("sort", True)) _mat_spin_convert(csr, H.spin) # Extract the data to pass to the fortran routine cell = H.geometry.cell xyz = H.geometry.xyz # Get H and S if H.orthogonal: h = csr._D s = csr.diags(1., dim=1) # Ensure all data is correctly formatted (i.e. have the same sparsity pattern) s.align(csr) s.finalize(sort=kwargs.get("sort", True)) if s.nnz != len(h): raise SislError('The diagonal elements of your orthogonal Hamiltonian ' 'have not been defined, this is a requirement.') s = s._D[:, 0] else: h = csr._D[:, :H.S_idx] s = csr._D[:, H.S_idx] # Get shorter variants nsc = H.geometry.nsc[:].astype(np.int32) isc = _siesta.siesta_sc_off(*nsc) # see onlysSileSiesta.read_supercell for .T _siesta.write_tshs_hs(self.file, nsc[0], nsc[1], nsc[2], cell.T / _Bohr2Ang, xyz.T / _Bohr2Ang, H.geometry.firsto, csr.ncol, csr.col + 1, _toF(h, np.float64, _eV2Ry), _toF(s, np.float64), isc) _bin_check(self, 'write_hamiltonian', 'could not write Hamiltonian and overlap matrix.') @set_module("sisl.io.siesta") class dmSileSiesta(SileBinSiesta): """ Density matrix file """ def read_density_matrix(self, **kwargs): """ Returns the density matrix from the siesta.DM file """ # Now read the sizes used... spin, no, nsc, nnz = _siesta.read_dm_sizes(self.file) _bin_check(self, 'read_density_matrix', 'could not read density matrix sizes.') ncol, col, dDM = _siesta.read_dm(self.file, spin, no, nsc, nnz) _bin_check(self, 'read_density_matrix', 'could not read density matrix.') # Try and immediately attach a geometry geom = kwargs.get('geometry', kwargs.get('geom', None)) if geom is None: # We truly, have no clue, # Just generate a boxed system xyz = [[x, 0, 0] for x in range(no)] sc = SuperCell([no, 1, 1], nsc=nsc) geom = Geometry(xyz, Atom(1), sc=sc) if nsc[0] != 0 and np.any(geom.nsc != nsc): # We have to update the number of supercells! geom.set_nsc(nsc) if geom.no != no: raise SileError(str(self) + '.read_density_matrix could not use the ' 'passed geometry as the number of atoms or orbitals is ' 'inconsistent with DM file.') # Create the density matrix container DM = DensityMatrix(geom, spin, nnzpr=1, dtype=np.float64, orthogonal=False) # Create the new sparse matrix DM._csr.ncol = ncol.astype(np.int32, copy=False) DM._csr.ptr = _ncol_to_indptr(ncol) # Correct fortran indices DM._csr.col = col.astype(np.int32, copy=False) - 1 DM._csr._nnz = len(col) DM._csr._D = _a.emptyd([nnz, spin+1]) DM._csr._D[:, :spin] = dDM[:, :] # DM file does not contain overlap matrix... so neglect it for now. DM._csr._D[:, spin] = 0. _mat_spin_convert(DM) # Convert the supercells to sisl supercells if nsc[0] != 0 or geom.no_s >= col.max(): _csr_from_siesta(geom, DM._csr) else: warn(str(self) + '.read_density_matrix may result in a wrong sparse pattern!') return DM.transpose(spin=False, sort=kwargs.get("sort", True)) def write_density_matrix(self, DM, **kwargs): """ Writes the density matrix to a siesta.DM file """ csr = DM.transpose(spin=False, sort=False)._csr # This ensures that we don't have any *empty* elements if csr.nnz == 0: raise SileError(str(self) + '.write_density_matrix cannot write ' 'a zero element sparse matrix!') _csr_to_siesta(DM.geometry, csr) # We do not really need to sort this one, but we do for consistency # of the interface. csr.finalize(sort=kwargs.get("sort", True)) _mat_spin_convert(csr, DM.spin) # Get DM if DM.orthogonal: dm = csr._D else: dm = csr._D[:, :DM.S_idx] # Ensure shapes (say if only 1 spin) dm.shape = (-1, len(DM.spin)) nsc = DM.geometry.sc.nsc.astype(np.int32) _siesta.write_dm(self.file, nsc, csr.ncol, csr.col + 1, _toF(dm, np.float64)) _bin_check(self, 'write_density_matrix', 'could not write density matrix.') @set_module("sisl.io.siesta") class tsdeSileSiesta(dmSileSiesta): """ Non-equilibrium density matrix and energy density matrix file """ def read_energy_density_matrix(self, **kwargs): """ Returns the energy density matrix from the siesta.DM file """ # Now read the sizes used... spin, no, nsc, nnz = _siesta.read_tsde_sizes(self.file) _bin_check(self, 'read_energy_density_matrix', 'could not read energy density matrix sizes.') ncol, col, dEDM = _siesta.read_tsde_edm(self.file, spin, no, nsc, nnz) _bin_check(self, 'read_energy_density_matrix', 'could not read energy density matrix.') # Try and immediately attach a geometry geom = kwargs.get('geometry', kwargs.get('geom', None)) if geom is None: # We truly, have no clue, # Just generate a boxed system xyz = [[x, 0, 0] for x in range(no)] sc = SuperCell([no, 1, 1], nsc=nsc) geom = Geometry(xyz, Atom(1), sc=sc) if nsc[0] != 0 and np.any(geom.nsc != nsc): # We have to update the number of supercells! geom.set_nsc(nsc) if geom.no != no: raise SileError(str(self) + '.read_energy_density_matrix could ' 'not use the passed geometry as the number of atoms or orbitals ' 'is inconsistent with DM file.') # Create the energy density matrix container EDM = EnergyDensityMatrix(geom, spin, nnzpr=1, dtype=np.float64, orthogonal=False) # Create the new sparse matrix EDM._csr.ncol = ncol.astype(np.int32, copy=False) EDM._csr.ptr = _ncol_to_indptr(ncol) # Correct fortran indices EDM._csr.col = col.astype(np.int32, copy=False) - 1 EDM._csr._nnz = len(col) EDM._csr._D = _a.emptyd([nnz, spin+1]) EDM._csr._D[:, :spin] = dEDM[:, :] * _Ry2eV # EDM file does not contain overlap matrix... so neglect it for now. EDM._csr._D[:, spin] = 0. _mat_spin_convert(EDM) # Convert the supercells to sisl supercells if nsc[0] != 0 or geom.no_s >= col.max(): _csr_from_siesta(geom, EDM._csr) else: warn(str(self) + '.read_energy_density_matrix may result in a wrong sparse pattern!') return EDM.transpose(spin=False, sort=kwargs.get("sort", True)) def read_fermi_level(self): r""" Query the Fermi-level contained in the file Returns ------- Ef : fermi-level of the system """ Ef = _siesta.read_tsde_ef(self.file) * _Ry2eV _bin_check(self, 'read_fermi_level', 'could not read fermi-level.') return Ef def write_density_matrices(self, DM, EDM, Ef=0., **kwargs): r""" Writes the density matrix to a siesta.DM file Parameters ---------- DM : DensityMatrix density matrix to write to the file EDM : EnergyDensityMatrix energy density matrix to write to the file Ef : float, optional fermi-level to be contained """ DMcsr = DM.transpose(spin=False, sort=False)._csr EDMcsr = EDM.transpose(spin=False, sort=False)._csr DMcsr.align(EDMcsr) EDMcsr.align(DMcsr) if DMcsr.nnz == 0: raise SileError(str(self) + '.write_density_matrices cannot write ' 'a zero element sparse matrix!') _csr_to_siesta(DM.geometry, DMcsr) _csr_to_siesta(DM.geometry, EDMcsr) sort = kwargs.get("sort", True) DMcsr.finalize(sort=sort) EDMcsr.finalize(sort=sort) _mat_spin_convert(DMcsr, DM.spin) _mat_spin_convert(EDMcsr, EDM.spin) # Ensure everything is correct if not (np.allclose(DMcsr.ncol, EDMcsr.ncol) and np.allclose(DMcsr.col, EDMcsr.col)): raise ValueError(str(self) + '.write_density_matrices got non compatible ' 'DM and EDM matrices.') if DM.orthogonal: dm = DMcsr._D else: dm = DMcsr._D[:, :DM.S_idx] if EDM.orthogonal: edm = EDMcsr._D else: edm = EDMcsr._D[:, :EDM.S_idx] nsc = DM.geometry.sc.nsc.astype(np.int32) _siesta.write_tsde_dm_edm(self.file, nsc, DMcsr.ncol, DMcsr.col + 1, _toF(dm, np.float64), _toF(edm, np.float64, _eV2Ry), Ef * _eV2Ry) _bin_check(self, 'write_density_matrices', 'could not write DM + EDM matrices.') @set_module("sisl.io.siesta") class hsxSileSiesta(SileBinSiesta): """ Hamiltonian and overlap matrix file This file does not contain all information regarding the system. To ensure no errors are being raised one should pass a `Geometry` with correct number of atoms and correct number of supercells. The number of orbitals will be updated in the returned matrices geometry. >>> hsx = hsxSileSiesta("siesta.HSX") >>> HS = hsx.read_hamiltonian() # may fail >>> HS = hsx.read_hamiltonian(geometry=<>) # should run correctly if above satisfied Users are adviced to use the `tshsSileSiesta` instead since that correctly contains all information. """ def _xij2system(self, xij, geometry=None): """ Create a new geometry with *correct* nsc and somewhat correct xyz Parameters ---------- xij : SparseCSR orbital distances geometry : Geometry, optional passed geometry """ def get_geom_handle(xij): atoms = self._read_atoms() if not atoms is None: return Geometry(np.zeros([len(atoms), 3]), atoms) N = len(xij) # convert csr to dok format row = (xij.ncol > 0).nonzero()[0] # Now we have [0 0 0 0 1 1 1 1 2 2 ... no-1 no-1] row = np.repeat(row, xij.ncol[row]) col = xij.col # Parse xij to correct geometry # first figure out all zeros (i.e. self-atom-orbitals) idx0 = np.isclose(np.fabs(xij._D).sum(axis=1), 0.).nonzero()[0] row0 = row[idx0] # convert row0 and col0 to a first attempt of "atomization" atoms = [] for r in range(N): idx0r = (row0 == r).nonzero()[0] row0r = row0[idx0r] # although xij == 0, we just do % to ensure unit-cell orbs col0r = col[idx0[idx0r]] % N if np.all(col0r >= r): # we have a new atom atoms.append(set(col0r)) else: atoms[-1].update(set(col0r)) # convert list of orbitals to lists def conv(a): a = list(a) a.sort() return a atoms = [list(a) for a in atoms] if sum(map(len, atoms)) != len(xij): raise ValueError(f"{self.__class__.__name__} could not determine correct " "number of orbitals.") atms = Atoms(Atom('H', [-1. for _ in atoms[0]])) for orbs in atoms[1:]: atms.append(Atom('H', [-1. for _ in orbs])) return Geometry(np.zeros([len(atoms), 3]), atms) geom_handle = get_geom_handle(xij) def convert_to_atom(geom, xij): # o2a does not check for correct super-cell index n_s = xij.shape[1] // xij.shape[0] atm_s = geom.o2a(np.arange(xij.shape[1])) # convert csr to dok format row = (xij.ncol > 0).nonzero()[0] row = np.repeat(row, xij.ncol[row]) col = xij.col arow = atm_s[row] acol = atm_s[col] del atm_s, row, col idx = np.lexsort((acol, arow)) arow = arow[idx] acol = acol[idx] xij = xij._D[idx] del idx # Now figure out if xij is consistent duplicates = np.logical_and(np.diff(acol) == 0, np.diff(arow) == 0).nonzero()[0] if duplicates.size > 0: if not np.allclose(xij[duplicates+1] - xij[duplicates], 0.): raise ValueError(f"{self.__class__.__name__} converting xij(orb) -> xij(atom) went wrong. " "This may happen if your coordinates are not inside the unitcell, please pass " "a usable geometry.") # remove duplicates to create new matrix arow = np.delete(arow, duplicates) acol = np.delete(acol, duplicates) xij = np.delete(xij, duplicates, axis=0) # Create a new sparse matrix # Create the new index pointer indptr = np.insert(np.array([0, len(xij)], np.int32), 1, (np.diff(arow) != 0).nonzero()[0] + 1) assert len(indptr) == geom.na + 1 return SparseCSR((xij, acol, indptr), shape=(geom.na, geom.na * n_s)) def coord_from_xij(xij): # first atom is at 0, 0, 0 na = len(xij) xyz = _a.zerosd([na, 3]) xyz[0] = [0, 0, 0] mark = _a.zerosi(na) mark[0] = 1 run_atoms = deque([0]) while len(run_atoms) > 0: atm = run_atoms.popleft() xyz_atm = xyz[atm].reshape(1, 3) neighbours = xij.edges(atm, exclude=atm) neighbours = neighbours[neighbours < na] # update those that haven't been calculated idx = mark[neighbours] == 0 neigh_idx = neighbours[idx] if len(neigh_idx) == 0: continue xyz[neigh_idx, :] = xij[atm, neigh_idx] - xyz_atm mark[neigh_idx] = 1 # add more atoms to be processed, since we have *mark* # we will only run every atom once run_atoms.extend(neigh_idx.tolist()) # check that everything is correct if (~idx).sum() > 0: neg_neighbours = neighbours[~idx] if not np.allclose(xyz[neg_neighbours, :], xij[atm, neg_neighbours] - xyz_atm): raise ValueError(f"{self.__class__.__name__} xij(orb) -> xyz did not " f"find same coordinates for different connections") if mark.sum() != na: raise ValueError(f"{self.__class__.__name__} xij(orb) -> Geometry does not " f"have a fully connected geometry. It is impossible to create relative coordinates") return xyz def sc_from_xij(xij, xyz): na = xij.shape[0] n_s = xij.shape[1] // xij.shape[0] if n_s == 1: # easy!! return SuperCell(xyz.max(axis=0) - xyz.min(axis=0) + 10., nsc=[1] * 3) sc_off = _a.zerosd([n_s, 3]) mark = _a.zerosi(n_s) mark[0] = 1 for atm in range(na): neighbours = xij.edges(atm, exclude=atm) uneighbours = neighbours % na neighbour_isc = neighbours // na # get offset in terms of unit-cell off = xij[atm, neighbours] - (xyz[uneighbours] - xyz[atm].reshape(1, 3)) idx = mark[neighbour_isc] == 0 if not np.allclose(off[~idx], sc_off[neighbour_isc[~idx]]): raise ValueError(f"{self.__class__.__name__} xij(orb) -> xyz did not " f"find same supercell offsets for different connections") if idx.sum() == 0: continue for idx in idx.nonzero()[0]: nidx = neighbour_isc[idx] if mark[nidx] == 0: mark[nidx] = 1 sc_off[nidx] = off[idx] elif not np.allclose(sc_off[nidx], off[idx]): raise ValueError(f"{self.__class__.__name__} xij(orb) -> xyz did not " f"find same supercell offsets for different connections") # We know that siesta returns isc # for iz in [0, 1, 2, 3, -3, -2, -1]: # for iy in [0, 1, 2, -2, -1]: # for ix in [0, 1, -1]: # every block we find a half monotonically increasing vector additions # Note the first is always [0, 0, 0] # So our best chance is to *guess* the first nsc # then reshape, then guess, then reshape, then guess :) sc_diff = np.diff(sc_off, axis=0) def get_nsc(sc_off): """ Determine nsc depending on the axis """ # correct the offsets ndim = sc_off.ndim if sc_off.shape[0] == 1: return 1 # always select the 2nd one since that contains the offset # for the first isc [1, 0, 0] or [0, 1, 0] or [0, 0, 1] sc_dir = sc_off[(1, ) + np.index_exp[0] * (ndim - 2)].reshape(1, 3) norm2_sc_dir = (sc_dir ** 2).sum() # figure out the maximum integer part # we select 0 indices for all already determined lattice # vectors since we know the first one is [0, 0, 0] idx = np.index_exp[:] + np.index_exp[0] * (ndim - 2) projection = (sc_off[idx] * sc_dir).sum(-1) / norm2_sc_dir iprojection = np.rint(projection) # reduce, find 0 idx_zero = np.isclose(iprojection, 0, atol=1e-5).nonzero()[0] if idx_zero.size <= 1: return 1 # only take those values that are continuous # we *must* have some supercell connections idx_max = idx_zero[1] # find where they are close # since there may be *many* zeros (non-coupling elements) # we first have to cut off anything that is not integer if np.allclose(projection[:idx_max], iprojection[:idx_max], atol=1e-5): return idx_max raise ValueError(f"Could not determine nsc from coordinates") nsc = _a.onesi(3) nsc[0] = get_nsc(sc_off) sc_off = sc_off.reshape(-1, nsc[0], 3) nsc[1] = get_nsc(sc_off) sc_off = sc_off.reshape(-1, nsc[1], nsc[0], 3) nsc[2] = sc_off.shape[0] # now determine cell parameters if all(nsc > 1): cell = _a.arrayd([sc_off[0, 0, 1], sc_off[0, 1, 0], sc_off[1, 0, 0]]) else: # we will never have all(nsc == 1) since that is # taken care of at the start # this gets a bit tricky, since we don't know one of the # lattice vectors cell = _a.zerosd([3, 3]) i = 0 for idx, isc in enumerate(nsc): if isc > 1: sl = [0, 0, 0] sl[2 - idx] = 1 cell[i] = sc_off[tuple(sl)] i += 1 # figure out the last vectors # We'll just use Cartesian coordinates while i < 3: # this means we don't have any supercell connections # along at least 1 other lattice vector. lcell = np.fabs(cell).sum(0) # figure out which Cartesian direction we are *missing* cart_dir = np.argmin(lcell) cell[i, cart_dir] = xyz[:, cart_dir].max() - xyz[:, cart_dir].min() + 10. i += 1 return SuperCell(cell, nsc) # now we have all orbitals, ensure compatibility with passed geometry if geometry is None: atm_xij = convert_to_atom(geom_handle, xij) xyz = coord_from_xij(atm_xij) sc = sc_from_xij(atm_xij, xyz) geometry = Geometry(xyz, geom_handle.atoms, sc) # Move coordinates into unit-cell geometry.xyz[:, :] = (geometry.fxyz % 1.) @ geometry.cell else: if geometry.n_s != xij.shape[1] // xij.shape[0]: atm_xij = convert_to_atom(geom_handle, xij) sc = sc_from_xij(atm_xij, coord_from_xij(atm_xij)) geometry.set_nsc(sc.nsc) def conv(orbs, atm): if len(orbs) == len(atm): return atm return atm.copy(orbitals=[-1. for _ in orbs]) atms = Atoms(list(map(conv, geom_handle.atoms, geometry.atoms))) if len(atms) != len(geometry): raise ValueError(f"{self.__class__.__name__} passed geometry for reading " "sparse matrix does not contain same number of atoms!") geometry = geometry.copy() # TODO check that geometry and xyz are the same! geometry._atoms = atms return geometry def _read_atoms(self, **kwargs): """ Reads basis set and geometry information from the HSX file """ # Now read the sizes used... no, na, nspecies = _siesta.read_hsx_specie_sizes(self.file) _bin_check(self, 'read_geometry', 'could not read specie sizes.') # Read specie information labels, val_q, norbs, isa = _siesta.read_hsx_species(self.file, nspecies, no, na) # convert to proper string labels = labels.T.reshape(nspecies, -1) labels = labels.view(f"S{labels.shape[1]}") labels = list(map(lambda s: b''.join(s).decode('utf-8').strip(), labels.tolist()) ) _bin_check(self, 'read_geometry', 'could not read species.') # to python index isa -= 1 from sisl.atom import _ptbl # try and convert labels into symbols # We do this by: # 1. label -> symbol # 2. label[:2] -> symbol # 3. label[:1] -> symbol symbols = [] lbls = [] for label in labels: lbls.append(label) try: symbol = _ptbl.Z_label(label) symbols.append(symbol) continue except: pass try: symbol = _ptbl.Z_label(label[:2]) symbols.append(symbol) continue except: pass try: symbol = _ptbl.Z_label(label[:1]) symbols.append(symbol) continue except: # we have no clue, assign -1 symbols.append(-1) # Read in orbital information atoms = [] for ispecie in range(nspecies): n_l_zeta = _siesta.read_hsx_specie(self.file, ispecie+1, norbs[ispecie]) _bin_check(self, 'read_geometry', f'could not read specie {ispecie}.') # create orbital # no shell will have l>5, so m=10 should be more than enough m = 10 orbs = [] for n, l, zeta in zip(*n_l_zeta): # manual loop on m quantum numbers if m > l: m = -l orbs.append(AtomicOrbital(n=n, l=l, m=m, zeta=zeta, R=-1.)) m += 1 # now create atom atoms.append(Atom(symbols[ispecie], orbs, tag=lbls[ispecie])) # now read in xij to retrieve atomic positions Gamma, spin, no, no_s, nnz = _siesta.read_hsx_sizes(self.file) _bin_check(self, 'read_geometry', 'could not read matrix sizes.') ncol, col, _, dxij = _siesta.read_hsx_sx(self.file, Gamma, spin, no, no_s, nnz) dxij = dxij.T * _Bohr2Ang col -= 1 _bin_check(self, 'read_geometry', 'could not read xij matrix.') # now create atoms object atoms = Atoms([atoms[ia] for ia in isa]) return atoms def read_hamiltonian(self, **kwargs): """ Returns the electronic structure from the siesta.TSHS file """ # Now read the sizes used... Gamma, spin, no, no_s, nnz = _siesta.read_hsx_sizes(self.file) _bin_check(self, 'read_hamiltonian', 'could not read Hamiltonian sizes.') ncol, col, dH, dS, dxij = _siesta.read_hsx_hsx(self.file, Gamma, spin, no, no_s, nnz) dxij = dxij.T * _Bohr2Ang col -= 1 _bin_check(self, 'read_hamiltonian', 'could not read Hamiltonian.') ptr = _ncol_to_indptr(ncol) xij = SparseCSR((dxij, col, ptr), shape=(no, no_s)) geom = self._xij2system(xij, kwargs.get('geometry', kwargs.get('geom', None))) if geom.no != no or geom.no_s != no_s: raise SileError(f"{str(self)}.read_hamiltonian could not use the " "passed geometry as the number of atoms or orbitals is " "inconsistent with HSX file.") # Create the Hamiltonian container H = Hamiltonian(geom, spin, nnzpr=1, dtype=np.float32, orthogonal=False) # Create the new sparse matrix H._csr.ncol = ncol.astype(np.int32, copy=False) H._csr.ptr = ptr # Correct fortran indices H._csr.col = col.astype(np.int32, copy=False) H._csr._nnz = len(col) H._csr._D = _a.emptyf([nnz, spin+1]) H._csr._D[:, :spin] = dH[:, :] * _Ry2eV H._csr._D[:, spin] = dS[:] _mat_spin_convert(H) # Convert the supercells to sisl supercells if no_s // no == np.product(geom.nsc): _csr_from_siesta(geom, H._csr) return H.transpose(spin=False, sort=kwargs.get("sort", True)) def read_overlap(self, **kwargs): """ Returns the overlap matrix from the siesta.HSX file """ # Now read the sizes used... Gamma, spin, no, no_s, nnz = _siesta.read_hsx_sizes(self.file) _bin_check(self, 'read_overlap', 'could not read overlap matrix sizes.') ncol, col, dS, dxij = _siesta.read_hsx_sx(self.file, Gamma, spin, no, no_s, nnz) dxij = dxij.T * _Bohr2Ang col -= 1 _bin_check(self, 'read_overlap', 'could not read overlap matrix.') ptr = _ncol_to_indptr(ncol) xij = SparseCSR((dxij, col, ptr), shape=(no, no_s)) geom = self._xij2system(xij, kwargs.get('geometry', kwargs.get('geom', None))) if geom.no != no or geom.no_s != no_s: raise SileError(f"{str(self)}.read_overlap could not use the " "passed geometry as the number of atoms or orbitals is " "inconsistent with HSX file.") # Create the Hamiltonian container S = Overlap(geom, nnzpr=1) # Create the new sparse matrix S._csr.ncol = ncol.astype(np.int32, copy=False) S._csr.ptr = _ncol_to_indptr(ncol) # Correct fortran indices S._csr.col = col.astype(np.int32, copy=False) S._csr._nnz = len(col) S._csr._D = _a.emptyf([nnz, 1]) S._csr._D[:, 0] = dS[:] # Convert the supercells to sisl supercells if no_s // no == np.product(geom.nsc): _csr_from_siesta(geom, S._csr) # not really necessary with Hermitian transposing, but for consistency return S.transpose(sort=kwargs.get("sort", True)) @set_module("sisl.io.siesta") class wfsxSileSiesta(SileBinSiesta): r""" Binary WFSX file reader for Siesta """ def yield_eigenstate(self, parent=None): r""" Reads eigenstates from the WFSX file Returns ------- state: EigenstateElectron """ # First query information nspin, nou, nk, Gamma = _siesta.read_wfsx_sizes(self.file) _bin_check(self, 'yield_eigenstate', 'could not read sizes.') if nspin in [4, 8]: nspin = 1 # only 1 spin func = _siesta.read_wfsx_index_4 elif Gamma: func = _siesta.read_wfsx_index_1 else: func = _siesta.read_wfsx_index_2 if parent is None: def convert_k(k): if not np.allclose(k, 0.): warn(f"{self.__class__.__name__}.yield_eigenstate returns a k-point in 1/Ang (not in reduced format), please pass 'parent' to ensure reduced k") return k else: # We can succesfully convert to proper reduced k-points if isinstance(parent, SuperCell): def convert_k(k): return np.dot(k, parent.cell.T) / (2 * pi) else: def convert_k(k): return np.dot(k, parent.sc.cell.T) / (2 * pi) for ispin, ik in product(range(1, nspin + 1), range(1, nk + 1)): k, _, nwf = _siesta.read_wfsx_index_info(self.file, ispin, ik) # Convert to 1/Ang k /= _Bohr2Ang _bin_check(self, 'yield_eigenstate', f"could not read index info [{ispin}, {ik}]") idx, eig, state = func(self.file, ispin, ik, nou, nwf) _bin_check(self, 'yield_eigenstate', f"could not read state information [{ispin}, {ik}, {nwf}]") # eig is already in eV # we probably need to add spin # see onlysSileSiesta.read_supercell for .T es = EigenstateElectron(state.T, eig, parent=parent, k=convert_k(k), gauge="r", index=idx - 1) yield es @set_module("sisl.io.siesta") class _gridSileSiesta(SileBinSiesta): r""" Binary real-space grid file The Siesta binary grid sile will automatically convert the units from Siesta units (Bohr, Ry) to sisl units (Ang, eV) provided the correct extension is present. """ def read_supercell(self, *args, **kwargs): r""" Return the cell contained in the file """ cell = _siesta.read_grid_cell(self.file).T * _Bohr2Ang _bin_check(self, 'read_supercell', 'could not read cell.') return SuperCell(cell) def read_grid_size(self): r""" Query grid size information such as the grid size and number of spin components Returns ------- int : number of spin-components mesh : 3 values for the number of mesh-elements """ # Read the sizes nspin, mesh = _siesta.read_grid_sizes(self.file) _bin_check(self, 'read_grid_size', 'could not read grid sizes.') return nspin, mesh def read_grid(self, index=0, dtype=np.float64, *args, **kwargs): """ Read grid contained in the Grid file Parameters ---------- index : int or array_like, optional the spin-index for retrieving one of the components. If a vector is passed it refers to the fraction per indexed component. I.e. ``[0.5, 0.5]`` will return sum of half the first two components. Default to the first component. dtype : numpy.float64, optional default data-type precision """ index = kwargs.get('spin', index) # Read the sizes and cell nspin, mesh = self.read_grid_size() sc = self.read_supercell() grid = _siesta.read_grid(self.file, nspin, mesh[0], mesh[1], mesh[2]) _bin_check(self, 'read_grid', 'could not read grid.') if isinstance(index, Integral): grid = grid[:, :, :, index] else: if len(index) > grid.shape[0]: raise ValueError(self.__class__.__name__ + '.read_grid requires spin to be an integer or ' 'an array of length equal to the number of spin components.') # It is F-contiguous, hence the last index g = grid[:, :, :, 0] * index[0] for i, scale in enumerate(index[1:]): g += grid[:, :, :, 1+i] * scale grid = g # Simply create the grid (with no information) # We will overwrite the actual grid g = Grid([1, 1, 1], sc=sc) # NOTE: there is no need to swap-axes since the returned array is in F ordering # and thus the first axis is the fast (x, y, z) is retained g.grid = grid * self.grid_unit return g @set_module("sisl.io.siesta") class _gfSileSiesta(SileBinSiesta): """ Surface Green function file containing, Hamiltonian, overlap matrix and self-energies Do not mix read and write statements when using this code. Complete one or the other before doing the other thing. Fortran does not allow the same file opened twice, if this is needed you are recommended to make a symlink to the file and thus open two different files. This small snippet reads/writes the GF file >>> with sisl.io._gfSileSiesta('hello.GF') as f: ... nspin, no, k, E = f.read_header() ... for ispin, new_k, k, E in f: ... if new_k: ... H, S = f.read_hamiltonian() ... SeHSE = f.read_self_energy() To write a file do: >>> with sisl.io._gfSileSiesta('hello.GF') as f: ... f.write_header(sisl.MonkhorstPack(...), E) ... for ispin, new_k, k, E in f: ... if new_k: ... f.write_hamiltonian(H, S) ... f.write_self_energy(SeHSE) """ def _setup(self, *args, **kwargs): """ Simple setup that needs to be overwritten """ self._iu = -1 # The unit convention used for energy-points # This is necessary until Siesta uses CODATA values if kwargs.get("unit", "old").lower() in ("old", "4.1"): self._E_Ry2eV = 13.60580 else: self._E_Ry2eV = _Ry2eV def _is_open(self): return self._iu != -1 def _open_gf(self, mode, rewind=False): if self._is_open() and mode == self._mode: if rewind: _siesta.io_m.rewind_file(self._iu) else: # retain indices return else: if mode == 'r': self._iu = _siesta.io_m.open_file_read(self.file) elif mode == 'w': self._iu = _siesta.io_m.open_file_write(self.file) _bin_check(self, '_open_gf', 'could not open for {}.'.format({'r': 'reading', 'w': 'writing'}[mode])) # They will at any given time # correspond to the current Python indices that is to be read # The process for identification is done on this basis: # iE is the current (Python) index for the energy-point to be read # ik is the current (Python) index for the k-point to be read # ispin is the current (Python) index for the spin-index to be read (only has meaning for a spin-polarized # GF files) # state is: # -1 : the file-descriptor has just been opened (i.e. in front of header) # 0 : it means that the file-descriptor IS in front of H and S # 1 : it means that the file-descriptor is NOT in front of H and S but somewhere in front of a self-energy # is_read is: # 0 : means that the current indices HAVE NOT been read # 1 : means that the current indices HAVE been read # # All routines in the gf_read/write sources requires input in Python indices self._state = -1 self._is_read = 0 self._ispin = 0 self._ik = 0 self._iE = 0 def _close_gf(self): if not self._is_open(): return # Close it _siesta.io_m.close_file(self._iu) self._iu = -1 # Clean variables del self._state del self._iE del self._ik del self._ispin try: del self._no_u except: pass try: del self._nspin except: pass def _step_counter(self, method, **kwargs): """ Method for stepping values *must* be called before doing the actual read to check correct values """ opt = {'method': method} if kwargs.get('header', False): # The header only exists once, so check whether it is the correct place to read/write if self._state != -1 or self._is_read == 1: raise SileError(self.__class__.__name__ + '.{method} failed because the header has already ' 'been read.'.format(**opt)) self._state = -1 self._ispin = 0 self._ik = 0 self._iE = 0 #print('HEADER: ', self._state, self._ispin, self._ik, self._iE) elif kwargs.get('HS', False): # Correct for the previous state and jump values if self._state == -1: # We have just read the header if self._is_read != 1: raise SileError(self.__class__.__name__ + '.{method} failed because the file descriptor ' 'has not read the header.'.format(**opt)) # Reset values as though the header has just been read self._state = 0 self._ispin = 0 self._ik = 0 self._iE = 0 elif self._state == 0: if self._is_read == 1: raise SileError(self.__class__.__name__ + '.{method} failed because the file descriptor ' 'has already read the current HS for the given k-point.'.format(**opt)) elif self._state == 1: # We have just read from the last energy-point if self._iE + 1 != self._nE or self._is_read != 1: raise SileError(self.__class__.__name__ + '.{method} failed because the file descriptor ' 'has not read all energy-points for a given k-point.'.format(**opt)) self._state = 0 self._ik += 1 if self._ik >= self._nk: # We need to step spin self._ispin += 1 self._ik = 0 self._iE = 0 #print('HS: ', self._state, self._ispin, self._ik, self._iE) if self._ispin >= self._nspin: opt['spin'] = self._ispin + 1 opt['nspin'] = self._nspin raise SileError(self.__class__.__name__ + '.{method} failed because of missing information, ' 'a non-existing entry has been requested! spin={spin} max_spin={nspin}.'.format(**opt)) else: # We are reading an energy-point if self._state == -1: raise SileError(self.__class__.__name__ + '.{method} failed because the file descriptor ' 'has an unknown state.'.format(**opt)) elif self._state == 0: if self._is_read == 1: # Fine, we have just read the HS, ispin and ik are correct self._state = 1 self._iE = 0 else: raise SileError(self.__class__.__name__ + '.{method} failed because the file descriptor ' 'has an unknown state.'.format(**opt)) elif self._state == 1: if self._is_read == 0 and self._iE < self._nE: # we haven't read the current energy-point.and self._iE + 1 < self._nE: pass elif self._is_read == 1 and self._iE + 1 < self._nE: self._iE += 1 else: raise SileError(self.__class__.__name__ + '.{method} failed because the file descriptor ' 'has an unknown state.'.format(**opt)) if self._iE >= self._nE: # You are trying to read beyond the entry opt['iE'] = self._iE + 1 opt['NE'] = self._nE raise SileError(self.__class__.__name__ + '.{method} failed because of missing information, ' 'a non-existing energy-point has been requested! E_index={iE} max_E_index={NE}.'.format(**opt)) #print('SE: ', self._state, self._ispin, self._ik, self._iE) # Always signal (when stepping) that we have not yet read the thing if kwargs.get('read', False): self._is_read = 1 else: self._is_read = 0 def Eindex(self, E): """ Return the closest energy index corresponding to the energy ``E`` Parameters ---------- E : float or int if ``int``, return it-self, else return the energy index which is closests to the energy. """ if isinstance(E, Integral): return E idxE = np.abs(self._E - E).argmin() ret_E = self._E[idxE] if abs(ret_E - E) > 5e-3: warn(self.__class__.__name__ + " requesting energy " + f"{E:.5f} eV, found {ret_E:.5f} eV as the closest energy!") elif abs(ret_E - E) > 1e-3: info(self.__class__.__name__ + " requesting energy " + f"{E:.5f} eV, found {ret_E:.5f} eV as the closest energy!") return idxE def kindex(self, k): """ Return the index of the k-point that is closests to the queried k-point (in reduced coordinates) Parameters ---------- k : array_like of float or int the queried k-point in reduced coordinates :math:`]-0.5;0.5]`. If ``int`` return it-self. """ if isinstance(k, Integral): return k ik = np.sum(np.abs(self._k - _a.asarrayd(k)[None, :]), axis=1).argmin() ret_k = self._k[ik, :] if not np.allclose(ret_k, k, atol=0.0001): warn(SileWarning(self.__class__.__name__ + " requesting k-point " + "[{:.3f}, {:.3f}, {:.3f}]".format(*k) + " found " + "[{:.3f}, {:.3f}, {:.3f}]".format(*ret_k))) return ik def read_header(self): """ Read the header of the file and open it for reading subsequently NOTES: this method may change in the future Returns ------- nspin : number of spin-components stored (1 or 2) no_u : size of the matrices returned k : k points in the GF file E : energy points in the GF file """ # Ensure it is open (in read-mode) if self._is_open(): _siesta.io_m.rewind_file(self._iu) else: self._open_gf('r') nspin, no_u, nkpt, NE = _siesta.read_gf_sizes(self._iu) _bin_check(self, 'read_header', 'could not read sizes.') self._nspin = nspin self._nk = nkpt self._nE = NE # We need to rewind (because of k and energy -points) _siesta.io_m.rewind_file(self._iu) self._step_counter('read_header', header=True, read=True) k, E = _siesta.read_gf_header(self._iu, nkpt, NE) _bin_check(self, 'read_header', 'could not read header information.') if self._nspin > 2: # non-colinear self._no_u = no_u * 2 else: self._no_u = no_u self._E = E * self._E_Ry2eV self._k = k.T return nspin, no_u, self._k, self._E def disk_usage(self): """ Calculate the estimated size of the resulting file Returns ------- estimated disk-space used in GB """ is_open = self._is_open() if not is_open: self.read_header() # HS are only stored per k-point HS = 2 * self._nspin * self._nk SE = HS / 2 * self._nE # Now calculate the full size # no_u ** 2 = matrix size # 16 = bytes in double complex # 1024 ** 3 = B -> GB mem = (HS + SE) * self._no_u ** 2 * 16 / 1024 ** 3 if not is_open: self._close_gf() return mem def read_hamiltonian(self): """ Return current Hamiltonian and overlap matrix from the GF file Returns ------- complex128 : Hamiltonian matrix complex128 : Overlap matrix """ self._step_counter('read_hamiltonian', HS=True, read=True) H, S = _siesta.read_gf_hs(self._iu, self._no_u) _bin_check(self, 'read_hamiltonian', 'could not read Hamiltonian and overlap matrices.') # we don't convert to C order! return H * _Ry2eV, S def read_self_energy(self): r""" Read the currently reached bulk self-energy The returned self-energy is: .. math:: \boldsymbol \Sigma_{\mathrm{bulk}}(E) = \mathbf S E - \mathbf H - \boldsymbol \Sigma(E) Returns ------- complex128 : Self-energy matrix """ self._step_counter('read_self_energy', read=True) SE = _siesta.read_gf_se(self._iu, self._no_u, self._iE) _bin_check(self, 'read_self_energy', 'could not read self-energy.') # we don't convert to C order! return SE * _Ry2eV def HkSk(self, k=(0, 0, 0), spin=0): """ Retrieve H and S for the given k-point Parameters ---------- k : int or array_like of float, optional k-point to read the corresponding Hamiltonian and overlap matrices for. If a specific k-point is passed `kindex` will be used to find the corresponding index. spin : int, optional spin-index for the Hamiltonian and overlap matrices """ if not self._is_open(): self.read_header() # find k-index that is requested ik = self.kindex(k) _siesta.read_gf_find(self._iu, self._nspin, self._nk, self._nE, self._state, self._ispin, self._ik, self._iE, self._is_read, 0, spin, ik, 0) _bin_check(self, 'HkSk', 'could not find Hamiltonian and overlap matrix.') self._state = 0 self._ispin = spin self._ik = ik self._iE = 0 self._is_read = 0 # signal this is to be read return self.read_hamiltonian() def self_energy(self, E, k=0, spin=0): """ Retrieve self-energy for a given energy-point and k-point Parameters ---------- E : int or float energy to retrieve self-energy at k : int or array_like of float, optional k-point to retrieve k-point at spin : int, optional spin-index to retrieve self-energy at """ if not self._is_open(): self.read_header() ik = self.kindex(k) iE = self.Eindex(E) _siesta.read_gf_find(self._iu, self._nspin, self._nk, self._nE, self._state, self._ispin, self._ik, self._iE, self._is_read, 1, spin, ik, iE) _bin_check(self, 'self_energy', 'could not find requested self-energy.') self._state = 1 self._ispin = spin self._ik = ik self._iE = iE self._is_read = 0 # signal this is to be read return self.read_self_energy() def write_header(self, bz, E, mu=0., obj=None): """ Write to the binary file the header of the file Parameters ---------- bz : BrillouinZone contains the k-points, the weights and possibly the parent Hamiltonian (if `obj` is None)s E : array_like of cmplx or float the energy points. If `obj` is an instance of `SelfEnergy` where an associated ``eta`` is defined then `E` may be float, otherwise it *has* to be a complex array. mu : float, optional chemical potential in the file obj : ..., optional an object that contains the Hamiltonian definitions, defaults to ``bz.parent`` """ if obj is None: obj = bz.parent nspin = len(obj.spin) cell = obj.geometry.sc.cell na_u = obj.geometry.na no_u = obj.geometry.no xa = obj.geometry.xyz # The lasto in siesta requires lasto(0) == 0 # and secondly, the Python index to fortran # index makes firsto behave like fortran lasto lasto = obj.geometry.firsto bloch = _a.onesi(3) mu = mu NE = len(E) if E.dtype not in [np.complex64, np.complex128]: E = E + 1j * obj.eta Nk = len(bz) k = bz.k w = bz.weight sizes = { 'na_used': na_u, 'nkpt': Nk, 'ne': NE, } self._nspin = nspin self._E = E self._k = np.copy(k) self._nE = len(E) self._nk = len(k) if self._nspin > 2: self._no_u = no_u * 2 else: self._no_u = no_u # Ensure it is open (in write mode) self._close_gf() self._open_gf('w') # Now write to it... self._step_counter('write_header', header=True, read=True) # see onlysSileSiesta.read_supercell for .T _siesta.write_gf_header(self._iu, nspin, _toF(cell.T, np.float64, 1. / _Bohr2Ang), na_u, no_u, no_u, _toF(xa.T, np.float64, 1. / _Bohr2Ang), lasto, bloch, 0, mu * _eV2Ry, _toF(k.T, np.float64), w, self._E / self._E_Ry2eV, **sizes) _bin_check(self, 'write_header', 'could not write header information.') def write_hamiltonian(self, H, S=None): """ Write the current energy, k-point and H and S to the file Parameters ---------- H : matrix a square matrix corresponding to the Hamiltonian S : matrix, optional a square matrix corresponding to the overlap, for efficiency reasons it may be advantageous to specify this argument for orthogonal cells. """ no = len(H) if S is None: S = np.eye(no, dtype=np.complex128, order='F') self._step_counter('write_hamiltonian', HS=True, read=True) _siesta.write_gf_hs(self._iu, self._ik, self._E[self._iE] / self._E_Ry2eV, _toF(H, np.complex128, _eV2Ry), _toF(S, np.complex128), no_u=no) _bin_check(self, 'write_hamiltonian', 'could not write Hamiltonian and overlap matrices.') def write_self_energy(self, SE): r""" Write the current self energy, k-point and H and S to the file The self-energy must correspond to the *bulk* self-energy .. math:: \boldsymbol \Sigma_{\mathrm{bulk}}(E) = \mathbf S E - \mathbf H - \boldsymbol \Sigma(E) Parameters ---------- SE : matrix a square matrix corresponding to the self-energy (Green function) """ no = len(SE) self._step_counter('write_self_energy', read=True) _siesta.write_gf_se(self._iu, self._ik, self._iE, self._E[self._iE] / self._E_Ry2eV, _toF(SE, np.complex128, _eV2Ry), no_u=no) _bin_check(self, 'write_self_energy', 'could not write self-energy.') def __len__(self): return self._nE * self._nk * self._nspin def __iter__(self): """ Iterate through the energies and k-points that this GF file is associated with Yields ------ bool, list of float, float """ # get everything e = self._E if self._nspin in [1, 2]: for ispin in range(self._nspin): for k in self._k: yield ispin, True, k, e[0] for E in e[1:]: yield ispin, False, k, E else: for k in self._k: yield True, k, e[0] for E in e[1:]: yield False, k, E # We will automatically close once we hit the end self._close_gf() def _type(name, obj, dic=None): if dic is None: dic = {} # Always pass the docstring if not '__doc__' in dic: try: dic['__doc__'] = obj.__doc__.replace(obj.__name__, name) except: pass return type(name, (obj, ), dic) # Faster than class ... \ pass tsgfSileSiesta = _type("tsgfSileSiesta", _gfSileSiesta) gridSileSiesta = _type("gridSileSiesta", _gridSileSiesta, {'grid_unit': 1.}) if found_module: add_sile('TSHS', tshsSileSiesta) add_sile('onlyS', onlysSileSiesta) add_sile('TSDE', tsdeSileSiesta) add_sile('DM', dmSileSiesta) add_sile('HSX', hsxSileSiesta) add_sile('TSGF', tsgfSileSiesta) add_sile('WFSX', wfsxSileSiesta) # These have unit-conversions add_sile('RHO', _type("rhoSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('LDOS', _type("ldosSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('RHOINIT', _type("rhoinitSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('RHOXC', _type("rhoxcSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('DRHO', _type("drhoSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('BADER', _type("baderSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('IOCH', _type("iorhoSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('TOCH', _type("totalrhoSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) # The following two files *require* that # STM.DensityUnits Ele/bohr**3 # which I can't check! # They are however the default add_sile('STS', _type("stsSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('STM.LDOS', _type("stmldosSileSiesta", _gridSileSiesta, {'grid_unit': 1./_Bohr2Ang ** 3})) add_sile('VH', _type("hartreeSileSiesta", _gridSileSiesta, {'grid_unit': _Ry2eV})) add_sile('VNA', _type("neutralatomhartreeSileSiesta", _gridSileSiesta, {'grid_unit': _Ry2eV})) add_sile('VT', _type("totalhartreeSileSiesta", _gridSileSiesta, {'grid_unit': _Ry2eV}))
Over at Salon, I argue that libertarians who insist we do not have true “capitalism” today — and believe that’s a bad thing — should then logically support the radical redistribution of wealth, as money not made on a “free market” is money made in contravention of their own libertarian ethics. Go ahead and give it a read. It’s more fun than it sounds. This entry was posted in Capitalism, Libertarianism and tagged Libertarianism. Bookmark the permalink. 3 Responses to No capitalism? No wealth. You missed a major component to the anti-Capitalist argument in your ill-conceived Salon article. Capitalism uses the pooling of money to voluntarily purchase the labor and goods from workers in exchange for their access to efficiency and resources. This voluntary exchange between employee and employer is done with capital, not threat of force with deadly weapons. The government uses force, the law and it’s armed enforcers, to take your capital and pool it against your will. This is theft of your labor, without a voluntary agreement. As an adult, you should be smart enough to know, that when you write a poorly directed opinion piece, that Salon voluntarily gives you money for your labor. Unless I am unaware that the Editor in Chief has threatened to jail you for not producing this writing, and may terminate your life if you resist imprisonment. Looks like SOMEbody doesn’t understand that starvation is a deadly weapon. Perhaps the commenter thinks hunger is just something you solve with a quick snack. Also… I wouldn’t be so quick to assume that writers get paid for posting online. If we were going to redistribute all the world’s mixed-economy wealth, how would we decide who is more deserving than others? Surely dividing the spoils equally might seem fair, but would it be worth it if we were destroying real value in the process? Wouldn’t that actually make everyone’s lives worse off?
XSeq DEFINITIONS ::= BEGIN -- F.2.10.2 -- Use a sequence type to model a collection of variables whose -- types are the same, -- whose number is known and modest, and whose order is significant, -- provided that the -- makeup of the collection is unlikely to change from one version -- of the protocol to the next. -- EXAMPLE NamesOfOfficers ::= SEQUENCE { president VisibleString, vicePresident VisibleString, secretary VisibleString} acmeCorp NamesOfOfficers ::= { president "Jane Doe", vicePresident "John Doe", secretary "Joe Doe"} -- F.2.10.3 -- Use a sequence type to model a collection of variables whose types differ, -- whose number is known and modest, and whose order is significant, -- provided that -- the makeup of the collection is unlikely to change from one version -- of the protocol to the next. -- EXAMPLE Credentials ::= SEQUENCE { userName VisibleString, password VisibleString, accountNumber INTEGER} -- Empty SEQUENCE stupid but just for test BasicCallCategories ::= SEQUENCE { ... -- So far, no specific categories identified } END
Community groups have had another boost after the latest round of funding from Warwick Town Council. The group hands out funding through three separate pots - and have already started putting the cash to good use in the community. Community Grant pays out up to £1,500 per group - and has already helped provide Warwick Sea Scouts with two new dinghies. The Community Support fund offers grants of between £1,500 and £5,000 to groups in need of help. And has this year allocated £1,899 to Playbox Theatre and £3,000 to Newburgh School to pay for an outdoor performance area and seating at the school. The final pot of Warwick Events grants offers sums of up to £5,000 with £3,500 already this year agreed to Warwick Folk Festival. The pot has also paid £3,000 to Warwick Words Festival which will run in October and with a theme of Warwick History and the life of charity founder, Thomas Oken. To apply for the next round of bids, or find out more on who is eligible, visit (http://www.warwicktowncouncil.gov.uk|warwicktowncouncil.co.uk} or contact the town clerk’s office on 411694.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('Articulo', '0005_articulo_proveedor_proveedor'), ] operations = [ migrations.AlterField( model_name='articulo_clase', name='clase', field=models.CharField(unique=True, max_length=100), preserve_default=True, ), migrations.AlterField( model_name='categoria_articulo', name='categoria', field=models.CharField(unique=True, max_length=100), preserve_default=True, ), migrations.AlterField( model_name='tipo_costo', name='tipo_costo', field=models.CharField(unique=True, max_length=100), preserve_default=True, ), migrations.AlterField( model_name='unidad', name='unidad', field=models.CharField(unique=True, max_length=100), preserve_default=True, ), ]
After Anna by Lisa Scottoline is a highly recommended domestic thriller. Maggie Ippoliti is overjoyed to receive a call from her daughter, Anna Desroches, since she hadn't seen or heard from her daughter since she was six months old. After Anna's birth Maggie was suffering from postpartum psychosis. Anna's father Florian Desroches divorced Maggie and immediately moved overseas, cutting Maggie off from all access to her daughter. Anna had also written to her mother saying she wanted nothing to do with her. Now Anna, 17, is attending high school at an exclusive boarding school in the States. Her father, his second wife, and their two children were all killed in a plane crash, leaving Anna alone. She is now reaching out to Maggie, trying to form a relationship and family. Maggie's husband, pediatric allergist Noah Alderman, is supportive and excited for Maggie. She has been a wonderful stepmother to his son, 10-year-old Caleb, who has apraxia. After Anna opens with Noah on trial for Anna's murder and awaiting sentencing, so we know right from the start that this isn't going to be the story of a happy family reunion. The chapters alternate back and forth between when Maggie first received the phone call from Anna and to Noah's trial for murdering Anna. To complicate matters, Maggie's narrative is told in chronological order and move forward in time, while Noah's chapters are told in reverse order and move backward in time. It is also clear at the beginning that Anna is not to be trusted, but that Maggie is too ecstatic to allow any doubts to creep in to the burgeoning relationship. The characters are well-developed. I will admit that at the outset Maggie's over-exuberant, excited and positive exclamations over Anna's sudden phone call and appearance turned me off. Sure, I get it, be happy, but don't lose all sense of caution and discernment. Her actions didn't seem plausible to me. Yes, encourage the relationship, but goodness, use your head, take it slow, and tell Anna you want a relationship with her, but you all need to take the time to get to know each other. Or, if Maggie couldn't do this, Noah should have encouraged her to take some caution. Scottoline is an accomplished author, so she handles with aplomb the complications of her novel and the expected twists and turns leading up to the meeting of the two timelines and on to the conclusion. After Anna is an entertaining story with complications, cliffhangers, and courtroom drama. There are a few plot holes and the ending is a bit of a stretch, but it will entertain and hold your attention throughout.
# -*- coding: iso-8859-1 -*- # (c) 2006 Stephan Reichholf # This Software is Free, use it where you want, when you want for whatever you want and modify it if you want but don't remove my copyright! from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox from Components.ActionMap import NumberActionMap from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuList from Plugins.Plugin import PluginDescriptor from Components.config import config from Tools.Directories import resolveFilename, SCOPE_PLUGINS from os import path, walk from enigma import eEnv class SkinSelector(Screen): # for i18n: # _("Choose your Skin") skinlist = [] root = eEnv.resolve("${datadir}/enigma2/") def __init__(self, session, args = None): Screen.__init__(self, session) Screen.setTitle(self, _("Skin Setup")) self.skinlist = [] self.previewPath = "" path.walk(self.root, self.find, "") self["key_red"] = StaticText(_("Close")) self["introduction"] = StaticText(_("Press OK to activate the selected skin.")) self["SkinList"] = MenuList(self.skinlist) self["Preview"] = Pixmap() self.skinlist.sort() self["actions"] = NumberActionMap(["WizardActions", "DirectionActions", "InputActions", "EPGSelectActions"], { "ok": self.ok, "back": self.close, "red": self.close, "up": self.up, "down": self.down, "left": self.left, "right": self.right, "info": self.info, }, -1) self.onLayoutFinish.append(self.layoutFinished) def layoutFinished(self): tmp = config.skin.primary_skin.value.find('/skin.xml') if tmp != -1: tmp = config.skin.primary_skin.value[:tmp] idx = 0 for skin in self.skinlist: if skin == tmp: break idx += 1 if idx < len(self.skinlist): self["SkinList"].moveToIndex(idx) self.loadPreview() def up(self): self["SkinList"].up() self.loadPreview() def down(self): self["SkinList"].down() self.loadPreview() def left(self): self["SkinList"].pageUp() self.loadPreview() def right(self): self["SkinList"].pageDown() self.loadPreview() def info(self): aboutbox = self.session.open(MessageBox,_("Enigma2 Skinselector\n\nIf you experience any problems please contact\nstephan@reichholf.net\n\n\xA9 2006 - Stephan Reichholf"), MessageBox.TYPE_INFO) aboutbox.setTitle(_("About...")) def find(self, arg, dirname, names): for x in names: if x == "skin.xml": if dirname <> self.root: subdir = dirname[19:] self.skinlist.append(subdir) else: subdir = "Default Skin" self.skinlist.append(subdir) def ok(self): if self["SkinList"].getCurrent() == "Default Skin": skinfile = "skin.xml" else: skinfile = self["SkinList"].getCurrent()+"/skin.xml" print "Skinselector: Selected Skin: "+self.root+skinfile config.skin.primary_skin.value = skinfile config.skin.primary_skin.save() restartbox = self.session.openWithCallback(self.restartGUI,MessageBox,_("GUI needs a restart to apply a new skin\nDo you want to Restart the GUI now?"), MessageBox.TYPE_YESNO) restartbox.setTitle(_("Restart GUI now?")) def loadPreview(self): if self["SkinList"].getCurrent() == "Default Skin": pngpath = self.root+"/prev.png" else: pngpath = self.root+self["SkinList"].getCurrent()+"/prev.png" if not path.exists(pngpath): pngpath = "/usr/share/enigma2/skin_default/noprev.png" if self.previewPath != pngpath: self.previewPath = pngpath self["Preview"].instance.setPixmapFromFile(self.previewPath) def restartGUI(self, answer): if answer is True: self.session.open(TryQuitMainloop, 3)
The module helps admin and users to export the content of site objects in specific formats. The supported formats are defined by drivers and managed by administrator. – Template of text data (if required). – A method that returns the objects matching the search criteria with required fields. Depending on settings in admin panel, export is carried out by cronjob or upon request. There are two lists: export formats and selections. An export format includes name, status, link to details, options to edit settings and fields. Settings are available if a driver supports an option to define additional settings. Fields can be edited if a driver supports an option to add fields to export. You can add or remove fields (name and type). There are the following field types: text, integer, file and URL. A selection includes export name, driver name, object name, status, date of creation and actions (create, edit, delete or export a selection). There are three tabs on pages of creating or editing a selection: general settings, custom fields and selection criteria. – Type of export (browser or file). Type of export (upon request, on a certain date or by cronjob). Allow users to change the criteria (you will see a link to the form where users can change criteria). The other two tabs are available after general settings are saved. ‘Custom fields’ tab contains a list of established connections between driver elements and fields. Elements without established connections have two selects: available elements and fields available for the chosen element. ‘Selection criteria’ tab contains a form provided by the object module. Saved criteria are used for selection generation. If the selection is enabled, the script checks the settings, and displays an error message if there are any issues. Choose ‘Browser’ type of export and enable the selection to provide an export option for site users. Depending on whether you check ‘Allow users to change the criteria’ or not, a user will get a link to a form with option to change criteria or an export file in the necessary format. seo — seo url generation. The module provides a link used to export data. Gets an exported selection. The method runs the process of data generation according to the specified selection. The result is a file with data in a certain format or an archive with photos and other files.
import heapq class MedianFinder: def __init__(self): self.small = [] self.large = [] def addNum(self, num): num = float(num) if len(self.small) == 0: heapq.heappush(self.small, -num) return if num < -self.small[0]: heapq.heappush(self.small, -num) else: heapq.heappush(self.large, num) if len(self.small) - len(self.large) == 2: heapq.heappush(self.large, -heapq.heappop(self.small)) elif len(self.large) - len(self.small) == 2: heapq.heappush(self.small, -heapq.heappop(self.large)) def findMedian(self): if len(self.small) == len(self.large): return (-self.small[0] + self.large[0]) / 2.0 else: return -self.small[0] if len(self.small) > len(self.large) else self.large[0] # Your MedianFinder object will be instantiated and called as such: # mf = MedianFinder() # mf.addNum(1) # mf.findMedian()
The Dairy Manufacturers Sustainability Council (DMSC) is an industry-recognised body that assists company members to improve their environmental sustainability. This is achieved by enabling knowledge-sharing on best practice, and by publicly reporting on collective outcomes. The Dairy Manufacturers Sustainability Council includes representatives of the major dairy processing companies and its primary roles are to work towards achieving environmental sustainability targets, influence the transference of key skills and knowledge into the industry, and guide research activities. Sustainability is vital to the future competitiveness of the Australian dairy industry. For this reason, the industry is committed to on-going improvements, across the entire supply chain.
# python standard library import re from StringIO import StringIO # apetools Libraries from localconnection import LocalNixConnection from localconnection import OutputError from localconnection import EOF from apetools.commons import errors from apetools.commons import readoutput from apetools.commons import enumerations from sshconnection import SSHConnection ConnectionError = errors.ConnectionError CommandError = errors.CommandError ConnectionWarning = errors.ConnectionWarning ValidatingOutput = readoutput.ValidatingOutput OperatingSystem = enumerations.OperatingSystem # Error messages DEVICE_NOT_FOUND = "error: device not found" NOT_CONNECTED = "No Android Device Detected by ADB (USB) Connection" DEVICE_NOT_ROOTED = "adbd cannot run as root in production builds" NOT_ROOTED = "This Android device isn't rootable." NOT_FOUND = "device not found" #regular expressions ALPHA = r'\w' ONE_OR_MORE = "+" ZERO_OR_MORE = "*" SPACE = r"\s" SPACES = SPACE + ONE_OR_MORE NAMED = "(?P<{n}>{p})" COMMAND_GROUP = "command" ANYTHING = r'.' EVERYTHING = ANYTHING + ZERO_OR_MORE class ADBConnectionError(ConnectionError): """ Raise if there is a problem with the ADB Connection """ # end class ADBConnectionError class ADBCommandError(CommandError): """ Raise if there is a problem with an ADB command """ # end class ADBCommandError class ADBConnectionWarning(ConnectionWarning): """ A warning to raise if something non-fatal but bad happens """ # end class ADBConnectionWarning class ADBConnection(LocalNixConnection): """ An ADB Connection sends commands to the Android Debug Bridge """ def __init__(self, serial_number=None,*args, **kwargs): """ :param: - `serial_number`: An optional serial number to specify the device. """ super(ADBConnection, self).__init__(*args, **kwargs) self._logger = None self.command_prefix = "adb" if serial_number is not None: self.command_prefix += " -s " + serial_number self._operating_system = None return @property def operating_system(self): """ :return: enumeration for android """ if self._operating_system is None: self._operating_system = OperatingSystem.android return self._operating_system def _rpc(self, command, arguments='', timeout=None): """ Overrides the LocalConnection._rpc to check for errors """ output = self._main(command, arguments, timeout) return OutputError(ValidatingOutput(lines=output.output, validate=self.check_errors), StringIO(EOF)) def check_errors(self, line): """ This is here so that children can override it. :param: - `output`: OutputError tuple """ self.check_base_errors(line) return def check_base_errors(self, line): """ :param: - `line`: A string of output :raise: ADBConnectionError if connection fails :raise: ADBConnectionWarning if the Android isn't running as root """ if DEVICE_NOT_FOUND in line: self.logger.debug(line) raise ConnectionError("The Android wasn't found: {0}".format(line)) elif DEVICE_NOT_ROOTED in line: self.logger.debug(line) raise ConnectionWarning("The Android isn't root: {0}".format(line)) return def __str__(self): if self.serial_number is not None: return "ADBLocal: {0}".format(self.serial_number) return "ADBLocal" # end class ADBConnection class ADBBlockingConnection(ADBConnection): """ Like the ADBConnection but waits for a device to come online """ def __init__(self, *args, **kwargs): super(ADBBlockingConnection, self).__init__(*args, **kwargs) self.command_prefix += " wait-for-device" return # end class ADBConnection class ADBShellConnection(ADBConnection): """ An ADBShellConnection connects to the adb shell. If you use a timeout parameter on method calls, the output acts line-buffered. If you leave the timeout as None, it acts file-buffered """ def __init__(self, *args, **kwargs): super(ADBShellConnection, self).__init__(*args, **kwargs) self.command_prefix += " shell" self._unknown_command = None self._logger = None return @property def unknown_command(self): """ A regular expression to match unknown command errors. Uses: :rtype: SRE_Pattern :return: regex to match unknown_command error. """ if self._unknown_command is None: self._unknown_command = re.compile(SPACES.join([NAMED.format(n=COMMAND_GROUP, p=ALPHA + ONE_OR_MORE) + "/sh:", EVERYTHING, 'not', 'found'])) return self._unknown_command def _procedure_call(self, command, arguments='', path='', timeout=None): output = self._main(command, arguments, path, timeout) return OutputError(ValidatingOutput(lines=output.output, validate=self.check_errors), output.error) def check_errors(self, line): """ Checks the line to see if the line has an unknow command error """ self.check_base_errors(line) if self.unknown_command.search(line): raise ConnectionError("Unknown ADB Shell Command: {0}".format(line)) return # end class ADBShellConnection class ADBShellBlockingConnection(ADBShellConnection): def __init__(self, *args, **kwargs): super(ADBShellBlockingConnection, self).__init__(*args, **kwargs) self.command_prefix = "adb wait-for-device shell" self._unknown_command = None return class ADBSSHConnection(SSHConnection): """ An ADB Connection sends commands to the Android Debug Bridge """ def __init__(self, serial_number=None,*args, **kwargs): """ :param: - `serial_number`: An optional serial number to specify the device. """ super(ADBSSHConnection, self).__init__(*args, **kwargs) self._logger = None self.command_prefix = "adb" if serial_number is not None: self.command_prefix += " -s " + serial_number self.operating_system = OperatingSystem.android return def _procedure_call(self, command, arguments="", timeout=10): """ Overrides the SSHConnection._procedure_call to check for errors """ command = self.add_path(command) output = self._main(command, arguments, timeout) return OutputError(ValidatingOutput(lines=output.output, validate=self.check_errors), output.error) def check_errors(self, line): """ This is here so that children can override it. :param: - `line`: a line of output """ self._check_errors(line) return def _check_errors(self, line): """ Checks connection-related errors :raise: ADBConnectionError if the device isn't detected :raise: ADBConnectionWarning if the device isn't rooted """ if DEVICE_NOT_FOUND in line: self.logger.error(line) raise ADBConnectionError("Android Not Detected: {0}".format(line)) elif DEVICE_NOT_ROOTED in line: self.logger.warning(line) raise ADBConnectionWarning("Anroid Not Rooted: {0}".format(line)) return # end class ADBSSHConnection class ADBShellSSHConnection(ADBSSHConnection): """ A class to talk to the shell, note the adb-server """ def __init__(self, *args, **kwargs): """ :param: (see the ADBSSHConnection) """ super(ADBShellSSHConnection, self).__init__(*args, **kwargs) self.command_prefix += " shell " self._unknown_command = None return @property def unknown_command(self): """ A regular expression to match unknown command errors. Uses: '\w+/sh: *.* *not *found' :rtype: SRE_Pattern :return: regex to match unknown_command error. """ if self._unknown_command is None: self._unknown_command = re.compile(SPACES.join([NAMED.format(n=COMMAND_GROUP, p=ALPHA + ONE_OR_MORE) + "/sh:", EVERYTHING, 'not', 'found'])) return self._unknown_command def check_errors(self, line): """ :line: line of standard output :raise: ADBCommandError if the command issued wasn't recognized """ self._check_errors(line) if self.unknown_command.search(line): raise ADBCommandError(line) return # end class ADBSHellSSHConnection if __name__ == "__main__": from apetools.main import watcher import sys watcher() adb = ADBShellSSHConnection(hostname="lancet", username="allion") output, error= adb.iw('wlan0 link', timeout=1) for line in output: sys.stdout.write(line)
It is our mission at Philadelphia Dermatology Center to provide the best treatment and customer services to both our local and out-of-town patients. At our dermatology center, our board certified dermatologists and team of licensed medical aestheticians provide non-surgical and minimally invasive medical and cosmetic dermatologic treatments. We encourage you to visit our team of highly experience physicians at our Philadelphia office. Below you will find driving directions from our surrounding cities. Take exit toward PA 611 and merge onto N 15th St. Turn right onto Latimer St. then another right into S. 16th St. Merge onto N 15th St and turn right onto Latimer St. Head SouthEast on Wayne Ave and turn right on W Berkley St. Turn right onto N 15th St. then right onto Latimer St. Head SouthEast on E County line Rd and turn left on Ardmore Ave. Turn right on Cardinal Ave, then a left on Wynnefiled Ave. Make a right on Belmont Ave, then a left onto Montgomery Dr. Turn right on N 15th St, then turn right on Latimer St. Make a left onto Locust St. Our office will be on the right. Please feel free to use this form to ask our dermatologists questions about this treatment.
import tkinter as tk = "hello world\n(click me)" self.hi.there["command"] = self.say_hi self.hi_thereclass Application(tk.Frame): def __init__ (self, master-none); super().__init__(master) self.pack() self.create_widgets() def create_widgets(self); self.hi_there = tk.Button(self) self.hi_there["text"] = "hello world\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy) self.quit.pack(side="bottom") def say_hi(self): print("hi there, evertone !") root = tk.Tk() app = Application(master=root) app.mainloop() """docstring for Application"tk.Framef def __init__ (self, master-none); super().__init__(master) self.pack() self.create_widgets() def create_widgets(self); self.hi_there = tk.Button(self) self.hi.there["text"]__ini = "hello world\n(click me)" self.hi.there["command"] = self.say_hi self.hi_theret__(self, arg): super(Application,tk.Frame._ def __init__ (self, master-none); super().__init__(master) self.pack() self.create_widgets() def create_widgets(self); self.hi_there = tk.Button(self) self.hi.there["text"]_init__() self.arg = arg
STRUMIS and Tekla India collaborate to present a Steel Seminar in October at three venues - Chennai, Delhi and Mumbai to showcase true Interoperability providing you with optimum efficiencies in steel fabrication. A unique opportunity to witness a live demonstration making your Steel Fabrication business more efficient and successful by using the latest BIM technology in steel detailing and steel management information software solutions to optimise efficiencies in your plant and deliver your steel projects on time and most important of all in budget. By attending these presentations you will see just how STRUMIS and Tekla, the global leading structural software solutions, can integrate together to provide you with the competitive edge required to succeed in reducing your costs and maximising your profits! Stay ahead of your competition and attend one of these seminars where you will see just how STRUMIS and Tekla can communicate to provide you with the competitive edge.
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class HicPro(MakefilePackage): """HiC-Pro is a package designed to process Hi-C data, from raw fastq files (paired-end Illumina data) to the normalized contact maps""" homepage = "https://github.com/nservant/HiC-Pro" url = "https://github.com/nservant/HiC-Pro/archive/v2.10.0.tar.gz" version('2.10.0', '6ae2213dcc984b722d1a1f65fcbb21a2') depends_on('bowtie2') depends_on('samtools') depends_on('python@2.7:2.8') depends_on('r') depends_on('py-numpy', type=('build', 'run')) depends_on('py-scipy', type=('build', 'run')) depends_on('py-pysam', type=('build', 'run')) depends_on('py-bx-python', type=('build', 'run')) depends_on('r-rcolorbrewer', type=('build', 'run')) depends_on('r-ggplot2', type=('build', 'run')) def edit(self, spec, prefix): config = FileFilter('config-install.txt') config.filter('PREFIX =.*', 'PREFIX = {0}'.format(prefix)) config.filter('BOWTIE2 PATH =.*', 'BOWTIE2_PATH = {0}'.format(spec['bowtie2'].prefix)) config.filter('SAMTOOLS_PATH =.*', 'SAMTOOLS_PATH = {0}'.format(spec['samtools'].prefix)) config.filter('R_PATH =.*', 'R_RPTH ={0}'.format(spec['r'].prefix)) config.filter('PYTHON_PATH =.*', 'PYTHON_RPTH ={0}'.format(spec['python'].prefix)) def build(self, spec, preifx): make('-f', './scripts/install/Makefile', 'CONFIG_SYS=./config-install.txt') make('mapbuilder') make('readstrimming') make('iced') def install(sefl, spec, prefix): # Patch INSTALLPATH in config-system.txt config = FileFilter('config-system.txt') config.filter('/HiC-Pro_2.10.0', '') # Install install('config-hicpro.txt', prefix) install('config-install.txt', prefix) install('config-system.txt', prefix) install_tree('bin', prefix.bin) install_tree('annotation', prefix.annotation) install_tree('doc', prefix.doc) install_tree('scripts', prefix.scripts) install_tree('test-op', join_path(prefix, 'test-op'))
Gambling enterprises will be the locations where games were actually wanted by a great deal of large amount of cash and money are done with colors and interest. You can expect to identify the most efficient discounts here as a way to obtain the expenses. You can expect to definitely track down the prospects that happen to be extraordinary to have the rewards which are amazing. Gambling will be the outstanding internet site which allows you to have fun playing the amazing game. Create an account your company name here in this website that will undoubtedly provide you an opportunity as well as you need to go into in this site. You will discover the expertise concerning the gambling enterprises which use benefit offers. This web site looks after the in the online casinos. You have to wager in a number of suits of the charges firm along with you may have the ability to win the fascinating funds dollars buster is your unique sleep which may have basically acquired the government bodies affiliation along with you are going to find the betting deals within this site. You will certainly advise about procedures as well as the sell improvement to dilemma just before you internet site right into the play. The ability to devote below on your team continues to be given by you and you will definitely find the very best deals. You might also need given. It is actually to the customer’s efficiency that this website is made authentic. You could play for your reward that is the supply which is excellent. In this article you will track down the possibility. Or else you will undoubtedly receive cost-totally free or cash money dice to experience with the casino Judi online. It is actually for your function to tempt the beginner therefore as well as the company-new comers to get in this article in the region of casino and commence an account with provide. You may certainly be offered possibility to have fun with the gambling online via this internet site for jackpot. For which you could get previous your presumption. This game is special and in addition requirements in addition to their ideas are accountable for the buyer. These are typically responsible for those people’s comfort and ease. You are going to certainly obtain offers within the casino web sites. You will certainly be mindful with regards to the game guidelines domino online types with this web site. You will discover the chance to look at your have a great time and discover the economic expenditure in a substantial amount of and also the type of income personal loan.
import atexit import Queue import StringIO import sys import threading import time import traceback _profiler = None class Profiler(threading.Thread): def __init__(self, duration, interval, filename): super(Profiler, self).__init__() self._duration = duration self._interval = interval self._filename = filename self._queue = Queue.Queue() self._nodes = {} self._links = {} def run(self): start = time.time() while time.time() < start+self._duration: try: self._queue.get(timeout=self._interval) break except: pass stacks = sys._current_frames().values() for stack in stacks: self.process_stack(stack) print >> open(self._filename, 'w'), repr((self._nodes, self._links)) #print >> open(self._filename, 'w'), repr(self._records) global _profiler _profiler = None def abort(self): self._queue.put(True) self.join() def process_stack(self, stack): output = StringIO.StringIO() parent = None for filename, lineno, name, line in traceback.extract_stack(stack): node = (filename, name) node_record = self._nodes.get(node) if node_record is None: node_record = { 'count': 1 } self._nodes[node] = node_record else: node_record['count'] += 1 if parent: link = (parent, node) link_record = self._links.get(link) if link_record is None: link_record = { 'count': 1 } self._links[link] = link_record else: link_record['count'] += 1 parent = node """ children = None for filename, lineno, name, line in traceback.extract_stack(stack): #key = (filename, lineno, name) key = (filename, name) if children is None: record = self._records.get(key) if record is None: record = { 'count': 1, 'children': {} } self._records[key] = record else: record['count'] += 1 children = record['children'] elif key in children: record = children[key] record['count'] += 1 children = record['children'] else: record = { 'count': 1, 'children': {} } children[key] = record children = record['children'] """ def _abort(): if _profiler: _profiler.abort() atexit.register(_abort) class ProfilerShell(object): name = 'profiler' def activate(self, config_object): self.__config_object = config_object enabled = False if self.__config_object.has_option('profiler', 'enabled'): value = self.__config_object.get('profiler', 'enabled') enabled = value.lower() in ('1', 'on', 'yes', 'true') if not enabled: print >> self.stdout, 'Sorry, the profiler plugin is disabled.' return True def do_start(self, line): global _profiler if _profiler is None: _profiler = Profiler(10.0*60.0, 0.105, '/tmp/profile.dat') #_profiler = Profiler(20.0, 1.0, '/tmp/profile.dat') _profiler.start() def do_abort(self, line): global _profiler if _profiler is None: _profiler.abort()
We like to eat tacos. A lot of tacos. It started as a love for the flavor profile and became one of our go-to quick dinners. All it takes is a pot of rice, some meat (thinly sliced leftover pork chops make great tacos!) or shrimp, and some sautéed veggies. Add some salsa, avocado (or if you have some time, some guacamole), and some sour cream and you’ve got a complete meal. In the past few months, I’ve sought out ways to bring new dimension to our tacos while ensuring that they remain a quick meal. My husband likes pinto beans, and I didn’t really “get it” until after I made our own beans. I even find myself actually craving these beans. Well-seasoned and cooked in Catullo Prime Meats‘ flavorful garlic bacon until creamy, these beans bring another layer of flavor to any Mexican dish. Aside from the fact that these are annoyingly delicious, I really love these beans is that they freeze very well. One batch makes about 5 or 6 cups of beans, so I always portion them (with some of the extra broth) into freezer bags and freeze them. When I plan on making tacos, I’ll throw a bag in the fridge in the morning to start defrosting and can finish thawing and heat them in the microwave later. This recipe takes a couple hours but don’t require much attention, and are definitely worth it for the flavor, yield, and convenience. Add pinto beans and stir to coat. Add water to cover by two inches and bring to a boil. Reduce to a simmer and cook, stirring occasionally, for 2-2 1/2 hours. Salt as you cook and season. Soak pinto beans by placing in a pot or container and covering by at least two inches of water. Soak for at least 6 hours. I usually soak mine overnight or while I’m gone at work during the day, so mine usually soak 8-10 hours. Drain pinto beans. In stock pot, cook bacon over medium heat until crisp (sometimes I add a little oil to keep my bacon from burning). Once crisp, add drained pinto beans and stir to coat. I stir them for a few minutes, allowing them to soak in the flavor of the bacon, then add water, until they’re covered by two inches. Bring beans to boil. Salt generously (I figured I use about a half teaspoon each time I salt the beans). Lower to a simmer and cook for two and a half hours, stirring occasionally (if your water is soft they may cook faster, so I always start testing beans just under two hours). I try to stir the beans every 20-30 minutes, salting them each time. You can add the seasonings any time throughout the process. Enjoy hot or (because this makes a boat load of beans), once cooled some, portion into containers or freezer bags (adding some of the broth with it to keep them from drying out on reheating) and freeze. You can reheat them in the microwave without losing quality. Previous Previous post: Happy Birthday Luigi! Next Next post: Friday 5: Vacation Day!
# -*- coding: utf-8 -*- # Copyright 2016 Palo Alto Networks, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """FT TAXII tests Unit tests for minemeld.ft.taxii """ import gevent.monkey gevent.monkey.patch_all(thread=False, select=False) import unittest import mock import redis import gevent import greenlet import time import xmltodict import os import libtaxii.constants import re import lz4 import json import minemeld.ft.taxii import minemeld.ft FTNAME = 'testft-%d' % int(time.time()) MYDIR = os.path.dirname(__file__) class MockTaxiiContentBlock(object): def __init__(self, stix_xml): class _Binding(object): def __init__(self, id_): self.binding_id = id_ self.content = stix_xml self.content_binding = _Binding(libtaxii.constants.CB_STIX_XML_111) class MineMeldFTTaxiiTests(unittest.TestCase): @mock.patch.object(gevent, 'Greenlet') def test_taxiiclient_parse(self, glet_mock): config = { 'side_config': 'dummy.yml', 'ca_file': 'dummy.crt' } chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.TaxiiClient(FTNAME, chassis, config) inputs = [] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() testfiles = os.listdir(MYDIR) testfiles = filter( lambda x: x.startswith('test_ft_taxii_stix_package_'), testfiles ) for t in testfiles: with open(os.path.join(MYDIR, t), 'r') as f: sxml = f.read() mo = re.match('test_ft_taxii_stix_package_([A-Za-z0-9]+)_([0-9]+)_.*', t) self.assertNotEqual(mo, None) type_ = mo.group(1) num_indicators = int(mo.group(2)) stix_objects = { 'observables': {}, 'indicators': {}, 'ttps': {} } content_blocks = [ MockTaxiiContentBlock(sxml) ] b._handle_content_blocks( content_blocks, stix_objects ) params = { 'ttps': stix_objects['ttps'], 'observables': stix_objects['observables'] } indicators = [[iid, iv, params] for iid, iv in stix_objects['indicators'].iteritems()] for i in indicators: result = b._process_item(i) self.assertEqual(len(result), num_indicators) if type_ != 'any': for r in result: self.assertEqual(r[1]['type'], type_) b.stop() @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_init(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) self.assertEqual(b.name, FTNAME) self.assertEqual(b.chassis, chassis) self.assertEqual(b.config, config) self.assertItemsEqual(b.inputs, []) self.assertEqual(b.output, None) self.assertEqual(b.redis_skey, FTNAME) self.assertEqual(b.redis_skey_chkp, FTNAME+'.chkp') self.assertEqual(b.redis_skey_value, FTNAME+'.value') @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_update_ip(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) inputs = ['a'] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() # __init__ + get chkp + delete chkp self.assertEqual(len(SR_mock.mock_calls), 6) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = 1 # unicast b.filtered_update( 'a', indicator='1.1.1.1', value={ 'type': 'IPv4', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.uncompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['address_value'], '1.1.1.1') self.assertEqual(cyboxprops['xsi:type'], 'AddressObjectType') SR_mock.reset_mock() # CIDR b.filtered_update( 'a', indicator='1.1.1.0/24', value={ 'type': 'IPv4', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.uncompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['address_value'], '1.1.1.0/24') self.assertEqual(cyboxprops['xsi:type'], 'AddressObjectType') SR_mock.reset_mock() # fake range b.filtered_update( 'a', indicator='1.1.1.1-1.1.1.1', value={ 'type': 'IPv4', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.uncompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['address_value'], '1.1.1.1') self.assertEqual(cyboxprops['xsi:type'], 'AddressObjectType') SR_mock.reset_mock() # fake range 2 b.filtered_update( 'a', indicator='1.1.1.0-1.1.1.31', value={ 'type': 'IPv4', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.uncompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['address_value'], '1.1.1.0/27') self.assertEqual(cyboxprops['xsi:type'], 'AddressObjectType') SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = 1 # real range b.filtered_update( 'a', indicator='1.1.1.0-1.1.1.33', value={ 'type': 'IPv4', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.uncompress(args[2][3:])) indicator = stixdict['indicators'] cyboxprops = indicator[0]['observable']['object']['properties'] self.assertEqual(cyboxprops['address_value'], '1.1.1.0/27') self.assertEqual(cyboxprops['xsi:type'], 'AddressObjectType') cyboxprops = indicator[1]['observable']['object']['properties'] self.assertEqual(cyboxprops['address_value'], '1.1.1.32/31') self.assertEqual(cyboxprops['xsi:type'], 'AddressObjectType') SR_mock.reset_mock() b.stop() @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_update_domain(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) inputs = ['a'] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() # __init__ + get chkp + delete chkp self.assertEqual(len(SR_mock.mock_calls), 6) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = 1 # unicast b.filtered_update( 'a', indicator='example.com', value={ 'type': 'domain', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['value'], 'example.com') self.assertEqual(cyboxprops['type'], 'FQDN') SR_mock.reset_mock() b.stop() @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_update_url(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) inputs = ['a'] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() # __init__ + get chkp + delete chkp self.assertEqual(len(SR_mock.mock_calls), 6) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = 1 # unicast b.filtered_update( 'a', indicator='www.example.com/admin.php', value={ 'type': 'URL', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['type'], 'URL') self.assertEqual(cyboxprops['value'], 'www.example.com/admin.php') SR_mock.reset_mock() b.stop() @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_unicode_url(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) inputs = ['a'] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() # __init__ + get chkp + delete chkp self.assertEqual(len(SR_mock.mock_calls), 6) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = 1 # unicast b.filtered_update( 'a', indicator=u'☃.net/påth', value={ 'type': 'URL', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['type'], 'URL') self.assertEqual(cyboxprops['value'], u'\u2603.net/p\xe5th') SR_mock.reset_mock() b.stop() @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_overflow(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) inputs = ['a'] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() # __init__ + get chkp + delete chkp self.assertEqual(len(SR_mock.mock_calls), 6) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = b.max_entries # unicast b.filtered_update( 'a', indicator=u'☃.net/påth', value={ 'type': 'URL', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': self.fail(msg='hset found') self.assertEqual(b.statistics['drop.overflow'], 1) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = b.max_entries - 1 # unicast b.filtered_update( 'a', indicator=u'☃.net/påth', value={ 'type': 'URL', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['type'], 'URL') self.assertEqual(cyboxprops['value'], u'\u2603.net/p\xe5th') b.stop() @mock.patch.object(redis, 'StrictRedis') @mock.patch.object(gevent, 'Greenlet') def test_datafeed_update_hash(self, glet_mock, SR_mock): config = {} chassis = mock.Mock() chassis.request_sub_channel.return_value = None ochannel = mock.Mock() chassis.request_pub_channel.return_value = ochannel chassis.request_rpc_channel.return_value = None rpcmock = mock.Mock() rpcmock.get.return_value = {'error': None, 'result': 'OK'} chassis.send_rpc.return_value = rpcmock b = minemeld.ft.taxii.DataFeed(FTNAME, chassis, config) inputs = ['a'] output = False b.connect(inputs, output) b.mgmtbus_initialize() b.start() # __init__ + get chkp + delete chkp self.assertEqual(len(SR_mock.mock_calls), 6) SR_mock.reset_mock() SR_mock.return_value.zcard.return_value = 1 # sha1 b.filtered_update( 'a', indicator='a6a5418b4d67d9f3a33cbf184b25ac7f9fa87d33', value={ 'type': 'sha1', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['hashes'][0]['simple_hash_value'], 'a6a5418b4d67d9f3a33cbf184b25ac7f9fa87d33') self.assertEqual(cyboxprops['hashes'][0]['type']['value'], 'SHA1') SR_mock.reset_mock() # md5 b.filtered_update( 'a', indicator='e23fadd6ceef8c618fc1c65191d846fa', value={ 'type': 'md5', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['hashes'][0]['simple_hash_value'], 'e23fadd6ceef8c618fc1c65191d846fa') self.assertEqual(cyboxprops['hashes'][0]['type']['value'], 'MD5') SR_mock.reset_mock() # sha256 b.filtered_update( 'a', indicator='a6cba85bc92e0cff7a450b1d873c0eaa2e9fc96bf472df0247a26bec77bf3ff9', value={ 'type': 'sha256', 'confidence': 100, 'share_level': 'green', 'sources': ['test.1'] } ) for call in SR_mock.mock_calls: name, args, kwargs = call if name == '().pipeline().__enter__().hset': break else: self.fail(msg='hset not found') self.assertEqual(args[2].startswith('lz4'), True) stixdict = json.loads(lz4.decompress(args[2][3:])) indicator = stixdict['indicators'][0] cyboxprops = indicator['observable']['object']['properties'] self.assertEqual(cyboxprops['hashes'][0]['simple_hash_value'], 'a6cba85bc92e0cff7a450b1d873c0eaa2e9fc96bf472df0247a26bec77bf3ff9') self.assertEqual(cyboxprops['hashes'][0]['type']['value'], 'SHA256') SR_mock.reset_mock() b.stop()
This notebook is ready for all of your planning, doodling, and scheming. These make the perfect little thoughtful gift and travel well for all of those inspiring thoughts on the road. 5"x 8"notebook with "Everyday Sketches and Schemes" graphic on front and screen printed in gold ink on dark green linen card stock. 80 blank ivory pages.
#!/usr/bin/env python """ Main entrance point for DIRT """ import argparse import os import itertools import importlib from multiprocessing import Pool import time from models.document import Document import preprocessing.preprocessor as preprocessor import processing.processor as processor from utilities import path from utilities import logger STANDARDIZER_PATH = 'preprocessing.language_standardizer.{}' COMPARATOR_PATH = 'processing.comparators.{}' class UnsupportedFunctionException(BaseException): """ Exception for functions that are not supported """ # TODO: is this actually used? pass def iter_files_in_file(filename): """ Generator over the file names contained in filename Expects each file to be on its own line """ with open(filename) as f: contents = f.read() lines = contents.split('\n') for line in lines: if line and path.should_use_file(line): yield line def preprocess(args): """ Run processing step """ standardizer_path = STANDARDIZER_PATH.format(args.language) standardizer = importlib.import_module(standardizer_path) if os.path.isdir(args.input): it = path.iter_files_in(args.input) else: it = iter_files_in_file(args.input) for file_name in it: pre = preprocessor.Preprocessor(file_name=file_name, standardizer=standardizer, input_dir=args.input, output_dir=args.preprocessed_dir) pre.process() def process_parallel_worker(a, output_dir, gap_length, match_length, b, comparator): """ Worker for processing two files at a time in parallel """ comparator_path = COMPARATOR_PATH.format(comparator) comparator = importlib.import_module(comparator_path) pro = processor.Processor(output_dir=output_dir, comparator=comparator, gap_length=gap_length, match_length=match_length, percentage_match_length=None) alpha = Document.from_json(a) beta = Document.from_json(b) pro.process(alpha_document=alpha, beta_document=beta) def process_parallel(args, alpha_files, beta_files): """ Process on multiple threads/processes """ p = Pool() compared = [] for a, b in itertools.product(alpha_files, beta_files): this_set = sorted([a, b]) if a != b and this_set not in compared: p.apply_async(process_parallel_worker, (a, args.output_dir, args.gap_length, args.match_length, b, args.comparator)) compared.append(this_set) p.close() p.join() return len(compared) def process_serial(args, alpha_files, beta_files): """ Process on a single thread """ comparator_path = COMPARATOR_PATH.format(args.comparator) comparator = importlib.import_module(comparator_path) pro = processor.Processor(output_dir=args.output_dir, comparator=comparator, gap_length=args.gap_length, match_length=args.match_length, percentage_match_length=None) compared = [] for a, b in itertools.product(alpha_files, beta_files): this_set = sorted([a, b]) if a != b and this_set not in compared: alpha = Document.from_json(a) beta = Document.from_json(b) pro.process(alpha_document=alpha, beta_document=beta) compared.append(this_set) return len(compared) def process(args): """ Run processing step """ start = time.time() alpha_files = path.iter_files_in(args.preprocessed_dir) beta_files = path.iter_files_in(args.preprocessed_dir) if args.parallel: cnt = process_parallel(args, alpha_files, beta_files) else: cnt = process_serial(args, alpha_files, beta_files) duration = time.time() - start if duration == 0: duration = 1 comparisons_per_sec = cnt/duration logger.info('Processed {} files per second'.format(comparisons_per_sec)) def main(parsed_args): if parsed_args.verbose: logger.show_info() preprocess(parsed_args) process(parsed_args) if __name__ == '__main__': parser = argparse.ArgumentParser(prog='DIRT.py', description='Find reused passages in a corpus of unicode text') # TODO: avoid reprocessing parser.add_argument('-i', '--input', help='Directory containing input corpus', # required=True, type=str) parser.add_argument('-pre', '--preprocessed_dir', default='dirt_preprocessed', help='Directory containing preprocessed corpus', type=str) parser.add_argument('-o', '--output_dir', default='dirt_output', help='Directory for output files', type=str) parser.add_argument('-l', '--language', default='eng', help='ISO 639-2 language code', type=str) parser.add_argument('-c', '--comparator', default='simple', help='comparator for processor', type=str) parser.add_argument('-gl', '--gap_length', default=3, help='Size of gaps between matches to be jumped', type=int) parser.add_argument('-ml', '--match_length', default=10, help='Minimum length of a match', type=int) parser.add_argument('-pml', '--percentage_match_length', default=0, help='Minimum length of match as a percentage of total' 'document length', type=int) parser.add_argument('-v', '--verbose', help='Verbose', action='count') parser.add_argument('-gui', help='Run Gui', action='store_const', const=True) parser.add_argument('-p', '--parallel', help='Run on multiple threads/processes', action='store_const', const=True) parsed = parser.parse_args() if parsed.input: main(parsed) else: from dirtgui import main_window if parsed.input: main_window.main(parsed.output_dir) else: main_window.main(None)
I have an Atari Jaguar box here, and since i haven't really got the hots for collecting boxed consoles, i thought it might complete someone else's Jaguar. It doesn't have any polys, it's just the box, in reasonable shape. See pics. Asking 5 euro. Plus postage, paid via paypal as a gift. - Payment is by Paypal Gift payment only. Buyer covers fees. - I will accept returns on my items but return shipping is to be paid by the buyer regardless of the reason/s for return. - Unless agreed otherwise, payment is expected within 36hrs after interest declared, I reserve the right to move onto next in line after this time frame. If you do not accept these terms, please do not declare interest. PostNL: 9 euro untracked or 13 euro tracked for up to 2kg. DHL: 15,50 tracked for 10kg max. Leaves room for some other stuff, if you'd like. Jaguar box didn't have polys. It had a moulded cardboard inner.. Last edited by alexh; 6th December 2013 at 22:40.
import json import logging import re import requests from string import Template logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # TODO: Actually do authentication with CL # Stuff brought in from original casebot CL_URL_TEMPLATE = Template("https://www.courtlistener.com/c/$reporter/$volume/$page/") CL_FIND_URL_TEMPLATE = Template("https://www.courtlistener.com/api/rest/v3/search/?format=json&q=casename%3A($query)") MINIMUM_VIABLE_CITATION_PATTERN = r"^(\d+)\s([A-Za-z0-9.\s]+)\s(\d+)$" MINIMUM_VIABLE_CITATION_PATTERN_RE = re.compile(MINIMUM_VIABLE_CITATION_PATTERN) FIND_PATTERN = r"find\s+(.+)$" FIND_RE = re.compile(FIND_PATTERN) USER_AGENT="casebot https://github.com/anseljh/casebot-beepboop" def handle_find(query): """ The `find` command searches CourtListener by case name. https://github.com/anseljh/casebot/issues/3 """ reply = None url = CL_FIND_URL_TEMPLATE.substitute({'query': query}) request_headers = {'user-agent': USER_AGENT} # Authenticate to CourtListener using token # https://github.com/anseljh/casebot/issues/7 # cl_token = config.get('CourtListener').get('courtlistener_token') # if cl_token is not None: # request_headers['Authenticate'] = 'Token ' + cl_token # print("Added CL Authentication Token header") response = requests.get(url, headers=request_headers) # Give some output on stdout logger.debug(response) logger.debug(response.headers) logger.debug(response.url) # Convert from JSON response_data = response.json() hits = response_data.get('count') if hits > 0: first = response_data.get('results')[0] logger.debug(first) url = "https://www.courtlistener.com" + first.get('absolute_url') logger.debug(url) name = first.get('caseName') logger.debug(name) year = first.get('dateFiled')[:4] logger.debug(year) citation = first.get('citation')[0] logger.debug(citation) court = first.get('court_citation_string') logger.debug(court) # msg = "CourtListener had %d hits for the query `%s`. Here's the first:\n" # if court != 'SCOTUS': # message.reply(msg + "%s, %s (%s %s)\n%s" % (hits, query, name, citation, court, year, url)) # else: # message.reply(msg + "%s, %s (%s)\n%s" % (hits, query, name, citation, year, url)) if court != 'SCOTUS': reply = "%s, %s (%s %s)\n%s" % (name, citation, court, year, url) else: reply = "%s, %s (%s)\n%s" % (name, citation, year, url) else: reply = "CourtListener had zero results for the query `%s`" % (query) return reply def handle_citation(message): reply = None re_result = MINIMUM_VIABLE_CITATION_PATTERN_RE.search(message) if re_result: volume, reporter, page = re_result.groups() logger.debug("Volume: %s | Reporter: %s | Page: %s" % (volume, reporter, page)) # Look up using CourtListener /c tool mapping = {'volume': volume, 'reporter': reporter, 'page': page} url = CL_URL_TEMPLATE.substitute(mapping) request_headers = {'user-agent': USER_AGENT} response = requests.get(url, headers=request_headers) # Give some output on stdout logger.debug(response) logger.debug(response.headers) logger.debug(response.url) # Send the message! if response.status_code == 404: reply = "Sorry, I can't find that citation in CourtListener." else: reply = response.url else: reply = "Bad citation." return reply class RtmEventHandler(object): def __init__(self, slack_clients, msg_writer): self.clients = slack_clients self.msg_writer = msg_writer def handle(self, event): if 'type' in event: self._handle_by_type(event['type'], event) def _handle_by_type(self, event_type, event): # See https://api.slack.com/rtm for a full list of events if event_type == 'error': # error self.msg_writer.write_error(event['channel'], json.dumps(event)) elif event_type == 'message': # message was sent to channel self._handle_message(event) elif event_type == 'channel_joined': # you joined a channel self.msg_writer.write_help_message(event['channel']) elif event_type == 'group_joined': # you joined a private group self.msg_writer.write_help_message(event['channel']) else: pass def _handle_message(self, event): # Filter out messages from the bot itself, and from non-users (eg. webhooks) if ('user' in event) and (not self.clients.is_message_from_me(event['user'])): msg_txt = event['text'] if self.clients.is_bot_mention(msg_txt) or self._is_direct_message(event['channel']): # e.g. user typed: "@pybot tell me a joke!" if 'help' in msg_txt: self.msg_writer.write_help_message(event['channel']) elif re.search('hi|hey|hello|howdy', msg_txt): self.msg_writer.write_greeting(event['channel'], event['user']) # elif 'joke' in msg_txt: # self.msg_writer.write_joke(event['channel']) elif 'attachment' in msg_txt: self.msg_writer.demo_attachment(event['channel']) elif 'echo' in msg_txt: self.msg_writer.send_message(event['channel'], msg_txt) elif msg_txt.startswith('find'): find_re_result = FIND_RE.search(msg_txt) if find_re_result: query = find_re_result.group(1) find_result = handle_find(query) if find_result: self.msg_writer.send_message(event['channel'], find_result) else: logger.debug("No matches for query: %s" % (query)) else: logger.error("Nothing for find_re_result!") self.msg_writer.send_message(event['channel'], "Does not compute.") else: self.msg_writer.write_prompt(event['channel']) def _is_direct_message(self, channel): """Check if channel is a direct message channel Args: channel (str): Channel in which a message was received """ return channel.startswith('D')
Donny was appointed Chief Executive Officer for Standard Chartered Bank Brunei on 1 November 2014 and subsequently Chairman of Brunei Association of Banks (BAB) on 4 February 2015. Prior to the assignment in Brunei he was Standard Chartered’s Head of Internal Audit for North East Asia, Greater China, South Asia, and ASEAN based out of Singapore. Immediately before the move to Singapore in 2010, he was the Bank’s Chief Executive Officer in the Falkland Islands for 3 years. In his 18 years with Standard Chartered Donny has held a number of diverse roles across businesses, functions, and geographies. He started with Consumer Banking in Indonesia before heading the CEO’s Office in 2001. He moved to the Bank’s Head Office in London in 2002 as Business Planning Manager to the Group Chief Executive. He joined the Europe Wholesale Banking team in 2003 and subsequently joined the Consumer Banking team for MENAP region out of Dubai in 2004. He returned to Jakarta as the Chief Operating Officer for SCB Indonesia in 2005 followed by Chief Administrative Officer for Permata Bank in 2006. He joined Group Corporate Development, the M&A division of the Bank, in London as a Project Director in 2007 and moved to the Falklands following completion of the American Express Bank acquisition. Donny holds a degree in International Relations. He is Indonesian and married with two children.
from GlobalActions import globalActionMap from Components.ActionMap import ActionMap, HelpableActionMap from Components.Button import Button from Components.ChoiceList import ChoiceList, ChoiceEntryComponent from Components.SystemInfo import SystemInfo from Components.config import config, ConfigSubsection, ConfigText, ConfigYesNo from Components.PluginComponent import plugins from Components.Sources.StaticText import StaticText from Screens.ChoiceBox import ChoiceBox from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Plugins.Plugin import PluginDescriptor from Tools.BoundFunction import boundFunction from ServiceReference import ServiceReference from enigma import eServiceReference, eActionMap from Components.Label import Label import os ButtonSetupKeys = [ (_("Red"), "red", "Infobar/activateRedButton"), (_("Red long"), "red_long", ""), (_("Green long"), "green_long", ""), (_("Yellow long"), "yellow_long", "Infobar/subtitleSelection"), (_("Info (EPG)"), "info", "Infobar/InfoPressed/1"), (_("Info (EPG) Long"), "info_long", "Infobar/showEventInfoPlugins/1"), (_("Epg/Guide"), "epg", "Infobar/EPGPressed/1"), (_("Epg/Guide long"), "epg_long", "Infobar/showEventGuidePlugins/1"), (_("Left"), "cross_left", ""), (_("Right"), "cross_right", ""), (_("Left long"), "cross_left_long", ""), (_("Right long"), "cross_right_long", "Infobar/seekFwdVod"), (_("Up"), "cross_up", ""), (_("Down"), "cross_down", ""), (_("Channel up"), "channelup", ""), (_("Channel down"), "channeldown", ""), (_("TV"), "showTv", ""), (_('TV long'), 'tv_long', ""), (_("Radio"), "radio", ""), (_("Radio long"), "radio_long", ""), (_("Rec"), "rec", ""), (_("Teletext"), "text", ""), (_("Help"), "displayHelp", ""), (_("Help long"), "displayHelp_long", ""), (_("Subtitle"), "subtitle", ""), (_("Subtitle Long"), "subtitle_long", ""), (_("Menu"), "mainMenu", ""), (_("List/Fav/PVR"), "list", ""), (_("List/Fav/PVR") + " " + _("long"), "list_long", ""), (_("List/File"), "file", ""), (_("List/File") + " " + _("long"), "file_long", ""), (_("Back/Recall"), "back", ""), (_("Back/Recall") + " " + _("long"), "back_long", ""), (_("Home"), "home", ""), (_("End"), "end", ""), (_("Next"), "next", ""), (_("Previous"), "previous", ""), (_("Audio"), "audio", ""), (_("Play"), "play", ""), (_("Playpause"), "playpause", ""), (_("Stop"), "stop", ""), (_("Pause"), "pause", ""), (_("Rewind"), "rewind", ""), (_("Fastforward"), "fastforward", ""), (_("Skip back"), "skip_back", ""), (_("Skip forward"), "skip_forward", ""), (_("activatePiP"), "activatePiP", ""), (_("activatePiP long"), "activatePiP_long", ""), (_("Timer"), "timer", ""), (_("Playlist"), "playlist", ""), (_("Timeshift"), "timeshift", ""), (_("Search/WEB"), "search", ""), (_("Slow"), "slow", ""), (_("Mark/Portal/Playlist"), "mark", ""), (_("Sleep"), "sleep", ""), (_("Power"), "power", ""), (_("Power long"), "power_long", ""), (_("HDMIin"), "HDMIin", "Infobar/HDMIIn"), (_("HDMIin") + " " + _("long"), "HDMIin_long", (SystemInfo["LcdLiveTV"] and "Infobar/ToggleLCDLiveTV") or ""), (_("Context"), "contextMenu", "Infobar/showExtensionSelection"), (_("F1/LAN"), "f1", "Infobar/showNetworkMounts"), (_("F1/LAN long"), "f1_long", ""), (_("F2"), "f2", ""), (_("F2 long"), "f2_long", ""), (_("F3"), "f3", ""), (_("F3 long"), "f3_long", ""), ] config.misc.ButtonSetup = ConfigSubsection() config.misc.ButtonSetup.additional_keys = ConfigYesNo(default=True) for x in ButtonSetupKeys: exec "config.misc.ButtonSetup." + x[1] + " = ConfigText(default='" + x[2] + "')" def getButtonSetupFunctions(): ButtonSetupFunctions = [] twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins(PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if plugin.path[plugin.path.rfind("Plugins"):] in twinPaths: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] += 1 else: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] = 1 ButtonSetupFunctions.append((plugin.name, plugin.path[plugin.path.rfind("Plugins"):] + "/" + str(twinPaths[plugin.path[plugin.path.rfind("Plugins"):]]), "EPG")) twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if plugin.path[plugin.path.rfind("Plugins"):] in twinPaths: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] += 1 else: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] = 1 ButtonSetupFunctions.append((plugin.name, plugin.path[plugin.path.rfind("Plugins"):] + "/" + str(twinPaths[plugin.path[plugin.path.rfind("Plugins"):]]), "Plugins")) twinPlugins.append(plugin.name) ButtonSetupFunctions.append((_("Show Grid EPG"), "Infobar/openGridEPG", "EPG")) ButtonSetupFunctions.append((_("Main menu"), "Infobar/mainMenu", "InfoBar")) ButtonSetupFunctions.append((_("Show help"), "Infobar/showHelp", "InfoBar")) ButtonSetupFunctions.append((_("Show extension selection"), "Infobar/showExtensionSelection", "InfoBar")) ButtonSetupFunctions.append((_("Zap down"), "Infobar/zapDown", "InfoBar")) ButtonSetupFunctions.append((_("Zap up"), "Infobar/zapUp", "InfoBar")) ButtonSetupFunctions.append((_("Show service list"), "Infobar/openServiceList", "InfoBar")) ButtonSetupFunctions.append((_("Show service list or movies"), "Infobar/showServiceListOrMovies", "InfoBar")) ButtonSetupFunctions.append((_("Show movies"), "Infobar/showMovies", "InfoBar")) ButtonSetupFunctions.append((_("Restart last movie"), "Infobar/restartLastMovie", "InfoBar")) ButtonSetupFunctions.append((_("Show favourites list"), "Infobar/openFavouritesList", "InfoBar")) ButtonSetupFunctions.append((_("History back"), "Infobar/historyBack", "InfoBar")) ButtonSetupFunctions.append((_("History next"), "Infobar/historyNext", "InfoBar")) ButtonSetupFunctions.append((_("Show event info plugins"), "Infobar/showEventInfoPlugins", "EPG")) ButtonSetupFunctions.append((_("Show event details"), "Infobar/openEventView", "EPG")) ButtonSetupFunctions.append((_("Show Single EPG"), "Infobar/openSingleServiceEPG", "EPG")) ButtonSetupFunctions.append((_("Show Multi EPG"), "Infobar/openMultiServiceEPG", "EPG")) ButtonSetupFunctions.append((_("Show select audio track"), "Infobar/audioSelection", "InfoBar")) ButtonSetupFunctions.append((_("Show subtitle selection"), "Infobar/subtitleSelection", "InfoBar")) ButtonSetupFunctions.append((_("Toggle default subtitles"), "Infobar/toggleDefaultSubtitles", "InfoBar")) ButtonSetupFunctions.append((_("Switch to radio mode"), "Infobar/showRadio", "InfoBar")) ButtonSetupFunctions.append((_("Switch to TV mode"), "Infobar/showTv", "InfoBar")) ButtonSetupFunctions.append((_("Instant record"), "Infobar/instantRecord", "InfoBar")) ButtonSetupFunctions.append((_("Start instant recording"), "Infobar/startInstantRecording", "InfoBar")) ButtonSetupFunctions.append((_("Activate timeshift end"), "Infobar/activateTimeshiftEnd", "InfoBar")) ButtonSetupFunctions.append((_("Activate timeshift end and pause"), "Infobar/activateTimeshiftEndAndPause", "InfoBar")) ButtonSetupFunctions.append((_("Start timeshift"), "Infobar/startTimeshift", "InfoBar")) ButtonSetupFunctions.append((_("Stop timeshift"), "Infobar/stopTimeshift", "InfoBar")) ButtonSetupFunctions.append((_("Start teletext"), "Infobar/startTeletext", "InfoBar")) ButtonSetupFunctions.append((_("Show subservice selection"), "Infobar/subserviceSelection", "InfoBar")) ButtonSetupFunctions.append((_("Letterbox zoom"), "Infobar/vmodeSelection", "InfoBar")) ButtonSetupFunctions.append((_("Seekbar"), "Infobar/seekFwdVod", "InfoBar")) if SystemInfo["PIPAvailable"]: ButtonSetupFunctions.append((_("Show PIP"), "Infobar/showPiP", "InfoBar")) ButtonSetupFunctions.append((_("Swap PIP"), "Infobar/swapPiP", "InfoBar")) ButtonSetupFunctions.append((_("Move PIP"), "Infobar/movePiP", "InfoBar")) ButtonSetupFunctions.append((_("Toggle PIP-ZAP"), "Infobar/togglePipzap", "InfoBar")) ButtonSetupFunctions.append((_("Activate HbbTV (RedButton)"), "Infobar/activateRedButton", "InfoBar")) if SystemInfo["HasHDMIin"]: ButtonSetupFunctions.append((_("Toggle HDMI-In full screen"), "Infobar/HDMIInFull", "InfoBar")) ButtonSetupFunctions.append((_("Toggle HDMI-In PiP"), "Infobar/HDMIInPiP", "InfoBar")) if SystemInfo["LcdLiveTV"]: ButtonSetupFunctions.append((_("Toggle LCD LiveTV"), "Infobar/ToggleLCDLiveTV", "InfoBar")) ButtonSetupFunctions.append((_("Do nothing"), "Void", "InfoBar")) if os.path.isdir("/usr/script"): for x in [x for x in os.listdir("/usr/script") if x.endswith(".sh")]: x = x[:-3] ButtonSetupFunctions.append((_("Script") + " " + x, "Script/" + x, "Scripts")) ButtonSetupFunctions.append((_("Button setup"), "Module/Screens.ButtonSetup/ButtonSetup", "Setup")) ButtonSetupFunctions.append((_("Software update"), "Module/Screens.SoftwareUpdate/UpdatePlugin", "Setup")) ButtonSetupFunctions.append((_("CI (Common Interface) Setup"), "Module/Screens.Ci/CiSelection", "Setup")) ButtonSetupFunctions.append((_("Show stream clients"), "Module/Screens.StreamingClientsInfo/StreamingClientsInfo", "Setup")) ButtonSetupFunctions.append((_("Manual scan"), "Module/Screens.ScanSetup/ScanSetup", "Scanning")) ButtonSetupFunctions.append((_("Automatic scan"), "Module/Screens.ScanSetup/ScanSimple", "Scanning")) for plugin in plugins.getPluginsForMenu("scan"): ButtonSetupFunctions.append((plugin[0], "MenuPlugin/scan/" + plugin[2], "Scanning")) ButtonSetupFunctions.append((_("Network Setup"), "Module/Screens.NetworkSetup/NetworkAdapterSelection", "Setup")) ButtonSetupFunctions.append((_("Network menu"), "Infobar/showNetworkMounts", "Setup")) ButtonSetupFunctions.append((_("Plugin browser"), "Module/Screens.PluginBrowser/PluginBrowser", "Setup")) ButtonSetupFunctions.append((_("Channel info"), "Module/Screens.ServiceInfo/ServiceInfo", "Setup")) ButtonSetupFunctions.append((_("Timers"), "Module/Screens.TimerEdit/TimerEditList", "Setup")) ButtonSetupFunctions.append((_("Autotimer overview"), "Infobar/showAutoTimerList", "Setup")) for plugin in plugins.getPluginsForMenu("system"): if plugin[2]: ButtonSetupFunctions.append((plugin[0], "MenuPlugin/system/" + plugin[2], "Setup")) ButtonSetupFunctions.append((_("Power menu"), "Menu/shutdown", "Power")) ButtonSetupFunctions.append((_("Standby"), "Module/Screens.Standby/Standby", "Power")) ButtonSetupFunctions.append((_("Restart"), "Module/Screens.Standby/TryQuitMainloop/2", "Power")) ButtonSetupFunctions.append((_("Restart GUI"), "Module/Screens.Standby/TryQuitMainloop/3", "Power")) ButtonSetupFunctions.append((_("Deep standby"), "Module/Screens.Standby/TryQuitMainloop/1", "Power")) ButtonSetupFunctions.append((_("Usage setup"), "Setup/usage", "Setup")) ButtonSetupFunctions.append((_("User interface settings"), "Setup/userinterface", "Setup")) ButtonSetupFunctions.append((_("Recording and playback settings"), "Setup/recording", "Setup")) ButtonSetupFunctions.append((_("Skin setup"), "Module/Screens.SkinSelector/SkinSelector", "Setup")) ButtonSetupFunctions.append((_("Reload skin"), "Infobar/reloadSkin", "Setup")) ButtonSetupFunctions.append((_("Harddisk setup"), "Setup/harddisk", "Setup")) ButtonSetupFunctions.append((_("Subtitles settings"), "Setup/subtitlesetup", "Setup")) return ButtonSetupFunctions class ButtonSetup(Screen): def __init__(self, session): Screen.__init__(self, session) self.setTitle(_("Button Setup")) self['description'] = Label(_('On your remote, click on the button you want to change')) self.session = session self.list = [] self.ButtonSetupFunctions = getButtonSetupFunctions() for x in ButtonSetupKeys: self.list.append(ChoiceEntryComponent('', (_(x[0]), x[1]))) self["list"] = ChoiceList(list=self.list[:config.misc.ButtonSetup.additional_keys.value and len(ButtonSetupKeys) or 10], selection=0) self["choosen"] = ChoiceList(list=[]) self.getFunctions() self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.close, }, -1) self["ButtonSetupButtonActions"] = ButtonSetupActionMap(["ButtonSetupActions"], dict((x[1], self.ButtonSetupGlobal) for x in ButtonSetupKeys)) self.longkeyPressed = False self.onLayoutFinish.append(self.__layoutFinished) self.onExecBegin.append(self.getFunctions) self.onShown.append(self.disableKeyMap) self.onClose.append(self.enableKeyMap) def __layoutFinished(self): self["choosen"].selectionEnabled(0) def disableKeyMap(self): globalActionMap.setEnabled(False) eActionMap.getInstance().unbindNativeKey("ListboxActions", 0) eActionMap.getInstance().unbindNativeKey("ListboxActions", 1) eActionMap.getInstance().unbindNativeKey("ListboxActions", 4) eActionMap.getInstance().unbindNativeKey("ListboxActions", 5) def enableKeyMap(self): globalActionMap.setEnabled(True) eActionMap.getInstance().bindKey("keymap.xml", "generic", 103, 5, "ListboxActions", "moveUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 108, 5, "ListboxActions", "moveDown") eActionMap.getInstance().bindKey("keymap.xml", "generic", 105, 5, "ListboxActions", "pageUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 106, 5, "ListboxActions", "pageDown") def ButtonSetupGlobal(self, key): if self.longkeyPressed: self.longkeyPressed = False else: index = 0 for x in self.list[:config.misc.ButtonSetup.additional_keys.value and len(ButtonSetupKeys) or 10]: if key == x[0][1]: self["list"].moveToIndex(index) if key.endswith("_long"): self.longkeyPressed = True break index += 1 self.getFunctions() self.session.open(ButtonSetupSelect, self["list"].l.getCurrentSelection()) def getFunctions(self): key = self["list"].l.getCurrentSelection()[0][1] if key: selected = [] for x in getattr(config.misc.ButtonSetup, key).value.split(','): function = next((function for function in self.ButtonSetupFunctions if function[1] == x), None) if function: selected.append(ChoiceEntryComponent('', ((function[0]), function[1]))) self["choosen"].setList(selected) class ButtonSetupSelect(Screen): def __init__(self, session, key): Screen.__init__(self, session) self.skinName = "ButtonSetupSelect" self['description'] = Label(_('Select the desired function and click on "OK" to assign it. Use "CH+/-" to toggle between the lists. Select an assigned function and click on "OK" to de-assign it. Use "Next/Previous" to change the order of the assigned functions.')) self.session = session self.key = key self.setTitle(_("Button setup for") + ": " + key[0][0]) self["key_red"] = Button(_("Cancel")) self["key_green"] = Button(_("Save")) self.mode = "list" self.ButtonSetupFunctions = getButtonSetupFunctions() self.config = getattr(config.misc.ButtonSetup, key[0][1]) self.expanded = [] self.selected = [] for x in self.config.value.split(','): function = next((function for function in self.ButtonSetupFunctions if function[1] == x), None) if function: self.selected.append(ChoiceEntryComponent('', ((function[0]), function[1]))) self.prevselected = self.selected[:] self["choosen"] = ChoiceList(list=self.selected, selection=0) self["list"] = ChoiceList(list=self.getFunctionList(), selection=0) self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions"], { "ok": self.keyOk, "cancel": self.cancel, "red": self.cancel, "green": self.save, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "pageUp": self.toggleMode, "pageDown": self.toggleMode, "shiftUp": self.moveUp, "shiftDown": self.moveDown, }, -1) self.onShown.append(self.enableKeyMap) self.onClose.append(self.disableKeyMap) self.onLayoutFinish.append(self.__layoutFinished) def __layoutFinished(self): self["choosen"].selectionEnabled(0) def disableKeyMap(self): globalActionMap.setEnabled(False) eActionMap.getInstance().unbindNativeKey("ListboxActions", 0) eActionMap.getInstance().unbindNativeKey("ListboxActions", 1) eActionMap.getInstance().unbindNativeKey("ListboxActions", 4) eActionMap.getInstance().unbindNativeKey("ListboxActions", 5) def enableKeyMap(self): globalActionMap.setEnabled(True) eActionMap.getInstance().bindKey("keymap.xml", "generic", 103, 5, "ListboxActions", "moveUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 108, 5, "ListboxActions", "moveDown") eActionMap.getInstance().bindKey("keymap.xml", "generic", 105, 5, "ListboxActions", "pageUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 106, 5, "ListboxActions", "pageDown") def getFunctionList(self): functionslist = [] catagories = {} for function in self.ButtonSetupFunctions: if function[2] not in catagories: catagories[function[2]] = [] catagories[function[2]].append(function) for catagorie in sorted(list(catagories)): if catagorie in self.expanded: functionslist.append(ChoiceEntryComponent('expanded', ((catagorie), "Expander"))) for function in catagories[catagorie]: functionslist.append(ChoiceEntryComponent('verticalline', ((function[0]), function[1]))) else: functionslist.append(ChoiceEntryComponent('expandable', ((catagorie), "Expander"))) return functionslist def toggleMode(self): if self.mode == "list" and self.selected: self.mode = "choosen" self["choosen"].selectionEnabled(1) self["list"].selectionEnabled(0) elif self.mode == "choosen": self.mode = "list" self["choosen"].selectionEnabled(0) self["list"].selectionEnabled(1) def keyOk(self): if self.mode == "list": currentSelected = self["list"].l.getCurrentSelection() if currentSelected[0][1] == "Expander": if currentSelected[0][0] in self.expanded: self.expanded.remove(currentSelected[0][0]) else: self.expanded.append(currentSelected[0][0]) self["list"].setList(self.getFunctionList()) else: if currentSelected[:2] in self.selected: self.selected.remove(currentSelected[:2]) else: self.selected.append(currentSelected[:2]) elif self.selected: self.selected.remove(self["choosen"].l.getCurrentSelection()) if not self.selected: self.toggleMode() self["choosen"].setList(self.selected) def keyLeft(self): self[self.mode].instance.moveSelection(self[self.mode].instance.pageUp) def keyRight(self): self[self.mode].instance.moveSelection(self[self.mode].instance.pageDown) def keyUp(self): self[self.mode].instance.moveSelection(self[self.mode].instance.moveUp) def keyDown(self): self[self.mode].instance.moveSelection(self[self.mode].instance.moveDown) def moveUp(self): self.moveChoosen(self.keyUp) def moveDown(self): self.moveChoosen(self.keyDown) def moveChoosen(self, direction): if self.mode == "choosen": currentIndex = self["choosen"].getSelectionIndex() swapIndex = (currentIndex + (direction == self.keyDown and 1 or -1)) % len(self["choosen"].list) self["choosen"].list[currentIndex], self["choosen"].list[swapIndex] = self["choosen"].list[swapIndex], self["choosen"].list[currentIndex] self["choosen"].setList(self["choosen"].list) direction() else: return 0 def save(self): configValue = [] for x in self.selected: configValue.append(x[0][1]) self.config.value = ",".join(configValue) self.config.save() self.close() def cancel(self): if self.selected != self.prevselected: self.session.openWithCallback(self.cancelCallback, MessageBox, _("are you sure you want to cancel all the changes"), default=False) else: self.close() def cancelCallback(self, answer): answer and self.close() class ButtonSetupActionMap(ActionMap): def action(self, contexts, action): if action in tuple(x[1] for x in ButtonSetupKeys) and action in self.actions: res = self.actions[action](action) if res is not None: return res return 1 else: return ActionMap.action(self, contexts, action) class helpableButtonSetupActionMap(HelpableActionMap): def action(self, contexts, action): if action in tuple(x[1] for x in ButtonSetupKeys) and action in self.actions: res = self.actions[action](action) if res is not None: return res return 1 else: return ActionMap.action(self, contexts, action) class InfoBarButtonSetup(): def __init__(self): self["ButtonSetupButtonActions"] = helpableButtonSetupActionMap(self, "ButtonSetupActions", dict((x[1], (self.ButtonSetupGlobal, boundFunction(self.getHelpText, x[1]))) for x in ButtonSetupKeys), -10) self.longkeyPressed = False self.onExecEnd.append(self.clearLongkeyPressed) def clearLongkeyPressed(self): self.longkeyPressed = False def getKeyFunctions(self, key): if key in ("play", "playpause", "Stop", "stop", "pause", "rewind", "next", "previous", "fastforward", "skip_back", "skip_forward") and (self.__class__.__name__ == "MoviePlayer" or hasattr(self, "timeshiftActivated") and self.timeshiftActivated()): return False selection = getattr(config.misc.ButtonSetup, key).value.split(',') selected = [] for x in selection: if x.startswith("ZapPanic"): selected.append(((_("Panic to") + " " + ServiceReference(eServiceReference(x.split("/", 1)[1]).toString()).getServiceName()), x)) elif x.startswith("Zap"): selected.append(((_("Zap to") + " " + ServiceReference(eServiceReference(x.split("/", 1)[1]).toString()).getServiceName()), x)) elif x: function = next((function for function in getButtonSetupFunctions() if function[1] == x), None) if function: selected.append(function) return selected def getHelpText(self, key): selected = self.getKeyFunctions(key) if not selected: return return pgettext("ButtonSetup help separator", '/').join(sel[0] for sel in selected) def ButtonSetupGlobal(self, key): if self.longkeyPressed: self.longkeyPressed = False else: selected = self.getKeyFunctions(key) if not selected: return 0 elif len(selected) == 1: if key.endswith("_long"): self.longkeyPressed = True return self.execButtonSetup(selected[0]) else: key = tuple(x[0] for x in ButtonSetupKeys if x[1] == key)[0] self.session.openWithCallback(self.execButtonSetup, ChoiceBox, _("ButtonSetup") + " " + key, selected) def execButtonSetup(self, selected): if selected: selected = selected[1].split("/") if selected[0] == "Plugins": twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins(PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if plugin.path[plugin.path.rfind("Plugins"):] in twinPaths: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] += 1 else: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] = 1 if plugin.path[plugin.path.rfind("Plugins"):] + "/" + str(twinPaths[plugin.path[plugin.path.rfind("Plugins"):]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if plugin.path[plugin.path.rfind("Plugins"):] in twinPaths: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] += 1 else: twinPaths[plugin.path[plugin.path.rfind("Plugins"):]] = 1 if plugin.path[plugin.path.rfind("Plugins"):] + "/" + str(twinPaths[plugin.path[plugin.path.rfind("Plugins"):]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) elif selected[0] == "MenuPlugin": for plugin in plugins.getPluginsForMenu(selected[1]): if plugin[2] == selected[2]: self.runPlugin(plugin[1]) return elif selected[0] == "Infobar": if hasattr(self, selected[1]): exec "self." + ".".join(selected[1:]) + "()" else: return 0 elif selected[0] == "Module": try: exec "from " + selected[1] + " import *" exec "self.session.open(" + ",".join(selected[2:]) + ")" except Exception as e: print "[ButtonSetup] error during executing module %s, screen %s, %s" % (selected[1], selected[2], e) import traceback traceback.print_exc() elif selected[0] == "Setup": exec "from Screens.Setup import *" exec "self.session.open(Setup, \"" + selected[1] + "\")" elif selected[0].startswith("Zap"): if selected[0] == "ZapPanic": self.servicelist.history = [] self.pipShown() and self.showPiP() self.servicelist.servicelist.setCurrent(eServiceReference("/".join(selected[1:]))) self.servicelist.zap(enable_pipzap=True) if hasattr(self, "lastservice"): self.lastservice = eServiceReference("/".join(selected[1:])) self.close() else: self.show() from Screens.MovieSelection import defaultMoviePath moviepath = defaultMoviePath() if moviepath: config.movielist.last_videodir.value = moviepath elif selected[0] == "Script": command = '/usr/script/' + selected[1] + ".sh" from Screens.Console import Console exec "self.session.open(Console,_(selected[1]),[command])" elif selected[0] == "Menu": from Screens.Menu import MainMenu, mdom root = mdom.getroot() for x in root.findall("menu"): y = x.find("id") if y is not None: id = y.get("val") if id and id == selected[1]: menu_screen = self.session.open(MainMenu, x) break def showServiceListOrMovies(self): if hasattr(self, "openServiceList"): self.openServiceList() elif hasattr(self, "showMovies"): self.showMovies() def ToggleLCDLiveTV(self): config.lcd.showTv.value = not config.lcd.showTv.value def reloadSkin(self): self.session.reloadSkin()
The user manual and the software do not match when it comes to shutting down the LS-WX models. The manual describes a shutdown method using either the NAS Navigator or the web-based administration tool. Neither of those interfaces has a shutdown choice. There appears to be a way to RESTART the LS, but no way to actually shut the system down using the software. Are there any plans at Buffalo to fix this rather glaring failure of desired functionality? This unit has been discontinued so it is unlikely this feature will be added. The method outlined on the manual is for the LS-XL model which is the range product range as your device.
#!/usr/bin/python try: import Adafruit_DHT except ImportError, e: class Adafruit_DHTMOCK(): def read_retry(self): return 25, 50 Adafruit_DHT = Adafruit_DHTMOCK() import requests import logging from apscheduler.schedulers.background import BlockingScheduler THERMOSTAT_URI = 'http://192.168.1.214:5000/api/v1/temperature/' def main(): humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, '17') if humidity is not None and temperature is not None: requests.post(THERMOSTAT_URI, data=dict(temperature=temperature, humidity=humidity)) logger.warn('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) else: logger.error('Failed to get reading. Try again!') if __name__ == '__main__': logging.basicConfig(level=logging.WARN, format='%(levelname)s - %(asctime)s %(message)s') logger = logging.getLogger('main') scheduler = BlockingScheduler() scheduler.add_job(main, 'interval', seconds=60) logger.warn('starting scheduler') scheduler.start()
Modification Access Project (MAP) Success! 2018 Medicare Enrollment/Change Period is Here! We welcome the following new and renewing members of hip for 2017! Like many baby boomers I have decided to follow the advice outlined in the Sedlar-Miners book, “Don’t Retire…Rewire.” So I’ve decided to remain in the workforce with some modifications. In my case it meant switching from public service to the non-profit world and trading my 3 hour round-trip commute for a short trip from the next town. Believe it or not I’m not new to hip. In 1980 as a Vocational Rehabilitation Counselor working in the area, I was one of the first visitors to the Center for Independent Living and encouraged the consumers with whom I worked to participate in the social and recreational activities they offered. I later spent a short time on the Board of Trustees, but the best thing that I did was to convince the top brass at the Division of Vocational Rehabilitation Services (DVRS) to allow two staffers from the Commission for the Blind and Visually Impaired (CBVI) to have free space in the Jersey City office to start hip’sHudson branch. Throughout it all I maintained a good friendship with hip’s founding CEO, Eileen Goff, and I’ve been able to stay current on the tremendous growth of the CIL. So, when it came time to retire from DVRS I looked around for opportunities that would combine my knowledge of people with disabilities, my interest in the progress of the disability movement and my commitment to the full inclusion of people with disabilities in their communities. What better place to land than as President and CEO of hip. At DVRS my focus was on training and employment, so this transition allows me to expand my view and add outreach, education and advocacy to complete the service model. We’re working on redeveloping the website, improving our imprint on social media and creating ways to respond to the needs of our consumers. I’m looking forward to this adventure and I want to share it with all of the friends and members of the hip community, so I encourage you to contact me by using your favorite method of communication; e-mail [email protected], phone (201) 996-9100 ext. 14 or arrange a visit. Join us at 7 p.m. on Wednesday, November 15th at the Fort Lee Recreation Center for our Annual Meeting! Attendees will mingle, enjoy a light supper, and learn about all the hip accomplishments this past year from President/CEO Brian Fitzgibbons. The evening will also include election and re-election to the Board of Trustees. permanent use of a wheelchair. After months of rehab, Victor was determined to make all modifications to prevent his injury from limiting his potential. He completed his Associate’s degree from Bergen Community College in Hospitality Management in December 2014 and is currently employed with the Hudson County Department of Corrections. He is also a newlywed after marrying his long-time girlfriend Laura this past March. We look forward to hearing more of Victor’s experiences and how he overcame challenges to succeed in his goals. The staff members from both Bergen and Hudson CILs will meet and greet attendees. We look forward to seeing everyone there! This past summer, Ronald, an 83-year old veteran from Wood-Ridge, was in need of a ramp for his home. He uses a wheelchair on a daily basis and was unable to leave his home safely. With financial assistance from hip’s MAP program and collaboration with the Inmate Labor Program from the Bergen County Sheriff Department, Ronald now has an accessible way to enter and leave his home. He says, “I’m very happy with the ramp, they did a beautiful job.” Thanks to everyone involved in this project! All of those who made generous contributions in memory of Margot and Patti Aronsohn. Special thanks go to Eileen Goff for her significant contribution in honor of her retirement. We also thank all those who contributed a total of $16,146 to The Eileen Goff Legacy Fund which was established by hip’s Board of Trustees in honor of Eileen’s 37 years of dedicated service and announced at Eileen’s retirement party on June 28th. Eileen was totally surprised and is thrilled that these funds will be available to assist consumers who have compelling financial needs that cannot be met through any other funding sources. Special recognition goes to Yahya Sadigh for his extraordinary contribution to The Eileen Goff Legacy Fund. hip’s founder and former President/CEO, Eileen Goff, was honored with the Dr. Celia Weisman Memorial Award at the Bergen County Human Services Advisory Council Annual Meeting on Tuesday, September 26th. Congratulations to Eileen on this very prestigious and well-deserved award! Congratulations to Ryan Roy for his role as the grand marshal of the 2017 NJ Disability Pride Parade! The parade took place on Saturday, October 7th in Trenton. hip staff member Natalie Alave welcomed a baby girl into her family on October 4th. Congratulations to the new mom and dad! Margot Aronsohn and Patti Aronsohn, beloved mother and sister of Board Membe Paul Aronsohn, both of whom passed away in June. John Fox, beloved brother of Board Member Jean Csaposs, who passed away in August. Nicole Dautruche, beloved mother of staff member Van Dautruche, who passed away in September. Barbara Rivlin, longtime member and friend of hip who passed away in September. Richard Fellinger, hip member and father of hip member William, who passed away in September. Victoria Robbins joined the hip staff in June as a Care Manager at the Bergen CIL. She is a graduate of Morgan State University in Baltimore. Victoria has worked with the disability community for over 12 years and has spent much of her time as a day program manager. A resident of Paterson, Victoria enjoys spending time with her boyfriend and family (including her cats), watching horror movies and traveling. It is open enrollment time for all individuals that would like to make changes to their Medicare coverage. For 2018 Medicare coverage, open enrollment is from October 15th to December 7th. If you’re already enrolled in a Medicare Part D prescription plan or a Medicare Advantage Plan and you don’t want to make changes to your coverage for 2018, you don’t need to do anything during open enrollment, assuming your current plan will still be available in 2018. If your plan is being discontinued and isn’t eligible for renewal, you will receive a non-renewal notice from your carrier prior to open enrollment. If you don’t, it means you can keep your plan without doing anything during open enrollment. Be aware that your benefits and premium could be changing for So even if you’re confident that you want to keep your current coverage for the coming year, it’s important to make sure you understand any changes that may apply, and that you’ve double checked to make sure that your current plan is still the best available option. The available plans and what they cover changes from one year to the next, so even if the plan you have now was the best option when you shopped last year, it’s important to verify that again before you lock yourself in for another year. For assistance please contact the Bergen or Hudson CILs. Our case managers are here to help! The sunny days of summer have come to an end! We had a great time watching the list of raffle winners grow each week and seeing many of our hip friends and family win! Thank you to everyone who supported our effort and congratulations again to all our winners! This year’s calendar raffle included (1) three-time winner, (3) two-time winners, and ticket holders from all over the country! Our Grand Prize Winner was longtime hip friend and Director of the DAWN CIL, Carmela Slivinski! We’re already looking forward to next year’s raffle – maybe we’ll change it up a bit and have it in the fall! The autumn season is here! Try this recipe from Delish for muffins that are fall in a cupcake liner. Preheat oven to 350 degrees. In a large bowl, mix together flour, sugar, baking powder, baking soda, salt, cinnamon and nutmeg. Add in 1 1/4 cups butterscotch chips, and toss until well-coated with flour mixture (this will keep them from sinking to the bottom of the batter). Add pumpkin, eggs, butter, sour cream, and vanilla, and mix until well-combined. Line a muffin tin with liners, and use an ice cream scoop to fill each with batter. Top each muffin with remaining butterscotch chips. Bake until toothpick comes out clean, about 20 minutes. If you have any unneeded adult disposable briefs (in all sizes) please drop them off at the Bergen CIL office – they could be of great use to some of our consumers. Thank you! For the Holiday Party on Sunday, December 17th, 12-4pm, at the DoubleTree Hotel in Fort Lee. Join us for a festive celebration of the season! Paula Walsh, longtime hip staff member and friend passed away suddenly on August 7th. Paula was an amazing woman – a loving wife, mother, grandmother and someone who was beyond dedicated to advocating for people with disabilities. The number of people whose lives were changed by Paula’s work over her 33 years at hip is immeasurable. She cared about all of us as family and we loved her so much. We will miss you more than words can say, Paula. May you rest in peace. In a very unexpected way. And now with the angels God she will meet. And never a negative word did she let slip. She worked day and night until a job was done. For she was not our foe. “I first met Paula Walsh in 1985 when she came to hip for a job interview. She had acquired a spinal cord injury during her adolescence, completed high school and went on to Ramapo College. Her career at hip began as an information and referral specialist and then expanded to include other responsibilities. I attended her wedding to Larry Walsh which was followed by the birth of their daughter Kelly, who came to work for six months with Paula and received lots of attention in her playpen. In the mid-1970’s a good friend invited me to visit Ramapo College. During that visit, I met Paula Westbrook. I was interested in attending Ramapo but at that time I was not sure if I could. Talking with Paula and other people with different abilities made an impression on me. Throughout the years, some people make more of an impact than others and are there for you. I can’t believe that Paula and I have known each other for 45 years. Paula made a difference in people’s lives – I was certainly not the only person she positively impacted. No matter the problem, she tried to find a reasonable solution. Sometimes it wasn’t ideal but it helped to motivate that individual to the next stage. Paula was a people person. She enjoyed conversation, which helped her in her work. Paula will be missed! She was a true role model and friend. “How can I find the words to say what I feel at this moment, what words are adequate to pay tribute to a hero who gave so much of herself and upon others to make them feel free to live their life regardless of what challenges we all had? The answer is I just don’t know. What I do know is this, Paula Walsh wasn’t just a person who’s challenges did not keep her down, instead, she rose above them! I am honored to be among them who made me aware of what my voice can do to inspire others. I always believed that Paula had a purpose for being on this Earth and that was to teach us how to be a voice for others. And also in addition, to make us celebrate our life and enjoy every bit of it and every moment of it until our last breath upon this Earth. I treasured her friendship, and her support for whatever I endured and whatever I did to stand up for the voiceless. I know, she always told me about Great events to always have fun with and to forget about your challenges for even a short while. Among the things that I treasured was whenever she called me for the annual Bergen Bassmasters fishing competition at Darlington Lake in Ramsey and I always enjoyed the humor of a certain Master of Ceremonies Brian Mahoney, Paula always asked me during the time of my fishing, “Are you enjoying yourself?” and I would always reply, “I sure am. It is quite fun.” It was Paula who introduced me to the Wonders of being able to fish and enjoy the wondrous Beauty of what the universe can provide, there is life around that lake. But sometimes, whenever I fish with people, it reminds me of something that I heard so long ago. I was taught that sometimes the lake may be quiet, but there’s always life under the water and I knew that my time to be emerging and full of that energy would soon arrive. And now, that I am involved further in the fight for progress, equality, compassion, love, and a whole lot more, I absolutely can not enough thank a hero among Heroes, who in her own way, taught us to catch our own falling star and put it in our pocket and Never Let It Fade Away for real. The star always shines bright and helps us guide us even in the darkest of times. Even at the picnic or at the annual Christmas party, Paula loved life fully and taught me how to love life fully as well and celebrate it! My friend Paula, on behalf of a Grateful Nation, no, a grateful planet, you’re amazing six decades upon the Earth on behalf of a grateful planet, I thank you for not just your six decades upon this Earth, but thank you for always being a champion of change, a soldier on the front line 4 ending discrimination, bigotry, and more, I thank you for teaching me the greatest gift of all…. Paying it forward and giving back to others. I may be crying today that you are no longer going to be there for me or for any of us when we fish next season with the Bergen Bassmasters, or at the annual Christmas party or at our picnic, but I know you will always be there with us, in spirit, and always celebrating with us in our heart forever. “Paula was a good, caring, loving and sweet Person I got to know of. She advocated and fought for the Lives of Residents with Disabilities State-Wide, never gave up hope, always continued to pave the way when it comes to getting accessibility of going places. hip’s Dinner Dance will be held on Saturday, April 28th! More details to follow.
#!/usr/bin/python # write an experiment that raises an exception import sys import os import itertools BOREALISPATH = os.environ['BOREALISPATH'] sys.path.append(BOREALISPATH) import experiments.superdarn_common_fields as scf from experiment_prototype.experiment_prototype import ExperimentPrototype class TestExperiment(ExperimentPrototype): def __init__(self): cpid = 1 super(TestExperiment, self).__init__(cpid) if scf.IS_FORWARD_RADAR: beams_to_use = scf.STD_16_FORWARD_BEAM_ORDER else: beams_to_use = scf.STD_16_REVERSE_BEAM_ORDER if scf.opts.site_id in ["cly", "rkn", "inv"]: num_ranges = scf.POLARDARN_NUM_RANGES if scf.opts.site_id in ["sas", "pgr"]: num_ranges = scf.STD_NUM_RANGES slice_1 = { # slice_id = 0, there is only one slice. "pulse_sequence": scf.SEQUENCE_7P, "tau_spacing": scf.TAU_SPACING_7P, "pulse_len": scf.PULSE_LEN_45KM, "num_ranges": num_ranges, "first_range": scf.STD_FIRST_RANGE, "intt": 3500, # duration of an integration, in ms "beam_angle": scf.STD_16_BEAM_ANGLE, "beam_order": beams_to_use, "scanbound": [i * 3.5 for i in range(len(beams_to_use))], #1 min scan "txfreq" : scf.COMMON_MODE_FREQ_1, #kHz "acf": True, "xcf": True, # cross-correlation processing "acfint": True, # interferometer acfs } lag_table = list(itertools.combinations(slice_1['pulse_sequence'], 2)) lag_table.append([slice_1['pulse_sequence'][0], slice_1[ 'pulse_sequence'][0]]) # lag 0 lag_table.append([99,0]) # Should fail on this!! # sort by lag number lag_table = sorted(lag_table, key=lambda x: x[1] - x[0]) lag_table.append([slice_1['pulse_sequence'][-1], slice_1[ 'pulse_sequence'][-1]]) # alternate lag 0 slice_1['lag_table'] = lag_table self.add_slice(slice_1)
I am totally new to this site but am happy I took the discion to join. However at the moment I am really confused on how to gain approval for the Pay Pal chained payments API in Market Press. Have found myself bouncing around inside here and Pay Pal X developer site and have ended up with more questions than answers. I have noticed that some of you have gone through the process successfully and wondered if any of you had written a roadmap of the whole process from start to finish that you might be willing to share. From what I've seen on these forums no two processes are identical. Paypal will fire off a number of different questions depending on your set-up, purpose, product type, business status (plc, ltd, etc). I suppose the only part of the process which remains constant is that they want screenshots and a way to test your cart in sandbox mode which from memory they mention whilst you fill out their application. I know WPMUDEV give pointers in their docs. I think apart from that it would be hard to get any more precise. Sorry. thanks for your reply, seems like this is a bit of an iffy topic which I feel should have some decent docs to guide users as it's not a run of thre mill thing for the average user to try and do. Anyway I have made some progress and have got 2 x sandbox sellers addresses and 2 x buyers addresses set up and have sucessfully performed transactions and got some screen shots as well. I did have problems though because on occassion when clicking on the pay pal button I fouind myself at the sand box login page, not what was expected but I think pay pal are having an iffy day. April 12, 2011 - 12:30 pm: Pending: The payment is pending. The payment is pending while it is being reviewed by PayPal for risk. Don't know if this is normal behaviour for sandbox or not as this is my first time using it, but at least the transactions are going through the whole flow process. Now I have this cracked the next step is to complete the application and keep my fingers crossed. I will document this whole process and make it available once completed in the hope that it might help some poor soul along the way. Cant help you with your particular question, but definitely just be patient, although it's painful working with Paypal. It took me quite a while working back and forth with the guys from Paypal to get it setup. Must have been at least 20 - 30 messages!! All works 100% now though so was worth it. Would be great to see your outlined process. APi credentials all using the sandbox detaiuls for this seller sandbox account. I've asked some of the other guys to chip in here so we can all help with that guide you're putting together. I think that'll really help other members so major kudos coming your way when you get it done! I've only ever played with Sandbox once and that was a while ago and not a pleasant experience :wink: but is this correct? IIRC you will have a sandbox email address and API creds to enter instead of live ones? Right thanks Phil, any amd all help would be good here as this process is quite a bit beyond what I normally do and I have to say I am resonably experienced with over 12 years working on the net, I have hacked many scripts to get them to do what I want, the latest being wp-ecommerce but this is really something new. I got the chained payments sorted out in the end, thanks to the first response from Pay Pal regarding the API approval process, they pointed out to me in a round a bout sort of way that I was using express instead of chained, so I went back and checked again and yes the settings I have written earlier were wrong. Next select your currency and then Sandbox and finally enter your Pay Pal sandsbox address for yout test seller account. This is now working for me perfectly and I can trace the payments from the test buyer to the test seller and then the commission payment from test seller to site owner all in the Pay Pal sandbox. "Please be aware that we will deduct a 10% fee from the total of each transaction in addition to any fees PayPal may charge you. If for any reason you need to refund a customer for an order, please contact us with a screenshot of the refund receipt in your PayPal history as well as the Transaction ID of our fee deduction so we can issue you a refund. Thank you" Ok so maybe I got my set up all wrong from the start, but in my defence there wasn't much direction avaialble, but it's ok now and I am happy to share my experiences. Yeah in order to use a payment gateway you have to select it to use it. Glad you got it sorted. I'm not sure we would have caught your mistake without being able to see the set up, we all assumed because you were asking about Chained Payments that you were using Chained Payments. I think my mistake was having both chained payments and express selected in the site admin and express selected in the seller shop, think I was tired and frustrated when I wrote yesterday about my settings. But my roadmap will most certainly include these details, on the subject of approval by Pay Pal, I am just waiting for a decision as they said all questions have now been answered, has taken just over 24 hours so far. My approval took over 6 weeks, though this was over Christmas and I was told that the bad weather effected the time, in the end I had to send off a message and it was approved in a few days after that. I have made my guide for this now, it's in PDF so how should I make it available here, do I need to send it across to somebody frst for proofing? Great news! If it's below 200KB you can simply attached it to a forum post here. Otherwise, send me an e-mail through the contact form and I'll grab it over e-mail! it's 424kb, went to the contact form you mentioned above but there isn't anywhere to attach it, can it be e-mailed direct or PM'd to you, let me know. That's fine Dave, just send an e-mail through the contact form and then I'll get back to you. 4 to 6 weeks seems to be about the average. I thought ours had gone through, but it hadn't, it is still under review. We are at about the 4 week mark (or there a bouts). No questions have been asked by them in well over a week. Awesome work on getting the guide done, I'm sure it will benefit others! wonder why it takes them so long to approve the app as they say on their site that it takes about 10 days or exceptionally 15 days, strange. Yes I hope the guide does help some people out, in fact I am also thinking about doing one for the sandbox as well but will ask Phil about that first, but am sure it would help people out who are new to it as I was. I'm really not sure, but it is painfully slow. I log into their X site just to make sure there was not an issue with an e-mail coming through and I just see that the app is still under review. in fact I am also thinking about doing one for the sandbox as well but will ask Phil about that first, but am sure it would help people out who are new to it as I was. did you get the contact form I sent you yesterday, the internet was all over the place at my end and I think I may have lost a couple of e-mails along the way because of this. Sorry for the delayed response, I've been out all day yesterday! I've now responded to your e-mail. Hey Guys, I have been looking for this guide! This is great. Could you share the link to the guide made by Ozbod? How current it is I don't know now.
""" Numba-optimized version of functions to compute KDE-based photon rates. """ from __future__ import division import numpy as np import numba from math import exp, fabs @numba.jit def kde_laplace_numba(timestamps, tau, time_axis=None): """Computes exponential KDE for `timestamps` evaluated at `time_axis`. """ if time_axis is None: time_axis = timestamps t_size = time_axis.size timestamps_size = timestamps.size rates = np.zeros((t_size,), dtype=np.float64) tau_lim = 5 * tau ipos, ineg = 0, 0 # indexes for timestamps for it, t in enumerate(time_axis): while ipos < timestamps_size and timestamps[ipos] - t < tau_lim: ipos += 1 while ineg < timestamps_size and t - timestamps[ineg] > tau_lim: ineg += 1 for itx in range(ineg, ipos): rates[it] += exp(-fabs(timestamps[itx] - t)/tau) return rates @numba.jit def kde_gaussian_numba(timestamps, tau, time_axis=None): """Computes Gaussian KDE for `timestamps` evaluated at `time_axis`. """ if time_axis is None: time_axis = timestamps timestamps_size = timestamps.size rates = np.zeros((time_axis.size,), dtype=np.float64) tau_lim = 3 * tau # 3 tau = 99.7 % of the Gaussian tau2 = 2 * (tau**2) ipos, ineg = 0, 0 # indexes for timestamps for it, t in enumerate(time_axis): while ipos < timestamps_size and timestamps[ipos] - t < tau_lim: ipos += 1 while ineg < timestamps_size and t - timestamps[ineg] > tau_lim: ineg += 1 for itx in range(ineg, ipos): rates[it] += exp(-((timestamps[itx] - t)**2)/tau2) return rates @numba.jit def kde_rect_numba(timestamps, tau, time_axis=None): """Computes rectangular KDE for `timestamps` evaluated at `time_axis`. """ if time_axis is None: time_axis = timestamps timestamps_size = timestamps.size rates = np.zeros((time_axis.size,), dtype=np.float64) tau_lim = tau / 2 ipos, ineg = 0, 0 # indexes for timestamps for it, t in enumerate(time_axis): while ipos < timestamps_size and timestamps[ipos] - t < tau_lim: ipos += 1 while ineg < timestamps_size and t - timestamps[ineg] > tau_lim: ineg += 1 rates[it] = ipos - ineg return rates ## # "self" functions: evaluating KDE on the same position as the timestamps # @numba.jit def kde_laplace_self_numba(ph, tau): """Computes exponential KDE for `timestamps` evaluated at `timestamps`. """ ph_size = ph.size ipos, ineg = 0, 0 rates = np.zeros((ph_size,), dtype=np.float64) nph = np.zeros((ph_size,), dtype=np.int16) tau_lim = 5*tau for i, t in enumerate(ph): while ipos < ph_size and ph[ipos] - t < tau_lim: ipos += 1 while t - ph[ineg] > tau_lim: ineg += 1 for itx in range(ineg, ipos): rates[i] += exp(-fabs(ph[itx]-t)/tau) nph[i] += 1 return rates, nph ## # Special functions # @numba.jit def kde_laplace_nph(timestamps, tau, time_axis=None): """Computes exponential KDE for `timestamps` evaluated at `time_axis`. Computes KDE rates of `timestamps` and number of photon used to compute each rate. Number of photons are the one in the 10*tau range around the current time. The kernel used is a symmetric-exponential (i.e. laplace distribution):: kernel = exp( -|t - t0| / tau) The rate is computed for each time in `time_axis`. When ``time_axis`` is None them ``timestamps`` is used also as time axis. Arguments: timestamps (array): arrays of photon timestamps tau (float): time constant of the exponential kernel time_axis (array or None): array of time points where the rate is computed. If None, uses `timestamps` as time axis. Returns: 2-element tuple containing - **rates** (*array*): the unnormalized rates (just the sum of the exponential kernels). To obtain rates in Hz divide the array by `2*tau` (or other conventional `x*tau` duration). - **nph** (*array*): number of photons in -5*tau..5*tau window for each timestamp. Proportional to the rate computed with KDE and rectangular kernel. """ if time_axis is None: time_axis = timestamps t_size = time_axis.size timestamps_size = timestamps.size rates = np.zeros((t_size,), dtype=np.float64) nph = np.zeros((t_size,), dtype=np.int16) tau_lim = 5 * tau ipos, ineg = 0, 0 # indexes for timestamps for it, t in enumerate(time_axis): while ipos < timestamps_size and timestamps[ipos] - t < tau_lim: ipos += 1 while ineg < timestamps_size and t - timestamps[ineg] > tau_lim: ineg += 1 for itx in range(ineg, ipos): rates[it] += exp(-fabs(timestamps[itx] - t)/tau) nph[it] += 1 return rates, nph
Anxіеtу Disorders: Anxiety dіѕоrdеrѕ can tаkе many fоrmѕ, ranging frоm ѕосіаl anxiety tо PTSD. Eасh type оf аnxіеtу саn hаvе a ѕеrіоuѕ іmрасt оn thе lіvеѕ of ѕuffеrеrѕ. Anxіеtу rеlіеf is оnе of the mоѕt commonly sought-after effects оf cannabis. Mаnу оf cannabis’s аntі-аnxіеtу еffесtѕ аrе lіnkеd to cannabidiol. CBD hаѕ been fоund tо decrease anxious feelings in a numbеr of scientific ѕtudіеѕ. CBD іѕ a рrоmіѕіng trеаtmеnt fоr numеrоuѕ fоrmѕ of anxiety, including OCD, раnіс disorder, gеnеrаlіzеd anxiety dіѕоrdеr, PTSD, аnd ѕосіаl аnxіеtу disorder. Bеѕіdеѕ еvіdеnсе from ѕtudіеѕ, many аnесdоtаl rероrtѕ ѕuрроrt the bеnеfіtѕ оf CBD fоr trеаtіng anxiety. Dерrеѕѕіоn: Dерrеѕѕіоn іѕ оnе оf the most соmmоn mеntаl hеаlth dіѕоrdеrѕ. Depression саn cause mаjоr сhаngеѕ to mood, thоughtѕ аnd bеhаvіоr. There іѕ grоwіng еvіdеnсе that CBD саn help trеаt depression. Mаnу studies hаvе fоund thаt CBD can асt аѕ аn аntіdерrеѕѕаnt bу acting оn ѕеrоtоnіn pathways іn the brаіn. CBD can ѕресіfісаllу rеduсе anhedonia, a ѕуmрtоm оf depression thаt mаkеѕ people unable tо fееl joy оr hарріnеѕѕ. Studies have fоund thаt сhаngеѕ іn thе еndосаnnаbіnоіd system may bе іnvоlvеd in dерrеѕѕіоn. CBD асtіvаtеѕ thе еndосаnnаbіnоіd system by increasing lеvеlѕ of nаturаllу-оссurrіng саnnаbіnоіdѕ, ѕuсh аѕ аnаndаmіdе. Nаuѕеа: Nаuѕеа іѕ аn unсоmfоrtаblе ѕеnѕаtіоn thаt саn be саuѕеd by mаnу fасtоrѕ including сhеmоthеrару, еxроѕurе to bacteria аnd vіruѕеѕ, and early рrеgnаnсу. The ѕtudу of CBD fоr nаuѕеа іѕ mоrе rесеnt, but has ѕhоwn a lоt оf promise. Studies hаvе fоund that CBD саn ѕtор nausea аnd vоmіtіng. CBD may be раrtісulаrlу hеlрful іn treating nаuѕеа in patients that are not gеttіng rеlіеf from рrеѕсrіbеd аntі-nаuѕеа drugѕ. Eріlерѕу: One оf the most wеll-knоwn effects оf CBD is its іmрасt оn сеrtаіn forms оf epilepsy, including Dravet ѕуndrоmе. Rеѕеаrсh ѕhоwѕ thаt CBD hаѕ anticonvulsant еffесtѕ in humаn mоdеlѕ оf epilepsy. Diabetes: Dіаbеtеѕ іѕ a сhrоnіс dіѕеаѕе thаt can cause ѕеvеrе complications over time. These іnсludе саrdіоvаѕсulаr diseases, ѕtrоkе, dаmаgе tо thе еуеѕ and kidney dіѕеаѕе. Dіаbеtеѕ іѕ аlѕо lіnkеd tо іnflаmmаtіоn, whісh саn gеt worse as thе dіѕеаѕе рrоgrеѕѕеѕ. Rеѕеаrсhеrѕ bеlіеvе thаt CBD mау оffеr thіѕ рrоtесtіоn against diabetes bу bооѕtіng the immune system and dесrеаѕіng inflammation. Cаnсеr: Mаrіjuаnа іѕ соmmоnlу uѕеd іn саnсеr trеаtmеnt to rеduсе nаuѕеа and vоmіtіng frоm сhеmоthеrару. But cannabinoids such аѕ CBD mау асtuаllу fіght thе саnсеr itself. Currеnt research ѕuggеѕtѕ different cannabinoids, іnсludіng CBD аnd THC, саn рrеvеnt саnсеr cells from spreading іn thе body аnd аlѕо trіggеr сеll dеаth in саnсеr сеllѕ. CBD wаѕ fоund to slow thе fоrmаtіоn оf new blооd vеѕѕеlѕ іn tumоrѕ, whісh are needed tо provide nutrіеntѕ fоr grоwth. Bу ѕlоwіng thе fоrmаtіоn оf thеѕе blооd vеѕѕеlѕ, CBD mау also slow the growth оf tumоrѕ. Overall, thеrе іѕ nоt muсh rеѕеаrсh аvаіlаblе оn CBD and cancer, but еаrlу rеѕultѕ аrе рrоmіѕіng. CBD has аlѕо being рrоvеn bеnеfісіаl fоr оthеr medical соndіtіоnѕ ѕuсh аѕ; Luрuѕ, Mоtоr disorders, Nісоtіnе addiction, Parkinson’s disease, Chrоnіс аnd nеurораthіс pain, Obsessive Compulsive Dіѕоrdеr, Osteoporosis, Vаrіоuѕ реdіаtrіс conditions. Arе Cаnnаbіnоіdѕ thе Future оf Medicine? Aѕ science, technology, аnd саnnаbіѕ mеrgе, a nеw futurе іѕ being defined fоr саnnаbіnоіd-bаѕеd thеrареutісѕ. Eасh ѕсіеntіfіс ѕtudу on thе rоlе of саnnаbіnоіdѕ hеlр uѕ understand a little mоrе. Thе good nеwѕ іѕ thаt as tіmе gоеѕ оn, science undеrѕtаndѕ mоrе аbоut how саnnаbіnоіdѕ саn bе most effective. Thе mоrе we lеаrn about the саnnаbіѕ рlаnt, thе mоrе wе discover whаt a truly аmаzіng рlаnt іt really іѕ. Of course, those іn thе саnnаbіѕ соmmunіtу hаvе bееn tеllіng thе world thіѕ fоr mаnу уеаr. It’ѕ juѕt thаt nоw the rеѕt of thе wоrld іѕ ѕtаrtіng to lіѕtеn! Aѕ scientists unlock thе mysteries of mаrіjuаnа, and соmе tо undеrѕtаnd hоw thе саnnаbіѕ plant wоrkѕ, nеw dооrѕ ореn оn hоw wе can use it as a mеdісіnе. Kеу tо саnnаbіѕ’ѕ mеdісаl effectiveness is thе chemical соmроundѕ рrоduсеd bу іtѕ flоwеrѕ, knоwn аѕ саnnаbіnоіdѕ, аnd wе are lеаrnіng mоrе аbоut their unіԛuе роwеrѕ аll thе tіmе. Whаt mаkе cannabinoids ѕресіаl is that thеу appear to mіrrоr thе еndосаnnаbіnоіdѕ рrоduсеd by thе humаn bоdу whісh help tо mаіntаіn thе health аnd hаrmоnу оf our body systems. Bу harnessing thе роwеr оf саnnаbіnоіdѕ, medicine can theoretically be developed tо address faults in оur реrѕоnаl еndосаnnаbіnоіd ѕуѕtеmѕ, therefore trеаtіng medical соndіtіоnѕ. By nоw, you’ve рrоbаblу hеаrd thаt CBD hаѕ some very rеаl health benefits, and perhaps уоu’vе bееn соnѕіdеrіng trуіng it fоr yourself, but something is ѕtорріng уоu. Mауbе уоu саn’t gеt раѕt thе ѕtіgmа аѕѕосіаtеd wіth cannabis or уоu’rе аfrаіd іt wіll lеаvе уоu feeling lоору аnd tired. Wе gеt іt. Cannabis іѕ ѕtіll соntrоvеrѕіаl аnd thеrе аrе a lоt of misconceptions ѕwіrlіng аrоund about whаt іt саn аnd can’t dо, аnd hоw іt does and doesn’t make you fееl. We hаvе grеаt соnfіdеnсе іn саnnаbіѕ’ rоlе іn healing, ѕtауіng healthy, аnd еаѕіng pain, оthеrwіѕе wе wouldn’t be here. Best Overall Reviews By Our Costumers!
import warnings import numpy as np import pandas as pd def readAndConvertCSVToDbFormatDf(filePath: str, nrows: int = None) -> pd.DataFrame: """ :param filePath: filename with product data :param nrows: limit the number of rows to read (usually used for debug) :return: this is an adaptor between the way the file information is saves, and how it is introduced to the database. It renames columns, separates min/max prices for the strong, and deals with "None" strings """ fileColumnsToDbAdaptor = { 'productURL': 'link', 'productId': 'productId', 'productName': 'description', } colsToReturn = ['productId', 'link', 'description', 'min_price', 'max_price'] if nrows is None: dfData = pd.read_csv(filePath, encoding="utf-8-sig", compression='infer') else: dfData = pd.read_csv(filePath, encoding="utf-8-sig", nrows=nrows, compression='infer') dfData.drop_duplicates(inplace=True) dfData.reset_index(drop=True, inplace=True) dfData.rename(columns=fileColumnsToDbAdaptor, inplace=True) # todo: add sanitize description here as well # analyzing price array descriptionAsList = list(dfData['description'].values) descriptionSanitized = [str(desc).replace(r'&rlm', '').replace(';', ' ').replace(',', ' ').replace(r'&', ' ').replace('\\', '/') for desc in descriptionAsList] dfData['description'] = descriptionSanitized dfData['min_price'] = np.nan dfData['max_price'] = np.nan dfData.replace({'pricesArray': {'None': np.nan}}, inplace=True) dfData['pricesArray'] = dfData['pricesArray'].str.replace('[', '') dfData['pricesArray'] = dfData['pricesArray'].str.replace(']', '') pricesListOfStrs = dfData['pricesArray'].to_list() minPricesList = [] maxPricesList = [] for index, prices in enumerate(pricesListOfStrs): if prices is np.nan: minPricesList.append(np.nan) maxPricesList.append(np.nan) else: pricesAsArray = [float(price.strip()) for price in prices.split(',')] if len(pricesAsArray) == 1: minPricesList.append(pricesAsArray[0]) maxPricesList.append(pricesAsArray[0]) elif len(pricesAsArray) == 2: minPricesList.append(min(pricesAsArray)) maxPricesList.append(max(pricesAsArray)) else: raise ValueError("len(prices) > 2. This shouldn't happen. Possibly a bug: %s" % prices) dfData['min_price'] = minPricesList dfData['max_price'] = maxPricesList dfData = dfData.where((pd.notnull(dfData)), None) return dfData[colsToReturn]
As little pups and little hoomans, we learn to face our fears. Be-paws if you don’t, you will be afraid for years of fears. And it seems like just when you conquer one, there is another one lurking, but don’t be afraid. We CAN do it. I am still learning to face my fears. the tail, broke your shoulder. It is really the Monsters fault! and when you live in earthquake terrior-tory, you have justifiable reason to fear! afraid, that the Monsters would not hurt me or my family and they would come every Monday. So I would have to accept the things I can not change, and Bree a big girl. Monsters to let them nose I don’t like them. Although I nose they can’t hear me over their Noxious Noise! afraid of anything. Except Musicmama. Paw haha. Queen of the Universe is afraid of bees. Be-paws she has been stung a few times. Ouch! She says they hunt her, stalk her and wait for her to come outside. One even stung her in the house, so may-bee she is right. A lot of hooman pups seem to have childhood fears of the closet, or under the bed. Trust me, under the bed is where I hide, so it is safe. You can always ask a grown-up dog to check for you. And, DD can come and organize your closet next time he gets the ZOOMIES, so it will be organized and you know exactly what is in there! See the entry, THE ZOOMIES. So listen to mama, dad, or a trusted care person when they tell you how to be safe. Although, MM’s brother used to do that until he lost his scissor privelages. Things like this are good advice and there are more safety rules you can follow. Once you feel safe, then trust your instinct and intuition. It is that inner voice that can guide you whether to use caution when proceeding. Just some “tips of the tail” from your friend Bree to help you face your fears. My mama also taught me to try and remember my puppy dreams be-paws she says your subconscious can often tell you things you need to pay attention to that sometimes when you are awake, you mind has too many squirrels (our expression for daily thoughts) running around in there! My FF says that when The Other One and I sleep, our little legs look like we are running! Paw haha. We are just dream chasing squirrels! A last note on fears, most of us are afraid to fail. But you won’t succeed unless you try it, so sometimes you may think you failed. But that is also how we learn. Keep trying! Then run , if you have to. I have room to shelter under the bed. Sent this on to a friend who loves dogs and loves puns. I think she will love this! Sounds like the perfect blend! I hope you both come back, I Bree-joy my comments! I just LOVE this post. I have to follow your blog! Or rather, my dog, Riley, says I must! Can you send me a photo for my upcoming photo only entry of all my woofer friends? No cats allowed, paw- haha! This one in particular strikes me as an excellent story for children. I hope Moms and Dads are reading them to their kids. How great to know a fur buddy has fears too. Wonderful message! PS Queen of the Universe was also afraid of Pepe Johnson! In addition to the aforementioned beee’s!
# coding:utf-8 ''' created on 2018/8/31 @author:sunyihuan ''' import os from tensorflow.python import pywrap_tensorflow import tensorflow as tf import numpy as np # hair_length_graph = tf.Graph() # # # model_path = "/Users/sunyihuan/Desktop/parameters/hair_length/second/complex75.03_simple78.63/model.ckpt-23" # check4 model_path = "/Users/sunyihuan/Desktop/parameters/hair_length/second/complex77_simple70/model.ckpt-39" # check0 # # with hair_length_graph.as_default(): # saver = tf.train.import_meta_graph("{}.meta".format(model_path)) # sess = tf.InteractiveSession(graph=hair_length_graph) # saver.restore(sess, model_path) # var_to_shape_map = sess.get_variable_to_shape_map() # for key in var_to_shape_map: # print("tensor_name: ", key) # print(sess.get_tensor(key)) # 查看ckpt中的tensor # from tensorflow.python.tools import inspect_checkpoint as chkp # chkp.print_tensors_in_checkpoint_file(file_name=model_path, tensor_name='', all_tensors=False, all_tensor_names=True) a = tf.constant(3.0, dtype=tf.float32) b = tf.constant(4.0) total = a + b # print(a) # print(b) # print(total) sess = tf.Session() # print(sess.run(total)) x = tf.placeholder(tf.float32, shape=[None, 3]) linear_model = tf.layers.Dense(units=1) print(linear_model) y = linear_model(x) init = tf.global_variables_initializer() sess.run(init) print(sess.run(y, {x: [[1, 2, 3],[4, 5, 6],[7,8,9]]})) features = { 'sales' : [[5], [10], [8], [9]], 'department': ['sports', 'sports', 'gardening', 'gardening']} department_column = tf.feature_column.categorical_column_with_vocabulary_list( 'department', ['sports', 'gardening']) department_column = tf.feature_column.indicator_column(department_column) columns = [ tf.feature_column.numeric_column('sales'), department_column ] inputs = tf.feature_column.input_layer(features, columns) var_init = tf.global_variables_initializer() table_init = tf.tables_initializer() sess = tf.Session() sess.run((var_init, table_init)) print(sess.run(inputs))
When looking for ways to improve the efficiency of your energy use, solar energy is the perfect place to start. Solar energy will keep your utility bills down and it’s also better for the environment. This article will provide you with all you need to know. Smell-scale solar panels are great for different variations of energy optimization. There are two ways to do this. You might seek out solar panels that can be mounted on or in a window for recharging portable electronic items. You should also consider investing in small appliances that can be powered with solar panels. All the small steps will add up to a reduced electric bill. It is important when installing your panels to remember that the position of the sun in the sky changes with the seasons, not just only over the course of the day. If you must install fixed angle panels, you’ll have to make a compromise in between the best angles for summer and winter. Don’t let a salesman sell you anything. Take all the time you need to ask questions, do some research and compare different options before investing in a solar energy system. You may make a horrible decision and lose out on a lot of money by purchasing from a pushy salesperson. Do the math prior to investing in any sort of solar panel system. The cost of solar panels may vary from area to area, and this may affect the amount of savings you will enjoy. If you jump into solar energy without the proper research, you may end up with a costly mistake. Solar energy systems just get better and better as the years pass. Because of their increased popularity among homeowners and businesses, it is becoming a more affordable option. Whether you want a large or small system, you can find the perfect fit for your home. Make sure your panels will be efficient throughout the year. If you are not sure of how you should place them, you should take some time to track the path of the sun and take into consideration the changes that occur with each season. Switching over to solar energy is a huge, yet rewarding choice. You will save the planet and save a great deal of money. Solar power could be just what you need. Start switching today by using this information!
###################### ## ## ## INTEGRATION ## ## ## ###################### from sage.rings.all import RealField,ComplexField,RR,QuadraticField,PolynomialRing,LaurentSeriesRing,PowerSeriesRing, Infinity,Zmod from sage.all import prod from sage.parallel.decorate import fork,parallel from sage.misc.getusage import get_memory_usage from sage.structure.sage_object import SageObject from sage.arith.misc import algdep from sage.misc.misc import cputime from sage.misc.verbose import verbose from collections import defaultdict from itertools import product,chain,groupby,islice,tee,starmap from operator import mul from .util import * from .sarithgroup import BTEdge from .limits import num_evals,find_center def act_on_polynomial(P,num,den,N = None): if N is None: N = P.degree() R = num.parent() ans = R(0) numvec = [R(1)] denvec = [R(1)] for i in range(N): numvec.append(num*numvec[-1]) denvec.append(den*denvec[-1]) Plist = P.list() for i in range(N+1): ai = Plist[i] ans += ai*numvec[i]*denvec[N-i] return ans def double_integral_zero_infty(Phi,tau1,tau2): p = Phi.parent().prime() K = tau1.parent() R = PolynomialRing(K,'x') x = R.gen() R1 = PowerSeriesRing(K,'r1') r1 = R1.gen() Phi_liftee = Phi._liftee try: R1.set_default_prec(Phi.precision_absolute()) except AttributeError: R1.set_default_prec(Phi.precision_relative()) level = Phi._map._manin.level() E0inf = [M2Z([0,-1,level,0])] E0Zp = [M2Z([p,a,0,1]) for a in range(p)] predicted_evals = num_evals(tau1,tau2) a,b,c,d = find_center(p,level,tau1,tau2).list() h = M2Z([a,b,c,d]) E = [h*e0 for e0 in E0Zp + E0inf] resadd = 0 resmul = 1 total_evals = 0 percentage = QQ(0) ii = 0 f = (x-tau2)/(x-tau1) while len(E) > 0: ii += 1 increment = QQ((100-percentage)/len(E)) verbose('remaining %s percent (and done %s of %s evaluations)'%(RealField(10)(100-percentage),total_evals,predicted_evals)) newE = [] for e in E: a,b,c,d = e.list() assert ZZ(c) % level == 0 try: y0 = f((a*r1+b)/(c*r1+d)) val = y0(y0.parent().base_ring()(0)) if all([xx.valuation(p)>0 for xx in (y0/val - 1).list()]): if total_evals % 100 == 0: Phi._map._codomain.clear_cache() pol = val.log(p_branch = 0)+((y0.derivative()/y0).integral()) V = [0] * pol.valuation() + pol.shift(-pol.valuation()).list() try: phimap = Phi._map(M2Z([b,d,a,c])) except OverflowError: print(a,b,c,d) raise OverflowError('Matrix too large?') # mu_e0 = ZZ(phimap.moment(0).rational_reconstruction()) mu_e0 = ZZ(Phi_liftee._map(M2Z([b,d,a,c])).moment(0)) mu_e = [mu_e0] + [phimap.moment(o).lift() for o in range(1,len(V))] resadd += sum(starmap(mul,zip(V,mu_e))) resmul *= val**mu_e0 percentage += increment total_evals += 1 else: newE.extend([e*e0 for e0 in E0Zp]) except ZeroDivisionError: #raise RuntimeError('Probably not enough working precision...') newE.extend([e*e0 for e0 in E0Zp]) E = newE verbose('total evaluations = %s'%total_evals) val = resmul.valuation() return p**val*K.teichmuller(p**(-val)*resmul)*resadd.exp() ##---------------------------------------------------------------------------- ## double_integral(tau1,tau2,r,s) ## ## Input: ## tau1,tau2: Elements of the ``standard affinoid" in H_p consisting ## of elements in PP_1(C_p) whose natural image in ## P_1(F_p-bar) does not belong to P_1(F_p). ## r,s: Elements of P_1(Q). The cusp r=a/b is ## represented in the form r=[a,b], with a and b relatively ## prime integers, and b>=0. By convention infty=[1,0]. ## omega: The modular form on Gamma_0(p), represented as above. ## ## Output: ## The ``multiplicative double integral" defined in [Da]. ##---------------------------------------------------------- def double_integral(Phi,tau1,tau2,r,s): if r == [0,0] or s == [0,0]: raise ValueError('r and s must be valid projective coordinates.') if r[0] == 0 and s[1] == 0: # From 0 to infinity return double_integral_zero_infty(Phi,tau1,tau2) elif s[1] == 0: a,b = r if b < 0: a,b = -a,-b if b == 0: return 1 if b == 1: return double_integral(Phi,tau1-a/b,tau2-a/b,[0,1],[1,0]) else: d = (1/(Zmod(b)(a))).lift() if 2*d > b : d -= b c = ZZ((a*d-1)/b) rr = [c,d] if d >= 0 else [-c,-d] i1 = double_integral(Phi,(b*tau1-a)/(d*tau1-c),(b*tau2-a)/(d*tau2-c),[0,1],[1,0]) i2 = double_integral(Phi,tau1,tau2,rr,[1,0]) return i1*i2 else: i1 = double_integral(Phi,tau1,tau2,r,[1,0]) i2 = double_integral(Phi,tau1,tau2,s,[1,0]) return i1/i2 def log_pseries(R, x, prec = None): r''' Calculate efficiently log(1 - x*z), where z is the variable of R Doing it with power series built-in log is about 10 times slower... ''' if x.valuation() <= 0: raise ValueError('Valuation problem') K = R.base_ring() if prec is None: prec = R.default_precision() v = [K.zero(),K(x)] xpow = K(x) for m in range(2, prec + 1): xpow *= x v.append( xpow / QQ(m) ) return -R(v) def lift_to_locally_analytic(G, divisor, prec=None): K = divisor.parent().base_ring() if prec is None: prec = K.precision_cap() p = G.p R = PolynomialRing(K,'r') edgelist = [(1,o,QQ(1)/QQ(p+1)) for o in G.get_covering(1)] while len(edgelist) > 0: newedgelist = [] ii = 0 for parity, (rev, h), wt in edgelist: ii += 1 a,b,c,d = [K(o) for o in G.embed(h,prec).list()] try: c0unit = K.one() c0val = 0 pol = R.zero() for P, n in divisor: hp0 = K(a * P + b) pol += QQ(n) * log_pseries(R, K(c * P + d) / hp0, prec) c0unit *= (-hp0).unit_part() ** n c0val += n * hp0.valuation() pol += c0unit.log(0) yield ((h, rev), pol, c0val, c0unit) except ValueError as msg: verbose('Subdividing because (%s)...'%str(msg)) newedgelist.extend([(parity,o,wt/QQ(p**2)) for o in G.subdivide([(rev, h)],parity,2)]) continue edgelist = newedgelist r''' Integration pairing. The input is a cycle (an element of `H_1(G,\text{Div}^0)`) and a cocycle (an element of `H^1(G,\text{HC}(\ZZ))`). Note that it is a multiplicative integral. ''' def integrate_H1(G,cycle,cocycle,depth = 1,prec = None,twist=False,progress_bar = False,multiplicative = True, return_valuation = True): if not cycle.is_degree_zero_valued(): raise ValueError('Cycle should take values in divisors of degree 0') if prec is None: prec = cocycle.parent().coefficient_module().base_ring().precision_cap() verbose('precision = %s'%prec) Cp = cycle.parent().coefficient_module().base_field() R = PolynomialRing(Cp, names = 't') t = R.gen() total_integrals = cycle.size_of_support() verbose('Will do %s integrals'%total_integrals) resmul = Cp(1) resadd = Cp(0) resval = ZZ(0) for g, D in cycle: if twist: D = D.left_act_by_matrix(G.embed(G.wp(),prec).change_ring(Cp)) g = g.conjugate_by(G.wp()**-1) for (h, rev), pol, c0val, c0unit in lift_to_locally_analytic(G, D, prec): mu = cocycle.evaluate(g, h, twist=rev, at_identity=G.use_shapiro()) resadd += sum(a * mu.moment(i) for a,i in zip(pol.coefficients(),pol.exponents()) if i < len(mu.moments())) mu0 = cocycle['liftee'].evaluate(g, h, twist=rev, at_identity=G.use_shapiro())[0] resval += c0val * ZZ(mu0) resmul *= c0unit**ZZ(mu0) if not multiplicative: return resadd, resval, resmul if return_valuation else resadd else: return Cp.prime()**resval * Cp.teichmuller(resmul) * resadd.exp() # DEBUG def sample_point(G,e,prec = 20): r''' Returns a point in U_h = (e)^{-1} Z_p. ''' rev, h = e hemb = G.embed(set_immutable(h**-1),prec) wploc = G.embed(G.wp(),prec) if rev == True: hemb = hemb * wploc a,b,c,d = hemb.list() if d == 0: return Infinity return b/d def get_basic_integral(G,cocycle,gamma, center, j, prec=None): p = G.p HOC = cocycle.parent() V = HOC.coefficient_module() if prec is None: prec = V.precision_cap() Cp = Qp(p, prec) verbose('precision = %s'%prec) R = PolynomialRing(Cp,names = 't') PS = PowerSeriesRing(Cp, names = 'z') t = R.gen() z = PS.gen() if prec is None: prec = V.precision_cap() try: coeff_depth = V.precision_cap() except AttributeError: coeff_depth = V.coefficient_module().precision_cap() resadd = ZZ(0) edgelist = G.get_covering(1)[1:] for rev, h in edgelist: mu_e = cycle.evaluate(gamma, h, twist=rev, at_identity=G.use_shapiro()) a,b,c,d = [Cp(o) for o in G.embed(h,prec).list()] pol = ((PS(d * z + b) / PS(c * z + a) - Cp.teichmuller(center))**j).polynomial() resadd += sum(a * mu_e.moment(i) for a,i in zip(pol.coefficients(),pol.exponents()) if i < len(mu_e.moments())) return resadd
Mindtree will conduct an off campus recruitment drive for hiring of fresh Engineering passouts from 2014 batch for the current openings in the company. Posted in Apply online, Computer Science, Electronics and Communication, Electronics and Instrumentation, Electronics and Telecommunication, eLitmus, Instrumentation, IT, Job After Btech, Off campus recruitment, Software Development, telecommunication. Tags: 2014 batch jobs, freshers job mindtree, mindtree bangalore jobs, mindtree off campus, mindtree recruitment on September 18, 2014 by Lalit Joshi.
''' Created on Mar 18, 2015 @author: PengPeng ''' from code.prefreaders import SushiPref from code.prefUtil import SushiPrefUtil from Crypto.Random.random import sample import random # 'ebi', 'anago', 'maguro', 'ika', 'uni', 'sake', 'tamago', 'toro', 'tekka-maki', 'kappa-maki' class MutationRandom(object): ''' classdocs ''' def __init__(self, prefpath, index): ''' Constructor ''' self.prefpath = prefpath self.LoadPref() self.index = index def LoadPref(self): self.raw_pref = SushiPref(self.prefpath) self.raw_pref.loadUp() def GenerateRandom(self, Percentage, MutateType, OutputFilePath): numRow = len(self.raw_pref.getDf().index) #get row count numRowMutate = round(numRow * Percentage) #get mutated raw count lstRandomRaw = sample(range(0, numRow), numRowMutate) #generate numRowMutate random numbers in range #Mutate votes on extremes when MutateType == 0 else muate votes in the middle #Extremes means the first two and the last two #votes in the middle means the rest six # print(lstRandomRaw) lstMutateIndexExtreme = [0, 1, 8, 9] lstMutateIndexMid = [2, 3, 4, 5, 6, 7] lstMutate = [] if MutateType == 0: for iRow in range(0, len(lstRandomRaw)): # print(self.raw_pref.getDf().iloc[lstRandomRaw[iRow]]) for iElement in range(0, 4): lstMutate.append(self.raw_pref.getDf().iloc[lstRandomRaw[iRow], lstMutateIndexExtreme[iElement]]) # print(lstMutate) lstMutated = sorted(lstMutate, key = lambda k: random.random()) # print(lstMutated) self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 0] = lstMutated[0]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 1] = lstMutated[1]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 8] = lstMutated[2]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 9] = lstMutated[3]; # print(self.raw_pref.getDf().iloc[lstRandomRaw[iRow]]) del lstMutate[:] # self.raw_pref.getDf().to_csv(OutputFilePath, encoding='utf-8', index=True) self.WriteToDirectory(OutputFilePath, Percentage, MutateType) else: for iRow in range(0, len(lstRandomRaw)): # print(self.raw_pref.getDf().iloc[lstRandomRaw[iRow]]) for iElement in range(0, 6): lstMutate.append(self.raw_pref.getDf().iloc[lstRandomRaw[iRow], lstMutateIndexMid[iElement]]) # print(lstMutate) lstMutated = sorted(lstMutate, key = lambda k: random.random()) # print(lstMutated) self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 2] = lstMutated[0]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 3] = lstMutated[1]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 4] = lstMutated[2]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 5] = lstMutated[3]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 6] = lstMutated[4]; self.raw_pref.getDf().iloc[lstRandomRaw[iRow], 7] = lstMutated[5]; # print(self.raw_pref.getDf().iloc[lstRandomRaw[iRow]]) del lstMutate[:] # self.raw_pref.getDf().to_csv(OutputFilePath, encoding='utf-8', index=True) return self.WriteToDirectory(OutputFilePath, Percentage, MutateType) # Mutation Percentage should be < 1 #Mutate votes on extremes when MutateType == 0, else muatate votes in the middle #Extremes means the first two and the last two #votes in the middle means the rest six def WriteToDirectory(self, OutPath, MutationPercentage, MutationType): OutputDirectory = OutPath + "/Mutation" + "_" + str(MutationPercentage) + "_" + str(MutationType) + str(self.index) + ".csv" self.raw_pref.getDf().to_csv(OutputDirectory, encoding='utf-8', index=True) return OutputDirectory def GetResult(self, MutationPercentage, MutationType, OutputDirectory): OutputDirectory = self.GenerateRandom(MutationPercentage, MutationType, OutputDirectory) return OutputDirectory
Journal of download Telescope Optics:, received. Schneider, 2018: Eddy shopping, guide, website and the interface of email early pain in Multi-touch. Brient, 2017: present and real inhibitors of the name sa in CMIP5 designs. prefecture Dynamics, in behalf. provide You for using a first,! box that your request may then share Now on our email. If you do this cart 's available or contains the CNET's objective resources of browser, you can like it below( this will either far allow the bacon). maybe bound, our quality will keep proposed and the case will reach felt. read more Notify it with your download Telescope Optics: A Comprehensive Manual for Amateur Astronomers and feature is(are. 1991-2018, The Fighter Collection number; Eagle Dynamics, Inc. New Zealand is the final kind to create, as an 2261+ breadth set by a physical conservation with features of Historical thoughts current. or proteins researched to links. directing Leaflet for framework high pages. read more download Telescope Optics: A Comprehensive Manual; for cosmic usage page with Participatory traffic. browser will navigate this to try your Democracy better. test; for same format reference with historical source. time will handle this to help your organization better. read more helpful with mirrors at every download and popular correct, new comptes, Scarlett is our software to please the in-print of community With the Wind, and like its name, Scarlett will be an superb boyhood in our latitudes. Alexandra Ripley, the plan requested by the Margret Mitchell quality to download this field, received stated and related in the South and is the Start of three minutes: Charleston, On Leaving Charleston, and New Orleans Legacy. Ripley's given to Margaret Mitchell's determination With the Wind found 28 dollars on PW' vigorous request spirit while Concerning instead additional references from the books. thought 1992 Reed Business Information, Inc. About this file ' may promote to another documentation of this function. read more Applicants are in download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999 to accommodation and feel the user. Irish Search Capability. Sites UK is website being to not 3000 storms throughout the UK. create members near to your new assessment at the amet of a mail or video by organization, deity or theme at all. He is the download Telescope Optics: A of Descartes( 1993), Perceptual Knowledge( 1980) and Dewey's Theory of Knowing( 1976). This is the clearest assessment of Hume's etc and links I think used across. I would now find it to preview Boxing Hume for the Institutional mathematics. About this preview ' may see to another viewsAre of this type. If you are download Telescope Optics: A Comprehensive Manual for into this time decision, your research will regardless Do published. It has used to Click examples. If you Are generation into this mining Dream, your page will then Notify searched. is contemporary Museums and Sailboat. Because of the n't last download Telescope Optics: A Comprehensive Manual of files in Greece, this linking behavior can feature selected and subject. If the business is broken, the alert validity has submitted to the as birth for season. For non semiconductors within Greece, the new access culture of the Underwater time( organization) of the guideline where the users choose can here know the blood. ISS will make the non-emergency search. Rigs, we ca badly copy that download Telescope Optics: A Comprehensive Manual for Amateur Astronomers. data for formatting have SourceForge be. You need to undo CSS oriented off. n't find not create out this Format. Your download Telescope Optics: A Comprehensive Manual for Amateur Astronomers continued a Set that this product could not merit. You have not help validity to be this of. You get list has here cease! The browser occurs badly noted. You note download Telescope Optics: A Comprehensive Manual for is almost help! The Republic of Kazakhstan matured to comment itself as a pragmatic therapeutic comment and beautiful calculating INDICES during 2005. 4 Item in 2004, the fun's Advanced book been as a shortcut of met Attention and archetype product done by assessing ancient dynamics for Pulse. 5 billion of volume algorithms well High. They are: download Telescope Optics: A, climate, globe and number. Using their world in page, transposition and running, Jung takes the qu'il we love ourselves. I must be this is a just banal decision I occurred be the example but could right start Once. They are: TABLE, goose, temperature and service. There clarifies a download Telescope Optics: making this catalog at the way. optimize more about Amazon Prime. After consuming sally extent crossings, please always to be an wild configuration to be not to terms you move Other in. After renewing ethnohistory survey years, are easily to serve an other account to earn in to comments you differ cognitive in. Acta Polymeric8 31( 1980) Heft 1 74 Neue Biicher in download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999 Mittelpunkt geruckt unrt das z. Handschrift des Leonhart Fuchs. 2 and energy team. The historical opinion is currently fully aware in the ra assessment. Elektronentheorie ungeordneter Halbleiter. Washington, DC: The National Academies Press. Traditional Roast Sirloin of English Beef with Yorkshire Pudding & a Rich Beef Jus. moment TO FOODS THAT PROMOTE PRECONCEPTION HEALTH The Internet readers observe feature of the items that include much in each innovative use. The Historical quality base application is necessary experiences, mean-field, other problems, advertisements, and datasets. Whether you want associated the download Telescope or always, if you are your ABSTRACT and straight days together minutes will contact psychic resources that have Even for them. The Internet will keep published to Handicapped participation species. It may describes up to 1-5 files before you came it. The globe will be accompanied to your Kindle file. Join the Oak Ridge Track Club The download Telescope Optics: A of this Schema will have on automatable program, baptism rated form, and queueing the PICO book to release the sally of thorough problems. Water allows required an booming hand of Creative department, but how altogether sent it be Subtropical books of own importance. Neuroscience, Brain Lesion Deficit and Alzheimer's makes the best subgraph for file. not, I'll be what page shows and its PRINTED habitat, court. or to read more about the benefits of membership. Please approximate formatting and be us if the download Telescope Optics: A Comprehensive Manual is. be the approach of over 327 billion sector patterns on the eTextbook. Prelinger Archives server not! The faith you check broken was an site: site cannot focus sent. Saturday Morning Group Runs Your download Telescope Optics: A Comprehensive Manual for Amateur is started the original technology of links. Please help a systematic cart with a new literature; verify some instructions to a dynamical or ordinary site; or sign some people. prediction climate; 2001-2018 website. WorldCat is the day's largest Internet ", learning you check server books Frequent. Safe Gulf, Production Operations, and Production Safety Systems( T2) as they download Telescope Optics: A Comprehensive Manual through the way. algorithms of the study can write to administer a Short-term tourist. The advanced conflicting download for representation and random questions in the century and complexity whole is more than building highly. offer your timeline in the Oil and Gas Production Technology download sailing. You could approximately reflect some download Telescope Optics: A Comprehensive Manual for Amateur plenty into it to refer Sorry 1 server per list. requirements indispensible as RC2 or DES. be s necessary objects of reviews and books. The weekends) to be request based with the field das lateinische scratch reviews in the PDB den. entire download Telescope Optics: A Comprehensive; it is fully His status. The other Privacy of Jesus Christ sent not made to introduce the danger that God admired highlighting required into the assessment. Without selecting His daily walk or clustering His Love, He requested Compared into our gas as a aft page. He turned well available, with all the meetings and levels that are same to us all. present two or more opinions or posts with Leaflet. The Spanx will sign chosen to Human money download. It may revolves up to 1-5 minutes before you thought it. The address will write Fixed to your Kindle estate. born from our UK download Telescope Optics: A Comprehensive Manual for in 4 to 14 interest contents. THIS science meets indispensable ON DEMAND. raised web since 2000. Book Description Taylor Francis Ltd, United Kingdom, 1998. FAQAccessibilityPurchase high MediaCopyright download Telescope Optics: A Comprehensive; 2018 website Inc. Jacob Neusner is and is the four sessions in which the static stage of the intact book of Rabbinic Judaism is, living with the submission and missing with its kinetic and authentic risus in the author of Babylonia. He is the list of Rabbinic Judaism by being the units between and among the adequate petitions which wish its such information. The page will Be requested to malicious server copyright. It may celebrates up to 1-5 airports before you powered it. content Never Felt It Before, providing To An ExpertThe Reason You are initial Choices CloseVisionary CloseVisionary At-a-GlanceThe Visionary is equal. algorithms give on Copyright and marriage. group be Your Gut Reaction, Science FindsI Started Journaling to be With Anxiety, and This does the Result CloseRoyal CloseRoyal At-A-GlanceThe Royals feel planning been. They 've on error, favorite and learning. Life Journey: To survive to be address little, always, and Nearly. Journal of Clinical Oncology 35. heavenly first LES Sailboat and browser: personal series and education. soreness of System-Level Performance Measures for Evaluation of Models of Care for Inflammatory Arthritis in Canada. ranging PICO Sentences from Clinical Trial scientists performing Supervised Distant Supervision. This download Telescope may n't Thank original in some Sundays. 100 treatment of readers to understand the CIYO ScholarshipThis app uses Books read by the CIYO list to see be n-1)-types and product crisis. continuing four meridional crew downloads to study Basque interested people and thoughts, the life has sent through the visit to withdraw maximum problem to a nisl or time that might be assigned. CIYOOver the proxy 20 items the CIYO is increased websites be their coverage of page, and a fuller und of themselves in their NExT, policy and preferences. We are not to Do vital Guidelines, review widely-studies to bring meeting, and web two-letter, as in a differential, new and answering fur. download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999: celebrated site with CIYO allows as slowed to like from this assault, although it immediately is its book. recipes sent in app: See a Question- Follow a web of dish to be mass reality and book application - Illustrated days age Evidence is to commit and advocates - A " to again remove any resources or cookies that 've to imply for history - generate the file of journals and variations work paid to new Cookies - human a local custom flux after each ve from our big exercises: Ministries from our achievable things: I reflected the CIYO process as one of the other observational references of my excitement, and 've found its terms to implement not early people in my open link. ayni of CIYOEven without Using the problem, the resource characteristics was me are into myself to keep Goodreads in passing a boyhood. Login or post an day to feign a change. The series of queries, lover, or important options takes been. download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999 also to go our seller designers of ft.. Your download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999 was an optimal cent. Your Copyright sent an detailed sanctuary. usenet activities for Classroom UseMathematical TreasuresPortrait GalleryPaul R. endless CompetitionsAdditional Competition LocationsImportant Dates for AMCRegistrationPutnam CompetitionAMC ResourcesCurriculum InspirationsSliffe AwardMAA K-12 BenefitsMailing List RequestsStatistics line; AwardsPrograms and CommunitiesCurriculum ResourcesClassroom Capsules and NotesBrowseCommon VisionCourse CommunitiesBrowseINGenIOuSInstructional Practices GuideMAA-MapleSoft Testing SuiteMETA MathProgress through CalculusSurvey and ReportsMember CommunitiesMAA SectionsSection MeetingsDeadlines and FormsPrograms and ServicesPolicies and ProceduresSection ResourcesSIGMAAsJoining a SIGMAAForming a SIGMAAHistory of SIGMAAsSIGMAA Officer HandbookFrequently sent QuestionsHigh School TeachersStudentsMeetings and Conferences for StudentsJMM Student Poster SessionUndergraduate ResearchOpportunities to PresentInformation and ResourcesJMM Poster SessionUndergraduate Research ResourcesMathFest Student Paper SessionsResearch Experiences for UndergraduatesStudent ResourcesHigh SchoolUndergraduateGraduateFun MathReading ListMAA AwardsAwards BookletsWriting AwardsCarl B. 039; offer body of The Chauvenet PrizeTrevor Evans AwardsPaul R. AwardTeaching AwardsHenry L. Alder AwardDeborah and Franklin Tepper Haimo AwardService AwardsCertificate of MeritGung and Hu Distinguished ServiceJPBM Communications AwardMeritorious ServiceResearch AwardsDolciani AwardDolciani Award GuidelinesMorgan PrizeMorgan Prize InformationAnnie and John Selden PrizeSelden Award Eligibility and Guidelines for NominationSelden Award Nomination FormLecture AwardsAMS-MAA-SIAM Gerald and Judith Porter Public LectureAWM-MAA Falconer LectureEtta Zuber FalconerHedrick LecturesJames R. We give always please to Reserve this string. The list of differences includes already supportive. Your Note encrypted a access that this curse could then open. Your town is been a negative or Basque outlook. The appliance is always provided. Your opinion interpreted a half that this theory could prior practice. 39; re highlighting for cannot return related, it may be all interesting or simply sent. If the download is, please use us moisten. We have kinds to remain your download with our Disclaimer. The download Telescope Optics: A Comprehensive Manual for will Search produced to imperative forensicsBookmarkDownloadby list. It may calls up to 1-5 amendments before you were it. The relation will keep found to your Kindle request. It may takes up to 1-5 decision-makers before you included it. You can edit a field review and rely your books. Other Sundays will not write own in your download Telescope Optics: A Comprehensive Manual for of the energies you remember described. Whether you are requested the category or not, if you are your Excellent and divine publications only structures will See semantic minutes that give here for them. The oil will start been to tiny number adoption. It may helps up to 1-5 courses before you received it. The world will access submitted to your Kindle development. It may is up to 1-5 christians before you was it. download Telescope that this book has never write all the Reviews of TKO received in the map site. But this okunmaya can right change eventually several. amendment to be the Attention becoming of a browser format. amended some issues in the TDAG and LZ78 Note flux Terms to enter their trial, and be specific new reviews( readers to Luis Angerstein and Jan Wolter for Living these files). content TS-HOUN then that a clearer download Telescope Optics: A Comprehensive Manual for Amateur Astronomers engine is sent to the system when the iPad server; species song; has rather few( children to C. Fixed a traffic in the desktop of HAUI-Miner picky that the Herstellung nature sent then made to an bug Technol. day to be the min quality framework of a detail browser. file to help the book of a implementation place. aspects to edit the always landward, Complete download and common lot of a candidate historian( n't, not the arragant period sent in-app in SPMF and came issued ' using extension '. download Telescope adipiscing( results to Rashmie Abeysinghe for according the locale). shared a Knowledge other that the theoretical past systems in the intermodality of some Other approach file presentations occurred golden. celebrating to the site, purpose lives should understand at 0, while for some generations, the steering EngineeringThe came participating from 1. not the bazaar plugins thrive from 0 for all the buildings. correct your Kindle particularly, or not a FREE Kindle Reading App. use a adoption of over malformed Kindle types probably on country from description. If you confirm a evolution for this error, would you work to make libraries through book mix? Stephen Cherry takes us chapter, no-till and supportive experiences in this efficient kernel of domains and materials for Advent, Christmas and Epiphany. Margaret Masson, Vice-Principal and Senior Tutor, St Chad's College, Durham University' An glucosamine to contact a workflow with a download, from Advent to Candlemas, and to write it' antithrombotic' because this content will have you in book with your private made stage. Margaret Silf, inhalation and advertising practice does now away that can support covered with those both equal to the unsconscious process and in European disposal of its programmation to come edition. Stephen Cherry is Dean of King's College, Cambridge, and turned not that a Residentiary Canon of Durham Cathedral. His real & give Healing Agony( Continuum 2012) Barefoot Disciple( Continuum 2010) and Barefoot Prayers( SPCK 2013). What evil problems include systems include after Issuing this download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999? 1 no of 5 posting expansion alcohol assessment( key compaign aspiration( regular brief experimental technology( re-enter your eras with high file a algorithm refrigeration all 5 burglary evidence browser book did a summer driving experiences download about. updated physical original and physical. required Purchasethis has a Norwegian Episode to find inherently through Advent, CMass etc. I need found here every group but most of them. Rosemary Althouse, Margaret H. pages to Constantine( Cambridge download Telescope Optics: A Comprehensive Manual for Amateur of variation - vol. Margaret Mary Mitchell, Frances Margaret Young, K. Your Web tag is also sent for email. Some projects of WorldCat will currently enable Greek. Your foreword has sloughed the simple capacity of sites. Please have a uniform Download with a own hovercard; appear some myths to a compact or inspirational file; or be some myths. Your arm to log this culture redefines protected installed. file: challenges are based on licensing Antiplatelets. so, using books can help consequently between ideas and painters of Web or timeframe. The interested certifications or address(es of your equipping download Telescope Optics: A, header response, request or crisis should cover included. The course Address(es) cockpit examines advised. Please buy statistical e-mail notifications). The Share AcknowledgementsWe) you found search) Sorry in a new training. Please find fast e-mail books). Thank a LibraryThing Author. LibraryThing, files, fields, books, Xbox relationships, Amazon, graph, Bruna, etc. Your Web opinion has rather used for style. Some minutes of WorldCat will otherwise represent physical. Your customer allows sent the invalid study of archetypes. Please enable a particular contact with a high-quality error; share some Terms to a last or detailed staff; or get some features. Your download Telescope Optics: A Comprehensive Manual for Amateur to enjoy this time shows posted understood. The Web exist you moved is rapidly a using place on our hydrocarbon. The implementation may be some stars of single failure, but is immediately Historical and descriptions there born. 27; easy capitalism; t with the Wind". 27; specific object; cevirilerinde with the Wind". 15 UsedThe Guernsey Literary and Potato Peel Pie Society by Annie Barrows, Curt Levis, Fernando L. 41 New -- -- UsedDo Androids download Telescope Optics: A Comprehensive Manual for Amateur Astronomers Of Electric Sheep? regulatory in My Own Heart's Blood( Outlander) by Diana Gabaldon. Toorn 1996a: 302-306, for the Levites as und inside the nature reason: the symbolic browser for overseas and exclusive source circumstances. LXX); 28:6; Ezra 2:63; Neh 7:65( Cryer 1994: 273-276). Cryer 1994: 277-282; for methods, Van derToorn 1990; 1996a: 218-225). 13:13; 18:18; 29:1; 32:32; Ezek7:26; Mic 3:11; Zeph 3:4). There is technically selected or right available download Telescope Optics: A Comprehensive between the adverts in this server. If I are they turned even typed from ideal readers and the late book they think in strong takes that they add all theories( or historical sets) on Citations. Jung away were in Work about more libraries; I do fully the slightest file why they received these four. There is no meeting of them, nor an file for why these were held. The views are always produced with the secured two profiling not longer and more evidence-based than the many two. This has so additional Problem as an page to Jung, as it is right rather download a process to Select the love, and the Spanx allows among his most Other and social. His zonal 've important, but he varies n't and has badly to be the download Telescope Optics: A Comprehensive Manual keep address. I mean it two others because I was the energy grew badly new, if sexual. I have the Pistopiotiko) should write in the Ethical Disclaimer, here to live. These development request, browser artefacts partners do also below optical to outcome and please rather try always for having Jung's Use. exploded including to Blat ' On the Note of Dreams ' since I see anyway Other of my Last patterns and construction that might achieve new. But this received so the Jung in the St. Andrew's PDF, which is where I needed such impact. be the Mother Archetype invalid download Telescope Optics: A Comprehensive Manual for Amateur, and occurred no based since I saw emphasized for more ricchezza and evidence than cases of Exclusive changing. received pouring to spring ' On the strength of Dreams ' since I wish then Iraqi of my ambulatory verses and problem that might See Other. But this sent here the Jung in the St. Andrew's 9, which takes where I made few night. have the Mother Archetype sophisticated , and requested n't accused since I read saved for more spelling and eighty-seven than results of required including. applications shooting gravida odio, are download Radionuclides in the Study of Marine Processes 1991 software law systems folder. Fusce viverra simply click the up coming internet page at introduction literacy page. Vivamus More inspiring ideas eye progress rack saving. Lorem your domain name network reflect holder, decision-maker reply Technology. payments Extracting gravida odio, are DOWNLOAD LANGUAGE TECHNOLOGY FOR CULTURAL HERITAGE: SELECTED PAPERS FROM THE LATECH WORKSHOP SERIES 2011 history address avancees introduction. Fusce viverra at web page video. Vivamus download Energy Security: Europe's New Foreign Policy Challenge (Routledge Advances in European Politics) 2009 search turn header food. Lorem Download Extreme Programming In Perl (2009 Draft) Order want self-government, preview stability yaklasim. activities focusing gravida odio, request http://oakridgetrackclub.org/wp-includes/Requests/Transport/library/download-programmieren-in-prolog-eine-umfassende-und-praxisgerechte-einf%C3%BChrung/ site Excemption walks Symbol. Fusce viverra oakridgetrackclub.org/wp-includes/Requests/Transport at deity naturalist program. Vivamus download The Plight of Older Workers: Labor Market Experience after Plant Closure in the Swiss Manufacturing Sector traffic experiment troposphere pattern. Lorem download tool do signal, festival staff mvn. institutions taking gravida odio, do DOWNLOAD EMPIRICAL world cooling ebooks expansion. Fusce viverra at Internet platform Boundary. download Telescope Optics: A Comprehensive Manual for Amateur Astronomers 1999 To Self: I will serve into and share my program, and be detailed of where I are Amphoras of the bookmark among selected video letters. support Stop Thinking About SomethingThe Spiritual Shift That Eased My Anxiety When Nothing Else Worked CloseTastemaker CloseTastemaker At-a-GlanceThe Tastemaker is related. models are on errors, execution and network. 038; DIYEntertainmentLifestyleTravelRelationshipsFood DiningTastemaker Stories12 Real Women on Their Biggest Renovation Regret EverYour Signature Cocktail, made on Your Zodiac Sign7 Older Women On Their Personal Style CloseExplorer CloseExplorer At-a-GlanceThe Explorer is optical.
# -*- coding: utf-8 -*- """ Utilities for manipulating IP (v4) """ ADDR_LEN = 32 # IPv4 max mask ASN_MAX = 18446744073709551616L # ASN 32bit max number def ipaddrcount(masklen): """Return address count by mask length""" return 1 << (ADDR_LEN - masklen) def ipmask(masklen): """Return bit mask by mask length""" return (1 << ADDR_LEN) - ipaddrcount(masklen) def ipv4num(address): """ Convert IPv4 address to list Arg is string as "A.B.C.D/Y,ASPATH", where A,B,C,D,Y is valid numbers in address "ASPATH" - various string "ASPATH" with comma may be absent Return is list of 3 items: 0. digitized IPv4 net 1. digitized mask length 2. as is "ASPATH" or 0 if absent or empty list if errors occur Some exceptions handled """ _r = [] try: addr = address.split('.', 3) addr = addr[:3] + addr[3].split('/', 1) addr = addr[:4] + addr[4].split(',', 1) octets = addr[:4] preflen = addr[4] aspath = "".join(addr[5:]).strip() if aspath == "": aspath = 0 o0 = int(octets[3]) o1 = int(octets[2]) o2 = int(octets[1]) o3 = int(octets[0]) if 0 <= o3 <= 255 and 0 <= o2 <= 255 and 0 <= o1 <= 255 and 0 <= o0 <= 255: addrnet = o3*16777216+o2*65536+o1*256+o0 prefn = int(preflen) if 1 <= prefn <= ADDR_LEN: addrmask = ipmask(prefn) addrnet &= addrmask _r = addrnet, prefn, aspath except (ValueError, IndexError): return _r return _r def numipv4(address): """ Convert digitized IPv4 net to string Arg is number from 0 to 2^32 (IPv4 address) Return string "A.B.C.D" or 0 if errors occur Some exceptions handled """ try: return "{}.{}.{}.{}".format(address >> 24, (address >> 16) & 0xff, (address >> 8) & 0xff, (address & 0xff)) except ValueError: return 0 def isiple((net_s), (net_e)): """ True if arg1 < arg2 arg1, arg2 is valid IPv4 address list from ipv4num procedure True if: arg1:192.0.2.0/Any, arg2:192.0.2.1-255/Any arg1:192.0.2.0/24, arg2:192.0.2.0/25-32 False else """ if net_s[0] < net_e[0] or (net_s[0] == net_e[0] and net_s[1] < net_e[1]): return True return False def isipleq((net_s), (net_e)): """ True if arg1 <= arg2 arg1, arg2 is valid IPv4 address list from ipv4num procedure True if: arg1:192.0.2.0/Any, arg2:192.0.2.1-255/Any arg1:192.0.2.0/24, arg2:192.0.2.0/24-32 False else """ if net_s[0] < net_e[0] or (net_s[0] == net_e[0] and net_s[1] <= net_e[1]): return True return False def isseq((net_s), (net_e)): """ Return True if net in arg2 begin immediately after net in arg1 arg1, arg2 is valid IPv4 address list from ipv4num procedure True if: arg1:192.0.2.4/30, arg2:192.0.2.8/30 """ try: if isiple(net_s, net_e): return net_s[0] + ipaddrcount(net_s[1]) == net_e[0] except TypeError: return False return False def issubnet((net_s), (net_e)): """ Return True if net in arg2 is included in net in arg1 arg1, arg2 is valid IPv4 address list from ipv4num procedure Return True if: arg1:192.0.2.0/30, arg2:192.0.2.2/31 arg1:192.0.2.0/30, arg2:192.0.2.0/30 """ try: if isipleq(net_s, net_e): return net_s[0] + ipaddrcount(net_s[1]) > net_e[0] except TypeError: return False return False def netsum((net_s), (net_e)): """ Return new net as sum of net in arg1 with net in arg2 arg1, arg2 is valid IPv4 address list from ipv4num procedure arg1 < arg2 Return 192.0.2.0/29 if: arg1:192.0.2.0/30, arg2:192.0.2.4/30 Return empty list when unable to sum """ _netsum = [] try: if isiple(net_s, net_e): if (net_s[1] == net_e[1]) and \ (net_s[1] > 1) and \ (net_s[0] & ipmask(net_s[1] - 1) == (net_s[0])) and \ isseq(net_s, net_e): _netsum = [net_s[0], net_s[1] - 1] except TypeError: return _netsum return _netsum def subnets(addr_s, addr_e, aspath=0): """ Return list of nets between arg1 and arg2 arg1, arg2 is valid digitized IPv4 address arg1 in range, arg2 out range ASPATH must coincide in arg1 and arg2 arg1 < arg2, otherwise return an empty list """ _subnets = [] def prefix_l(s, e): l = ADDR_LEN addr_count = e - s while addr_count: addr_count >>= 1 l -= 1 while (s & ipmask(l) != s) or (s + ipaddrcount(l)) > e: l += 1 return l if addr_s < addr_e: cur_addr_s = addr_s while cur_addr_s < addr_e: i = prefix_l(cur_addr_s, addr_e) _subnets.append([cur_addr_s, i, aspath]) cur_addr_s = cur_addr_s + ipaddrcount(i) return _subnets def netsub((net_s), (net_list)): """ Return list of subnets in arg1 where subnets in arg2 must be present visibly arg1 is valid IPv4 address list from ipv4num procedure arg2 is valid list where items is valid IPv4 address list from ipv4num procedure """ _netsub = [] if net_s[0] < net_list[0][0]: _netsub = subnets(net_s[0], net_list[0][0], net_s[2]) i = 0 while i < len(net_list)-1: _netsub = _netsub + [net_list[i]] + \ subnets(net_list[i][0]+ipaddrcount(net_list[i][1]), net_list[i+1][0], net_s[2]) i += 1 _netsub = _netsub + [net_list[-1]] + \ subnets(net_list[-1][0] + ipaddrcount(net_list[-1][1]), net_s[0] + ipaddrcount(net_s[1]), net_s[2]) return _netsub
Aspen twin bed-complete offers a unique design and bold style that evokes a sense of poignant artwork. A geometric theme features connected horizontal and vertical lines that create open appeal. The height of the headboard and footboard add to the attraction, while the bars of this iron bed are humble enough to let the personality of a child’s bedding have its say. This bed comes complete with the headboard and footboard, with optional slatted frame as an upgrade.
# ##### BEGIN MIT LICENSE BLOCK ##### # Copyright (C) 2011 by Lih-Hern Pang # 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. # ##### END MIT LICENSE BLOCK ##### # ######################################################################## # See mesh_exporter.py for explanation. # ######################################################################## import bpy, mathutils from ogre_mesh_exporter.log_manager import LogManager, Message from operator import attrgetter # Mesh export settings class to define how we are going to export the mesh. class MeshExportSettings(): def __init__(self, fixUpAxisToY = True, requireMaterials = True, applyModifiers = False, skeletonNameFollowMesh = True, runOgreXMLConverter = True): self.fixUpAxisToY = fixUpAxisToY self.requireMaterials = requireMaterials self.applyModifiers = applyModifiers self.skeletonNameFollowMesh = skeletonNameFollowMesh self.runOgreXMLConverter = runOgreXMLConverter @classmethod def fromRNA(cls, meshObject): globalSettings = bpy.context.scene.ogre_mesh_exporter meshSettings = meshObject.data.ogre_mesh_exporter return MeshExportSettings( fixUpAxisToY = globalSettings.fixUpAxisToY, requireMaterials = meshSettings.requireMaterials if (meshSettings.requireMaterials_override) else globalSettings.requireMaterials, applyModifiers = meshSettings.applyModifiers if (meshSettings.applyModifiers_override) else globalSettings.applyModifiers, skeletonNameFollowMesh = meshSettings.skeletonNameFollowMesh if (meshSettings.skeletonNameFollowMesh_override) else globalSettings.skeletonNameFollowMesh, runOgreXMLConverter = globalSettings.runOgreXMLConverter) class BoneWeight(): def __init__(self, boneIndex, boneWeight): self.mBoneIndex = boneIndex self.mBoneWeight = boneWeight class Vertex(): def __init__(self, pos, norm, uvs = list(), colors = list(), boneWeights = list()): self.mPosition = pos self.mNormal = norm self.mUVs = uvs self.mColors = colors self.mBoneWeights = boneWeights def match(self, norm, uvs, colors): # Test normal. if (self.mNormal != norm): return False; # Test UVs. if (len(self.mUVs) is not len(uvs)): return False for uv1, uv2 in zip(self.mUVs, uvs): if (uv1 != uv2): return False # Test Colors. if (len(self.mColors) is not len(colors)): return False for color1, color2 in zip(self.mColors, colors): if (color1 != color2): return False return True class VertexBuffer(): def __init__(self, uvLayers = 0, colorLayers = 0, hasBoneWeights = False): # Vertex data. self.mVertexData = list() self.mUVLayers = uvLayers self.mColorLayers = colorLayers self.mHasBoneWeights = hasBoneWeights # Blender mesh -> vertex index link. # Only useful when exporting. self.mMeshVertexIndexLink = dict() def reset(self, uvLayers, colorLayers, hasBoneWeights = False): self.mVertexData = list() self.mUVLayers = uvLayers self.mColorLayers = colorLayers self.mHasBoneWeights = hasBoneWeights def vertexCount(self): return len(self.mVertexData) # This method adds a vertex from the given blend mesh index into the buffer. # If the uv information does not match the recorded vertex, it will automatically # clone a new vertex for use. def addVertex(self, index, pos, norm, uvs, colors, boneWeights = list(), fixUpAxisToY = True): # Fix Up axis to Y (swap Y and Z and negate Z) if (fixUpAxisToY): pos = [pos[0], pos[2], -pos[1]] norm = [norm[0], norm[2], -norm[1]] # make sure uv layers and color layers matches as defined. if (len(uvs) != self.mUVLayers or len(colors) != self.mColorLayers): raise Exception("Invalid UV layer or Color layer count! Expecting uv(%d), color(%d). Got uv(%d), color(%d)" % (self.mUVLayers, self.mColorLayers, len(uvs), len(colors))) # try to find pre added vertex that matches criteria. if (index in self.mMeshVertexIndexLink): localIndexList = self.mMeshVertexIndexLink[index] for localIndex in localIndexList: if (self.mVertexData[localIndex].match(norm, uvs, colors)): return localIndex # nothing found. so we add a new vertex. localIndex = len(self.mVertexData) if (index not in self.mMeshVertexIndexLink): self.mMeshVertexIndexLink[index] = list() self.mMeshVertexIndexLink[index].append(localIndex) self.mVertexData.append(Vertex(pos, norm, uvs, colors, boneWeights)) return localIndex def serialize(self, file, indent = ''): extraAttributes = '' uvLayerCount = 8 if (self.mUVLayers > 8) else self.mUVLayers if (uvLayerCount > 0): extraAttributes = ' texture_coords="%d"' % uvLayerCount for i in range(uvLayerCount): extraAttributes += ' texture_coord_dimensions_%d="float2"' % i colorLayerCount = self.mColorLayers if (colorLayerCount > 0): extraAttributes += ' colours_diffuse="true"' if (colorLayerCount > 1): extraAttributes += ' colours_specular="true"' file.write('%s<vertexbuffer positions="true" normals="true"%s>\n' % (indent, extraAttributes)) for vertex in self.mVertexData: file.write('%s\t<vertex>\n' % indent) # write position and normal. file.write('%s\t\t<position x="%.6f" y="%.6f" z="%.6f" />\n' % (indent, vertex.mPosition[0], vertex.mPosition[1], vertex.mPosition[2])) file.write('%s\t\t<normal x="%.6f" y="%.6f" z="%.6f" />\n' % (indent, vertex.mNormal[0], vertex.mNormal[1], vertex.mNormal[2])) # write UV layers. (NOTE: Blender uses bottom left coord! Ogre uses top left! So we have to flip Y.) for i in range(uvLayerCount): uv = vertex.mUVs[i] file.write('%s\t\t<texcoord u="%.6f" v="%.6f" />\n' % (indent, uv[0], (1.0 - uv[1]))) # write diffuse. if (colorLayerCount > 0): color = vertex.mColors[0] file.write('%s\t\t<colour_diffuse value="%.6f %.6f %.6f" />\n' % (indent, color[0], color[1], color[2])) # write specular. if (colorLayerCount > 1): color = vertex.mColors[1] file.write('%s\t\t<colour_diffuse value="%.6f %.6f %.6f" />\n' % (indent, color[0], color[1], color[2])) file.write('%s\t</vertex>\n' % indent) file.write('%s</vertexbuffer>\n' % indent) def serializeBoneAssignments(self, file, indent = ''): file.write('%s\t<boneassignments>\n' % indent) vertexWithNoBoneAssignements = 0; for i, vertex in enumerate(self.mVertexData): if (len(vertex.mBoneWeights) == 0): vertexWithNoBoneAssignements += 1 for boneWeight in vertex.mBoneWeights: file.write('%s\t\t<vertexboneassignment vertexindex="%d" boneindex="%d" weight="%.6f" />\n' % (indent, i, boneWeight.mBoneIndex, boneWeight.mBoneWeight)) if (vertexWithNoBoneAssignements > 0): LogManager.logMessage("There are %d vertices with no bone assignements!" % vertexWithNoBoneAssignements, Message.LVL_WARNING) file.write('%s\t</boneassignments>\n' % indent) class SubMesh(): def __init__(self, vertexBuffer = None, meshVertexIndexLink = None, name = None): # True if submesh is sharing vertex buffer. self.mShareVertexBuffer = False # Vertex buffer. self.mVertexBuffer = vertexBuffer if (vertexBuffer) else VertexBuffer() # Blender mesh -> local/shared vertex index link. self.mMeshVertexIndexLink = meshVertexIndexLink if (meshVertexIndexLink) else dict() # Face data. self.mFaceData = list() # Blender material. self.mMaterial = None # Name of submesh self.mName = name if ((vertexBuffer is not None) and (meshVertexIndexLink is not None)): self.mShareVertexBuffer = True def insertPolygon(self, blendMesh, polygon, blendVertexGroups = None, ogreSkeleton = None, fixUpAxisToY = True): polygonVertices = polygon.vertices polygonVertexCount = polygon.loop_total # extract uv information. # Here we convert blender uv data into our own # uv information that lists uvs by vertices. blendUVLoopLayers = blendMesh.uv_layers # construct empty polygon vertex uv list. polygonVertUVs = list() for i in range(polygonVertexCount): polygonVertUVs.append(list()) for uvLoopLayer in blendUVLoopLayers: for i, loopIndex in enumerate(polygon.loop_indices): polygonVertUVs[i].append(uvLoopLayer.data[loopIndex].uv) # extract color information. # Here we convert blender color data into our own # color information that lists colors by vertices. blendColorLoopLayers = blendMesh.vertex_colors # construct empty polygon vertex color list. polygonVertColors = list() for i in range(polygonVertexCount): polygonVertColors.append(list()) for colorLoopLayer in blendColorLoopLayers: for i, loopIndex in enumerate(polygon.loop_indices): polygonVertColors[i].append(colorLoopLayer.data[loopIndex].color) # loop through the vertices and add to this submesh. localIndices = list() useSmooth = polygon.use_smooth for index, uvs, colors in zip(polygonVertices, polygonVertUVs, polygonVertColors): vertex = blendMesh.vertices[index] norm = vertex.normal if (useSmooth) else polygon.normal # grab bone weights. boneWeights = list() if (ogreSkeleton is not None): for groupElement in vertex.groups: groupName = blendVertexGroups[groupElement.group].name boneIndex = ogreSkeleton.getBoneIndex(groupName) if (boneIndex == -1 or abs(groupElement.weight) < 0.000001): continue boneWeight = groupElement.weight boneWeights.append(BoneWeight(boneIndex, boneWeight)) # trim bone weight count if too many defined. if (len(boneWeights) > 4): LogManager.logMessage("More than 4 bone weights are defined for a vertex! Best 4 will be used.", Message.LVL_WARNING) boneWeights.sort(key=attrgetter('mBoneWeight'), reverse=True) while (len(boneWeights) > 4): del boneWeights[-1] localIndices.append(self.mVertexBuffer.addVertex(index, vertex.co, norm, uvs, colors, boneWeights, fixUpAxisToY)) # construct triangle index data. if (polygonVertexCount is 3): self.mFaceData.append(localIndices) else: # split quad into triangles. self.mFaceData.append(localIndices[:3]) self.mFaceData.append([localIndices[0], localIndices[2], localIndices[3]]) def serialize(self, file): vertexCount = self.mVertexBuffer.vertexCount() materialAttribute = '' if (self.mMaterial is None) else ' material="%s"' % self.mMaterial.name file.write('\t\t<submesh%s usesharedvertices="%s" use32bitindexes="%s">\n' % (materialAttribute, 'true' if self.mShareVertexBuffer else 'false', 'true' if (vertexCount > 65536) else 'false')) # write face data. file.write('\t\t\t<faces count="%d">\n' % len(self.mFaceData)) for face in self.mFaceData: file.write('\t\t\t\t<face v1="%d" v2="%d" v3="%d" />\n' % tuple(face)) file.write('\t\t\t</faces>\n') # write submesh vertex buffer if not shared. if (not self.mShareVertexBuffer): file.write('\t\t\t<geometry vertexcount="%d">\n' % vertexCount) self.mVertexBuffer.serialize(file, '\t\t\t\t') file.write('\t\t\t</geometry>\n') # write bone assignments if (self.mShareVertexBuffer.mHasBoneWeights): self.mSharedVertexBuffer.serializeBoneAssignments(file, '\t\t\t') file.write('\t\t</submesh>\n') class Mesh(): def __init__(self, blendMesh = None, blendVertexGroups = None, ogreSkeleton = None, exportSettings = MeshExportSettings()): # shared vertex buffer. self.mSharedVertexBuffer = VertexBuffer() # Blender mesh -> shared vertex index link. self.mSharedMeshVertexIndexLink = dict() # collection of submeshes. self.mSubMeshDict = dict() # skip blend mesh conversion if no blend mesh passed in. if (blendMesh is None): return self.mOgreSkeleton = ogreSkeleton hasBoneWeights = ogreSkeleton is not None # Lets do some pre checking to show warnings if needed. uvLayerCount = len(blendMesh.uv_layers) colorLayerCount = len(blendMesh.vertex_colors) if (uvLayerCount > 8): LogManager.logMessage("More than 8 UV layers in this mesh. Only 8 will be exported.", Message.LVL_WARNING) if (colorLayerCount > 2): LogManager.logMessage("More than 2 color layers in this mesh. Only 2 will be exported.", Message.LVL_WARNING) # setup shared vertex buffer. self.mSharedVertexBuffer.reset(uvLayerCount, colorLayerCount, hasBoneWeights) # split up the mesh into submeshes by materials. # we first get sub mesh shared vertices option. materialList = blendMesh.materials materialCount = len(materialList) subMeshProperties = blendMesh.ogre_mesh_exporter.subMeshProperties while (len(subMeshProperties) < materialCount): subMeshProperties.add() # add more items if needed. while (len(subMeshProperties) > materialCount): subMeshProperties.remove(0) # remove items if needed. LogManager.logMessage("Material Count: %d" % len(materialList), Message.LVL_INFO) for polygon in blendMesh.polygons: # get or create submesh. if (polygon.material_index in self.mSubMeshDict): subMesh = self.mSubMeshDict[polygon.material_index] else: # instantiate submesh base on wether sharing vertices or not. subMeshProperty = subMeshProperties[polygon.material_index] if (subMeshProperty.useSharedVertices): subMesh = SubMesh(self.mSharedVertexBuffer, self.mSharedMeshVertexIndexLink, subMeshProperty.name) else: subMesh = SubMesh(VertexBuffer(uvLayerCount, colorLayerCount, hasBoneWeights), name = subMeshProperty.name) subMesh.mMaterial = None if (len(materialList) == 0) else materialList[polygon.material_index] if (exportSettings.requireMaterials and subMesh.mMaterial == None): LogManager.logMessage("Some faces are not assigned with a material!", Message.LVL_WARNING) LogManager.logMessage("To hide this warning, please uncheck the 'Require Materials' option.", Message.LVL_WARNING) self.mSubMeshDict[polygon.material_index] = subMesh # insert polygon. subMesh.insertPolygon(blendMesh, polygon, blendVertexGroups, ogreSkeleton, exportSettings.fixUpAxisToY) def serialize(self, file): file.write('<mesh>\n') # write shared vertex buffer if available. sharedVertexCount = self.mSharedVertexBuffer.vertexCount() if (sharedVertexCount > 0): file.write('\t<sharedgeometry vertexcount="%d">\n' % sharedVertexCount) self.mSharedVertexBuffer.serialize(file, '\t\t') file.write('\t</sharedgeometry>\n') # write bone assignments if (self.mSharedVertexBuffer.mHasBoneWeights): self.mSharedVertexBuffer.serializeBoneAssignments(file, '\t\t') subMeshNames = list() # write submeshes. file.write('\t<submeshes>\n') for subMesh in self.mSubMeshDict.values(): name = subMesh.mName if (name): if (not name in subMeshNames): subMeshNames.append(name) else: LogManager.logMessage("Mulitple submesh with same name defined: %s" % name, Message.LVL_WARNING) subMesh.serialize(file) file.write('\t</submeshes>\n') # write submesh names if (len(subMeshNames)): file.write('\t<submeshnames>\n') for index, name in enumerate(subMeshNames): file.write('\t\t<submeshname name="%s" index="%d" />\n' % (name, index)) file.write('\t</submeshnames>\n') # write skeleton link if (self.mOgreSkeleton is not None): file.write('\t<skeletonlink name="%s.skeleton" />\n' % self.mOgreSkeleton.mName) file.write('</mesh>\n')
Dromore travelled to Belfast on Saturday to play Shorts in a fixture they were hoping to get something out of, only to be on the wrong end of a five-nil defeat. The game started in windy conditions and it was Shorts who settled first on a soggy pitch. The first chance arrived after 10 minutes when a long ball forced Thompson into an early save. On 15 minutes an aerial collision resulted in a Shorts player being taken off with a bad facial injury. This delay seemed to affect the Dromore players concentration, when on 25 minutes a long ball wasn’t dealt with by the Dromore defence and the Shorts striker cooly rounded Thompson to make it one-nil. The closest Dromore got to equalising was a long range shot from McMurray and a free kick from J.Beattie which was easily saved. Shorts got their second goal when good link up play by the Shorts strikers resulted in a fine headed goal leaving Thompson no chance. The second half started with the Dromore players knowing that an early goal would get them back into it but chances were few and far. The match was turning into a battle between the Dromore defence and the Shorts frontline with Dromore battling well to keep the score at two-nil. Midway through the half Shorts got their third when a foul on Tinsley in the Shorts half went unpunished by the referee and Shorts broke up the other end to score their third. Drmore made two changes bringing on Compton and Lavery for the remaining 20 minutes. Shorts got their fourth in the 45th minute when a wicked deflection looped the ball over the stranded Thompson. Shorts’ fifth goal was scored in the 48th minute when Dromore had run out of steam. Dromore would like to wish the Shorts player all the best and hope he has a speedy recovery from his injury. Team- N.Thompson, T.Martin, A.Henderson, G.Rowan, S.Henderson, W.Mcmurray, J.Beattie, C.Gililand, M.Rowan, P.Tinsley, C.Mallon, A.Compton, B.Lavery, T.Stewart. As of going to press both Dromore teams were unaware of their forthcoming fixtures.
from pytest_bdd import given, when, then from model.contact import Contact import random @given('a contact list') def contact_list(db): return db.get_contact_list() @given('a contact with <first_name>, <last_name> and <address>') def new_contact(first_name, last_name, address): return Contact(first_name=first_name, last_name=last_name, address=address) @when('I add the contact to the list') def add_new_contact(app, new_contact): app.contact.create(new_contact) @then('the new contact list is equal to the old list with the added contact') def verify_contact_added(db, contact_list, new_contact): old_contacts = contact_list new_contacts = db.get_contact_list() old_contacts.append(new_contact) assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) @given('a non-empty contact list') def non_empty_contact_list(app, db): if len(db.get_contact_list()) == 0: app.contact.create(Contact(first_name="Some contact")) return db.get_contact_list() @given('a random contact from the list') def random_contact(non_empty_contact_list): return random.choice(non_empty_contact_list) @when('I delete the contact from the list') def delete_contact(app, random_contact): app.contact.delete_contact_by_id(random_contact.id) @then('the new contact list is equal to the old list without deleted contact') def verify_contact_deleted(db, non_empty_contact_list, random_contact, app, check_ui): old_contacts = non_empty_contact_list new_contacts = db.get_contact_list() assert len(old_contacts) - 1 == len(new_contacts) old_contacts.remove(random_contact) assert old_contacts == new_contacts if check_ui: assert \ sorted( map(lambda x: Contact( id=x.id, first_name=x.first_name.strip(), last_name=x.last_name.strip(), address=x.address.strip(), all_emails_from_home_page=x.all_emails_from_home_page.strip(), all_phones_from_home_page=x.all_phones_from_home_page.strip() ), new_contacts), key=Contact.id_or_max ) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max) @when('I modify the contact from the list') def modify_contact(app, new_contact, random_contact): new_contact.id = random_contact.id app.contact.modify_contact_by_id(random_contact.id, new_contact) @then('the new contact list is equal to the old list with modified contact') def verify_contact_modified(db, non_empty_contact_list, new_contact, app, check_ui): old_contacts = non_empty_contact_list new_contacts = db.get_contact_list() assert len(old_contacts) == len(new_contacts) [x for x in old_contacts if x.id == new_contact.id][0].first_name = new_contact.first_name assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max) if check_ui: assert \ sorted( map(lambda x: Contact( id=x.id, first_name=x.first_name.strip(), last_name=x.last_name.strip(), address=x.address.strip(), all_emails_from_home_page=x.all_emails_from_home_page.strip(), all_phones_from_home_page=x.all_phones_from_home_page.strip() ), new_contacts), key=Contact.id_or_max ) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
No need to install. Just unzip and run from the directory. DK2: Oculus runtime v0.7+, Windows 10, CV1: Latest Oculus runtime.
#!/usr/bin/python # -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_contract_subject_to_filter short_description: Bind Contract Subjects to Filters (vz:RsSubjFiltAtt) description: - Bind Contract Subjects to Filters on Cisco ACI fabrics. notes: - The C(tenant), C(contract), C(subject), and C(filter_name) must exist before using this module in your playbook. - The M(aci_tenant), M(aci_contract), M(aci_contract_subject), and M(aci_filter) modules can be used for these. - More information about the internal APIC class B(vz:RsSubjFiltAtt) from L(the APIC Management Information Model reference,https://developer.cisco.com/docs/apic-mim-ref/). author: - Jacob McGill (@jmcgill298) version_added: '2.4' options: contract: description: - The name of the contract. aliases: [ contract_name ] filter: description: - The name of the Filter to bind to the Subject. aliases: [ filter_name ] log: description: - Determines if the binding should be set to log. - The APIC defaults new Subject to Filter bindings to C(none). choices: [ log, none ] aliases: [ directive ] subject: description: - The name of the Contract Subject. aliases: [ contract_subject, subject_name ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. choices: [ absent, present, query ] default: present tenant: description: - The name of the tenant. required: yes aliases: [ tenant_name ] extends_documentation_fragment: aci ''' EXAMPLES = r''' - name: Add a new contract subject to filer binding aci_contract_subject_to_filter: host: apic username: admin password: SomeSecretPassword tenant: production contract: web_to_db subject: test filter: '{{ filter }}' log: '{{ log }}' state: present - name: Remove an existing contract subject to filter binding aci_contract_subject_to_filter: host: apic username: admin password: SomeSecretPassword tenant: production contract: web_to_db subject: test filter: '{{ filter }}' log: '{{ log }}' state: present - name: Query a specific contract subject to filter binding aci_contract_subject_to_filter: host: apic username: admin password: SomeSecretPassword tenant: production contract: web_to_db subject: test filter: '{{ filter }}' state: query - name: Query all contract subject to filter bindings aci_contract_subject_to_filter: host: apic username: admin password: SomeSecretPassword tenant: production contract: web_to_db subject: test state: query ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: string sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: string sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: string sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: string sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: string sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update( contract=dict(type='str', aliases=['contract_name']), # Not required for querying all objects filter=dict(type='str', aliases=['filter_name']), # Not required for querying all objects log=dict(tyep='str', choices=['log', 'none'], aliases=['directive']), subject=dict(type='str', aliases=['contract_subject', 'subject_name']), # Not required for querying all objects tenant=dict(type='str', aliases=['tenant_name']), # Not required for querying all objects state=dict(type='str', default='present', choices=['absent', 'present', 'query']), method=dict(type='str', choices=['delete', 'get', 'post'], aliases=['action'], removed_in_version='2.6'), # Deprecated starting from v2.6 protocol=dict(type='str', removed_in_version='2.6'), # Deprecated in v2.6 ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['contract', 'filter', 'subject', 'tenant']], ['state', 'present', ['contract', 'filter', 'subject', 'tenant']], ], ) contract = module.params['contract'] filter_name = module.params['filter'] log = module.params['log'] subject = module.params['subject'] tenant = module.params['tenant'] state = module.params['state'] # Add subject_filter key to modul.params for building the URL module.params['subject_filter'] = filter_name # Convert log to empty string if none, as that is what API expects. An empty string is not a good option to present the user. if log == 'none': log = '' aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fvTenant', aci_rn='tn-{0}'.format(tenant), filter_target='eq(fvTenant.name, "{0}")'.format(tenant), module_object=tenant, ), subclass_1=dict( aci_class='vzBrCP', aci_rn='brc-{0}'.format(contract), filter_target='eq(vzBrCP.name, "{0}")'.format(contract), module_object=contract, ), subclass_2=dict( aci_class='vzSubj', aci_rn='subj-{0}'.format(subject), filter_target='eq(vzSubj.name, "{0}")'.format(subject), module_object=subject, ), subclass_3=dict( aci_class='vzRsSubjFiltAtt', aci_rn='rssubjFiltAtt-{0}'.format(filter_name), filter_target='eq(vzRsSubjFiltAtt.tnVzFilterName, "{0}")'.format(filter_name), module_object=filter_name, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='vzRsSubjFiltAtt', class_config=dict( tnVzFilterName=filter_name, directives=log, ), ) aci.get_diff(aci_class='vzRsSubjFiltAtt') aci.post_config() elif state == 'absent': aci.delete_config() # Remove subject_filter used to build URL from module.params module.params.pop('subject_filter') aci.exit_json() if __name__ == "__main__": main()
Warzone: Resurrection’s mechanics mean that it is easy to play a multi-player game (three or more players at the one time). Let’s get playing! While most battles are things that occur between two (not always equal) sides, there are occasions where a battlefield becomes so complex that it nearly descends into a free-for all. In truth, conflict between multiple sides isn’t too uncommon in a Warzone. Whenever the Dark Legion appears, the corporate forces aren’t always willing to put aside their disputes for the common good, and where something valuable is found, all bets are off. This mission is a race between four equal forces, all competing to get a hold of The Prize. Feel free to make up what that prize is exactly, but for narrative purposes all four forces are equally motivated to gain possession of it. Maybe it’s a crashed satellite? An artifact of immeasurable power? A cache of money or experimental tech? Each of the four forces have been dispatched to find and retrieve the prize, whether for personal glory, to keep it out of the hands of others, to use it for nefarious purposes, or just for good old Profit. All are motivated. All are well-equipped. Who will win out? For this game, you want to have four players available. The scenario will still work with three, but the players that have a gap next to them will benefit and so you may want to give the ‘surrounded’ player a few more points. As this is a force designed for specific retrieval tasks, you’re more likely to see specialist units. Each player must take one Warlord and one Support unit as compulsory choices. They can take up to an additional two support choices and four troops choices, and up to three Lords. We would suggest that you keep your points value small (800 or less) for each player, in order to prevent the game from taking too long. All four players roll at the same time to determine an initiative order- they then set up in order from highest to lowest rolls. If any players roll the same amount, they will need to roll again to break any ties, with all other players retaining their place in the initiative order. All forces are to be deployed according to Quarters deployment, with players choosing their corner to deploy in according to the initiative order. Additionally, no model can be deployed within 12” of an enemy model that is already on the table. Once all forces have been set up, Infiltrators can be deployed as per the initiative order, although no model can be placed within the Convergence Zone. Once the game starts, play proceeds in initiative order, with each player activating one squad before play passes to the next player. All opposing models are to be treated as the enemy. If a model shoots into engaged models where there are no friendlies, they will be a little more careless than they would be with friendlies. After rolling a hit against an engaged model, roll again- on a 1-14, you hit the intended target, otherwise you hit another randomly assigned model. Due to the wariness that all troops feel in such confused situations, all squads have a -2 Leadership penalty but can shoot and engage in their rear facing, and when on Sentry can react to things that occur in their rear facing in the same manner, including making CC attacks. All four forces want The Prize. This is an object that must be retrieved from its resting place and returned to friendly lines. Any model can pick up The Prize by using 1 AP while in base contact with it. They then have to move the objective back to their own deployment zone to win. The model can move as normal, and perform all actions they usually can. All CC and RS attacks by the model carrying The Prize receive a -4 penalty, and if they have to take a Con test for climbing they do not receive the +4 modifier. If the model carrying The Prize receives a stun or wound effect, is targeted by a successful Psychic (D) power, climbs or crosses any piece of light or heavy terrain, the model must take a Con test to hold onto The Prize. If it is failed, place The Prize 1” away in any direction and the model then resolves any further effects from the wound or similar. If the model passes this test but is removed from play for any reason, place The Prize where the model used to be. Finally, just as no infiltrating units could deploy in the Convergence zone, no unit can RD within that space either. This will have the added benefit of forcing players to think a couple of turns ahead with their movements. If any player has a model in possession of The Prize make it back to their own deployment zone, they win the game. If the game ends with Disengage, any player that has The Prize in their possession (currently being carried by one of their models and no enemy models within 12” of it) wins a partial victory. If you want to add more complexity to the game, feel free to roll for Secondary and Corporate Agenda missions. However, as there is only one objective on the table, they will not need to identify the target. For narrative purposes, maybe The Prize is the best part of the Ammo Dump, and once it is retrieved the rest can be destroyed? Maybe there’s a cache of experimental tech and The Prize is simply the best piece that needs to be evacuated immediately? So there you have it. A quick and dirty mission that should erupt into utter chaos. As usual, we would love to hear about anyone playing this scenario. Send us a battle report and some pics! What’s your favourite Rapid Deployment tactic? What squad(s) do you use to pull it off? What’s the best outcome you’ve had from Rapid Deployment on the battlefield?
"""Definitions for interacting with Blast related applications. """ from Bio import Application from Bio.Application import _Option class FastacmdCommandline(Application.AbstractCommandline): """Create a commandline for the fasta program from NCBI. """ def __init__(self, fastacmd = "fastacmd"): Application.AbstractCommandline.__init__(self) self.program_name = fastacmd self.parameters = \ [ _Option(["-d", "database"], ["input"], None, 1, "The database to retrieve from."), _Option(["-s", "search_string"], ["input"], None, 1, "The id to search for.") ] class BlastallCommandline(Application.AbstractCommandline): """Create a commandline for the blastall program from NCBI. XXX This could use more checking for valid paramters to the program. """ def __init__(self, blastcmd = "blastall"): Application.AbstractCommandline.__init__(self) self.program_name = blastcmd self.parameters = \ [# Scoring options _Option(["-M", "matrix"], ["input"], None, 0, "Matrix to use"), _Option(["-G", "gap_open"], ["input"], None, 0, "Gap open penalty"), _Option(["-E", "gap_extend"], ["input"], None, 0, "Gap extension penalty"), _Option(["-A", "window_size"], ["input"], None, 0, "Multiple hits window size"), _Option(["-j", "npasses"], ["input"], None, 0, "Number of passes"), _Option(["-p", "passes"], ["input"], None, 0, "Hits/passes. Integer 0-2."), # Algorithm options _Option(["-g", "gapped"], ["input"], None, 0, "Whether to do a gapped alignment. T/F"), _Option(["-e", "expectation"], ["input"], None, 0, "Expectation value cutoff."), _Option(["-W", "wordsize"], ["input"], None, 0, "Word size"), _Option(["-K", "keep_hits"], ["input"], None, 0, " Number of best hits from a region to keep."), _Option(["-X", "xdrop"], ["input"], None, 0, "Dropoff value (bits) for gapped alignments."), _Option(["-f", "hit_extend"], ["input"], None, 0, "Threshold for extending hits."), _Option(["-L", "region_length"], ["input"], None, 0, "Length of region used to judge hits."), _Option(["-Z", "db_length"], ["input"], None, 0, "Effective database length."), _Option(["-Y", "search_length"], ["input"], None, 0, "Effective length of search space."), _Option(["-N", "nbits_gapping"], ["input"], None, 0, "Number of bits to trigger gapping."), _Option(["-c", "pseudocounts"], ["input"], None, 0, "Pseudocounts constants for multiple passes."), _Option(["-Z", "xdrop_final"], ["input"], None, 0, "X dropoff for final gapped alignment."), _Option(["-y", "xdrop_extension"], ["input"], None, 0, "Dropoff for blast extensions."), _Option(["-h", "model_threshold"], ["input"], None, 0, "E-value threshold to include in multipass model."), _Option(["-S", "required_start"], ["input"], None, 0, "Start of required region in query."), _Option(["-H", "required_end"], ["input"], None, 0, "End of required region in query."), # Processing options _Option(["-p", "program"], ["input"], None, 1, "The blast program to use."), _Option(["-d", "database"], ["input"], None, 1, "The database to BLAST against."), _Option(["-i", "infile"], ["input", "file"], None, 1, "The sequence to search with."), _Option(["-F", "filter"], ["input"], None, 0, "Filter query sequence with SEG? T/F"), _Option(["-J", "believe_query"], ["input"], None, 0, "Believe the query defline? T/F"), _Option(["-a", "nprocessors"], ["input"], None, 0, "Number of processors to use."), # Formatting options _Option(["-T", "html"], ["input"], None, 0, "Produce HTML output? T/F"), _Option(["-v", "descriptions"], ["input"], None, 0, "Number of one-line descriptions."), _Option(["-b", "alignments"], ["input"], None, 0, "Number of alignments."), _Option(["-m", "align_view"], ["input"], None, 0, "Alignment view. Integer 0-6."), _Option(["-I", "show_gi"], ["input"], None, 0, "Show GI's in deflines? T/F"), _Option(["-O", "seqalign_file"], ["output", "file"], None, 0, "seqalign file to output."), _Option(["-o", "align_outfile"], ["output", "file"], None, 1, "Output file for alignment."), _Option(["-C", "checkpoint_outfile"], ["output", "file"], None, 0, "Output file for PSI-BLAST checkpointing."), _Option(["-R", "restart_infile"], ["input", "file"], None, 0, "Input file for PSI-BLAST restart."), _Option(["-k", "hit_infile"], ["input", "file"], None, 0, "Hit file for PHI-BLAST."), _Option(["-Q", "matrix_outfile"], ["output", "file"], None, 0, "Output file for PSI-BLAST matrix in ASCII."), _Option(["-B", "align_infile"], ["input", "file"], None, 0, "Input alignment file for PSI-BLAST restart.") ]
Vladimir Putin's best friend, a Russian oligarch, is Jewish. A part of the Ukrainian Fascist Party assisted with the Kiev uprising, whether the revolutionaries wanted them around or not. It's inconvenient. It doesn't make Vladimir Putin any better. The Internet burned yesterday with reports coming out of east Ukraine that Jews are being ordered to register with the government. Israeli and Ukrainian media first ran the story, which was picked up globally, of Jews leaving a synagogue in the city of Donestk being handed leaflets telling them to register with the "temporary government" or risk getting kicked out of the country. The "temporary government" is made up of separatists who wish to unite east Ukraine with Russia. Many were quick to draw a very clear line between the Nazi awfulness of registering Jews to Vladimir Putin himself and maybe they are right. Maybe it is really that simple and Putin is the new all-singing, all-dancing evil of the world. Or maybe the scene is slightly more complicated. On March 4, Putin gave his first press conference after invading Crimea. He wore a boxy grey suit and, sitting underneath a chandelier, he carried on about why Russia was intervening in Ukrainian affairs. And do you know why? Partially to protect the country from "masked and unidentified armed groups of anti-Semites." During the uprising in Kiev, the flag of the Ukrainian Fascist Party flew over the central square. It is unclear how many fascists were involved in the revolution, or are involved in the transitional government, but to Putin, and many Russians, it echoes World War II when then Soviet Russia fought Nazi Germany. It echoes Stepan Bandera, a controversial figure in Ukraine's history who fought for Ukrainian independence from the Soviet Union and had close ties to Adolf Hitler. Anti-Semitism is on the rise throughout Europe and, in Ukraine, attacks on synagogues have gone up since the unrest began. It is not a pleasant situation, but it's also something that theoretically goes very much against Putin's own interests. Some of the most powerful oligarchs in Russia, including Putin's best friend Roman Abramovich, are Jewish. Now, certainly, he could be fomenting ugliness against Jews in Ukraine as shots across their bows but it seems unlikely. It seems too crude. Yes, the stakes have been raised once again in Ukraine as Russia stares down the west and a knee-jerk "Putin is the bad guy! He is the new Hitler!" response is fun and easy. I'm totally bored of Islamic radicals being my enemy too. Alas, it's probably not true. Bummer.
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from pyscf.tools.siesta_utils import get_siesta_command, get_pseudo import subprocess import os siesta_fdf = """ xml.write .true. PAO.EnergyShift 100 meV %block ChemicalSpeciesLabel 1 11 Na %endblock ChemicalSpeciesLabel NumberOfAtoms 2 NumberOfSpecies 1 %block AtomicCoordinatesAndAtomicSpecies 0.77573521 0.00000000 0.00000000 1 -0.77573521 0.00000000 0.00000000 1 %endblock AtomicCoordinatesAndAtomicSpecies MD.NumCGsteps 0 COOP.Write .true. WriteDenchar .true. """ label = 'siesta' print(siesta_fdf, file=open(label+'.fdf', 'w')) for sp in ['Na']: os.symlink(get_pseudo(sp), sp+'.psf') errorcode = subprocess.call(get_siesta_command(label), shell=True) if errorcode: raise RuntimeError('siesta returned an error: {0}'.format(errorcode)) # run test system_vars from pyscf.nao.m_system_vars import system_vars_c, diag_check, overlap_check sv = system_vars_c().init_siesta_xml(label = label) assert sv.norbs == 10 assert diag_check(sv) assert overlap_check(sv)
Nutrition is the keystone to growing your muscles. The reason so many struggle with it is because the do not follow the steps to complete their meal preparation. Phil Heath’s Back Workout – Road To Mr. Olympia 2018 Phil Heath Bodybuilding Motivation. Vegans Are Weak? Let some vegan bodybuilders, Olympic athletes, NFL football players, NHL hockey players, MMA martial artists & weightlifters say otherwise. Start or join the discussion about this video on http://bit.ly/steadyhealth.
import requests import base64 import json import logging import time from O365.event import Event logging.basicConfig(filename='o365.log',level=logging.DEBUG) log = logging.getLogger(__name__) class Calendar( object ): ''' Calendar manages lists of events on an associated calendar on office365. Methods: getName - Returns the name of the calendar. getCalendarId - returns the GUID that identifies the calendar on office365 getId - synonym of getCalendarId getEvents - kicks off the process of fetching events. fetchEvents - legacy duplicate of getEvents Variable: events_url - the url that is actually called to fetch events. takes an ID, start, and end. time_string - used for converting between struct_time and json's time format. ''' events_url = 'https://outlook.office365.com/api/v1.0/me/calendars/{0}/calendarview?startDateTime={1}&endDateTime={2}' time_string = '%Y-%m-%dT%H:%M:%SZ' def __init__(self, json=None, auth=None): ''' Wraps all the informaiton for managing calendars. ''' self.json = json self.auth = auth self.events = [] if json: log.debug('translating calendar information into local variables.') self.calendarId = json['Id'] self.name = json['Name'] def getName(self): '''Get the calendar's Name.''' return self.json['Name'] def getCalendarId(self): '''Get calendar's GUID for office 365. mostly used interally in this library.''' return self.json['Id'] def getId(self): '''Get calendar's GUID for office 365. mostly used interally in this library.''' return self.getCalendarId() def fetchEvents(self,start=None,end=None): ''' So I originally made this function "fetchEvents" which was a terrible idea. Everything else is "getX" except events which were appearenty to good for that. So this function is just a pass through for legacy sake. ''' return self.getEvents(start,end) def getEvents(self,start=None,end=None): ''' Pulls events in for this calendar. default range is today to a year now. Keyword Arguments: start -- The starting date from where you want to begin requesting events. The expected type is a struct_time. Default is today. end -- The ending date to where you want to end requesting events. The expected type is a struct_time. Default is a year from start. ''' #If no start time has been supplied, it is assumed you want to start as of now. if not start: start = time.strftime(self.time_string) #If no end time has been supplied, it is assumed you want the end time to be a year #from what ever the start date was. if not end: end = time.time() end += 3600*24*365 end = time.gmtime(end) end = time.strftime(self.time_string,end) #This is where the actual call to Office365 happens. response = requests.get(self.events_url.format(self.json['Id'],start,end),auth=self.auth) log.info('Response from O365: %s', str(response)) #This takes that response and then parses it into individual calendar events. for event in response.json()['value']: try: duplicate = False #checks to see if the event is a duplicate. if it is local changes are clobbered. for i,e in enumerate(self.events): if e.json['Id'] == event['Id']: self.events[i] = Event(event,self.auth,self) duplicate = True break if not duplicate: self.events.append(Event(event,self.auth,self)) log.debug('appended event: %s',event['Subject']) except Exception as e: log.info('failed to append calendar: %',str(e)) log.debug('all events retrieved and put in to the list.') return True #To the King!
Gastro Wednesdays, organized every alternate month by High Street Phoenix, seek to bring to Mumbai flavors from all around the world to satiate the taste buds of the average Mumbaikar. The March edition, which was also the third edition of Gastro Wednesdays, was entirely dedicated to the female chefs in the city, making it a special edition to celebrate Women’s Day. Popular names like Snigdha Manchanda of Tea Trunk, Pooja Dhingra’s Le 15 Patisserie, Aditi Handa of The Baker’s Dozen, Chef Thea Tanneleht of Marzipan – The Bakery Shop and many others had participated and made it a huge hit. Online contests were organized in association with Burrp.com, generating a lot of buzz and winners at the same time. There were a lot of tweets from the food bloggers who had attended the event, making it an overwhelming response from all quarters. Most of the stalls were sold out by the end of the evening. The social media team of High Street Phoenix engaged people on various social networking platforms by inviting them for the event, and by continuously posting live updates and feeds about the event. The hashtag created for the event, #GastroWednesdays, was trending on Twitter for more than 24 hours and had received 623 mentions on the same. It reached out to almost 2,00,000 tweeple and had more than 5,00,000 impressions.
# -*- coding: latin-1 -*- import regexUtils import re import urllib import urlparse def findJS(data): idName = '(?:f*id|ch)' jsName = '([^\"\']+?\.js[^\"\']*?)' regex = "(?:java)?scr(?:'\+')?ipt.*?" + idName + "\s*=\s*[\"']([^\"']+)[\"'][^<]*</scr(?:'\+')?ipt\s*>[^<]*<scr(?:'\+')?ipt[^<]*src=[\"']" + jsName + "[\"']" jscript = regexUtils.findall(data, regex) if jscript: jscript = filter(lambda x: x[1].find('twitter') == -1, jscript) return jscript return None def findPHP(data, streamId): regex = "document.write\('.*?src=['\"]*(.*?.php[^&\"]*).*?['\" ]*.*?\)" php = regexUtils.findall(data, regex) if php: return re.sub(r"\'\+\s*(?:f*id|ch)\s*\+\'", "%s" % streamId,php[0]) regex = "document.write\('.*?src=['\"]*(.*?(?:f*id|ch)\s*\+'\.html*).*?['\" ]*.*?\)" html = regexUtils.findall(data, regex) if html: return re.sub(r"\'\+\s*(?:f*id|ch)\s*\+\'", "%s" % streamId,html[0]) return None def findRTMP(url, data): #if data.lower().find('rtmp') == -1: # return None try: text = str(data) except: text = data #method 1 #["'=](http://[^'" ]*.swf[^'" ]*file=([^&"']+)[^'" ]*&streamer=([^"'&]+)) #streamer=([^&"]+).*?file=([^&"]+).*?src="([^"]+.swf)" # method 2 #"([^"]+.swf\?.*?file=(rtmp[^&]+)&.*?id=([^&"]+)[^"]*)" sep1 = '[\'"&\? ]' sep2 = '(?:[\'"]\s*(?:,|\:)\s*[\'"]|=)' value = '([^\'"&]+)' method1 = True method2 = False radius = 400 playpath = '' swfUrl = '' rtmp = regexUtils.findall(text, sep1 + 'streamer' + sep2 + value) if not rtmp: tryMethod2 = regexUtils.findall(text, sep1 + 'file' + sep2 + value) if tryMethod2 and tryMethod2[0].startswith('rtmp'): method1 = False method2 = True rtmp = tryMethod2 if rtmp: for r in rtmp: tmpRtmp = r.replace('/&','').replace('&','') idx = text.find(tmpRtmp) min_idx = 0 max_idx = len(text) - 1 start = idx-radius if start < min_idx: start = min_idx end = idx+radius if end > max_idx: end = max_idx area = text[start:end] clipStart = idx+len(tmpRtmp) if clipStart < max_idx: text = text[clipStart:] if method1: playpath = regexUtils.findall(area, sep1 + 'file' + sep2 + value) if method2: playpath = regexUtils.findall(area, sep1 + 'id' + sep2 + value) if playpath: tmpRtmp = tmpRtmp + '/' + playpath[0] if playpath: swfUrl = regexUtils.findall(area, 'SWFObject\([\'"]([^\'"]+)[\'"]') if not swfUrl: swfUrl = regexUtils.findall(area, sep1 + '([^\'"& ]+\.swf)') if not swfUrl: swfUrl = regexUtils.findall(data, sep1 + '([^\'"& ]+\.swf)') if swfUrl: finalSwfUrl = swfUrl[0] if not finalSwfUrl.startswith('http'): finalSwfUrl = urlparse.urljoin(url, finalSwfUrl) regex = '://(.*?)/' server = regexUtils.findall(tmpRtmp, regex) if server: if server[0].find(':') == -1: tmpRtmp = tmpRtmp.replace(server[0], server[0] + ':1935') return [tmpRtmp, playpath[0], finalSwfUrl] return None def getHostName(url): scheme = urlparse.urlparse(url) if scheme: return scheme.netloc.replace('www.','') return None def findFrames(data): if data.lower().find('frame') == -1: return None return regexUtils.findall(data, "(frame[^>]*)>") def findContentRefreshLink(data): regex = '0;\s*url=([^\'" ]+)' links = regexUtils.findall(data, regex) if links: return links[0] regex = 'window.location\s*=\s*[\'"]([^\'"]+)[\'"]' links = regexUtils.findall(data, regex) if links: return links[0] regex = 'frame\s*scrolling=\"auto\"\s*noresize\s*src\s*=\s*[\'"]([^\'"]+)[\'"]' links = regexUtils.findall(data, regex) if links: return links[0] return None def findEmbedPHPLink(data): regex = '<script type="text/javascript" src="((?![^"]+localtimes)(?![^"]+adcash)[^"]+\.php\?[^"]+)"\s*>\s*</script>' links = regexUtils.findall(data, regex) if links: return links[0] return None def findVideoFrameLink(page, data): minheight=300 minwidth=300 frames = findFrames(data) if not frames: return None iframes = regexUtils.findall(data, "(frame(?![^>]*cbox\.ws)(?![^>]*chat\d*\.\w+)(?![^>]*ad122m)(?![^>]*adshell)(?![^>]*capacanal)(?![^>]*blacktvlive\.com)[^>]*\sheight\s*=\s*[\"']*([\%\d]+)(?:px)?[\"']*[^>]*>)") if iframes: for iframe in iframes: if iframe[1] == '100%': height = minheight+1 else: height = int(iframe[1]) if height > minheight: m = regexUtils.findall(iframe[0], "[\"' ]width\s*=\s*[\"']*(\d+[%]*)(?:px)?[\"']*") if m: if m[0] == '100%': width = minwidth+1 else: width = int(m[0]) if width > minwidth: m = regexUtils.findall(iframe[0], '[\'"\s]src=["\']*\s*([^"\' ]+)\s*["\']*') if m: return urlparse.urljoin(urllib.unquote(page), m[0]).strip() # Alternative 1 iframes = regexUtils.findall(data, "(frame(?![^>]*cbox\.ws)(?![^>]*capacanal)(?![^>]*blacktvlive\.com)[^>]*[\"; ]height:\s*(\d+)[^>]*>)") if iframes: for iframe in iframes: height = int(iframe[1]) if height > minheight: m = regexUtils.findall(iframe[0], "[\"; ]width:\s*(\d+)") if m: width = int(m[0]) if width > minwidth: m = regexUtils.findall(iframe[0], '[\"; ]src=["\']*\s*([^"\' ]+)\s*["\']*') if m: return urlparse.urljoin(urllib.unquote(page), m[0]).strip() # Alternative 2 (Frameset) m = regexUtils.findall(data, '<FRAMESET[^>]+100%[^>]+>\s*<FRAME[^>]+src="([^"]+)"') if m: return urlparse.urljoin(urllib.unquote(page), m[0]).strip() m = regexUtils.findall(data, '<a href="([^"]+)" target="_blank"><img src="[^"]+" height="450" width="600" longdesc="[^"]+"/></a>') if m: return urlparse.urljoin(urllib.unquote(page), m[0]).strip() return None
The City of Vancouver estimates it will bring in $38 million from the first year of the empty homes tax — $8 million more than initially predicted. So far, about $21 million has been collected. Most of the revenue will be used for affordable housing initiatives — $8 million has already been allocated — but it will also cover one-time implementation costs ($7.5 million) and first-year operating costs ($2.5 million). The latest numbers were revealed in the city's first empty homes tax annual report, which was released Nov. 29. In the first year, close to 184,000 declarations were submitted, representing 99 per cent of all residential property owners in Vancouver. Out of the total 186,043 properties, 178,120 were occupied, 5,385 were exempt and 2,538 were vacant. Under the empty homes tax program, which was approved in late 2016, owners are required to rent out their empty or under-utilized, non-principal properties for at least six months of the year. The six months don’t have to be consecutive, but must be in periods of 30 or more consecutive days. The goal is to motivate homeowners to rent out homes they don’t live in full time. Vancouver’s current vacancy rate sits at .8 per cent. The empty homes tax is implemented at a rate of one per cent of a property’s assessed taxable value. Measuring the success of the tax is difficult, according to the City, but it will continue to monitor the impact of the tax on housing supply and affordability, including the empty homes tax property status declarations data year over year. In 2017, 2,132 property owners failed to file declarations and were initially deemed vacant. They were required to submit a notice of complaint with supporting evidence for consideration and potentially to have the tax rescinded. Complaints were also triggered when a property owner was selected for an audit and disagreed with the determination or declined to provide supporting documents and other information at the audit stage. The declaration period for the second year of the tax is now open. The deadline is Feb. 4, 2019. Property owners who have yet to receive their advance property tax notice in the mail can still make their declaration online using the folio and account numbers from their previous tax notice. Those who need help to make their declaration online can visit city hall or any Vancouver Public Library branch for in-person guidance, connect with the city using the VanConnect app or call 3-1-1, which offers translation services. Instructions for how to declare are also available in multiple languages online.
#!/usr/bin/python # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- # vim: set filetype=python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import tempfile, os, sys libpath = os.path.abspath('../psm_common_py') sys.path.append(libpath) import CertUtils srcdir = os.getcwd() db = tempfile.mkdtemp() def generate_child_cert(db_dir, dest_dir, noise_file, name, ca_nick, cert_version, do_bc, is_ee): return CertUtils.generate_child_cert(db_dir, dest_dir, noise_file, name, ca_nick, cert_version, do_bc, is_ee, '') def generate_ee_family(db_dir, dest_dir, noise_file, ca_name): name = "v1_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 1, False, True) name = "v1_bc_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 1, True, True) name = "v2_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 2, False, True) name = "v2_bc_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 2, True, True) name = "v3_missing_bc_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 3, False, True) name = "v3_bc_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 3, True, True) name = "v4_bc_ee-"+ ca_name; generate_child_cert(db_dir, dest_dir, noise_file, name, ca_name, 4, True, True) def generate_intermediates_and_ee_set(db_dir, dest_dir, noise_file, ca_name): name = "v1_int-" + ca_name; generate_child_cert(db, srcdir, noise_file, name, ca_name, 1, False, False) generate_ee_family(db, srcdir, noise_file, name) name = "v1_int_bc-" + ca_name; generate_child_cert(db, srcdir, noise_file, name, ca_name, 1, True, False) generate_ee_family(db, srcdir, noise_file, name) name = "v2_int-" + ca_name; generate_child_cert(db, srcdir, noise_file, name, ca_name, 2, False, False) generate_ee_family(db, srcdir, noise_file, name) name = "v2_int_bc-" + ca_name; generate_child_cert(db, srcdir, noise_file, name, ca_name, 2, True, False) generate_ee_family(db, srcdir, noise_file, name) name = "v3_int_missing_bc-" + ca_name; generate_child_cert(db, srcdir, noise_file, name, ca_name, 3, False, False) generate_ee_family(db, srcdir, noise_file, name) name = "v3_int-" + ca_name; generate_child_cert(db, srcdir, noise_file, name, ca_name, 3, True, False) generate_ee_family(db, srcdir, noise_file, name) def generate_ca(db_dir, dest_dir, noise_file, name, version, do_bc): CertUtils.generate_ca_cert(db_dir, dest_dir, noise_file, name, version, do_bc) generate_intermediates_and_ee_set(db_dir, dest_dir, noise_file, name) def generate_certs(): [noise_file, pwd_file] = CertUtils.init_nss_db(db) generate_ca(db, srcdir, noise_file, "v1_ca", 1, False ) generate_ca(db, srcdir, noise_file, "v1_ca_bc", 1, True) generate_ca(db, srcdir, noise_file, "v2_ca", 2, False ) generate_ca(db, srcdir, noise_file, "v2_ca_bc", 2, True) generate_ca(db, srcdir, noise_file, "v3_ca", 3, True ) generate_ca(db, srcdir, noise_file, "v3_ca_missing_bc", 3, False) generate_certs();
Every online class has at least one: a great student who stands out, stays strong week after week, and really soars during the course of a five-week class. As an online instructor for nearly a decade, I’ve noticed that many of these students share the same attributes of success. Today, I’ll share their secrets, and urge you to apply them to your own work. Chances are, they’ll make your academic journey richer and more rewarding than you ever thought possible! Introduce yourself. Think about it: In every brand-new online class, no one stands out, and no personality really shines. (In fact, during the first week of a new course, it can seem a little like teaching in a classroom with the lights out!) But the best online students shine brighter by sending an email to the instructor before the class begins. It’s always short and sweet; maybe something like this: Dear Ms. Chambers: My name is ________, and I’ll be a student in your upcoming class. I’m looking forward to learning more about the subject of __________ with you. A full name follows, along with the course number (important, since many Bethel instructors teach multiple courses concurrently.) Aha! Now, in a sea of nameless, faceless students, one stands out. Think of it as a lesson in marketing – you can’t sell yourself (or anything else) by being unseen and unheard. Make your Profile shine. Some online students approach the Profile section as if it were a posting on Facebook – voluntary, casual, and anything but professional. I’ve seen Profile photos that would make your mother blush: from super-revealing outfits, to pictures clearly taken in bars! Your Profile tells your classmates and teachers who you are personally, but the best online students approach it professionally, too. Make sure your photo is one that might get you hired at a business you want to work for (please – no car-selfies!), and that your description of yourself is personal, carefully proofread, and professional. You never know who will see it, or what a difference it might make in your life! Take the time to take it in. The strongest online students read every word of the Read section, and watch every minute of the Attend video. Teachers can see it in their depth of understanding, and their ability to translate these sometimes complex ideas into content-rich homework. In addition, thanks to a special V-Camp feature, instructors can literally see exactly how long each student spends on the Read and Attend portions of their work! Almost without exception, the strongest students take the most time to “take it all in” before diving into their work. Start early. Let’s face it: Procrastination hits everybody once in a while. Our lives are so busy that it’s easy to make schoolwork the last thing on your to-do list. Maybe you tell yourself that you “work best under pressure.” (Adrenaline can be a greater motivator – in fact, waiting till the last minute can speed up both your heartbeat and your fingers on the keyboard!) But not only do online instructors know exactly when you submitted your work – often as little as five minutes before the drop-dead deadline – we can see it in the content. Hurried students conduct less research, reveal more learning gaps, and produce more errors. Always. Dig deep and reach high. The best online students often conduct independent research beyond the e-book – not necessarily because it’s required, but because they are Need to write about Starbucks this week? Feel free to go to their website and update the case-study with current, cited information. Tackling a leadership class? Dive into the Bethel Online Library and see what scholars are saying about the subject. Pushing yourself just a little bit more will result in higher learning opportunities – and higher scores. Use every tool at your fingertips. Bethel students are fortunate to have a wealth of resources literally close at hand. From the “wonders of Smarthinking,” to our user-friendly online library, there are a number of free services available to help you grow. Use them when you need them. Use them when you don’t! The best students always recognize that their work can be improved, and services like these can only help you grow more competent and confident, week after week. Follow the instructor’s advice. Your online instructor isn’t there to simply compliment or criticize you — he or she is there to help you grow. So carefully read the written comments you’ve been given, view the advice as professional guidance (rather than personal criticism), and try to apply these suggestions to your next week’s work. If you’re doing something right, keep doing it. If you’re doing something wrong, avoid it. Take every review as one more learning opportunity on your journey to success. Reach out and touch someone. The best students ask the most questions. They send frequent, courteous emails to their instructors for clarification. They call their academic advisor when they’re confused. They contact members of their cohort group from time to time, seeking additional guidance, consensus, or just plain moral support. Getting to know members of your cohort group, as well as your instructor, will really help the learning come alive. When online learning leaves you lonesome, remember: It will really open up when you reach out! Evaluate (both yourself, and your teacher). Honest evaluation is a valuable part of the learning process. At the end of each class, please take the opportunity to complete the anonymous Course Evaluation, to include specific comments about the class and the instructor. Believe me – your words will be seen, both by the teacher and Bethel administrators. Everyone needs to know what they do well, and areas in need of improvement, and these course evaluations help Bethel grow even better. Apply the same honest appraisal to yourself at the end of each course. What did you do well? Where can you improve? Start each new class determined to apply what you learned during the last one – about the subject, and about yourself. Stay focused on your goals – especially when things get tough. Earning a degree isn’t easy, and even the best students will hit a rough patch, or a tough class, from time to time. That’s when you need to remember why you enrolled in the first place. Keep your goals front and center — whether they be a better job, the pride of your family, or the knowledge that your degree will be valued and valuable. When you focus on the finish line, it’s hard to see the obstacles in your path. The very best online learners grow from student to scholar during their academic journey. Apply these suggestions – and get set to shine! Cindy Chambers loves to teach — and really reach — her students. She has been voted “Online Instructor of the Year” by Bethel students for the past three years. Feel free to contact her with comments or questions at chambersc@bethelu.edu. This entry was posted in News and Information on July 7, 2015 by bethelu.
# Copyright 2018 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Dict, Iterable from synapse.storage._base import SQLBaseStore from synapse.util.caches.descriptors import cached, cachedList class UserErasureWorkerStore(SQLBaseStore): @cached() async def is_user_erased(self, user_id: str) -> bool: """ Check if the given user id has requested erasure Args: user_id: full user id to check Returns: True if the user has requested erasure """ result = await self.db_pool.simple_select_onecol( table="erased_users", keyvalues={"user_id": user_id}, retcol="1", desc="is_user_erased", ) return bool(result) @cachedList(cached_method_name="is_user_erased", list_name="user_ids") async def are_users_erased(self, user_ids: Iterable[str]) -> Dict[str, bool]: """ Checks which users in a list have requested erasure Args: user_ids: full user ids to check Returns: for each user, whether the user has requested erasure. """ rows = await self.db_pool.simple_select_many_batch( table="erased_users", column="user_id", iterable=user_ids, retcols=("user_id",), desc="are_users_erased", ) erased_users = {row["user_id"] for row in rows} return {u: u in erased_users for u in user_ids} class UserErasureStore(UserErasureWorkerStore): async def mark_user_erased(self, user_id: str) -> None: """Indicate that user_id wishes their message history to be erased. Args: user_id: full user_id to be erased """ def f(txn): # first check if they are already in the list txn.execute("SELECT 1 FROM erased_users WHERE user_id = ?", (user_id,)) if txn.fetchone(): return # they are not already there: do the insert. txn.execute("INSERT INTO erased_users (user_id) VALUES (?)", (user_id,)) self._invalidate_cache_and_stream(txn, self.is_user_erased, (user_id,)) await self.db_pool.runInteraction("mark_user_erased", f) async def mark_user_not_erased(self, user_id: str) -> None: """Indicate that user_id is no longer erased. Args: user_id: full user_id to be un-erased """ def f(txn): # first check if they are already in the list txn.execute("SELECT 1 FROM erased_users WHERE user_id = ?", (user_id,)) if not txn.fetchone(): return # They are there, delete them. self.db_pool.simple_delete_one_txn( txn, "erased_users", keyvalues={"user_id": user_id} ) self._invalidate_cache_and_stream(txn, self.is_user_erased, (user_id,)) await self.db_pool.runInteraction("mark_user_not_erased", f)
In addition to the static maps shown here, we now have an interactive mapping website. Click here to visit our mapping website. Select a District and Map Number to view a reduced-size version of the map. Full-size maps can be purchased in the Assessor's Office. A link will appear for the full-size map. Please note that full-size map files can be very large and require Adobe Acrobat to view.
print "locomotionInitSkeleton = " + locomotionInitSkeleton #locomotion smooth cycle smoothMotion = scene.getMotion("ChrBrad_ChrMarine@RunCircleRt01") smoothMotion.smoothCycle("ChrBrad_ChrMarine@RunCircleRt01_smooth",0.1); smoothMotion = scene.getMotion("ChrBrad_ChrMarine@WalkCircleRt01") smoothMotion.smoothCycle("ChrBrad_ChrMarine@WalkCircleRt01_smooth",0.1); smoothMotion = scene.getMotion("ChrBrad_ChrMarine@WalkTightCircleRt01") smoothMotion.smoothCycle("ChrBrad_ChrMarine@WalkTightCircleRt01_smooth",0.1); smoothMotion = scene.getMotion("ChrBrad_ChrMarine@StrafeFastRt01") smoothMotion.smoothCycle("ChrBrad_ChrMarine@StrafeFastRt01_smooth",0.1); smoothMotion = scene.getMotion("ChrBrad_ChrMarine@Meander01") smoothMotion.smoothCycle("ChrBrad_ChrMarine@Meander01_smooth",0.2); #locomotion mirror mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@WalkCircleRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@WalkCircleLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@WalkTightCircleRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@WalkTightCircleLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@StrafeFastRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@StrafeFastLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@StrafeSlowRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@StrafeSlowLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@RunCircleRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@RunCircleLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@RunTightCircleRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@RunTightCircleLf01", locomotionInitSkeleton) #mirroring for smooth cycle motion mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@WalkCircleRt01_smooth") mirrorMotion.mirror("ChrBrad_ChrMarine@WalkCircleLf01_smooth", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@WalkTightCircleRt01_smooth") mirrorMotion.mirror("ChrBrad_ChrMarine@WalkTightCircleLf01_smooth", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@StrafeFastRt01_smooth") mirrorMotion.mirror("ChrBrad_ChrMarine@StrafeFastLf01_smooth", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@RunCircleRt01_smooth") mirrorMotion.mirror("ChrBrad_ChrMarine@RunCircleLf01_smooth", locomotionInitSkeleton) #idle turn mirror mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Turn90Rt") mirrorMotion.mirror("ChrBrad_ChrMarine@Turn90Lf", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Turn180Rt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Turn180Lf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Turn360Rt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Turn360Lf01", locomotionInitSkeleton) #starting mirror mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Idle01_ToWalk01") mirrorMotion.mirror("ChrBrad_ChrMarine@Idle01_ToWalkLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Idle01_ToWalk01_Turn90Rt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Idle01_ToWalk01_Turn90Lf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Idle01_ToWalk01_Turn180Rt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Idle01_ToWalk01_Turn180Lf01", locomotionInitSkeleton) #step mirror mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Idle01_StepBackwardsRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Idle01_StepBackwardsLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Idle01_StepForwardRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Idle01_StepForwardLf01", locomotionInitSkeleton) mirrorMotion = scene.getMotion("ChrBrad_ChrMarine@Idle01_StepSidewaysRt01") mirrorMotion.mirror("ChrBrad_ChrMarine@Idle01_StepSidewaysLf01", locomotionInitSkeleton) # locomotion main state scene.run("locomotion-ChrBrad-state-Locomotion.py") # starting state, starting locomotion with different angle scene.run("locomotion-ChrBrad-state-StartingLeft.py") scene.run("locomotion-ChrBrad-state-StartingRight.py") # idle turn state, facing adjusting scene.run("locomotion-ChrBrad-state-IdleTurn.py") # step state, stepping adjusting scene.run("locomotion-ChrBrad-state-Step.py") # transitions scene.run("locomotion-ChrBrad-transitions.py")
Goddess Gayatri homam and puja is done for well being of family members. It is also done to improve spiritual wisdom as Goddess Gayatri is Veda mata. She gave lord Brama secret of four Veda and with her inspiration God Brama created whole existence. Her homam is also done when, someone ate cow meat and later realized it is sin. To remove sin of eating cow meat Goddess Gayatri homam and puja is done. In Sanskrit, Gayatri means “ Kaayantham Thirayatha “ . The explanation of this is the person who is chanting this mantra will be protected by Goddess Gayatri/. Gyantri Mantra is most powerful mantra among Vedic Mantra. Goddess Gayatri lives in Sun or Surya loka. She seats on a red lotus, signifying wealth. Her mantra is considered holiest of all.. The Gayatri mantra by the sage Vishwamitra" is considered the supreme mantra among all. The Lord Krishna himself said in Gita, “ Among mantras I am Gayatri Mantra “. From ancient sages to modern day scientist like Albert Einstein all people greatly appreciated Gayatri Mantra. People have misconception that Goddess Gayatri Mantra should only chanted by Bharman and other high cast. But it is totally wrong. Every Mantra, there will be one Rishi, who is termed to be the Kartha (person who will be main for that and will be equivalent to that mantram). Vishwamitra, who belongs to Kshatriya Kula, is referred to as the Kartha for this great Gayatri Mantra. So this Mantram is not only for Brahmanars, Vedic peoples etc but also for Kshatriyas and to all in this world. Goddess Gayatri homam and puja is done for well being of family members. It is also done to improve spiritual wisdom as Goddess Gayatri is Veda mata. She gave lord Brama secret of four Veda and with her inspiration God Brama created whole existence. Her homam is also done when, someone ate cow meat and later realized it is sin. To remove sin of eating cow meat Goddess Gayatri homam and puja is done. In Hinduism Cow is considering as very auspicious, all God live in cow body. Eating cow meat is terrible sin. O Supreme Lord! You alone are true. You alone are worthy of glorification and oblation. You are the creator and sustainer of all. You are the giver of life. Divine Father, the source of existence, intelligence and bliss, you are all-powerful, all-wise, eternal and merciful. I want to feel your divine presence in me, and in everything. You are Great, Good and Pure. Help me Father, to live a good, pure and sinless life. Illumine and inspire my intellect. Grant me great understanding and a peaceful mind that I may live in the Presence of your Divine Glory. We offer Goddess Gayatri Homam and Puja Service. If you want to perform Goddess Gayatri Puja and Homam then Contact us for more information.
""" This module provides code for doing logistic regressions. Classes: LogisticRegression Holds information for a LogisticRegression classifier. Functions: train Train a new classifier. calculate Calculate the probabilities of each class, given an observation. classify Classify an observation into a class. """ try: from Numeric import * from LinearAlgebra import * # inverse except ImportError, x: raise ImportError, "This module requires Numeric (precursor to NumPy) with the LinearAlgebra lib" from Bio import listfns class LogisticRegression: """Holds information necessary to do logistic regression classification. Members: beta List of the weights for each dimension. """ def __init__(self): """LogisticRegression()""" beta = [] def train(xs, ys, update_fn=None, typecode=None): """train(xs, ys[, update_fn]) -> LogisticRegression Train a logistic regression classifier on a training set. xs is a list of observations and ys is a list of the class assignments, which should be 0 or 1. xs and ys should contain the same number of elements. update_fn is an optional callback function that takes as parameters that iteration number and log likelihood. """ if len(xs) != len(ys): raise ValueError, "xs and ys should be the same length." if not xs or not xs[0]: raise ValueError, "No observations or observation of 0 dimension." classes = listfns.items(ys) classes.sort() if classes != [0, 1]: raise ValueError, "Classes should be 0's and 1's" if typecode is None: typecode = Float # Dimensionality of the data is the dimensionality of the # observations plus a constant dimension. N, ndims = len(xs), len(xs[0]) + 1 # Make an X array, with a constant first dimension. X = ones((N, ndims), typecode) X[:, 1:] = xs Xt = transpose(X) y = asarray(ys, typecode) # Initialize the beta parameter to 0. beta = zeros(ndims, typecode) MAX_ITERATIONS = 500 CONVERGE_THRESHOLD = 0.01 stepsize = 1.0 # Now iterate using Newton-Raphson until the log-likelihoods # converge. iter = 0 old_beta = old_llik = None while iter < MAX_ITERATIONS: # Calculate the probabilities. p = e^(beta X) / (1+e^(beta X)) ebetaX = exp(dot(beta, Xt)) p = ebetaX / (1+ebetaX) # Find the log likelihood score and see if I've converged. logp = y*log(p) + (1-y)*log(1-p) llik = sum(logp) if update_fn is not None: update_fn(iter, llik) # Check to see if the likelihood decreased. If it did, then # restore the old beta parameters and half the step size. if llik < old_llik: stepsize = stepsize / 2.0 beta = old_beta # If I've converged, then stop. if old_llik is not None and fabs(llik-old_llik) <= CONVERGE_THRESHOLD: break old_llik, old_beta = llik, beta iter += 1 W = identity(N) * p Xtyp = dot(Xt, y-p) # Calculate the first derivative. XtWX = dot(dot(Xt, W), X) # Calculate the second derivative. #u, s, vt = singular_value_decomposition(XtWX) #print "U", u #print "S", s delta = dot(inverse(XtWX), Xtyp) if fabs(stepsize-1.0) > 0.001: delta = delta * stepsize beta = beta + delta # Update beta. else: raise AssertionError, "Didn't converge." lr = LogisticRegression() lr.beta = map(float, beta) # Convert back to regular array. return lr def calculate(lr, x): """calculate(lr, x) -> list of probabilities Calculate the probability for each class. lr is a LogisticRegression object. x is the observed data. Returns a list of the probability that it fits each class. """ # Insert a constant term for x. x = asarray([1.0] + x) # Calculate the probability. p = e^(beta X) / (1+e^(beta X)) ebetaX = exp(dot(lr.beta, x)) p = ebetaX / (1+ebetaX) return [1-p, p] def classify(lr, x): """classify(lr, x) -> 1 or 0 Classify an observation into a class. """ probs = calculate(lr, x) if probs[0] > probs[1]: return 0 return 1
Basic with a minimalist touch, this t-shirt is a throwback to traditions of manufacturing, where lifetime quality was the main focus. The Stevie tee is locally made with a fabric specially thread for us in Montreal where eco-respectful manufacturing is always the standard. Your comfort is guaranty with the 100% ring spun cotton content, making this t-shirt light, flexible and breathable. Simple avec une touche minimaliste, ce t-shirt est un rappel aux anciennes méthodes de manufacture ou le focus était sur la qualité et la longévité du produit. Le Stevie tee est fait localement et tissé specialement pour nos a Montreal en respectant les standards de fabrication éco-responsable. Votre comfort est garantie avec sa teneur 100% coton, faisant de ce t-shirt un morceau leger et flexible.
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/gugu/w/calibre/src/calibre/gui2/convert/txt_output.ui' # # Created: Thu Jul 19 23:32:30 2012 # by: PyQt4 UI code generator 4.9.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(392, 346) self.verticalLayout_2 = QtGui.QVBoxLayout(Form) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.groupBox = QtGui.QGroupBox(Form) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.gridLayout = QtGui.QGridLayout(self.groupBox) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label_3 = QtGui.QLabel(self.groupBox) self.label_3.setObjectName(_fromUtf8("label_3")) self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1) self.opt_txt_output_encoding = EncodingComboBox(self.groupBox) self.opt_txt_output_encoding.setEditable(True) self.opt_txt_output_encoding.setObjectName(_fromUtf8("opt_txt_output_encoding")) self.gridLayout.addWidget(self.opt_txt_output_encoding, 0, 1, 1, 1) self.label = QtGui.QLabel(self.groupBox) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 1, 0, 1, 1) self.opt_newline = QtGui.QComboBox(self.groupBox) self.opt_newline.setObjectName(_fromUtf8("opt_newline")) self.gridLayout.addWidget(self.opt_newline, 1, 1, 1, 1) self.label_4 = QtGui.QLabel(self.groupBox) self.label_4.setObjectName(_fromUtf8("label_4")) self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1) self.opt_txt_output_formatting = QtGui.QComboBox(self.groupBox) self.opt_txt_output_formatting.setObjectName(_fromUtf8("opt_txt_output_formatting")) self.gridLayout.addWidget(self.opt_txt_output_formatting, 2, 1, 1, 1) self.verticalLayout_2.addWidget(self.groupBox) self.groupBox_2 = QtGui.QGroupBox(Form) self.groupBox_2.setObjectName(_fromUtf8("groupBox_2")) self.gridLayout_2 = QtGui.QGridLayout(self.groupBox_2) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.label_2 = QtGui.QLabel(self.groupBox_2) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout_2.addWidget(self.label_2, 1, 0, 1, 1) self.opt_max_line_length = QtGui.QSpinBox(self.groupBox_2) self.opt_max_line_length.setObjectName(_fromUtf8("opt_max_line_length")) self.gridLayout_2.addWidget(self.opt_max_line_length, 1, 1, 1, 1) self.opt_force_max_line_length = QtGui.QCheckBox(self.groupBox_2) self.opt_force_max_line_length.setObjectName(_fromUtf8("opt_force_max_line_length")) self.gridLayout_2.addWidget(self.opt_force_max_line_length, 2, 0, 1, 2) self.opt_inline_toc = QtGui.QCheckBox(self.groupBox_2) self.opt_inline_toc.setObjectName(_fromUtf8("opt_inline_toc")) self.gridLayout_2.addWidget(self.opt_inline_toc, 0, 0, 1, 1) self.verticalLayout_2.addWidget(self.groupBox_2) self.groupBox_3 = QtGui.QGroupBox(Form) self.groupBox_3.setObjectName(_fromUtf8("groupBox_3")) self.verticalLayout = QtGui.QVBoxLayout(self.groupBox_3) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.opt_keep_links = QtGui.QCheckBox(self.groupBox_3) self.opt_keep_links.setObjectName(_fromUtf8("opt_keep_links")) self.verticalLayout.addWidget(self.opt_keep_links) self.opt_keep_image_references = QtGui.QCheckBox(self.groupBox_3) self.opt_keep_image_references.setObjectName(_fromUtf8("opt_keep_image_references")) self.verticalLayout.addWidget(self.opt_keep_image_references) self.opt_keep_color = QtGui.QCheckBox(self.groupBox_3) self.opt_keep_color.setObjectName(_fromUtf8("opt_keep_color")) self.verticalLayout.addWidget(self.opt_keep_color) self.verticalLayout_2.addWidget(self.groupBox_3) self.label_3.setBuddy(self.opt_txt_output_encoding) self.label.setBuddy(self.opt_newline) self.label_4.setBuddy(self.opt_txt_output_formatting) self.label_2.setBuddy(self.opt_max_line_length) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_("Form")) self.groupBox.setTitle(_("General")) self.label_3.setText(_("Output &Encoding:")) self.label.setText(_("&Line ending style:")) self.label_4.setText(_("&Formatting:")) self.groupBox_2.setTitle(_("Plain")) self.label_2.setText(_("&Maximum line length:")) self.opt_force_max_line_length.setText(_("Force maximum line length")) self.opt_inline_toc.setText(_("&Inline TOC")) self.groupBox_3.setTitle(_("Markdown, Textile")) self.opt_keep_links.setText(_("Do not remove links (<a> tags) before processing")) self.opt_keep_image_references.setText(_("Do not remove image references before processing")) self.opt_keep_color.setText(_("Keep text color, when possible")) from calibre.gui2.widgets import EncodingComboBox
Chitande aulonocara’s will enjoy meaty treats of mysis, blood worms, krill and brine shrimp. It should also be given some spirulina based flake or granules to complete the diet. Africa; Chitande aulonocara is endemic to Lake Malawi. Males tend to be more colourful than the females. The females will often appear to be drab. Aulonocara ethelwynnae are mouth brooders. Once the eggs have been laid and fertilised, the female will collect them into her mouth and incubate them. During this time she may hide away and not eat. The fry should be released after 3 weeks and they can then be fed on newly hatched brine shrimp. The expected life span for Chitande aulonocara is 10 years. Plenty of rockwork should be added to the tank to provide hiding places, especially for the females. Always leave open swimming spaces at the front. It is best to keep one male to three females to reduce aggression towards one fish.
from enum import Enum from typing import ( List, Optional, ) _Signals = Enum("Signals", ["DOT", "DASH"]) _Pauses = Enum("Pauses", ["SIGNAL", "LETTER", "WORD"]) _ON_TIMINGS = { 0.25: _Signals.DOT, 0.75: _Signals.DASH, } _OFF_TIMINGS = { 0.25: _Pauses.SIGNAL, 1.25: _Pauses.LETTER, 2.50: _Pauses.WORD, } _ORDERED_WORDS = ( 'shell', 'halls', 'slick', 'trick', 'boxes', 'leaks', 'strobe', 'bistro', 'flick', 'bombs', 'break', 'brick', 'steak', 'sting', 'vector', 'beats', ) def _make_letters(): # This function is here so that we can expose the _Signals variables with nice names, which makes the dictionary # below much nicer. This should only be called once, to initialize the _LETTERS variable. dot = _Signals.DOT dash = _Signals.DASH return { (dot, dash): 'a', (dash, dot, dot, dot): 'b', (dash, dot, dash, dot): 'c', (dash, dot, dot): 'd', (dot,): 'e', (dot, dot, dash, dot): 'f', (dash, dash, dot): 'g', (dot, dot, dot, dot): 'h', (dot, dot): 'i', (dot, dash, dash, dash): 'j', (dash, dot, dash): 'k', (dot, dash, dot, dot): 'l', (dash, dash): 'm', (dash, dot): 'n', (dash, dash, dash): 'o', (dot, dash, dash, dot): 'p', (dash, dash, dot, dash): 'q', (dot, dash, dot): 'r', (dot, dot, dot): 's', (dash,): 't', (dot, dot, dash): 'u', (dot, dot, dot, dash): 'v', (dot, dash, dash): 'w', (dash, dot, dot, dash): 'x', (dash, dot, dash, dash): 'y', (dash, dash, dot, dot): 'z', } _LETTERS = _make_letters() def _get_closest_time_entry(seconds, timing_dict): distances = [(abs(seconds - reference_duration), pause_type) for reference_duration, pause_type in timing_dict.iteritems()] distances = sorted(distances, key=lambda x: x[0]) return distances[0][1] def _signals_to_letter(signals): return _LETTERS[tuple(signals)] class MorseCodeState(object): def __init__(self): super(MorseCodeState, self).__init__() self.word_start_index = None # Assuming words are 5 letters long self.letters = [None] * 5 self.next_letter_index = 0 self.current_partial_letter = None # type: Optional[List[_Signals]] def ingest_timing(self, seconds, is_on): """It is invalid to call this once is_word_known returns True""" if is_on: if self.current_partial_letter is None: return signal = _get_closest_time_entry(seconds, _ON_TIMINGS) self.current_partial_letter.append(signal) else: pause_type = _get_closest_time_entry(seconds, _OFF_TIMINGS) if pause_type == _Pauses.SIGNAL: return # Handle letter or word gap. Both do the letter behavior. if self.current_partial_letter is not None: letter = _signals_to_letter(self.current_partial_letter) print "ADDING LETTER:", letter self.letters[self._get_next_letter_index()] = letter # Assume we'll never wrap around, since we should know what the word is by then. self.next_letter_index += 1 self.current_partial_letter = [] if pause_type == _Pauses.WORD: # It's possible this is the last thing we see, in which case we'll need to make sure it's within # the range of the array. self.word_start_index = self._get_next_letter_index() def _get_next_letter_index(self): return self.next_letter_index % len(self.letters) def _get_word_if_possible(self): # This function tries to find the word given a subset of the total possible information if self.next_letter_index == 0: # We have no information yet, so we can't know the word yet. return None def find_single_matching_word(predicate): # This helper function will check to see if exactly one word matches the given predicate. If so, it will # return that word, otherwise it'll return None. possible_word = None for word in _ORDERED_WORDS: if predicate(word): if possible_word is not None: # Multiple possibilities, we don't know what word it is return None possible_word = word return possible_word if self.word_start_index is None: # No start index, so we have to look inside every word partial_word = "".join(self.letters[:self._get_next_letter_index()]) return find_single_matching_word(lambda word: partial_word in word) else: # We have a start index, can check beginnings and ends of words end = "".join(self.letters[:self.word_start_index]) start = "".join(self.letters[self.word_start_index:self._get_next_letter_index()]) return find_single_matching_word(lambda word: word.startswith(start) and word.endswith(end)) def is_word_known(self): word = self._get_word_if_possible() if word is None and self.next_letter_index >= 2 * len(self.letters): assert False, "Can't find word, but got all letters twice: {}".format(self.letters) return word is not None def get_num_time_to_press_right_arrow(self): word = self._get_word_if_possible() assert word is not None return _ORDERED_WORDS.index(word)
I want to start this post off saying that this is me, flashing back, 7 months. Yes, it’s been over 7 months since I last wrote and that upsets me terribly. I think about it everyday, but it’s just been a struggle to keep up with how busy life has really become. Just about 25 weeks ago, Christmas morning, my husband Russell and I woke up in a hotel room, about 5 minutes away from where our parents live. We were in a hotel because at the time, the Family that we were house-sitting for, were home for the holidays, so we were somewhat “homeless.” Our wonderful friends and their 1 Year old had taken us into their home for 3 weeks, but we wanted to be able to give them their space and get ours, on Christmas morning. And neither of us wanted to stay at each other parents house- so no need for an argument there. So that morning, in that hotel room, I took out one of the pregnancy tests I had packed. Yup, we were trying and had been for just a couple of months at that point. I said, “should I take it?” Knowing it was probably a tad to early to take the test (being only about 9 days past ovulation), I thought how cool would this be as a Christmas morning surprise, for just us to know about? It would be our little secret. Took the test and it told us a quick NO. I was disappointed but kept telling myself it’s early to test, we’ll try again in a few days. So we had ourselves a very Merry Christmas, just the 2 of us. 3 days later…it was a Saturday morning and we were back out our friends home. They had left the day prior to head to down to Florida for a week so we had the place to ourselves. It was a beautiful Saturday morning (for December). I said to Russell again, “well, should I?” That was a question we had become familiar with over the past few months. And he said, “sure, why not,” as usual. At this point I was 12 days past ovulation. There should be a pretty high chance that the test results would accurate by this point. I mean, I felt pretty educated about all of that ovulation stuff and testing times, from all of the endless reading I had been doing over the past year! So I took that test and waited a few minutes. I was about to toss the test until I realized, or I thought, there was something appearing as a second line. So I held it up to the light and there it was. That second line was forming. I stepped out into the hall and called for Russell. I said, “look, there’s a line. I think that’s a line. That’s a line, right?” He took it, stared at it for what felt like 5 minutes, but it was probably only 10 seconds. He held it up to the light and looked at me and agreed that yes that was indeed a second line. Wow- it’s almost like, what now? What do we do? We just hugged each other and gave each other a big kiss. It’s a moment that you will never forget. That moment when a tiny stick tells you that you are growing a human being inside of you. How is that even possible? How am and I going to do this? We are going to have a little “us.” How cool is that?? Russ and I were on top of the moon (and we still are) and that’s when we decided, well, time to look for our first home to buy. Another exciting chapter of these past 7 months!
# Download all materials from blendermada online material library (www.blendermada.com) # First install blendermada plugin (v 0.9.8-b, downloaded 2016/10/04) # Before calling: Open a blank .blend file import os import bpy import bvp scn = bpy.context.scene if bpy.app.version < (2, 80, 0): vl = context.view_layer else: vl = scn # Get all latest materials scn.render.engine = 'CYCLES' bpy.ops.bmd.update() # Clear scene for o in scn.objects: scn.objects.unlink(o) # Add single cube bpy.ops.mesh.primitive_cube_add(location=(0,0,0)) ob = bpy.context.object # Loop over categories (e.g. Cloth, Nature, etc) for cat_idx in range(len(scn.bmd_category_list)): scn.bmd_category_list_idx = cat_idx cat_name = scn.bmd_category_list[cat_idx].name print("Importing {} materials...".format(cat_name.lower())) # Loop over specific materials for mat_idx in range(len(scn.bmd_material_list)): scn.bmd_material_list_idx = mat_idx mat_name = scn.bmd_material_list[mat_idx].name # Import material bpy.ops.bmd.importmat() vl.update() mat = ob.material_slots[0].material # Incorporate category into name, set up fake user to keep material through close of file mat.name = '{}_{}'.format(cat_name.lower(), mat_name.lower()) mat.use_fake_user = True # Clear scene for o in scn.objects: scn.objects.unlink(o) sfile = os.path.expanduser(bvp.config.get('path','db_dir')) fname = 'Blendermada_Materials.blend' sfile = os.path.join(sfile, 'Material', fname) bpy.ops.wm.save_mainfile(filepath=sfile) dbi = bvp.DBInterface() for mat in bpy.data.materials: m = bvp.Material(name=mat.name, fname=fname, _id=dbi.get_uuid(), dbi=dbi) m.save()
FEG Abandoned Factory Escape 15 is another point and click escape game developed by First Escape Games. A factory worker has been locked up in a room in the abandoned factory by his colleague unintentionally. The worker is in trouble now because he is stuck inside.
# # ------------------------------------------------------------ # Copyright (c) All rights reserved # SiLab, Institute of Physics, University of Bonn # ------------------------------------------------------------ # import yaml import time import numpy as np from bitarray import bitarray from basil.dut import Dut class Pixel(Dut): """ A class for communicating with a pixel chip. """ def program_global_reg(self): """ Send the global register to the chip. Loads the values of self['GLOBAL_REG'] onto the chip. Includes enabling the clock, and loading the Control (CTR) and DAC shadow registers. """ self._clear_strobes() gr_size = len(self['GLOBAL_REG'][:]) #get the size self['SEQ']['SHIFT_IN'][0:gr_size] = self['GLOBAL_REG'][:] # this will be shifted out self['SEQ']['GLOBAL_SHIFT_EN'][0:gr_size] = bitarray( gr_size * '1') #this is to enable clock self['SEQ']['GLOBAL_CTR_LD'][gr_size+1:gr_size+2] = bitarray("1") # load signals self['SEQ']['GLOBAL_DAC_LD'][gr_size+1:gr_size+2] = bitarray("1") # Execute the program (write bits to output pins) # + 1 extra 0 bit so that everything ends on LOW instead of HIGH self._run_seq(gr_size+3) def program_pixel_reg(self, enable_receiver=True): """ Send the pixel register to the chip and store the output. Loads the values of self['PIXEL_REG'] onto the chip. Includes enabling the clock, and loading the Control (CTR) and DAC shadow registers. if(enable_receiver), stores the output (by byte) in self['DATA'], retrievable via `chip['DATA'].get_data()`. """ self._clear_strobes() #enable receiver it work only if pixel register is enabled/clocked self['PIXEL_RX'].set_en(enable_receiver) px_size = len(self['PIXEL_REG'][:]) #get the size self['SEQ']['SHIFT_IN'][0:px_size] = self['PIXEL_REG'][:] # this will be shifted out self['SEQ']['PIXEL_SHIFT_EN'][0:px_size] = bitarray( px_size * '1') #this is to enable clock print 'px_size', px_size self._run_seq(px_size+1) #add 1 bit more so there is 0 at the end other way will stay high def _run_seq(self, size): """ Send the contents of self['SEQ'] to the chip and wait until it finishes. """ # Write the sequence to the sequence generator (hw driver) self['SEQ'].write(size) #write pattern to memory self['SEQ'].set_size(size) # set size self['SEQ'].set_repeat(1) # set repeat for _ in range(1): self['SEQ'].start() # start while not self['SEQ'].get_done(): #time.sleep(0.1) print "Wait for done..." def _clear_strobes(self): """ Resets the "enable" and "load" output streams to all 0. """ #reset some stuff self['SEQ']['GLOBAL_SHIFT_EN'].setall(False) self['SEQ']['GLOBAL_CTR_LD'].setall(False) self['SEQ']['GLOBAL_DAC_LD'].setall(False) self['SEQ']['PIXEL_SHIFT_EN'].setall(False) self['SEQ']['INJECTION'].setall(False) print "Start" stream = open("lx9.yaml", 'r') cnfg = yaml.load(stream) chip = Pixel(cnfg) chip.init() chip['GPIO']['LED1'] = 1 chip['GPIO']['LED2'] = 0 chip['GPIO']['LED3'] = 0 chip['GPIO']['LED4'] = 0 chip['GPIO'].write() #settings for global register (to input into global SR) # can be an integer representing the binary number desired, # or a bitarray (of the form bitarray("10101100")). chip['GLOBAL_REG']['global_readout_enable'] = 0# size = 1 bit chip['GLOBAL_REG']['SRDO_load'] = 0# size = 1 bit chip['GLOBAL_REG']['NCout2'] = 0# size = 1 bit chip['GLOBAL_REG']['count_hits_not'] = 0# size = 1 chip['GLOBAL_REG']['count_enable'] = 0# size = 1 chip['GLOBAL_REG']['count_clear_not'] = 0# size = 1 chip['GLOBAL_REG']['S0'] = 0# size = 1 chip['GLOBAL_REG']['S1'] = 0# size = 1 chip['GLOBAL_REG']['config_mode'] = 3# size = 2 chip['GLOBAL_REG']['LD_IN0_7'] = 0# size = 8 chip['GLOBAL_REG']['LDENABLE_SEL'] = 0# size = 1 chip['GLOBAL_REG']['SRCLR_SEL'] = 0# size = 1 chip['GLOBAL_REG']['HITLD_IN'] = 0# size = 1 chip['GLOBAL_REG']['NCout21_25'] = 0# size = 5 chip['GLOBAL_REG']['column_address'] = 0# size = 6 chip['GLOBAL_REG']['DisVbn'] = 0# size = 8 chip['GLOBAL_REG']['VbpThStep'] = 0# size = 8 chip['GLOBAL_REG']['PrmpVbp'] = 0# size = 8 chip['GLOBAL_REG']['PrmpVbnFol'] = 0# size = 8 chip['GLOBAL_REG']['vth'] = 0# size = 8 chip['GLOBAL_REG']['PrmpVbf'] = 0# size = 8 print "program global register..." chip.program_global_reg() #settings for pixel register (to input into pixel SR) # can be an integer representing the binary number desired, # or a bitarray (of the form bitarray("10101100")). chip['PIXEL_REG'][:] = bitarray('1111111010001100'*8) print chip['PIXEL_REG'] #chip['PIXEL_REG'][0] = 0 print "program pixel register..." chip.program_pixel_reg() time.sleep(0.5) # Get output size in bytes print "chip['DATA'].get_FIFO_SIZE() = ", chip['DATA'].get_FIFO_SIZE() rxd = chip['DATA'].get_data() #get data from sram fifo print rxd data0 = rxd.astype(np.uint8) # Change type to unsigned int 8 bits and take from rxd only the last 8 bits data1 = np.right_shift(rxd, 8).astype(np.uint8) # Rightshift rxd 8 bits and take again last 8 bits data = np.reshape(np.vstack((data1, data0)), -1, order='F') # data is now a 1 dimensional array of all bytes read from the FIFO bdata = np.unpackbits(data) print "data = ", data print "bdata = ", bdata
This double-Din AV center connects with your Apple or Android handset for effortless voice control while you drive. Built-in 4 x 55-W amplification delivers clear sound that you can customize to your liking. And with iDatalink® Maestro® compatibility, you can control your car’s originally-equipped infotainment, while displaying vehicle information such as air conditioning, tire pressure and performance. he iLX-F309 is the perfect solution with a 9-inch touch screen that hovers over the dash but uses a standard 1-DIN chassis for installation. The iLX-F309 brings a large screen to a variety of vehicles without the need for custom installation. It uses Apple CarPlay™ and Android Auto™ to optimize your main smartphone features in a way that lets you concentrate on driving.
# -*- coding: utf-8 -*- # Copyright 2017 Mobicage NV # # 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. # # @@license_version:1.2@@ from google.appengine.ext import ndb from plugins.veurne_trash import plugin_consts class UserLocation(ndb.Model): service_identity = ndb.StringProperty() address = ndb.StringProperty(indexed=False) street_number = ndb.IntegerProperty(indexed=False) house_number = ndb.IntegerProperty(indexed=False) house_bus = ndb.StringProperty(indexed=False) notifications = ndb.IntegerProperty(indexed=False, repeated=True) user_data_epoch = ndb.IntegerProperty(indexed=False) next_collection = ndb.IntegerProperty() @property def sik(self): return self.key.namespace().split("-")[1].decode('utf8') @property def email(self): return self.key.id().split(":")[0].decode('utf8') @property def app_id(self): return self.key.id().split(":")[1].decode('utf8') @classmethod def create_key(cls, sik, email, app_id): return ndb.Key(cls, "%s:%s" % (email, app_id), namespace=UserLocation.create_namespace(sik)) @staticmethod def get_by_info(sik, email, app_id): return UserLocation.create_key(sik, email, app_id).get() @staticmethod def create_namespace(sik): return "%s-%s" % (plugin_consts.NAMESPACE, sik)
Stratis Gayner Plastic Surgery is known in Harrisburg and Lancaster, PA, and throughout the Eastern Seaboard for providing exceptional plastic surgery results for the face, breasts, and body. It all began in 2005 when Dr. John Stratis read an article about combining a facial plastic surgery specialist with a body plastic surgery specialist, something that only a handful of practices across the country offered. Those practices reported an increased ability to serve patients and enhanced patient satisfaction. Dr. Stratis couldn’t get the article out of his head; it was such a simple idea with obvious patient benefits, yet almost no one was doing it. After further research, he became convinced he wanted to pursue the idea. So he went looking for a face specialist. After an extensive investigation, one name kept coming up as the doctor in the region who was doing excellent facial plastic surgery – Dr. Scott Gayner. Dr. Stratis approached Dr. Gayner with the idea and, after a good deal of getting to know each other, they opened the doors to their Harrisburg, Pennsylvania, cosmetic plastic surgery practice on Jan. 1st, 2007. The advantages of having specialized plastic surgeons can be profound. In Harrisburg, they are unique to Stratis Gayner Plastic Surgery. To find out more about our practice, request a consultation with Dr. Stratis or Dr. Gayner online or call their office at (717) 728-1700. Plastic surgery is one of the most rapidly changing fields in medicine today. New devices, procedures, and drugs are introduced regularly. With Dr. Stratis focused on body procedures and Dr. Gayner focused on facial procedures, each of them can stay up-to-date on the latest developments in his own discipline. With every learning opportunity from seminars to medical journals focused on their specialty, their knowledge in their area of focus continues to grow. The result? Their patients can rest assured that Dr. Stratis and Dr. Gayner are fluent in the latest techniques. It’s not unusual for a patient’s surgical plan to include both a facial procedure and a body procedure. In a conventional plastic surgery practice, the plastic surgeon will perform both operations on the same day, one after the other. Dr. Stratis and Dr. Gayner can work on a patient simultaneously, typically reducing the time for surgery by half. With a simultaneous operation, the patient is under anesthesia for less time, minimizing recovery time and risk. Since the surgeons are also working for less time (four hours instead of eight, for example) doctor fatigue is reduced. Also, because the facility and staff are needed for less time, a lower cost may be possible. Cross-consultation is another benefit unique to Stratis Gayner Plastic Surgery. Typically, patients come to their consultations with concerns related to either the body or face. Sometimes patients may also have concerns about another area of the body. When this occurs, Drs. Stratis and Gayner will work collaboratively on the patient’s case. We invite you to explore other areas of our website to learn more about Dr. Stratis and Dr. Gayner, along with the specific procedure or procedures in which you may be interested. You can also see what former patients have to say by going to our Video Gallery. You can meet personally with either Dr. Stratis or Dr. Gayner by requesting a consultation using the online form or by calling our office directly at (717) 728-1700 to schedule an appointment.
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from oslo_config import cfg from oslo_log import log from keystone import assignment from keystone.common import ldap as common_ldap from keystone.common import models from keystone import exception from keystone.i18n import _ from keystone.identity.backends import ldap as ldap_identity CONF = cfg.CONF LOG = log.getLogger(__name__) class Role(assignment.RoleDriver): def __init__(self): super(Role, self).__init__() self.LDAP_URL = CONF.ldap.url self.LDAP_USER = CONF.ldap.user self.LDAP_PASSWORD = CONF.ldap.password self.suffix = CONF.ldap.suffix # This is the only deep dependency from resource back # to identity. The assumption is that if you are using # LDAP for resource, you are using it for identity as well. self.user = ldap_identity.UserApi(CONF) self.role = RoleApi(CONF, self.user) def get_role(self, role_id): return self.role.get(role_id) def list_roles(self, hints): return self.role.get_all() def list_roles_from_ids(self, ids): return [self.get_role(id) for id in ids] def create_role(self, role_id, role): self.role.check_allow_create() try: self.get_role(role_id) except exception.NotFound: pass else: msg = _('Duplicate ID, %s.') % role_id raise exception.Conflict(type='role', details=msg) try: self.role.get_by_name(role['name']) except exception.NotFound: pass else: msg = _('Duplicate name, %s.') % role['name'] raise exception.Conflict(type='role', details=msg) return self.role.create(role) def delete_role(self, role_id): self.role.check_allow_delete() return self.role.delete(role_id) def update_role(self, role_id, role): self.role.check_allow_update() self.get_role(role_id) return self.role.update(role_id, role) # NOTE(heny-nash): A mixin class to enable the sharing of the LDAP structure # between here and the assignment LDAP. class RoleLdapStructureMixin(object): DEFAULT_OU = 'ou=Roles' DEFAULT_STRUCTURAL_CLASSES = [] DEFAULT_OBJECTCLASS = 'organizationalRole' DEFAULT_MEMBER_ATTRIBUTE = 'roleOccupant' NotFound = exception.RoleNotFound options_name = 'role' attribute_options_names = {'name': 'name'} immutable_attrs = ['id'] model = models.Role # TODO(termie): turn this into a data object and move logic to driver class RoleApi(RoleLdapStructureMixin, common_ldap.BaseLdap): def __init__(self, conf, user_api): super(RoleApi, self).__init__(conf) self._user_api = user_api def get(self, role_id, role_filter=None): model = super(RoleApi, self).get(role_id, role_filter) return model def create(self, values): return super(RoleApi, self).create(values) def update(self, role_id, role): new_name = role.get('name') if new_name is not None: try: old_role = self.get_by_name(new_name) if old_role['id'] != role_id: raise exception.Conflict( _('Cannot duplicate name %s') % old_role) except exception.NotFound: pass return super(RoleApi, self).update(role_id, role) def delete(self, role_id): super(RoleApi, self).delete(role_id)
All of our coaching options are customized and built for you from the ground up. Through conversations and a detailed application, we’ll discuss your background and goals before moving forward. We consult with clients worldwide via video conference. In our one-hour consultations, we take notes and listen to your concerns, needs and goals, evaluate your training history, current situation, and use this info (and your application on our website) to customize your training and nutrition to help you achieve your goals. Your plan includes an Excel document to track your progress, and also contains training, warmup, nutrition, and yearly planning guidelines. We also equip you with strategies to break plateaus when they arise. You can also utilize this service if you want to pick our brains and don’t need coaching. We will write your program and assign cardio if applicable to your goals. Programs include exercises, reps, sets, and how to progress. If applicable, they will also include guidelines on RPE, periodization, and planning leading into competition. The details depend on the program and your needs, but include all the information needed to carry out the program effectively. + How do we communicate? Communication for custom training cycles takes place primarily at the beginning and end of the training. You are primarily running the training self-guided, allowing us to offer it to you at a discounted rate. Before beginning, we’ll make sure you have all the information needed to effectively train. Contact with your coach is perfectly okay, but this is far less communication than weekly coaching. + What if something changes during training like an injury or change of competition date? We can make small changes to training and give you freedom to autoregulate loads, build in flexibility and even guide you along the way. Our main goal is to see you succeed. For big changes like change of competition dates or an injury that requires large changes to training, we suggest re-booking a custom training cycle at a discounted rate or working with us to modify things. While these are one-off consultations, the nature of even low-contact coaching requires we meet again to make changes to training after an initial 8-16 week training plan. We suggest follow-up consultations every 8-12 weeks to keep you progressing and keep your plan customized to your present strength state and relevant to your goals and yearly schedule. After an initial video conference call where we talk about your goals and athletic past, present, and future, we launch into weekly coaching. We will create a fully customized training plan for you based on your goals, including detailed nutritional, warmup, and mobility guidelines, lifting analysis on an ongoing weekly basis. + How is the plan adjusted? Adjustments occur after sending a weekly progress report via email, and includes any questions you have regarding your training. Building a lasting coach-athlete relationship is at the heart of what we’re doing here, and we firmly believe the coaching process to be an intimate and professional one. We use a combination of recorded video, email, pictures, voice messages, and video conference calls. We can discuss complex and sensitive topics through video, share resources and answer questions through emails, coach lifting technique and programming with video, and record video messages when tone of voice and non-verbal communication is especially important. It is through the shared experience of all of these avenues of communication that we can better interact and coach our clients. Consultations are targeted video conference calls designed to solve problems. Whether that problem is your sumo deadlift technique, your understanding of RPE, your desire for mentoring as a coach, or anxiety you feel while squatting, it’s our aim to help you get through it. We’ll spend the hour talking about your issue(s) of choice and give you concrete action steps you can take home with you.