repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
flavour/ifrc_qa
modules/s3/s3fields.py
Python
mit
55,566
0.002142
# -*- coding: utf-8 -*- """ S3 Extensions for gluon.dal.Field, reusable fields @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: 2009-2016 (c) Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ...
requires = ia.requires if requires: if not isinstance(requires, (list, tuple)): requires = [requires] if requires: r = requires[0] if isinstance(
r, IS_EMPTY_OR): requires = r.other ia.update(requires=requires) widget = attr.pop("widget", DEFAULT) ia.update(**attr) else: widget = DEFAULT if isinstance(widget, basestring): if widget == DEFAULT ...
lincolnloop/django-selenium-intro
selenium_intro/wsgi.py
Python
mit
1,150
0.00087
""" WSGI config for selenium_intro project.
This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application v
ia the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django applicatio...
rdo-management/tuskar
tuskar/tests/api/controllers/v1/test_overcloud_roles.py
Python
apache-2.0
4,280
0
# # 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 ...
self.assertTrue(isinstance(result, list)) self.assertEqual(1, len(r
esult)) self.assertEqual(result[0]['name'], 'foo') mock_db_get.assert_called_once() @mock.patch('tuskar.db.sqlalchemy.api.' 'Connection.get_overcloud_role_by_id') def test_get_one(self, mock_db_get): # Setup fake_result = db_models.OvercloudRole(name='foo') ...
siosio/intellij-community
python/testData/breadcrumbs/if.py
Python
apache-2.0
31
0.032258
if
True:
print "a<caret>bc"
christianurich/VIBe2UrbanSim
3rdparty/opus/src/opus_gui/main/controllers/dialogs/opusabout.py
Python
gpl-2.0
1,157
0.007779
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE # PyQt4 includes for python bindings to QT from PyQt4.QtCore import QString, QUrl from PyQt4.QtGui import QDialog, QDesktopServices # UI specific includes from opus_gui.main.views.ui_opusabout impor...
): #print "
cancelPushButton pressed" self.close()
psa-lab/siteinterlock
siteinterlock/proflex_utils/__init__.py
Python
gpl-3.0
741
0
# Sebastian Raschka 2016 # # `siteinterlo
ck` is a Python package for selecting near-native protein-ligand # docking poses based upon the hypothesis that interfacial rigidification # of both the protein and ligand prove to be important characteristics of # the native binding mode and are sensitive to the spatial coupling of # interactions and bond-rotational d...
University # License: GPLv3 # # SiteInterlock was developed in the # Protein Structural Analysis & Design Laboratory # (http://www.kuhnlab.bmb.msu.edu) # Contact email: kuhnlab@msu.edu # # Package author: Sebastian Raschka <http://sebastianraschka.com> # from .hether import hether __all__ = ["hether"]
vicnet/weboob
modules/groupamaes/module.py
Python
lgpl-3.0
2,269
0.001764
# -*- coding: utf-8 -*- # Copyright(C) 2014 Bezleputh # # This file is part of a weboob module. # # This weboob module 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 3 of the Licen...
not, see <http://www.gnu.org/licenses/>. from weboob.capabilities.bank import CapBankPockets, AccountNotFound from weboob.tools.backend import Module, BackendConfig from weboob.tools.value import ValueBackendPassword from weboob.capabilities.base import find_object from .browser import GroupamaesBrowser __all__ = [...
ankPockets): NAME = 'groupamaes' DESCRIPTION = u"Groupama Épargne Salariale" MAINTAINER = u'Bezleputh' EMAIL = 'carton_ben@yahoo.fr' LICENSE = 'LGPLv3+' VERSION = '1.6' BROWSER = GroupamaesBrowser CONFIG = BackendConfig(ValueBackendPassword('login', label='Identifiant', regexp='\d{8,}'...
neocogent/electrum
electrum/gui/qt/transaction_dialog.py
Python
mit
15,958
0.001755
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2012 thomasv@gitorious # # 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 witho...
op-level window QDialog.__init__(self, parent=Non
e) # Take a copy; it might get updated in the main window by # e.g. the FX plugin. If this happens during or after a long # sign operation the signatures are lost. self.tx = tx = copy.deepcopy(tx) # type: Transaction try: self.tx.deserialize() except BaseExc...
iw3hxn/LibrERP
sale_direct_buy/models/__init__.py
Python
agpl-3.0
1,069
0
# -*- encoding: utf-8 -*- ##################################
############################################ # # OpenERP, Open Source Management Solution # # Copyright (C) 2014 Didotech srl (<http://www.didotech.com>). # # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it un
der 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 # ...
SmileEric/SEIMS
preprocess/runoff_coef.py
Python
gpl-2.0
3,410
0.01261
#! /usr/bin/env python #coding=utf-8 from osgeo import gdal, osr import math, os, sys import sqlite3 from numpy import * from config import * import util def RunoffCoefficent(filepath, sqliteFile): #read landuselookup table from sqlite prcFields = ["PRC_ST%d" % (i,) for i in range(1,13)] scFields = ["SC_S...
nduse) runoff_c0 = {} runoff_s0 = {} for row in cursor: id = int(row[0]) runoff_c0[id] = [float(item) for item in row[1:13]] runoff_s0[id] = [float(item) for item in row[13:25]] cursor.close() conn.close() # end read data slope = filepath + os.sep +...
+ mask_to_ext ds = gdal.Open(mask) band = ds.GetRasterBand(1) mask_data = band.ReadAsArray() noDataValue1 = band.GetNoDataValue() landuse = filepath + os.sep + landuseMFile ds = gdal.Open(landuse) band = ds.GetRasterBand(1) landu_data = band.ReadAsArray() soilTe...
qutebrowser/qutebrowser
scripts/opengl_info.py
Python
gpl-3.0
1,537
0.000651
#!/usr/bin/env python3 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2020-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
# GNU General Public License for more details. # # You should have received a copy of the GNU Gen
eral Public License # along with qutebrowser. If not, see <https://www.gnu.org/licenses/>. """Show information about the OpenGL setup.""" from PyQt5.QtGui import (QOpenGLContext, QOpenGLVersionProfile, QOffscreenSurface, QGuiApplication) app = QGuiApplication([]) surface = QOffscreenSurfac...
tacticsiege/TacticToolkit
ttk/sandbox/udemy/LSTM.py
Python
mit
2,903
0.008956
import numpy as np import theano import theano.tensor as T from ttk.sandbox.udemy import init_weight class LSTM(object): def __init__(self, Mi, Mo, activation): self.Mi = Mi self.Mo = Mo self.f = activation # init weights for unit # input gate Wxi = init_we...
f = init_weight(Mo, Mo) bf = np.zeros(Mo) # cell Wxc = init_weight(Mi, Mo) Whc = init_weight(Mo, Mo)
bc = np.zeros(Mo) # output gate Wxo = init_weight(Mi, Mo) Who = init_weight(Mo, Mo) Wco = init_weight(Mo, Mo) bo = np.zeros(Mo) # initial values of cell and state c0 = np.zeros(Mo) h0 = np.zeros(Mo) # set theano vars # i...
chfoo/wpull
wpull/document/util.py
Python
gpl-3.0
1,443
0.000693
'''Misc functions.''' import logging from wpull.backport.logging import BraceMessage as __ import wpull.protocol.http.util import wpull.util import wpull.string _logger = logging.getLogger(__name__) def get_heading_encoding(response): '''Return the document encoding from a HTTP header. Args: resp...
return wpull.string.normalize_codec_name(encoding) else: return None def detect_response_encoding(response, is_html=False, peek=131072): '''Return the likely encoding of the response document. Args: response (Response): An instance of
:class:`.http.Response`. is_html (bool): See :func:`.util.detect_encoding`. peek (int): The maximum number of bytes of the document to be analyzed. Returns: ``str``, ``None``: The codec name. ''' encoding = get_heading_encoding(response) encoding = wpull.string.detect_encoding...
mleonard87/brewballot
brewballot/settings/base.py
Python
mit
3,445
0.001742
""" Django settings for brewballot project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...)...
rue ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'poll', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessi...
'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'brewballot.urls' WSGI_APPLICATION = 'brewballot....
line/line-bot-sdk-python
tests/api/test_get_delivery.py
Python
apache-2.0
3,393
0
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
from __future__ import unicode_literals, absolute_import import unit
test import responses from linebot import ( LineBotApi ) class TestLineBotApi(unittest.TestCase): def setUp(self): self.tested = LineBotApi('channel_secret') self.date = '20190101' @responses.activate def test_get_delivery_broadcast(self): responses.add( response...
jperelli/redmine2github
src/github_issues/github_issue_maker.py
Python
mit
17,531
0.015059
from __future__ import print_function import os import sys import json if __name__=='__main__': SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(SRC_ROOT) from datetime import datetime import requests from jinja2 import Template from jinja2 import Environment, PackageLoa...
e(self): if self.comments_service is None: self.comments_service = pygithub3.services.issues.Comments(**get_github_auth()) return self.comme
nts_service def get_github_conn(self): if self.github_conn is None: self.github_conn = pygithub3.Github(**get_github_auth()) return self.github_conn def format_name_for_github(self, author_name, include_at_sign=True): """ (1) Try the user map ...
Allardvm/LightGBM
python-package/lightgbm/callback.py
Python
mit
6,890
0.001597
# coding: utf-8 # pylint: disable = invalid-name, W0105, C0301 from __future__ import absolute_import import collections from operator import gt, lt from .compat import range_ class EarlyStopException(Exception): """Exception of early stopping. Parameters ---------- best_iteration : int The...
nv.iteration - best_iter[i] >= stopping_rounds: if verbose: print('Early stopping, best iteration is:\n[%d]\t%s' % ( best_iter[i] + 1, '\t'.join([_format_eval_result(x) for x in best_score_list[i]]))) raise EarlyStopException(best_iter[i], best...
ack
redhat-openstack/glance
glance/common/client.py
Python
apache-2.0
22,802
0
# Copyright 2010-2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
para
m port: The port where service resides :param timeout: Connection timeout. :param use_ssl: Should we use HTTPS? :param auth_token: The auth token to pass to the server :param creds: The credentials to pass to the auth plugin :param doc_root: Prefix for all URLs we request from ho...
openstack/python-openstacksdk
openstack/compute/v2/server_group.py
Python
apache-2.0
3,440
0
# 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 t...
action == 'create': # `policy` and `rules` are added with mv=2.64. In it also # `policies` are removed. if utils.supports_microversion(session, '2.64'): if self.policies: if not self.policy and isinstance(self.policies, list):
self.policy = self.policies[0] self._body.clean(only={'policies'}) microversion = self._max_microversion else: if self.rules: message = ("API version %s is required to set rules, but " "it is not avail...
LianaTech/rest-client
python/RestClient.py
Python
mit
3,505
0.00428
""" Liana REST API client Copyright Liana Technologies Ltd 2018 """ import json import hashlib import hmac import requests import time class APIException(Exception): pass class RestClient: def __init__(self, user_id, api_secret, api_url, api_version, api_realm): self._response = None self....
ata['result'] return data def get_http_response(self): """ Returns the raw response object of last performed API request """ return self._response """ INTERNAL METHODS FOLLOW """ def _get_new_timestamp(self): """ Returns a fresh timestamp in proper format """ re...
parameters hash for the API request """ md5 = hashlib.md5() md5.update(self._json_string.encode('utf-8')) return md5.hexdigest() def _get_message(self): """ Return the message in the format which is used to create signature of the request """ message = "\n".join([ ...
cpenv/autocpenv
packages/cpenv/vendor/shotgun_api3/lib/sgsix.py
Python
mit
3,822
0.000785
""" ----------------------------------------------------------------------------- Copyright (c) 2009-2019, Shotgun Software Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must re...
ps://bugs.python.org/issue12326 This function will normalize platform strings to always conform to Python2 or Python3 behavior. :param str platform: The platform string to normalize :param bool python2: The python version behavior to target. If True, a Python2-style platform string will be ret...
(i.e. 'linux2'), otherwise the modern 'linux' platform string will be returned. :returns: The normalized platform string. :rtype: str """ if python2: return "linux2" if platform.startswith("linux") else platform return "linux" if platform.startswith("linux") else platform # sgsix...
Br1an6/ACS_Netplumber_Implementation
hassel-c/net_plumbing/demo.py
Python
gpl-2.0
2,702
0.019985
''' Created on Jul 27, 2012 @author: Peyman Kazemian ''' from headerspace.tf import TF from headerspace.hs import headerspace from utils.wildcard import wildcard_create_bit_repeat from net_plumber import NetPlumber from time import time from config_parser.cisco_router_parser import cisco_router from examples.example_u...
oader = net_loader(settings) (map,inv_map) = loader.load_port_map() #topology f = TF(1) f.load_object_from_file("%s/topology.tf"%settings["input_path"]) #net plumber instance N = NetPlumber(f.length) #adding links for rule in f.rules: input_ports =
rule["in_ports"] output_ports = rule["out_ports"] for input_port in input_ports: for output_port in output_ports: N.add_link(input_port, output_port) # add links for intermediate port f = open("%s/port_map.txt"%settings["input_path"],'r') for line in f: if (not line.startswith("$")) and line != ""...
blitzmann/Pyfa
gui/builtinViews/implantEditor.py
Python
gpl-3.0
9,701
0.002062
# noinspection PyPackageRequirements import wx # noinspection PyPackageRequirements from wx.lib.buttons import GenBitmapButton import gui.builtinMarketBrowser.pfSearchBox as SBox import gui.display as d from gui.bitmap_loader import BitmapLoader from gui.marketBrowser import SearchBox from service.market import Market...
ee.AppendItem(childId, "dummy") else: tree.AppendItem(childId, "itemdummy") # replace dummy with actual items if text == "itemdummy": currentMktGrp = sMkt.getMarketGroup(tree.GetItemData(parent)) items = sMkt.getItemsByMarketGroup(currentMktGr...
elf.addMarketViewImage(item.iconID) tree.AppendItem(parent, item.name, iconId, data=item) tree.SortChildren(parent) def itemSelected(self, event): if event.EventObject is self.btnAdd: # janky fix that sets EventObject so that we don't have similar code elsewhere. ...
aidanf/SimpleICM
tests/testutils.py
Python
gpl-3.0
674
0.005935
import unittest from types import Module
Type def IsTestCase(test): if type(test) == type and issubclass(test, unittest.TestCase): return True return False def AddTests(suite, test): if isinstance(test, ModuleType): for entry in test.__dict__.values(): if IsTestCase(entry): suite.addTests(unittest...
e() for test in tests: AddTests(suite, test) return suite def RunTests(suite, **keywargs): return unittest.TextTestRunner(**keywargs).run(suite)
tomchristie/django-rest-framework
tests/test_relations_pk.py
Python
bsd-2-clause
24,852
0.000322
from django.test import TestCase from rest_framework import serializers from tests.models import ( ForeignKeySource, ForeignKeySourceWithLimitedChoices, ForeignKeySourceWithQLimitedChoices, ForeignKeyTarget, ManyToManySource, ManyToManyTarget, NullableForeignKeySource, NullableOneToOneSource, NullableU...
ssert seria
lizer.data == data # Ensure target 1 is updated, and everything else is as expected queryset = ManyToManyTarget.objects.all() serializer = ManyToManyTargetSerializer(queryset, many=True) expected = [ {'id': 1, 'name': 'target-1', 'sources': [1]}, {'id': 2, 'name'...
ucarion/git-code-debt
git_code_debt/generate_config.py
Python
mit
1,667
0
from __future__ import absolute_import from __future__ import unicode_literals import collections import jsonschema DEFAULT_GENERATE_CONFIG_FILENAME = 'generate_config.yaml' GENERATE_OPTIONS_SCHEMA = { 'type': 'object', 'required': ['repo', 'database'], 'properties': { '
skip_default_metrics': {'type': 'boolean'}, 'tempdir_location': {'type': ['string', 'null']}, 'metric_package_names': {'type': 'array', 'items': {'type': 'string'}}, 'repo': {'type': 'string'}, 'database': {'type': 'string'}, }, } class GenerateOptions(collections.namedtuple( ...
ault_metrics', 'tempdir_location', 'metric_package_names', 'repo', 'database', ], )): @classmethod def from_yaml(cls, yaml_dict): jsonschema.validate(yaml_dict, GENERATE_OPTIONS_SCHEMA) return cls( skip_default_metrics=yaml_dict...
jwhitlock/drf-cached-instances
sample_poll_app/urls.py
Python
mpl-2.0
652
0
"""URL routes for the sample app.""" from django.conf.urls import include, url from django.views.generic import TemplateView from rest_framework.routers import DefaultRouter from .viewsets import ChoiceViewSet, QuestionViewSet, UserViewSet router = DefaultRouter() router.register(r'users', UserViewSet) router.regist...
ll_app/home.html'), name='home'), url(r'^api-auth/', include( 'rest_framework.urls', namespace='rest_framework')), url(
r'^api/', include(router.urls)) ]
Maselkov/GW2Bot
guildwars2/notifiers.py
Python
mit
37,063
0.000135
import asyncio import datetime import unicodedata import xml.etree.ElementTree as et import discord from bs4 import BeautifulS
oup from discord.ext import tasks from discord_slash import cog_ext from discord_slash.model import SlashCommandOptionType from discord_slash.utils.manage_components import (create_actionrow,
create_select, create_select_option, wait_for_component) from .daily import DAILY_CATEGORIES from .exceptions import APIError class NotiifiersMixin: @cog_ext.cog_subcommand( base="notifier"...
Reactive-Extensions/RxPy
rx/subjects/behaviorsubject.py
Python
apache-2.0
2,617
0.006878
from rx.observable import Observable from rx.internal import DisposedException from rx.disposables import Disposable from rx.abstractobserver import AbstractObserver from .anonymoussubject import AnonymousSubject from .innersubscription import InnerSubscription class BehaviorSubject(Observable, AbstractObserv...
k_disposed(self): if self.is_disposed: raise DisposedException() def __subscribe(self, observer): self.check_disposed() if not self.is_stopped: self.observers.append(observer) observer.on_next(self.value) retu
rn InnerSubscription(self, observer) ex = self.exception if ex: observer.on_error(ex) else: observer.on_completed() return Disposable.empty() def on_completed(self): self.check_disposed() if not self.is_stoppe...
plxaye/chromium
src/native_client_sdk/src/site_scons/site_tools/target_platform_mac.py
Python
apache-2.0
7,631
0.007732
#!/usr/bin/python2.4 # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of...
for libraries which are published # in Contents/MacOS next to their executables. DYLIB_INSTALL_NAME_FLAGS=[ '-install_name', '@loader_path/${TARGET.file}' ], ) env.Append( # Mac apps and dylibs have a more strict relationship about where they # expect to find each...
o any dylibs it links against. Override # this so that it will store the relative path from $LIB_DIR instead. # This is similar to RPATH on Linux. LINKFLAGS = [ '-Xlinker', '-executable_path', '-Xlinker', '$LIB_DIR', ], # Similarly, tell the library where it expects to...
VictorXianwu/Python-Program
net/cpNbnet.py
Python
mit
9,406
0.000358
#!/usr/bin/env python # coding:utf-8 import select import socket from nbNetUtils import DEBUG, dbgPrint __all__ = ["nbNet"] class STATE: def __init__(self): self.state = "accept" # 定义状态 self.have_read = 0 # 记录读了的字节 self.need_read = 10 # 头文件需要读取10个字节 self.have_write = 0 # 记录读了...
dbgPrint('\n - current state of fd: %d' % self.sock_obj.fileno()) dbgPrint(" - - state: %s" % self.state) dbgPrint(" - - have_read: %s" % self.have_read) dbgPrint(" - - need_read: %s" % self.need_read) dbgPrint(" - - have_write: %s" % self.have_write) ...
ite: %s" % self.need_write) dbgPrint(" - - buff_read: %s" % self.buff_read) dbgPrint(" - - buff_write: %s" % self.buff_write) dbgPrint(" - - sock_obj: %s" % self.sock_obj) class nbNetBase: def setFd(self, sock): dbgPrint("\n setFd start") tmp_state = STATE() # ...
dimagi/commcare-hq
corehq/form_processor/migrations/0070_auto_20180329_1016.py
Python
bsd-3-clause
391
0
# Generated by Django 1.11.11 on 2018-03-29 10:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('form_processor', '0069_add_metafields'), ]
operations = [ migrations.AlterField( model_name='xformoperationsql', name='date', fiel
d=models.DateTimeField(), ), ]
a25patel/whos-in-the-news
newsApp.py
Python
apache-2.0
2,605
0.016507
import requests import os from multiprocessing import Pool, Queue, Manager from flask import Flask, url_for, render_template, json app = Flask(__name__) API_KEY=YOUR_API_KEY def get_image(resource, entity, article, queue): try: i_get_url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbped...
_KEY results = requests.get(url=get_url) response = results.json() except Exception as e: print e entityList=[] l_pool = Pool(processes = 30) l_mgr = Manager() l_resultQueue = l_mgr.Queue() f
or article in response['result']['docs']: for entity in article['source']['enriched']['url']['enrichedTitle']['entities']: if entity['type']=="Person" and entity['disambiguated']: if entity['disambiguated']['dbpedia']: resource=entity['disambiguate...
johngian/marketpulse
marketpulse/base/mozillians.py
Python
mpl-2.0
4,751
0.001263
from urlparse import urljoin, urlparse import requests class BadStatusCode(Exception): pass class ResourceDoesNotExist(Exception): pass class MultipleResourcesReturned(Exception): pass class MozilliansClient(): def __init__(self, api_base_url, api_key): # Validate api_base_url ...
n response.""" response = requests.get(url, headers=self.headers, params=params) if not response.status_code == 200: raise BadStatusCode('{0} on: {1}'.format(response.status_code, url)) return response.json() def _get_resource_url(self, resource): """Build Mozillians.o
rg API resource url.""" return urljoin(self.base_url, resource) def get_users(self, params=None): """GET Mozillians.org users.""" url = self._get_resource_url('users') return self.get(url, params=params) def get_groups(self, params=None): """GET Mozillians.org groups"""...
Hariri-Institute-SAIL/materials
materials/db/__init__.py
Python
mit
221
0.00905
from .t
ables import Base, Component, Mixture, Ref, Measurement, Listing, Property from .utils import get_or_cre
ate __all__ = ['Base', 'Component', 'Mixture', 'Ref', 'Measurement', 'Listing', 'Property', 'get_or_create']
JoseluCross/MiniThunder
src/minithunder.py
Python
lgpl-3.0
3,335
0.004498
#!/usr/bin/python3 import os from sys import argv as _ from shutil import copyfile from jsmin import jsmin from rcssmin import cssmin VERSION = "0.1.1.0" verbose = False FORMATS = { "supported": ["js", "css", "htm", "html", "twig"] } def copyStructure(originalPath, finalPath): """Copy folder structure and s...
final+"/"+i) if verbose: print(origin + "/" + i + " has been copied") else: minimizeFile(or
igin+"/"+i,final+"/"+i,part[len(part)-1]) def minimizeFile(source, production, format): """Minify files""" input = open(source, "r") output = open(production, "w") output.write(globals()[format+"min"](input.read())) input.close() output.close() if verbose: print(source + " has been ...
cpcloud/luigi
test/_hive_test.py
Python
apache-2.0
362
0.002762
from u
nittest import TestCase from luigi import hive class TestHiveTask(TestCase): def test_error_cmd(self): self.assertRaises(hive.HiveCommandError, hive.run_hive_cmd, "this is a bogus command and should cause an error;") def test_ok_cmd(self): "Test that SHOW TABLES doesn't throw an error" ...
ve_cmd("SHOW TABLES;")
harlowja/zk_shell
zk_shell/cli.py
Python
apache-2.0
5,253
0.001904
""" entry point for CLI wrap
per """ from collections import namedtuple from functools import partial import argparse import logging import signal import sys from . import __version__ from .shell import Shell try: raw_input except NameError: raw_input = input class CLIParams( namedtuple("CLIParams"
, "connect_timeout run_once run_from_stdin sync_connect hosts readonly tunnel version")): """ This defines the running params for a CLI() object. If you'd like to do parameters processing from some other point you'll need to fill up an instance of this class and pass it to CLI()(), i....
Junnplus/firefly
firefly/views/user.py
Python
mit
868
0.001152
# coding=utf-8 from __future__ import absolute_import from flask import url_for, redirect from flask.views import MethodView from flask.blueprints import Blueprint from flask.ext.login import login_required, current_user from firefly.libs.template import render_template from firefly.forms.user import ProfileForm bp...
ass UserSettingsView(MethodView): decorators = [login_required] def get(self): return render_template('user/settings.html', user=current_user) def post(self): form = ProfileForm() form.save() return redirect(url_for('user.settings')) bp.add_url_rule('/<id>/', view_func=Use...
_view('settings'))
Pragmatismo/Pigrow
scripts/triggers/write_log.py
Python
gpl-3.0
1,392
0
#!/usr/bin/python3 import datetime import sys import os homedir = os.environ['HOME'] log_path = homedir + "/Pigrow/logs/trigger_log.txt" script = "write_log.py" message = "" for argu in sys.argv[1:]: argu_l = str(argu).lower() if argu_l == 'help' or argu_l == '-h' or argu_l == '--help': print(" Script...
elif thearg == 'script': script = thevalue elif thearg == 'message': message = thevalue line = script + "@" + str(datetime.datetime.now()) + "@" + message + '\n'
with open(log_path, "a") as f: f.write(line) print("Log writen:" + line) print("to " + log_path)
RealTimeWeb/wikisite
MoinMoin/util/pysupport.py
Python
apache-2.0
3,165
0.001896
# -*- coding: iso-8859-1 -*- """ MoinMoin - Supporting function for Python magic @copyright: 2002 Juergen Hermann <jh@web.de> @license: GNU GPL, see COPYING for details. """ ############################################################################# ### Module import / Plugins ##########################...
**kw): lock.acquire() try: return function(*args, **kw)
finally: lock.release() return decorated
sadanandb/pmt
src/pyasm/prod/biz/prod_setting.py
Python
epl-1.0
5,082
0.005903
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permi...
y_key(key, search_type) if value: seq = value.split("|") for item in seq: try: key, value = item.split(':') dict[key] = value except Exception, e: raise TacticException('ProdSettings should be formated like &lt;key1&gt;:...
;key2&gt;:&lt;value2&gt;|...') return dict get_dict_by_key = classmethod(get_dict_by_key) def create(key, value, type, description='', search_type=''): '''create a ProdSetting''' if Project.get_project_name() in ['admin', 'sthpw']: return None ProdSetting.clea...
JulienMcJay/eclock
windows/Python27/Lib/site-packages/pygame/examples/macosx/macfont.py
Python
gpl-2.0
4,484
0.007583
""" EXPERIMENTAL CODE! Here we load a .TTF font file, and display it in a basic pygame window. It demonstrates several of the Font object attributes. Nothing exciting in here, but it makes a great example for basic window, event, and font management. """ import pygame import math from pygame.locals import * from pyg...
a = Numeric.reshape(Numeric.fromstring(rep.bitmapData(), typecode=Numeric.Int32),
(size[1], size[0])) blit_array(s, Numeric.swapaxes(a,0,1)) return s.convert_alpha() if __name__=='__main__': pygame.init() screen = pygame.display.set_mode((600, 600)) s = SysFont('Gill Sans', 36) s.set_italic(1) s.set_underline(1) done = False surf = s.render('OS X...
marmstr93ng/TimeManagementSystem
tms/scraper.py
Python
mit
1,986
0.004532
import logging import os import re from selenium import webdriver def scraper(): # tms_url = "http://intranet.andor.com/tms/" tms_url = '{}/test/tms_pages/TMSClockingsRecordTwoDays.html'.format(os.getcwd()) with webdriver.Chrome(executable_path='{}/tms/chromedriver.exe'.format(os.getcwd())) as browser: ...
l) user_id, user_name = re.match("TMS Clockings for ([0-9]+): (.*)", browser.find_element_by_tag_name("h1").text).groups() logging.info("Welcome {} ({})".format(user_name, user_id)) elem = browser.find_elements_by_class_name("past") #for i in range(0, len(elem)): #
print("{}: {}".format(i, elem[i].text)) for i in range(0, int(len(elem)/5)): day_str, date_str = re.match("([A-Za-z]+)\n([0-9]{2}/[0-9]{2}/[0-9]{2})", elem[0].text).groups() logging.debug("{}: {}".format(day_str, date_str)) logging.debug("{}".format(re.findall("([0-9]+:[0...
birdland/dlkit-doc
dlkit/id/managers.py
Python
mit
2,317
0.003021
from ..osid import managers as osid_managers from ..osid import sessions as osid_sessions class IdProfile(osid_managers.OsidProfile): """The ``IdProfile`` describes the interoperability among id services.""" class IdManager(osid_managers.OsidManager, osid_sessions.OsidSession, IdProfile): """This manager...
``IdBrowserSession`` can be used for mapping one ``Id`` to another in addition to getting a list of the assigned identifiers. """ def get_id_batch_proxy_manager(self): """Gets an ``IdnProxyManager``. :return: an ``IdBatchProxyManager`` :rtype: ``osid.id.batch.IdBatchProxyMana...
ional -- This method must be implemented if ``supports_id_batch()`` is ``true``.* """ return # osid.id.batch.IdBatchProxyManager id_batch_proxy_manager = property(fget=get_id_batch_proxy_manager)
veger/ansible
lib/ansible/modules/cloud/google/gcp_compute_ssl_certificate.py
Python
gpl-3.0
11,771
0.002719
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
rams['state'] kind = 'compute#sslCertificate' fetch = fetch_resource(module, self_link(module), kind) changed = False if fetch: if state == 'present': if is_different(module, fetch): update(module, self_link(module), kind) fetch = fetch_resource(modu...
delete(module, self_link(module), kind) fetch = {} changed = True else: if state == 'present': fetch = create(module, collection(module), kind) changed = True else: fetch = {} fetch.update({'changed': changed}) module.exit_js...
bebosudo/sest
web/sest/tests_reactions.py
Python
mit
3,797
0
from django.test import TestCase, Client from django.conf import settings from django.core import mail from .models import * class Reactions(TestCase): def setUp(self): self.client = Client() self.u = User.objects.create(username="test") ne = NotificationEmail.objects.create(user=self.u,...
the channel. self.ch
.conditionandreaction_set.create(condition_op="lt", field_no=2, val=2, action="email" ) self.client.post('/{}/'.format(...
percyfal/bokeh
examples/app/spectrogram/main.py
Python
bsd-3-clause
4,299
0.002094
from os.path import dirname, join from math import ceil import numpy as np from bokeh.io import curdoc from bokeh.layouts import row, column, widgetbox from bokeh.models import ColumnDataSource, Slider, Div from bokeh.plotting import figure import audio from audio import MAX_FREQ, TIMESLICE, NUM_BINS from waterfall ...
nes_like(eq_range)*eq_angle*(i+0.05) for i in range(NUM_BINS)]), end=np.hstack([np.ones_like(eq_range)*eq_angle*(i+0.95) for i in range(NUM_BINS)]), alpha=np.tile(np.zeros_like(eq_range), NUM_BINS), ) eq_source = ColumnDataSou
rce(data=eq_data) eq = figure(plot_width=400, plot_height=400, x_axis_type=None, y_axis_type=None, x_range=[-20, 20], y_range=[-20, 20], **PLOTARGS) eq.background_fill_color = "#eaeaea" eq.annular_wedge(x=0, y=0, fill_color="#024768", fill_alpha="alpha", line_color=None, inner_r...
guilhermebr/ppm
setup.py
Python
mit
489
0.00409
#!/usr/bin/env python from setuptools import setup requirements = [ "docopt>=0.6.1", "virtualenv", ] setup(name='ppm', version='1.0', description='Python Package Manager', author='Guilherme Rezende', author_email='guilhermebr@gmail.com', url='http://github.com/guilhermebr/pp...
s": [
"ppm=ppm:main", ], }, )
neysofu/qetesh
src/harvest/settings.py
Python
mit
404
0
import os BOT
_NAME = 'harvest' SPIDER_MODULES = ['harvest.spiders'] NEWSPIDER_MODULE = 'harvest.spiders' DOWNLOAD_DELAY = 3 CONCURRENT_REQUESTS = 4 COOKIES_ENABLED = False _src = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) _target = os.path.join(os.path.dirname(_src), 'target') JOBDIR = os.path.join(_target, 'res...
MAT = 'csv'
sigurdsa/angelika-api
measurement/migrations/0007_measurement_unit.py
Python
mit
580
0.001724
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migrati
on): dependencies = [ ('measurement', '0006_auto_20141028_1228'), ] operations = [ migrations.AddField( model_name='measurement', name='unit', field=models.CharField(default=b'', max_length=1, choices=[(b'B', b'BPM'), (b'E', b'%'), (b'S', b'Steps'), (b'M...
, (b'', b'')]), preserve_default=True, ), ]
saintdragon2/python-3-lecture-2015
civil_mid_mid/pymunk-4.0.0/pymunk/pyglet_util.py
Python
mit
8,362
0.013394
# ---------------------------------------------------------------------------- # pymunk # Copyright (c) 2007-2012 Victor Blomqvist # # 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 re...
room for optimizations still). """ __version__ = "$Id$" __docformat__ = "reStructuredText" __all__ = ["draw"] import math import pyglet import pymunk from pymunk.vec2d import Vec2d def draw(*objs, **kwargs): """Draw one or many pymunk objects. It is perfectly fine to pass in a whole Space object. ...
ymunk.Circle * pymunk.Poly If a Space is passed in all shapes in that space will be drawn. Unrecognized objects will be ignored (for example if you pass in a constraint). Typical usage:: >>> pymunk.pyglet_util.draw(my_space) You can control the color of a Shape by s...
chriselion/discreteopt
coloring/dsatur.py
Python
mit
1,761
0.006246
from . import Graph # Start with the node that has the maximum degree. # Color the current node with the lowest available color. # Select the next node by selecting the node with the maximum degree of saturation. This means that you have to select # the node that has the most number of unique neighbo
ring colors. In case of a tie, use the node with the largest # degree. # Goto step 2. until all nodes are colored. def get_node_ma
x_degree(g): max_deg = -1 max_node = -1 for i in xrange(0, g.get_num_nodes()): deg = len(g.nodes[i].edges) if deg > max_deg: max_deg = deg max_node = i return max_node def get_node_max_satur(g, colors): max_node = -1 max_satur = -1 max_deg = -1 fo...
e-dub/DesOptPy
examples/TestProblemsUnconstrained/Eggholder.py
Python
gpl-3.0
695
0
# -*- coding: utf-8 -*- """ Eggholder test function for design optimization xOp
t = [] fOpt = 0.0 """ from DesOptPy import OptimizationProblem import numpy as np class Eggh
older: z = [1, 1] def SysEq(self): x = self.z[0] y = self.z[1] self.f = -(y + 47.0) * np.sin( np.sqrt(abs(y + x / 2.0 + 47.0)) ) - x * np.sin(np.sqrt(abs(x - (y + 47.0)))) OptEggholder = OptimizationProblem(Eggholder) OptEggholder.x = 'z' OptEggholder.x0 = [0] * 2 ...
galak/zephyr
scripts/gen_syscalls.py
Python
apache-2.0
17,833
0.002299
#!/usr/bin/env python3 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 """ Script to generate system call invocation macros This script parses the system call metadata JSON file emitted by parse_syscalls.py to create several files: - A file containing weak aliases of any potentially ...
files. Each header corresponds to a header that was identified as containing system call declarations. These generated headers contain the inline invocation functions for each system call in that header. """ import sys import re import argparse import os import json # Some kernel headers cannot include automat...
ry specific tracing hooks for all relevant things # written by hand so are excluded. notracing = ["kernel.h", "errno_private.h"] types64 = ["int64_t", "uint64_t"] # The kernel linkage is complicated. These functions from # userspace_handlers.c are present in the kernel .a library after # userspace.c, which contains ...
hypernicon/pyec
pyec/distribution/pso.py
Python
mit
4,812
0.017456
""" Copyright (C) 2012 Alan J Lockett 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,...
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import inspect import numpy...
story(LocalBestHistory): """A :class:`History` for Particle Swarm Optimization. Rembers the local best and the velocities. """ def __init__(self, config): super(PSOHistory, self).__init__(config) self._positions = None self._velocities = None self.lowerv = None self.upperv ...
TudorRosca/enklave
server/backend/utils/ses_lib.py
Python
agpl-3.0
1,463
0.000684
__author__ = 'radu' from django.conf import settings from dj
ango.core.mail import EmailMultiAlternatives from django.template.load
er import render_to_string class SesLib(object): """ A wrapper around Django's EmailMultiAlternatives that renders txt and html templates. Example Usage: >>> email = Email(to='oz@example.com', subject='A great non-spammy email!') >>> ctx = {'username': 'Oz Katz'} >>> email.text('templates/...
siemens/django-dingos
dingos/core/datastructures.py
Python
gpl-2.0
25,709
0.00564
# Copyright (c) Siemens AG, 2013 # # This file is part of MANTIS. MANTIS is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either version 2 # of the License, or(at your option) any later version. # # This progr...
r elt in value: key_value.append(tuple2dict(elt, constructor=constructor)) else: key_value = value result[key] = key_value return result class ExtendedSortedDict(SortedDict): """ ExtendedSortedDict adds a few convenient methods to Django's SortedDict class. ...
er[:] # return obj def to_tuple(self): """ Turn an extended sorted dictionary of the form used by DINGO (i.e., a key is mapped to either another dictionary, a list or a value) into a tuple-representation. This is useful for providing a standard python object that ...
TuxSH/XDscriptTools
XDscriptLib/_Instruction.py
Python
bsd-3-clause
13,695
0.041043
# See LICENSE for license import struct import warnings from XDscriptLib import FunctionInfo class Instruction(object): """ Instruction -- represents a XD script instruction For the PAL version, the script interpreter is at 8023D83C ctx: ScriptCtx (attribute) label: string position: int, nextPosition OO...
struct.unpack(">i", packed)[0] self._nextPosition = self._position + 2 elif self._subOpcode == 2: # float self.ctx.sections["CODE"].instructions[self._position + 1] = struct.unpack(">f", packed)[0] self._nextPosition = self._position + 2 if self._subOpcode == 3: if self._param...
tive string offset encountered ({0} \ at instruction #{1})".format(self._parameter, hex(self.position))) elif self._subOpcode == 4: if self._parameter < 0: warnings.warn("negative vector ID encountered ({0} \ at instruction #{1})".format(self._parameter, hex(self.position))) elif self._s...
scionrep/scioncc
src/pyon/util/file_sys.py
Python
bsd-2-clause
10,353
0.003091
""" Utility for managing relative file system paths """ __author__ = "Luke Campbell, Michael Meisinger" import errno import StringIO import tempfile import shutil import os import re import random import string from pyon.core.bootstrap import CFG as bootcfg, get_sys_name from pyon.util.log import log from pyon.util....
f path.startswith('/'): # Like it should path = path[1:] # Strip the beginning / # Determine root tree = path.split('/') if tree[0].upper() not in FS: return None root = FileSystem.FS_DIRECTORY[tree.pop(0).upper()] fullpath = '/'.join([root] + tree) ...
values(): if path.startswith(root): return True return False @staticmethod def _sandbox(path): """ If the path is in a bad place return false. """ # List of bad places black_list = [ # Standard Unix '/', ...
dpinney/omf
omf/scratch/MPUPV/solarSwitch.py
Python
gpl-2.0
709
0.021157
import omf.cosim glw = omf.cosim.GridLabWorld('6267', 'localhost', 'GC-solarAdd.glm', '2000-01-01 0:00:00') glw.start() print (glw.readClock()) # Changing solar gen stat
us. print (glw.read('test_solar', 'generator_status')) glw.write('test_solar','generator_status', 'OFFLINE') print ('Switched off solar') print (glw.read('test_solar', 'generator_status')) # Changing reactive power output. print (glw.read('test_solar_inverter', 'Q_Out')) glw.write('test
_solar_inverter','Q_Out', '1000') print ('Change Q_Out') print (glw.read('test_solar_inverter', 'Q_Out')) #glw.waitUntil('2000-01-01 0:30:00') #print ('Stepped ahead 12 hours') print (glw.readClock()) glw.resume() print (glw.readClock()) glw.shutdown()
mezz64/home-assistant
homeassistant/components/lutron_caseta/__init__.py
Python
apache-2.0
10,684
0.000468
"""Component for interacting with a Lutron Caseta system.""" from __future__ import annotations import asyncio import contextlib import logging import ssl import async_timeout from pylutron_caseta import BUTTON_STATUS_PRESSED from pylutron_caseta.smartbridge import Smartbridge import voluptuous as vol from homeassis...
_by_id.values(): if "serial" not in device or device["serial"] in seen: continue seen.add(device["ser
ial"]) dr_device = device_registry.async_get_or_create( name=device["name"], suggested_area=device["name"].split("_")[0], manufacturer=MANUFACTURER, config_entry_id=config_entry_id, identifiers={(DOMAIN, device["serial"])}, model=f"{device...
monkut/deso
deso/deso/functions.py
Python
mit
3,384
0.006797
from math import sqrt, log10 class WelfordRunningVariance(object): """ Python implentation of Welford's running variance algorithm http://www.johndcook.com/standard_deviation.html """ def __init__(self): self._count = 0 self._mean = None self._last_mean = None self._...
entation of Welford's running variance algorithm (for dB calc) http://www.johndcook.com/standard_deviation.html ""
" def __init__(self): self._count = 0 self._mean = None self._last_mean = None self._s = None self._last_s = None def send(self, v): value = 10**(v/10.0) self._count += 1 if self._count == 1: self._mean = value self._la...
vecnet/om
website/tests/test_middleware.py
Python
mpl-2.0
1,263
0.000792
# -*- coding: utf-8 -*- # # This file is part of the VecNet OpenMalaria Portal. # For copyright and licensing information about this package, see the # NOTICE.txt and LICENSE.txt files in its top-level directory; they are # available at https://github.com/vecnet/om # # This Source Code Form is subject to the terms of t...
PL), version 2.0. If a copy of the MPL was not distributed # with this file, You can obtain one at http://mozilla.org/MPL/2.0/. from d
jango.http import HttpResponseRedirect from django.test.testcases import TestCase from website.middleware import RedirectionMiddleware, HttpRedirectException class RedirectionMiddlewareTest(TestCase): def setUp(self): # Could use RequestFactory if real HttpRequest object is necessary self.request...
pvital/patchew
tests/test_message.py
Python
mit
1,658
0
#!/usr/bin/env python3 # # Copyright 2016
Red Hat, Inc. # # Authors: # Fam Zheng <famz@redhat.com> # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. import time import datetime from .patchewtest import PatchewTestCase, main class ProjectTest(PatchewTestCase): def setUp(self): ...
i.models import Message message = Message() message.date = datetime.datetime.utcnow() age = message.get_age() self.assertEqual(age, "0 second") def test_now(self): from api.models import Message message = Message() dt = datetime.datetime.fromtimestamp(time....
MooseDojo/apt2
modules/action/exploit_responder.py
Python
mit
3,558
0.00534
import datetime import os from core.actionModule import actionModule from core.utils import Utils from core.keystore import KeyStore as kb class exploit_responder(actionModule): def __init__(self, config, display, lock): super(exploit_responder, self).__init__(config, display, lock) self.title = "...
result = Utils.execWait(command, temp_file1, timeout=int(self.config["responder_timeout"])) responder_path, temp1 = os.path.split(self.config["responder"]) responder_db = responder_path + "/Responder.
db" #STDOUT unreliable, grabbed hashes directly from the DB instead command = self.config["sqlite3"] + " " + responder_db + " \"select * from responder where timestamp > '" + start_time + "'\"" result = Utils.execWait(command, temp_file2, timeout=10) times_run += 1 #Have to accou...
xifle/home-assistant
tests/components/sensor/test_mqtt.py
Python
mit
2,148
0
"""The tests for the MQTT sensor platform.""" import unittest from homeassistant.bootstrap import setup_component import homeassistant.components.sensor as sensor from tests.common import m
ock_mqtt_component, fire_mqtt_message from tests.common import get_test_home_assistant class TestSensorMQTT(unittest.TestCase): """Test the MQTT sensor.""" def setUp(self): # pylint: disable=invalid-name """Setup things to be run when tests are started."""
self.hass = get_test_home_assistant() mock_mqtt_component(self.hass) def tearDown(self): # pylint: disable=invalid-name """Stop down everything that was started.""" self.hass.stop() def test_setting_sensor_value_via_mqtt_message(self): """Test the setting of the value via M...
rudikovrf/django_blog
comment/views.py
Python
mit
1,184
0.000845
from django.shortcuts import render from .models import Comments from article.models import Articles from .forms import CommentsForm def add_comment(request, article_id, parent_comment_id=None): form = CommentsForm() dictionary = {'article': Articles.objects.get(id=article_id)} if parent_comment_id is no...
if parent_comment_id is not None: dictionary['parent_comment'] = Comments.objects.get(id=parent_comment_id) dictionary['form'] = form return render( request,
template, dictionary )
dsajkl/reqiop
lms/djangoapps/courseware/tests/test_course_info.py
Python
agpl-3.0
2,849
0.001404
""" Test the course_info xblock """ import mock from django.test.utils import override_settings from django.core.urlresolvers import reverse from .helpers import LoginEnrollmentTestCase from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from courseware.tests.modulestore_config import TEST_DATA_MIXE...
self.assertIn("You are not currently enrolled in this course", resp.content) def test_logged_in_enrolled(self): self.enroll(self.course) url = reverse('info', args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertNotIn("You are not currently e
nrolled in this course", resp.content) def test_anonymous_user(self): url = reverse('info', args=[self.course.id.to_deprecated_string()]) resp = self.client.get(url) self.assertEqual(resp.status_code, 200) self.assertNotIn("OOGIE BLOOGIE", resp.content) @override_settings(MODULEST...
hfp/tensorflow-xsmm
tensorflow/python/grappler/layout_optimizer_test.py
Python
apache-2.0
58,406
0.014947
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
_def()) return meta_graph def _get_cluster(): named_device = device_properties_pb2.NamedDevice() named_device.name = '/GPU:0' named_device.properties.type = 'GPU' named_device.properties.num_cores = 24 named_device.properties.frequency = 1000 named_device.properties.environment['architecture'] = '4' c...
return cluster def _is_transpose(node): return node.endswith('TransposeNHWCToNCHW-LayoutOptimizer') or node.endswith( 'TransposeNCHWToNHWC-LayoutOptimizer') def _is_permute(node): return node.endswith('VecPermuteNHWCToNCHW-LayoutOptimizer') or node.endswith( 'VecPermuteNCHWToNHWC-LayoutOptimizer'...
Arahabica/NNTrain
train/basic/testNumpyTrain.py
Python
mit
1,817
0.004793
# -*- coding: utf-8 -*- import unittest import numpy as np class TestNumpyTrain(unittest.TestCase): """ Numpy の練習 """ @classmethod def setUpClass(cls): pass def test_basic_calc_array(self): """ 配列の四則演算 """ x = np.array([1.
0, 2.0, 3.0]) y = np.array([2.0, 4.0, 6.0]) # 足し算 np.testing.assert_equal(np.array([3.0, 6.0, 9.0]), x + y) # 引き算 np.testing.assert_equal(np.array([-1.0, -2.0, -3.0]), x - y) # 掛け算 np.testing.assert_equal(np.array([2.0, 8.0, 18.0]), x * y) # 割り算 np
.testing.assert_equal(np.array([0.5, 0.5, 0.5]), x / y) def test_basic_calc_matrix(self): """ 行列の四則演算 """ x = np.array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]]) y = np.array([[1.0, 3.0, 5.0], [1.0, 2.0, 7.0]]) # 足し算 np.testing.assert_equal(np.array([[2.0, 5.0, 8.0], [3.0, 6.0, 13....
hirodotp/mdata
inputs/csvfile.py
Python
gpl-2.0
678
0.029499
import os import pandas as pd from input import Input class Main(Input): name = "CSV File Input" def build_file_list(self): files = {} for s in self.symbols: normalized_file = "%s.%s" % (s, self.extension) if os.path.isfile(os.path.join(self.symbol_dir, normalized_file)): files[s] = os.path.join(self....
self.symbol_dir = self.base_config['symbol_dir'] files = self.build_file_list() for symbol in files.keys(): df = pd.read_csv(files[symbol]) df = df.reset_index() print df.tail self.d
ata[symbol] = df return self.data
kencochrane/scorinator
scorinator/score/tests/tags.py
Python
apache-2.0
638
0
from django.test import TestCase from score.templatetags.score_tags import display_score class TestDisplayScore(TestCase): def test_string(self): assert "?" in display_score("") def test_none(self): assert "?" in display_score(None) def test_danger(self): assert "danger" in disp...
assert "prim
ary" in display_score("65") def test_info(self): assert "info" in display_score("79") def test_success(self): assert "success" in display_score("81")
cseed/hail
hail/python/hail/expr/builders.py
Python
mit
9,202
0.001087
import hail as hl from hail.typecheck import typecheck_method from hail.expr.expressions import unify_types, unify_types_limited, expr_any, \ expr_bool, ExpressionException, construct_expr, expr_str from hail import ir class ConditionalBuilder(object): def __init__(self): self._ret_type = None ...
same type. Parameters ---------- missing_false: :obj:`.bool` Treat missing predicates as ``False``. See Also -------- :func:`.case`, :func:`.cond`, :func:`.switch` """ def __init__(self, missing_false=False): super(CaseBuilder, self).__init__() self._missing_...
functions import cond expr = default for conditional, then in self._cases[::-1]: expr = cond(conditional, then, expr, missing_false=self._missing_false) return expr @typecheck_method(condition=expr_bool, then=expr_any) def when(self, condition, then) -> 'CaseBuilder': ...
israeltobias/DownMedia
youtube-dl/setup.py
Python
gpl-3.0
4,022
0.001492
#!/usr/bin/env python # coding: utf-8 from __future__ import print_function import os.path import warnings import sys try: from setuptools import setup, Command setuptools_available = True except ImportError: from distutils.core import setup, Command setuptools_available = False from distutils.spawn ...
tderr) exit(1) py2exe_options = { 'bundle_files': 1, 'compressed': 1, 'optimize': 2, 'dist_dir': '.', 'dll_excludes': ['w9xpopen.exe', 'crypt32.dll'], } # Get the version from youtube_dl/version.py without importing the package exec(compile(open('youtube_dl/version.py').read(),
'youtube_dl/version.py', 'exec')) DESCRIPTION = 'YouTube video downloader' LONG_DESCRIPTION = 'Command-line program to download videos from YouTube.com and other video sites' py2exe_console = [{ 'script': './youtube_dl/__main__.py', 'dest_base': 'youtube-dl', 'version': __version__, 'description...
makinacorpus/django-ckeditor
ckeditor/utils.py
Python
bsd-3-clause
699
0
import mimetypes import os.path from django.core.files.storage import default_storage from django.template.defaultfilters import slugify def slugify_filename(filename): u""" Slugify filename """ name, ext = os.path.splitext(filename) return slugify(name) + ext def get_thumb_filename(file_name): """...
mb filename by adding _thumb to end of filename before . (if present) """ return '{0}_thumb{1}'.format(*os.path.splitext(file_name)) def get_image_form
at(extension): mimetypes.init() return mimetypes.types_map[extension] def get_media_url(path): """ Determine system file's media URL. """ return default_storage.url(path)
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/cloud/openstack/os_project_facts.py
Python
bsd-3-clause
5,044
0.001388
#!/usr/bin/python # Copyright (c) 2016 Hewlett-Packard Enterprise Corporation # # This module 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 ve...
tions: name: description: - Name or ID of the project required: true domain: description: - Name or ID of the domain containing the project if the cloud supports domains required: false default: None filters: description: - A dictionar
y of meta data to use for further filtering. Elements of this dictionary may be additional dictionaries. required: false default: None availability_zone: description: - Ignored. Present for backwards compatibility required: false ''' EXAMPLES = ''' # Gather facts about previous...
ucapdak/loewner
main/PythonTools/Interface.py
Python
mit
7,161
0.006144
from Constants import * from LoewnerRunFactory import LoewnerRunFactory from prompt_toolkit import PromptSession from os import popen from numpy import arange, linspace from InterfaceMode import * class CommandLineInterface: def __init__(self): # Create a dictionary of input-function pairs self.b...
return # Attempt to change the LoewenerRunFactory parameters if self.program_mode.change_parameters(user_input): continue # Get a list of driving functions (if any were given) if self.program_mode.change_driving_functions(user_input): ...
continue # Check if the start command was given if self.run_algorithm(user_input): # Validate the run parameters that were given and create a LoewnerRunFactory if not self.program_mode.validate_settings(): print("Could not create vali...
Palats/botcraft
botcraft_examples/__init__.py
Python
gpl-2.0
163
0
""
"Minecra
ft bots examples. Most module are just standalone bot executables, the rest is a couple of support libraries that do not belong to botcraft itself. """
verejnedigital/verejne.digital
obstaravania/data_model.py
Python
apache-2.0
4,625
0.002378
# -*- coding: utf-8 -*- import psycopg2 import sqlalchemy from sqlalchemy import Column, Float, Integer, String, Boolean, DateTime, and_ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker from sqlalche...
lename__ = 'last_notification_update' last_id = Column(Integer, primary_key=True) class NotificationStatus(e
num.Enum): GENERATED = 1 APPROVED = 2 DECLINED = 3 class Notification(Base): __tablename__ = 'notification' id = Column(Integer, primary_key=True) candidate_id = Column(Integer, ForeignKey("candidate.id")) candidate = relationship("Candidate", foreign_keys=[candidate_id]) status = Colu...
marado/pytalker
commands-en/go.py
Python
gpl-2.0
884
0.03733
# -*- coding: latin -*- MSG = "%s %s" NO_ARGS = "Go where?" GO_USER = "You went to room \"%s\"" NO_SUCH_ROOM = "No such room \"%s\"." HELP = """Usage: .go <room>\r Moves the user to room <room>.""" import os import src.me
ssages from config.config import ROOMS_DIR from src.userdata import ROOM_FIELD class Execute: def __init__(self,session,message): if not message: src.messages.Message(session).User(NO_ARGS) return #decode the room go_room=message.split()[0] found=0 for room in os.listdir(ROOMS_DIR): if go_room == r...
.SetField(session.username,ROOM_FIELD,go_room) else: src.messages.Message(session).User(NO_SUCH_ROOM % go_room) class Help: def __init__(self,session): src.messages.Message(session).User(HELP)
knuu/competitive-programming
yukicoder/yuki036.py
Python
mit
1,548
0.002584
# used in ProjectEuler No.12, yukicoder No.36 from copy import deepcopy from functools import reduce class Divisor: def __init__(self, n): """ make divisors list and prime factorization list of n""" number = n if number == 1: self.primeFactorization = {1: 1} else: ...
+= 1; number //= i if cnt > 0: self.primeFactorization[i] = cnt if number > 1: self.primeFactorization[number] = 1 def primeFactors(self): return deepcopy(self.primeFactorization)
def numDivisors(self): """ the number of divisors """ if self.primeFactorization.get(1, 0) == 1: return 1 numDiv = 1 for _, cnt in self.primeFactorization.items(): numDiv *= cnt+1 return numDiv def sumDivisors(self): return reduce(lambda x, y:...
jakesyl/fail2ban
fail2ban/server/datetemplate.py
Python
gpl-2.0
7,428
0.028406
# emacs: -*- mode: python; coding: utf-8; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban 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 Softw...
: """Check if regex for date matches on a log line. """ dateMatch = self._cRegex.search(line) return dateMatch @abstractmethod def getDate(self, line): """Abstra
ct method, which should return the date for a log line This should return the date for a log line, typically taking the date from the part of the line which matched the templates regex. This requires abstraction, therefore just raises exception. Parameters ---------- line : str Log line, of which the d...
cantora/pyc
p1tests/grader_tests/and0.py
Python
gpl-3.0
20
0
print
input() and 0
mmahut/openshift-ansible
roles/lib_openshift/library/oc_route.py
Python
apache-2.0
63,067
0.001062
#!/usr/bin/env python # pylint: disable=missing-docstring # flake8: noqa: T001 # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ ...
ice port or number of the container port the route will route traffic to required: false default: None aliases: [] author: - "Kenny Woodson <kwoodson@redhat.com>" extends_documentation_fragment: [] ''' EXAMPLES = ''' - name: Configure certificates for reencrypt route oc_route: name: myapproute na...
named_certificates/myapp_cacert dest_cacert_content: "{{ dest_cacert_content }}" service_name: myapp_php host: myapp.awesomeapp.openshift.com tls_termination: reencrypt run_once: true ''' # -*- -*- -*- End included fragment: doc/route -*- -*- -*- # -*- -*- -*- Begin included fragment: ../../lib_uti...
VirrageS/io-kawiarnie
caffe/reports/migrations/0002_auto_20160414_1749.py
Python
mit
681
0.001468
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-14 17:49 from __future__ import unicode_literals import django.db.models.deletion from django.db import
migrations, models class Migration(migrations.Migration): dependencies = [ ('reports', '0001_initial'), ] operations = [ migrations.RenameField( model_name='report', old_name='date', new_name='created_on', ), migrations.AlterField( ...
.Report'), ), ]
FuegoFro/KeepTalkingBot
src/modules/simple_wires_solution.py
Python
mit
2,191
0.002282
from collections import defaultdict from modules.simple_wires_common import WireColor def get_wire_index_to_cut(colors, sides_info): return _get_wire_position_to_cut(colors, sides_info) - 1 def _get_wire_position_to_cut(colors, sides_info): """ Note that this returns the 1-indexed "position" (rather than t...
.black] == 0: return 2 else: return 1 el
if len(colors) == 6: if color_counts[WireColor.yellow] == 0 and last_digit_odd: return 3 elif color_counts[WireColor.yellow] == 1 and color_counts[WireColor.white] > 1: return 4 elif color_counts[WireColor.red] == 0: return len(colors) else: ...
hujiajie/pa-chromium
build/android/device_status_check.py
Python
bsd-3-clause
8,815
0.010323
#!/usr/bin/env python # # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A class to keep track of devices across builds and report state.""" import logging import optparse import os import smtplib im...
vices not detected.' % len(missing_devs) buildbot_report.PrintSummaryText(devices_missing_msg) # TODO(navabi): Debug by printing both output from GetCmdOutput and # GetAttachedDevices to compare results. return ['Current online devices: %s' % adb_online_devs, '%s are no longer visible. Were...
oved?\n' % missing_devs, 'SHERIFF: See go/chrome_device_monitor', 'Cache file: %s\n\n' % last_devices_path, 'adb devices: %s' % GetCmdOutput(['adb', 'devices']), 'adb devices(GetAttachedDevices): %s' % android_commands.GetAttachedDevices()] else: new_dev...
gobins/python-redditcli
redditcli/main.py
Python
apache-2.0
893
0.003359
import logging import sys from cliff.app import App from cliff.commandmanager import CommandManager class RedditApiCli(App): log = logging.getLogger(__
name__) def __init__(self): super(RedditApiCl
i, self).__init__( description='Reddit API CLI', version='0.1', command_manager=CommandManager('redditcli.api'), ) def initialize_app(self, argv): self.log.debug('initialize_app') def prepare_to_run_command(self, cmd): self.log.debug('prepare_to_run_...
alexhayes/django-celery
djcelery/management/commands/celery.py
Python
bsd-3-clause
643
0.00311
from __future__ import absolute_import, unicode_literals from celery.bin import celery from djcelery.app import app from djcelery.management.base import CeleryCommand base = celery.Ce
leryCommand(app=app) class Command(CeleryCommand): """The celery command.""" help = 'celery commands, see celery help' requires_model_validation
= True options = (CeleryCommand.options + base.get_options() + base.preload_options) def run_from_argv(self, argv): argv = self.handle_default_options(argv) base.execute_from_commandline( ['{0[0]} {0[1]}'.format(argv)] + argv[2:])
holandes22/nodember-rain
deploy.py
Python
mit
674
0
import os import boto # Before running this script, set envars AWS_ACCESS_KEY_ID # and AWS_SECRET_ACCESS_KEY, Boto uses them automatically # ember build --environment="production" print b
oto.s3.regions() conn = boto.connect_s3() bucket = conn.get_bucket('nodember-rain') for root, fo
lder, files in os.walk('frontend/dist'): for filename in files: file_path = os.path.join(root, filename) print 'Uploading file: {}'.format(file_path) key = bucket.new_key(file_path[len('frontend/dist'):]) key.size = os.stat(file_path).st_size key.set_contents_from_filename(fi...
deanproxy/register
expenses/views.py
Python
bsd-3-clause
6,474
0.003398
import logging import json import datetime import math from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from expenses.forms import ExpenseForm, SignupForm from expenses.models import Expense, Balance from django.core import serializers from django.db import IntegrityError fro...
balance = Balance.objects.create(amount=0.0, user=request.user) ba
lance.amount += expense.amount balance.save() status = 201 else: errors = {'errors':form.errors} elif request.method == 'DELETE': expense = get_object_or_404(Expense, pk=id, user=request.user) try: # Make sure to update balance depending on the...
Zalewa/doomstats
presentation/management/commands/destroy_presentation.py
Python
bsd-2-clause
336
0.002976
#!/u
sr/bin/python #-*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps class Command(BaseCommand): def handle(self, *args, **options): app_m
odels = apps.get_app_config('presentation').get_models() for model in app_models: model.objects.all().delete()
benabraham/cz.pycon.org-2017
pyconcz_2017/speakers/urls.py
Python
mit
500
0.006
from django.conf.urls import url from django.views.generic import RedirectView from pyconcz_2017.speakers.views import speakers_list, schedule, talk_detail urlpatterns = [ url('^$', RedirectView.as_view(pattern_name='speakers_list'), {'type': 'talks'}), url('^(?P<type>(talks|workshops))/$', speakers_list, nam...
il/(?P<type>(talk|workshop))/(?P<talk_id>\d+)/$',
talk_detail, name='talk_detail'), url('^schedule/$', schedule, name="speakers_schedule"), ]
mydeco-dev-team/sworkflow
examples/graham_articles/parse_articles.py
Python
bsd-2-clause
397
0.010076
import re import sys import simplejson a
s json URL_PARSE = re.compile('paulgraham_2158_7512.+?<a href="([^\"]+?)".*?>([^<]+?)</a>') def main(): input, output = sys.argv[1:3] f = open(input) articles = f.read() f.close() larticles = URL_PARSE.findall(articles) f = open(output, 'w') f.write(json.dumps(larticles)) f.close() i
f __name__ == '__main__': main()
teoliphant/numpy-refactor
setupscons.py
Python
bsd-3-clause
5,138
0.008369
#!/usr/bin/env python """NumPy: array processing for numbers, strings, records, and objects. NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays of arbitrary records without sacrificing too much speed for small multi-dimensional arrays. NumPy is built ...
ot more robust than what was previously being used. __builtin__.__NUMPY_SETUP__ = True # DO NOT REMOVE numpy.distutils IMPORT ! This is necessary for numpy.distutils' # monkey patching to work. import numpy.distutils from distutils.errors import DistutilsError try: import numscons except ImportError, e: msg = ...
tutilsError('\n'.join(msg)) def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path, setup_name='setupscons.py') config.set_options(ignore_setup_xxx_py=True, ...
mfraezz/osf.io
api_tests/subjects/mixins.py
Python
apache-2.0
23,091
0.003075
# -*- coding: utf-8 -*- import pytest from api.base.settings.defaults import API_BASE from api.taxonomies.serializers import subjects_as_relationships_version from osf.models import Preprint, NodeLog from osf_tests.factories import ( AuthUserFactory, SubjectFactory, ) @pytest.mark.django_db class SubjectsFil...
pected == actual def test_subject_filter_using_text_v_2_2( self, app, user, subject_two, resource, resource_two, has_subject): resource_two.subje
cts.add(subject_two) expected = set([resource_two._id]) res = app.get( '{}{}&version=2.2'.format(has_subject, subject_two.text), auth=user.auth ) actual = set([obj['id'] for obj in res.json['data']]) assert expected == actual def test_subject_filter_u...
antoinecarme/pyaf
tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_MovingMedian_Seasonal_DayOfWeek_SVR.py
Python
bsd-3-clause
165
0.048485
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Difference'] , ['Moving
Median'] , ['Seasonal_DayOfWeek'] , ['SVR'] );
nschloe/meshio
tests/test_ply.py
Python
mit
1,964
0
import pathlib import numpy as np import pytest import meshio from . import helpers @pytest.mark.parametrize( "mesh", [ # helpers.empty_mesh, helpers.tri_mesh, helpers.quad_mesh, helpers.tri_quad_mesh, helpers.add_point_data(helpers.tri_mesh, 1, dtype=int), h...
cells", [ ("bun_zipper_res4.ply", 3.414583969116211e01, 948), ("tet.ply", 6, 4), ], ) def test_reference_file(filename, ref_sum, ref_num_cells): this_dir = pathlib.Path(__file__).resolve().parent filename = this_dir / "meshes" / "ply" / filename mesh = meshio.read(filename) tol ...
* abs(ref_sum) assert len(mesh.get_cells_type("triangle")) == ref_num_cells @pytest.mark.parametrize("binary", [False, True]) def test_no_cells(binary): import io vertices = np.random.random((30, 3)) mesh = meshio.Mesh(vertices, []) file = io.BytesIO() mesh.write(file, "ply", binary=binary) ...
rallured/PyXFocus
conicsolve.py
Python
mit
10,370
0.025169
import numpy as np from numpy import * from matplotlib.pyplot import * import pdb #Return radius of mirror at arbitrary z coordinate def primrad(z,r0,z0,psi=1.): alpha = .25*arctan(r0/z0) thetah = 2*(1+2*psi)/(1+psi) * alpha thetap = 2*psi/(1+psi) * alpha p = z0*tan(4*alpha)*tan(thetap) d = z0*tan(...
eters def wsPrimFunction(r0,z0,psi,x,y,z): a,p,d,e = woltparam(r0,z0) betas = 4*a ff = z0/np.cos(betas) g = ff / psi k = tan(betas/2)**2 pdb.set_trace() beta = arcsin(sqrt(x**2+y**2)/ff) ind = beta<betas beta[ind] = betas kterm= (1/k)
*tan(beta/2)**2 -1 pdb.set_trace() F = -z - ff*sin(betas/2)**2 + \ ff**2*sin(beta)**2/(4*ff*sin(betas/2)**2) + \ g*cos(beta/2)**4*kterm**(1-k) Fb = ff**2*sin(beta)*cos(beta)/(2*ff*sin(betas/2)**2) - \ 2*g*cos(beta/2)**3*sin(beta/2)*(kterm)**(1-k) + \ g*(1-k)*cos(beta/2)...