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 |
|---|---|---|---|---|---|---|---|---|
nickleefly/youtube-dl | youtube_dl/extractor/internetvideoarchive.py | Python | unlicense | 3,764 | 0.00186 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_parse_qs,
compat_urlparse,
)
from ..utils import (
determine_ext,
int_or_none,
xpath_text,
)
class InternetVideoArchiveIE(InfoExtractor):
_VALID_URL = r'https?://video\.internetvideoarchive... | m3u8_formats = self._extract_m3u8_formats(
file_url, video_id, 'mp4', 'm3u8_native', m3 | u8_id='hls', fatal=False)
if m3u8_formats:
formats.extend(m3u8_formats)
file_url = m3u8_formats[0]['url']
formats.extend(self._extract_f4m_formats(
file_url.replace('.m3u8', '.f4m'),
... |
prasannav7/ggrc-core | src/ggrc_risk_assessments/models/__init__.py | Python | apache-2.0 | 365 | 0 | # Copyright (C) | 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Maintained By: dan@reciprocitylabs.com
from ggrc.models.all_models import register_model
from .risk_as | sessment import RiskAssessment
register_model(RiskAssessment)
|
summer-liu/events_cache_scripts | report/report03.py | Python | mit | 14,920 | 0.003611 | # _*_ coding:utf-8 _*_
from __future__ import print_function
from dataFunctions import *
import time
from collections import OrderedDict
import pickle
s = time.time()
ONLINE_30 = datetime.datetime(2015, 12, 18, 16)
START_DATE = datetime.datetime(2016, 1, 3) - datetime.timedelta(hours=8)
END_DATE = START_DATE + date... | --------- 视频播放PV ----------\n', file=f)
def video_play_pv(start, end, platform, event):
return events.count({
"eventKey": event,
"platform2": platform,
"serverTime": {"$gte": start, "$lt": end}
})
eventKey = 'startVideo'
iosVideoPlay = video_play_pv(START_DATE, END_DATE, 'iOS', eventK... | DATE, 'iOS', 'startLearning')
androidVideoPlay = video_play_pv(START_DATE, END_DATE, 'android', eventKey)
pcVideoPlay = video_play_pv(START_DATE, END_DATE, 'PC', eventKey)
totalPlay = iosVideoPlay + androidVideoPlay + pcVideoPlay
print('PC本周视频播放数: ', pcVideoPlay, str(round(pcVideoPlay*100.0/totalPlay, 2))+'%', '\n', f... |
Azure/azure-sdk-for-python | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/_autoscale_settings_operations.py | Python | mit | 22,225 | 0.004949 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2015-04-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Cons... | = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'autoscaleSettingName': self._serialize.url("autoscale_setting_name", autoscale_setting_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.s... |
camradal/ansible | contrib/inventory/abiquo.py | Python | gpl-3.0 | 8,807 | 0.008175 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
External inventory script for Abiquo
====================================
Shamelessly copied from an existing inventory script.
This script generates an inventory that Ansible can understand by making API requests to Abiquo API
Requires some python libraries, ensure ... | rl, headers=headers, url_username=config.get('auth','apiuser').replace('\n', ''),
url_password=config.get('auth','apipass').replace('\n', ''))
return json.loads(result.read())
except:
return None
def save_cache(data, config):
''' saves item to cache '''
dpath = config.get('c... | pass # not really sure what to do here
def get_cache(cache_item, config):
''' returns cached item '''
dpath = config.get('cache','cache_dir')
inv = {}
try:
cache = open('/'.join([dpath,'inventory']), 'r')
inv = cache.read()
cache.close()
except IOError as e:
pa... |
KohlsTechnology/ansible | lib/ansible/modules/monitoring/sensu_handler.py | Python | gpl-3.0 | 9,200 | 0.002174 | #!/usr/bin/python
# (c) 2017, Red Hat Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | xecuted.
- The event data is passed to the process via STDIN.
- 'NOTE: the command attribute is only required for Pipe handlers (i.e. handlers configured with "type": "pipe").'
socket:
description:
- The socket definition scope, used to configure the TCP/UDP handler socket.
- 'NOTE: the so... | tion:
- The pipe definition scope, used to configure the Sensu transport pipe.
- 'NOTE: the pipe attribute is only required for Transport handlers (i.e. handlers configured with "type": "transport").'
handlers:
description:
- An array of Sensu event handlers (names) to use for events using the h... |
johnparker007/mame | src/devices/cpu/m6809/m6809make.py | Python | gpl-2.0 | 3,562 | 0.029478 | #!/usr/bin/python
# license:BSD-3-Clause
# copyright-holders:Olivier Galibert
import io
import re
import sys
# Initial state
state = 1
text = ""
dispatch_to_states = { "MAIN" : 0 }
states_to_dispatch = { 0 : "MAIN" }
def load_file(fname, lines):
path = fname.rpartition('/')[0]
if path != "":
path += '/'
try:
... | io.open(fname, "r")
except Exception:
err = sys.exc_info()[1]
sys.stderr.write | ("Cannot read opcodes file %s [%s]\n" % (fname, err))
sys.exit(1)
rawlines = re.split('(\n|; *\n?)', f.read())
count = 0
while count < len(rawlines)-1:
line = rawlines[count+0] + rawlines[count+1]
if line.startswith("#include"):
load_file(path + line.split('"')[1], lines)
else:
lines.append(line)
c... |
jacobian-archive/python-storymarket | storymarket/orgs.py | Python | bsd-3-clause | 658 | 0.006079 | """
Organizations.
"""
from __future__ import absolute_import
from . import base
from . import links
class Org(links.LinkedResource):
def __repr__(self):
return "<Org: %s>" % self.name
class OrgMa | nager(base.Manager):
resource_class = Org
def all(sel | f):
"""
Get a list of all orgs.
:rtype: list of org instances.
"""
return self._list('/orgs/')
def get(self, resource):
"""
Get an individual org.
:param resource: The org instance or its ID.
:rtype: A list of org instances.
"""
... |
BorisJeremic/Real-ESSI-Examples | education_examples/_Chapter_Modeling_and_Simulation_Examples_Dynamic_Examples/Friction_SDOF_Oscillator_SoftContact_Nonlinear_Hardening_Softening_Shear_Model/plot.py | Python | cc0-1.0 | 812 | 0.011084 | #!/usr/bin/python
import h5py
import matplotlib.pylab as plt
import sys
# Go over each feioutput and plot each one.
thefile = "Frictional_SDOF_freeVibration.h5.feioutput";
finput = h5py.File(thefile)
# Read the time and displacement
times = finput["time"][:]
disp = finput["/Model/Nodes/Generalized_Displacements"][2... | hich='major', color='k', linestyle='-')
plt.grid(b=True, which='minor', color='r', linestyle='-', alpha=0.2)
plt.minorticks_on()
p | lt.xlabel("Time [s] ")
plt.ylabel("Displacement [m] ")
plt.savefig(outfigname, bbox_inches='tight')
plt.show()
|
Elico-Corp/openerp-7.0 | stock_landed_costs/__init__.py | Python | agpl-3.0 | 303 | 0 | # -*- coding: utf-8 -*-
# © 2014 Elico Corp (https://www. | elico-corp.com)
# Lic | ence AGPL-3.0 or later(http://www.gnu.org/licenses/agpl.html)
from . import product
from . import stock
from . import wizard
from . import product_price_history
from . import account_anglo_saxon_pos
from . import purchase
|
jtorrente/openstreetmap | jtorrente/openstreetmap/problemset1/ex3_nytimes.py | Python | lgpl-3.0 | 4,470 | 0.004698 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This exercise shows some important concepts that you should be aware about:
- using codecs module to write unicode files
- using authentication with web APIs
- using offset when accessing web APIs
To run this code locally you have to register at the NYTimes developer s... | API_KEY = { "popular": "8f59290cf487b2c40b3bbac5de38049c:17:72343821",
"article": "c3b8c7101c497404c903a3e1691ea96d:2:72343821"}
def get_from_file(kind, period):
filename = "popular-{0}-{1}.json".format(kind, period)
with open(filename, "r") as f:
return json.loads(f.read())
def article_... | iod)
titles = []
urls =[]
for article in data:
title_dic = {}
title_dic[article['section']] = article['title']
titles.append(title_dic)
media_list = article['media']
for media_metadata_container in media_list:
media_metadata_list = media_metadata_containe... |
OptimoJoe/Optizelle | src/examples/rosenbrock_advanced_api/rosenbrock_advanced_api.py | Python | bsd-2-clause | 6,736 | 0.019299 | # In this example, we duplicate the Rosenbrock example while demonstrating
# some of the more advanced API features such as custom vector spaces,
# messaging objects, and restarts.
import Optizelle
import sys
import copy
import array
import math
import functools
#---VectorSpace0---
# Defines the vector space used for... | utines
MySerialization()
# Read in the name for the input file
if not(len(sys.argv)==2 or len(sys.argv)==3):
sys.exit("python rosenbrock_advanced_api.py <parame | ters>\n" +
"python rosenbrock_advanced_api.py <parameters> <restart>")
pname = sys.argv[1]
rname = sys.argv[2] if len(sys.argv)==3 else ""
# Generate an initial guess for Rosenbrock
x = array.array('d',[-1.2,1.0])
# Create an unconstrained state based on this vector
state=Optizelle.Unconstrained.State.t(... |
creyesp/RF_Estimation | Clustering/helpers/gaussFitSTA/gaussFit.py | Python | gpl-2.0 | 2,992 | 0.027072 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# gaussFit.py
#
# Copyright 2014 Carlos "casep" Sepulveda <casep@alumnos.inf.utfsm.cl>
#
# 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; ... | ion OPTIONS structure.
# [fitresult,..., rr] = fmgaussfit(xx,yy,zz) uses ZZ for the surface
# height. XX and YY are vectors or matrices defining the x and y
# components of a surface. If XX and YY are vectors, length(XX) = n and
# length(YY) = m, where [m,n] = size(Z). In this | case, the vertices of the
# surface faces are (XX(j), YY(i), ZZ(i,j)) triples. To create XX and YY
# matrices for arbitrary domains, use the meshgrid function. FMGAUSSFIT
# uses the lsqcurvefit tool, and the OPTIMZATION TOOLBOX. The initial
# guess for the gaussian is places at the maxima in the ZZ plane. The... |
flyapen/UgFlu | flumotion/common/vfsgnome.py | Python | gpl-2.0 | 4,077 | 0 | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Founda... | .name
self.iconNames = ['gnome-fs-regular']
# IFile
| def getPath(self):
return os.path.join(self.parent, self.filename)
class GnomeVFSDirectory(Copyable, RemoteCopy):
"""I am object implementing L{IDirectory} on top of GnomeVFS,
see L{IDirectory} for more information.
"""
implements(IDirectory)
def __init__(self, path, name=None):
... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_12_01/aio/operations/_public_ip_addresses_operations.py | Python | mit | 40,646 | 0.004847 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
| lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_... |
daniel-deleon/PAM | predict.py | Python | gpl-3.0 | 5,173 | 0.007926 | #!/usr/bin/env python
__author__ = "Danelle Cline"
__copyright__ = "Copyright 2017, MBARI"
__license__ = "GNU License"
__maintainer__ = "Danelle Cline"
__email__ = "dcline at mbari.org"
__status__ = "Development"
__doc__ = '''
This script runs transfer learning on the data using the Inception v3 model trained on Imag... | rint("No images found in %s" % args.input_dir)
else:
# Create example images
exemplars = util.create_image_exemplars(args.exemplar_dir)
util.ensure_dir(args.prediction_dir)
util.make_image_predictions(sess, output_labels_file, args.bottleneck_dir, cl | assifier,
jpeg_data_tensor, bottleneck_tensor, img_list, labels_list,
args.prediction_dir, exemplars)
print("Done !")
|
mssever/odt2dynalist | sermons_to_dynalist.py | Python | bsd-2-clause | 8,843 | 0.007807 | #!/usr/bin/env python3
#
################################################################################
# Important note:
# Because of the highly individual nature of the ODT files to be processed, each
# user will have to adjust this script according to their needs. It will fail
# out of the box unless you happen to... | symbols.append([str(i) for i in range(1, 21)]) # 1, 2, 3, ..., 20
symbols.append(list(string.ascii_lowercase)) # a, b, c, ..., z
symbols.append(['i','ii','iii','iv','v','vi','vii','viii','ix','x'])
symbols.append(['α','β','γ','δ','ε']) |
return symbols
def format_item(text: str, depth: int) -> str:
'''Add tabs to the beginning of each item.'''
assert isinstance(depth, int) and depth >= 0
return '\t' * depth + text
def format_text_line(line: str, symbols: list) -> str:
'''Process a single item, when --type == "text"'''
depth =... |
cernops/neutron | neutron/db/migration/alembic_migrations/versions/5ac1c354a051_n1kv_segment_alloc.py | Python | apache-2.0 | 2,068 | 0.001451 | # Copyright 2014 OpenStack Foundation
#
# 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 ... | nullable=False)
)
op.create | _foreign_key(
'cisco_n1kv_vlan_allocations_ibfk_1',
source='cisco_n1kv_vlan_allocations',
referent='cisco_network_profiles',
local_cols=['network_profile_id'], remote_cols=['id'],
ondelete='CASCADE'
)
op.add_column(
'cisco_n1kv_vxlan_allocations',
sa.Colum... |
lemenkov/sippy | sippy/UaStateConnected.py | Python | gpl-2.0 | 11,513 | 0.013897 | # Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.
# Copyright (c) 2006-2007 Sippy Software, Inc. All rights reserved.
#
# This file is part of SIPPY, a free RFC3261 SIP stack and B2BUA.
#
# SIPPY is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | 0.0.0'
elif str(self.ua.rSDP) == str(body):
self.ua.global_config['_sip_tm'].sendResponse(req.genResponse(200, 'OK', self.ua.lSDP))
return None
event = CCEventUpdate(body, rtime = req.rtime, origin = self.ua.origin)
try:
event.reason = ... | one:
if self.ua.on_remote_sdp_change != None:
self.ua.on_remote_sdp_change(body, lambda x: self.ua.delayed_remote_sdp_update(event, x))
return (UasStateUpdating,)
else:
self.ua.rSDP = body.getCopy()
else:
... |
LaMi-/rbootstrap | rbootstrap/config.py | Python | gpl-2.0 | 3,462 | 0.009821 | #!/usr/bin/env python
# encoding: utf-8
#
# rbootstrap - Install RPM based Linux into chroot jails
# Copyright (C) 2014 Lars Michelsen <lm@larsmichelsen.com>
#
# 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 Softwar... | ostname != None:
if not re.match('^[A-Z][A-Z0-9-]*', hostname, re.IGNORECASE):
raise BailOut('Invalid hostname provided')
def load_rb_info():
"""e.g. rbchroot has no information about the the distro codename and arch
provided by t | he user. The info is stored in chroot in /etc/rbootstrap.info,
read it from there"""
for l in file(os.path.join(root, 'etc/rbootstrap.info')):
key, val = l.strip().split('=', 1)
if key == 'CODENAME':
globals()['codename'] = val.strip('"')
elif key == 'ARCH':
globa... |
rustyfausak/merc | merc/old/game.py | Python | mit | 7,938 | 0.028723 | from merc.actor import Actor
from merc.collision import Collision
from merc.player import Player
from pprint import pprint
import sys
import json
import numpy
import itertools
from PIL import Image, ImageDraw, ImageColor
class Game:
NUM_TWEENS = 10
def __init__(self, data):
"""
`data` should contain the JSON o... | me['Number'], self.tween, self.NUM_TWEENS)
rb2 = actor2.getRB(self.frame['Number'], self.tween, self.NUM_TWEENS)
if not rb1 or not rb2:
return rval
p1 = numpy.array(rb1['Position'])
p2 = numpy.array(rb2['Position'])
dist = numpy.linalg.norm(p1 - p2)
if return_midpoint:
return (dist, numpy.median([p1, ... | tor1, actor2, check_radius):
"""
Returns a Collision if the two actors intersect. Otherwise returns False.
"""
(dist, midpoint) = self.distance(actor1, actor2, True)
if not dist:
return False
if dist > check_radius + Collision.TOLERANCE:
return False
shape1 = actor1.getShape(self.frame['Number'], se... |
bcl/pykickstart | tests/commands/autostep.py | Python | gpl-2.0 | 2,273 | 0.0022 | #
# James Laska <jlaska@redhat.com>
#
# Copyright 2005, 2006, 2007 Red Hat, I | nc.
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2. This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, includi | ng the
# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Flo... |
icfaust/TRIPPy | TRIPPy/AXUV.py | Python | mit | 1,093 | 0.020128 | # setup file necessary to generate the AXUV20 geometry for BP-LY and will
# act as a rosetta stone for generating other detect | or geometries.
import geometry
import surface
import scipy
# aperature position in RZ coordinates, will | be redefined later with CAD work
#
def AXUV20(temp):
diodes = 20*[0]
area = [4e-3,7.5e-4]
vec = [geometry.Vecx((0.,1.,0.)),geometry.Vecx((0.,0.,1.))]
spacing = 9.5e-4
pos = scipy.mgrid[-9.5:9.5:20j]*spacing
#pos = scipy.linspace(-9.025e-3,9.025e-3,20)
for i in range(len(diodes)):
... |
esrille/ibus-replace-with-kanji | dic_tools/intersection.py | Python | apache-2.0 | 1,061 | 0 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Esrille Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
| # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
imp... | PE, SIG_DFL)
a = '/usr/share/skk/SKK-JISYO.ML'
if 2 <= len(sys.argv):
a = sys.argv[1]
b = '/usr/share/skk/SKK-JISYO.jinmei'
if 3 <= len(sys.argv):
b = sys.argv[2]
dict = dic.intersection(dic.load(a), dic.load(b))
print(";", a, "∩", b)
dic.output(dict)
|
theheros/kbengine | kbe/res/scripts/common/Lib/timeit.py | Python | lgpl-3.0 | 12,744 | 0.00102 | #! /usr/bin/env python3
"""Tool for measuring execution time of small code snippets.
This module avoids a number of common traps for measuring execution
times. See also Tim Peters' introduction to the Algorithms chapter in
the Python Cookbook, published by O'Reilly.
Library usage: see the Timer class.
Co... | used for setup, and a timer function. Both statements
default to 'pass'; the timer function is platform-dependent (see
module doc string).
To measure the execution time of the first statement, us | e the
timeit() method. The repeat() method is a convenience to call
timeit() multiple times and return a list of results.
The statements may contain newlines, as long as they don't contain
multi-line string literals.
"""
def __init__(self, stmt="pass", setup="pass", timer=default_time... |
Pikecillo/genna | external/4Suite-XML-1.0.2/Ft/Xml/Xslt/AttributeInfo.py | Python | gpl-2.0 | 15,340 | 0.001565 | ########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/AttributeInfo.py,v 1.30 2006/08/11 15:13:36 jkloth Exp $
"""
Classes that support validation and evaluation of attribute values in
XSLT instruction elements
Copyright 2003 Fourthought, Inc. (USA).
... | sltException(Error.INVALID_QNAME_ATTR, value)
prefix, local = SplitQName(value)
if prefix:
try:
namespace = element.namespaces[prefix]
except KeyError:
raise XsltR | untimeException(Error.UNDEFINED_PREFIX,
element, prefix)
else:
namespace = EMPTY_NAMESPACE
return (namespace, local)
reprocess = prepare
class QNameAvt(Avt, QName):
pass
class RawQName(QName):
def prepare(self, element, value):
... |
ritashugisha/OmniTube | splinter/browser.py | Python | gpl-3.0 | 1,638 | 0 | # -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from splinter.driver.webdriver.firefox import WebDriver as FirefoxWebDriver
from splinter.driver.webdriver.remote import WebDriver as Re... | FoundError
_DRIVERS = {
'firefox': FirefoxWebDriver,
'remote': RemoteWebDriver,
'chrome': ChromeWebDriver,
'phantomjs': PhantomJ | SWebDriver,
}
try:
from splinter.driver.zopetestbrowser import ZopeTestBrowser
_DRIVERS['zope.testbrowser'] = ZopeTestBrowser
except ImportError:
pass
try:
import django # noqa
from splinter.driver.djangoclient import DjangoClient
_DRIVERS['django'] = DjangoClient
except ImportError:
pass... |
paulfurley/django-google-analytics | __init__.py | Python | mit | 49 | 0 | from .context_processor impor | t context_process | or
|
tyndare/osmose-backend | analysers/analyser_osmosis_bad_intersection.py | Python | gpl-3.0 | 4,639 | 0.009489 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights Frédéric Rodrigo 2015 ##
## ... | not, see <http://www.gnu.org/licenses/>. ##
## ##
###########################################################################
from Analyser_Osmosis imp | ort Analyser_Osmosis
sql00 = """
CREATE TEMP TABLE {0}highway AS
SELECT
id,
nodes,
ST_Envelope(linestring) AS bbox
FROM
{0}ways
WHERE
tags?'highway'
"""
sql01 = """
CREATE INDEX {0}_idx_highway_bbox ON {0}highway USING GIST(bbox)
"""
sql10 = """
SELECT
w1_id,
w2_id,
ST_AsText(geom)
FROM
(
SELECT
... |
w0pke/oppgavegenerator | oppgavegen/view_logic/rating.py | Python | bsd-3-clause | 6,450 | 0.003256 | """Functions related to rating change."""
from oppgavegen.models import User, UserLevelProgress, Level, Template
from oppgavegen.utility.decorators import Debugger
def change_elo(temp | late, user, user_won, type):
"""Changes the elo of both user and task depending on who won."""
u = User.objects.get(username=user.username)
user_rating = u.extendeduser.rating
# Formula for elo: Rx = Rx(old) + prefactor *(W-Ex | ) where W=1 if wins and W=0 if x loses
# and Ex is the expected probability that x will win.
# Ea = (1+10^((Rb-Ra)/400))^-1
# Eb = (1+10^((Ra-Rb)/400))^-1
if type == 'blanks':
template_rating = template.fill_rating
elif type == 'multiple':
template_rating = template.choice_rating
... |
francbartoli/geonode | geonode/people/forms.py | Python | gpl-3.0 | 3,226 | 0 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | n from django-registration
attrs_dict = {'class': 'req | uired'}
class AllauthReCaptchaSignupForm(forms.Form):
captcha = ReCaptchaField()
def signup(self, request, user):
""" Required, or else it thorws deprecation warnings """
pass
class ProfileCreationForm(UserCreationForm):
class Meta:
model = get_user_model()
fields = ("... |
treasure-data/digdag | digdag-standards/src/main/resources/io/digdag/standards/operator/aws/runner.py | Python | apache-2.0 | 3,923 | 0.000765 | #!/usr/bin/env python
import argparse
import logging
import json
import subprocess
import sys
import os.path
import urllib2
from base64 import b64decode
from distutils.dir_util import mkpath
from tempfile import TemporaryFile
from shutil import copyfileobj
from urlparse import urlparse
from urllib2 import urlopen
from... | ('-v', '--verbose', action='store_true')
parser.add_argument('--aws-credentials', type=file)
args = parser.parse_args()
logging.basicConfig(
format='%(asctime)s %(levelname)s %(message)s | ',
level=(logging.DEBUG if args.verbose else logging.INFO))
aws_credentials = {}
if args.aws_credentials:
aws_credentials = json.loads(args.aws_credentials.read())
s3 = connect_s3(host='s3.amazonaws.com', **aws_credentials)
# Fetch config json
config_filename = os.path.basename(ar... |
martinjlowm/gr-gsm | python/misc_utils/clock_offset_corrector.py | Python | gpl-3.0 | 4,498 | 0.006003 | #!/usr/bin/env python
################ | ##################################
# Gnuradio Python Flow Graph
# Title: Clock offset corrector
# Author: Piotr Krysik
# Generated: Wed Nov 19 08:38:40 2014
##################################################
from gnuradio import blocks
from gnuradio import filter
from gnuradio import gr
from gnuradio.filter import fir... | ppm=0, samp_rate_in=1625000.0/6.0*4.0):
gr.hier_block2.__init__(
self, "Clock offset corrector",
gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
gr.io_signature(1, 1, gr.sizeof_gr_complex*1),
)
##################################################
# Para... |
atsuyim/OpenBazaar | tests/test_data_uri.py | Python | mit | 1,044 | 0.001916 | import os
import unittest
from node import data_uri
TEST_TXT_FILE = "data_uri_test.txt"
TEST_CONTENTS = "foo\n"
class TestDataURI(unittest.TestCase):
def setUp(self):
with open(TEST_TXT_FILE, 'w') as textfile:
textfile.write(TEST_CONTENTS)
def tearDown(self):
os.remove(TEST_TXT_... | se)
self.assertEqual(uri.data, TEST_CONTENTS)
self.assertEqual(uri.mimetype, "text/plain")
self.assertFalse(uri.is_base64)
def test_init_from_args(self):
data = "I like trains"
charset = 'us-ascii'
mime = 'text/plain'
uri = data_uri.DataURI.make(
... | ual(uri.data, data)
self.assertEqual(uri.charset, charset)
self.assertEqual(uri.mimetype, mime)
self.assertTrue(uri.is_base64)
if __name__ == '__main__':
unittest.main()
|
forevernull/incubator-airflow | airflow/example_dags/example_latest_only.py | Python | apache-2.0 | 1,116 | 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | stOnlyOperator
"""
import datetime as dt
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.latest_only_operator import LatestOnlyOperator
from airflow.utils.trigger_rule import TriggerRule
dag = DAG(
dag_id='latest_only',
schedule_interval=dt.tim... | est_only', dag=dag)
task1 = DummyOperator(task_id='task1', dag=dag)
task1.set_upstream(latest_only)
|
tylercal/dragonfly | dragonfly/actions/action_pause.py | Python | lgpl-3.0 | 1,839 | 0.006525 | #
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly 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... | THOUT 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 Dragonfly. If not, see
# <http://www.gnu... |
============================================================================
"""
import time
from dragonfly.actions.action_base import DynStrActionBase
class Pause(DynStrActionBase):
"""
Pause for the given amount of time.
The *spec* constructor argument should be a *string* giving the
... |
akintolga/superdesk-core | apps/publish/__init__.py | Python | agpl-3.0 | 2,328 | 0.003866 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import loggi... | ription='Correction to a published content') |
superdesk.privilege(name='publish_queue', label='Publish Queue', description='User can update publish queue')
superdesk.privilege(name='resend', label='Resending Stories', description='User can resend published stories')
def enqueue_content():
EnqueueContent().run()
|
aturon/rust | src/etc/generate-deriving-span-tests.py | Python | apache-2.0 | 4,052 | 0.005183 | #!/usr/bin/env python
#
# Copyright 2013 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
#... | o-generated using 'src/etc/generate-keyword-span-tests.py'
#![feature(struct_variant)]
extern crate rand;
{error_deriving}
struct Error;
{code}
fn main() {{}}
"""
ENUM_STRING = """
#[deriving({traits})]
enum Enum {{
A(
Error {errors}
)
}}
"""
ENUM_STRUCT_VARIANT_STRING = """
#[deriving({traits})]
enum E... | "
#[deriving({traits})]
struct Struct {{
x: Error {errors}
}}
"""
STRUCT_TUPLE_STRING = """
#[deriving({traits})]
struct Struct(
Error {errors}
);
"""
ENUM_TUPLE, ENUM_STRUCT, STRUCT_FIELDS, STRUCT_TUPLE = range(4)
def create_test_case(type, trait, super_traits, number_of_errors):
string = [ENUM_STRING, E... |
kingvuplus/ts-gui-3 | lib/python/Screens/ServiceInfo.py | Python | gpl-2.0 | 10,323 | 0.030611 | from Components.HTMLComponent import HTMLComponent
from Components.GUIComponent import GUIComponent
from Screen import Screen
from Components.ActionMap import ActionMap
from Components.Label import Label
from ServiceReference import ServiceReference
from enigma import eListboxPythonMultiContent, eListbox, gFont, iServi... | uner(self):
if self.type == TYPE_SERVICE_INFO:
self.showFrontendData(False)
def getFEData(self, frontendDataOrg):
if frontendDataOrg and len(frontendDataOrg):
frontendData = ConvertToHumanReadable(frontendDataOrg)
if frontendDataOrg["tuner_type"] == "DVB-S":
return ((_("NIM"), chr(ord('A') + frontend... | frontendData["tuner_type"], TYPE_TEXT),
(_("System"), frontendData["system"], TYPE_TEXT),
(_("Modulation"), frontendData["modulation"], TYPE_TEXT),
(_("Orbital position"), frontendData["orbital_position"], TYPE_VALUE_DEC),
(_("Frequency"), frontendData["frequency"], TYPE_VALUE_DEC),
(_("Sy... |
italomaia/turtle-linux | games/gHell/lib/levels.py | Python | gpl-3.0 | 6,134 | 0.037659 | import view
from world import *
DEFAULT_CAMERA_AREA = view.View.CAMERA_AREA
class LevelZero(view.View):
lives = 50
name = "Level 0: Grossini's return"
target = 5
order = 0
CAMERA_AREA=(0, -90, 0, -90)
mountainScale = 0.4
def setup_level(self):
self.step = 0.15
self.ene... | 0,20, force=-15) )
self.world.add_attractor( Attractor(5,-50, force=2) )
self.world.add_attractor( Attractor(30,-70, force=1) )
self.world.add_attractor( Attractor(60,-75, force=1) )
self.world.add_attractor( Attractor(100,20, | force=-15) )
self.world.add_passive( Goal(0,60,15.) )
self.world.add_passive( Floor(-200) )
class LevelSix(view.View):
lives = 30
name = "Level 6: Grossini and Grossini"
target = 5
order = 6
def setup_level(self):
self.step = 0.125
self.energyRegenCoef = 10
... |
pointhi/kicad-footprint-generator | scripts/Recom_DCDC/Recom_SIP.py | Python | gpl-3.0 | 5,607 | 0.030141 | #!/usr/bin/env python
import sys
import os
import math
# ensure that the kicad-footprint-generator directory is available
#sys.path.append(os.environ.get('KIFOOTPRINTGENERATOR')) # enable package import from parent directory
#sys.path.append("D:\hardware\KiCAD\kicad-footprint-generator") # enable package import fro... | tch {1:3.2f}mm, package size {2}x{3}x{4}mm^3, https://www.recom-power.com/pdf/Innoline/R-78Bxx-2.0.pdf".format(pins,rm,package_size[0],package_size[1],package_size[2]),
tags="dc-dc recom buck sip-{0} pitch {1:3.2f}mm".format(pins,rm),
lib_name='Converter_DCDC')
package_size=[11.6,8.5,10.4... | left_offset=package_size[0]-3.21-5.08
top_offset=package_size[1]-2
makeSIPVertical(pins=pins, rm=rm, ddrill=ddrill_small, pad=pad_small, package_size=package_size, left_offset=left_offset, top_offset=top_offset,
footprint_name='Converter_DCDC_RECOM_R-78E-0.5_THT',
description="DCDC-... |
loads/ailoads | molotov/listeners.py | Python | apache-2.0 | 3,733 | 0 | import io
from molotov.api import get_fixture
_UNREADABLE = "***WARNING: Molotov can't display this body***"
_BINARY = "**** Binary content ****"
_FILE = "**** File content ****"
_COMPRESSED = ('gzip', 'compress', 'deflate', 'identity', 'br')
class | BaseListener(object):
async def __call__(self, event, **options):
attr = getattr(self, 'on_' + event, None)
if attr is not None:
await attr(**options)
class StdoutListener(BaseListener):
def __init__(self, **opt | ions):
self.verbose = options.get('verbose', 0)
self.console = options['console']
def _body2str(self, body):
try:
from aiohttp.payload import Payload
except ImportError:
Payload = None
if Payload is not None and isinstance(body, Payload):
... |
biblepay/biblepay | contrib/zmq/zmq_sub.py | Python | mit | 5,995 | 0.001835 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
ZMQ example using python3's asyncio
BiblePay should be started with the command line argume... | elif topic == b"rawchainlock":
print('- R | AW CHAINLOCK ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8"))
elif topic == b"rawchainlocksig":
print('- RAW CHAINLOCK SIG ('+sequence+') -')
print(binascii.hexlify(body[:80]).decode("utf-8"))
elif topic == b"rawtx":
print('- RAW TX ('... |
leoliuabc/Colpon | br_colpon/models.py | Python | apache-2.0 | 1,170 | 0.003419 | from django.db import models
class Store(models.Model):
name = models.CharField(max_length=200, unique=True)
desc = models.TextField('description')
link = models.URLField()
slug = models.SlugField(max_length=200, unique=True)
status = models.BooleanField(default=True)
ishot = models.BooleanFiel... | s.ImageField(upload_to='logos')
pub_date = models.DateTimeField('date published', auto_now_add=True)
mod_date = models.DateTimeField('date modification', auto_now=True)
def __str__(self):
return self.name
class Offer(models.Model):
| store = models.ForeignKey(Store, on_delete=models.CASCADE)
type = models.CharField(max_length=10)
name = models.CharField(max_length=200)
desc = models.TextField('description')
link = models.URLField()
code = models.CharField(max_length=50, blank=True)
status = models.BooleanField(default=True... |
tyc85/nwsdr-3.6.3-dsc | dsc-coop/r_path.py | Python | gpl-3.0 | 6,193 | 0.007589 | #!/usr/bin/env python
#
# Copyright 2005-2007,2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at you... | "bitrate: %sb/s" % (eng_notation.num_to_str(self._bitrat | e))
print "samples/symbol: %.4f" % (self.samples_per_symbol())
print "Differential: %s" % (self.differential())
|
ojarva/home-info-display | sensor_consumers/ikettle2.py | Python | bsd-3-clause | 3,231 | 0 | """
2075 +-5 = empty
2153 +-5 = 6dl
2210 +-5 = 12dl
2260 +-5 = 18dl
"""
import socket
import sys
import select
import time
def get_status(value):
if value == 0:
return "ready"
if value == 1:
return "boiling"
if value == 2:
return "keep-warm"
if value == 3:
return "fini... | ater_level = (water_level1 << 8) + water_level2
parsed["water_level_raw"] = water_level
water_level = water_level - 2075
water_level_percentage = round(
min(1, max(0, float(water_level) / 185)), 3)
if not parsed["pre... | "] = water_level_percentage
output.append({"type": "status", "data": parsed})
if buf[0] == 3:
output.append({"type": "ack"})
message_data = ""
return output
def main(ip):
kettle = Kettle2(ip)
kettle.connect()
for _ in range(... |
lindenquan/draw-pedigree | Generator.py | Python | mit | 6,647 | 0.015496 | import collections
from sets import Set
from Drawer import Drawer
class Cultivar():
def __init__(self, id, name, year):
self.id = id
self.name = name
self.year = year
self.parent1 = None
self.parent2 = None
# row index starts from 0
self.row = 0
# column index starts from 0
self... | leColumn * 2 + 1
self.grid = []
self.initGrid(self.grid, self.rowTotalNumber, self.colTotalNumber, 0)
# only double columns
def doubleGrid(self):
colTotalNumber = self.colTotalNumber
middleColumn = Grid.middleColumn
Grid.middleColumn += Grid.middleColumn
self.colTotalNumber = Grid.middleCol... | 1
grid = []
self.initGrid(grid, self.rowTotalNumber, self.colTotalNumber, 0)
for rowIndex in range(self.rowTotalNumber):
for colIndex in range(colTotalNumber):
newColIndex = middleColumn + colIndex
grid[rowIndex][newColIndex] = self.grid[rowIndex][colIndex]
self.grid = grid
def... |
harikishen/addons-server | src/olympia/editors/management/commands/auto_approve.py | Python | bsd-3-clause | 7,550 | 0 | # -*- coding: utf-8 -*-
from collections import Counter
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from django.db import transaction
import waffle
import olympia.core.logger
from olympia import amo
from olympia.edito... | # Note: this should automatically use the TASK_USER_ID user.
helper = ReviewHelper(addon=version.addon, version=version)
helper.handler.data = {
# The comment is not translated on purpose, to behave like regular
# human approval does.
'comments': u'This version has b... | _final_summary(self, stats):
"""Log a summary of what happened."""
log.info('There were %d webextensions add-ons in the queue.',
stats['total'])
if stats['error']:
log.info(
'%d versions were skipped because they had no files or had '
... |
DiptoDas8/Biponi | lib/python2.7/site-packages/braintree/util/generator.py | Python | mit | 2,578 | 0.001552 | import datetime
import sys
from decimal import Decimal
if sys.version_info[0] == 2:
integer_types = int, long
text_type = unicode
binary_type = str
else:
integer_types = int,
text_type = str
binary_type = bytes
class Generator(obje | ct):
def __init__(self, dict):
self.dict = dict
def generate(self):
return self.__generate_dict(self.dict)
def __escape(self, value):
return value.replace("&", "&").rep | lace("<", "<").replace(">", ">").replace("'", "'").replace('"', """)
def __generate_boolean(self, value):
return str(value).lower()
def __generate_datetime(self, value):
return value.strftime("%Y-%m-%dT%H:%M:%SZ")
def __generate_dict(self, dictionary):
xml = ""
... |
johndoe31415/biblint | BibUtils.py | Python | gpl-3.0 | 1,488 | 0.02621 | #
# biblint - Static checking of BibTeX files to find errors or inconsistencies.
# Copyright (C) 2016-2016 Johannes Bauer
#
# This file is part of biblint.
#
# biblint 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 Found... | rt json
import collections
class BibUtils(object):
def __init__(self, bibliography):
self._bibliography = bibliography
def author_scan(self, file):
names = set()
for entry in self._bibliography:
for field in [ "author", "editor" ]:
if entry.haskey(field):
for name in entry.parsenames(field):
... | idname": person.midname } for person in sorted(names, key = lambda p: (p.lastname, p.firstname, p.midname)) ]
print(json.dumps(names), file = file)
|
freedomtan/tensorflow | tensorflow/python/saved_model/nested_structure_coder_test.py | Python | apache-2.0 | 14,586 | 0.00192 | # Copyright 2018 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... | oder = nested_structure_coder.StructureCoder()
def testEncodeDecodeList(self):
structure = [1.5, 2.5, 3.0]
self.assertTrue(self._coder.can_encode(structure))
encoded = self._coder.encode_structure(structure)
expected = struct_pb2.StructuredValue()
expected.list_v | alue.values.add().float64_value = 1.5
expected.list_value.values.add().float64_value = 2.5
expected.list_value.values.add().float64_value = 3.0
self.assertEqual(expected, encoded)
decoded = self._coder.decode_proto(encoded)
self.assertEqual(structure, decoded)
def testEncodeDecodeTuple(self):
... |
andr3wmac/metaTower | packages/http/HTTPOut.py | Python | gpl-3.0 | 7,153 | 0.017196 | import mt, os, mimetypes
from time import strftime
class HTTPOut():
class mtEntry():
def __init__(self):
self.html = False
self.css = False
self.js = False
self.data = ""
self.target = ""
def __init__(self, session = None):
self.sessi... | def append(self, targ):
if ( targ == None ): return
self.cookies.update(targ.cookies)
self.headers.update(targ.headers)
self.mt_entrys.extend(targ.mt_entrys)
se | lf.text_entry += targ.text_entry
if ( targ.http_version != "" ): self.http_version = targ.http_version
if ( targ.status != "" ): self.status = targ.status
if ( targ.binary_entry != "" ): self.binary_entry = targ.binary_entry
def send(self, socket, header_only = False):
self... |
caktus/smartmin | test_runner/blog/models.py | Python | bsd-3-clause | 1,319 | 0.003033 | from | __future__ import unicode_literals
from django.db import models
from smartmin.models import SmartModel, ActiveManager
class Post(SmartModel):
title = models.CharField(max_length=128,
help_text="The title of this blog post, keep it relevant")
body = models.TextField(help_text="The... | der for this post, posts with smaller orders come first")
tags = models.CharField(max_length=128,
help_text="Any tags for this post")
objects = models.Manager()
active = ActiveManager()
@classmethod
def pre_create_instance(cls, field_dict):
field_dict['body'] = ... |
DrigerG/IIITB-ML | project/CharRec/CharRec.py | Python | apache-2.0 | 4,197 | 0 | #!/usr/bin/env python
"""CharRec.py: Runs a suite of ML algorithms on a character dataset"""
import logging
import numpy as np
import pandas as pd
from skimage import io, filters, exposure, morphology
from sklearn | import tree, ensemble, neighbors, neural_network, multiclass
from sklearn.model_selection import cross_val_score
__author__ = "Pradeep Kumar A.V."
logging.basicConfig(filename='execution_log.log',
| format='%(asctime)s %(message)s',
level=logging.DEBUG)
def log_and_print(msg):
logging.info(msg)
print(msg)
def process_image(path):
"""
:param path: Image path
:return: processed image
"""
image = io.imread(path, as_grey=True)
image = exposure.adjust_sigmoid... |
google/eclipse2017 | src/solar_eclipse_analysis/generate_maps.py | Python | apache-2.0 | 6,384 | 0.004386 | #
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles | s 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 tra... | rt StringIO
import pickle
import os
import numpy as np
import string
import argparse
import cv2
from map_util import load_path, points_to_latlong
from multiprocessing import Pool
from PIL import Image
import matplotlib.cm as cm
import matplotlib # Force matplotlib to not use any Xwindows backend
matplotlib.use('Agg')
f... |
mdrasmus/spimap | python/spidir/deps/compbio/seqlib.py | Python | gpl-2.0 | 15,659 | 0.037614 |
# python imports
import copy
import math
import random
# rasmus imports
from rasmus import util
class SeqDict (dict):
"""
A dictionary for molecular sequences. Also keeps track of their order,
useful for reading and writing sequences from fasta's. See fasta.FastaDict
for subclass that implements F... | -3,
'M':-1, 'F':-2, 'P':-3, 'S':-1, 'T':-1, 'W':-2, 'Y':-2, 'V':-1, 'B':-3, 'Z':-3, 'X':-2, '*':-4},
'Q': {'A':-1, 'R': 1, 'N': 0, 'D': 0, 'C':-3, 'Q': 5, 'E': 2, 'G':-2, 'H': 0, 'I':-3, 'L':-2, 'K': 1,
'M': 0, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-2, 'Y':-1, 'V':-2, 'B': 0, 'Z': 3, '... | 'G':-2, 'H': 0, 'I':-3, 'L':-3, 'K': 1,
'M':-2, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-3, 'Y':-2, 'V':-2, 'B': 1, 'Z': 4, 'X':-1, '*':-4},
'G': {'A': 0, 'R':-2, 'N': 0, 'D':-1, 'C':-3, 'Q':-2, 'E':-2, 'G': 6, 'H':-2, 'I':-4, 'L':-4, 'K':-2,
'M':-3, 'F':-3, 'P':-2, 'S': |
ahmedelsers/atom-installer | atom_installer.py | Python | gpl-3.0 | 4,389 | 0.002734 | # Author: Ahmed Husam Elsers
# Email: ahmed.elsersi@gmail.com
# This is a Python3 script to install/upgrade Atom for Linux (Fedora, Ubuntu)
# Check The Host Linux Distro (Fedora/Ubuntu)
# Check if Atom installed or Not
# If Installed:
# check the latest version on Atom web page
# then compare it to inst... | atom_latest(atom_base_url, atom_latest_url, linux_distro)
is_atom_installed = atom_installed(linux_distro)
if is_atom_installed[0]:
if atom_link_pkgver_latest[1] > is_atom_installed[1]:
get_atom_install(linux_distro, atom_link_pkgver_latest[0])
if atom_link_pkgve... | :
print("You already have atom latest installed, Good for You.")
print("Thank You for using my Script.")
sys.exit(0)
else:
get_atom_install(linux_distro, atom_link_pkgver_latest[0])
except KeyboardInterrupt:
print("\nIt seems you entered Ct... |
comses/catalog | catalog/core/visualization/data_sources/publication_counts.py | Python | gpl-3.0 | 1,439 | 0.009729 | import logging
import pandas as pd
from catalog.core.search_indexes import PublicationDocSearch
from ..data_access im | port data_cache, IncludedStatistics
from query import Query
logger = logging.getLogger(__name__)
def _create_count_dataframe(df):
return df.groupby(['year_published']) \
.agg(dict(title='count', is_archived='sum', has_formal_description='sum',
has_odd='sum', has_visual_documentation='su... | ailability_count.name,
'has_formal_description': IncludedStatistics.formal_description_count.name,
'has_odd': IncludedStatistics.odd_count.name,
'has_visual_documentation': IncludedStatistics.visual_documentation_count.name
}).reindex(pd.RangeIndex(start=1995, stop=2018, name='year_published... |
MeGotsThis/Hanabi-AI | onlyfulltag_v1_0/tests/game_12711.py | Python | gpl-3.0 | 8,508 | 0.000118 | from enums import Color, Value
from testing.game_testing import GameSimulatorTesting
from onlyfulltag_v1_0.bot import Bot
class Game12711(GameSimulatorTesting):
def test_turn_0(self):
# Deck size 40, Bob, Clues 8, Score 0
self.load_game('games/12711.json', position=1, turn=0, botcls=Bot)
s... | # Deck size 35, Bob, Clues 2, Score 4
self.load_game('games/12711.json', position=1, turn=12, botcls=Bot)
self.send_action()
self.connection.assert_clue_value(0, Value.V2)
def test_turn_14(self | ):
# Deck size 34, Bob, Clues 1, Score 5
self.load_game('games/12711.json', position=1, turn=14, botcls=Bot)
self.send_action()
self.connection.assert_clue_value(0, Value.V3)
def test_turn_16(self):
# Deck size 33, Bob, Clues 1, Score 5
self.load_game('games/12711.js... |
travmi/ceph-ansible | tests/functional/tests/osd/test_osds.py | Python | apache-2.0 | 1,919 | 0.001042 | import pytest
class TestOSDs(object):
@pytest.mark.no_docker
def test_ceph_osd_package_is_installed(self, node, host):
assert host.package("ceph-osd").is_installed
def test_osds_listen_on_public_network(self, node, host):
# TODO: figure out way to paramaterize this test
nb_port =... | ("ceph-osd@%s" % osd).is_enabled
@pytest.mark.no_docker
def test_osd_are_mounted(self, node, host):
# TODO: figure out way to paramaterize node['osd_ids'] for this test
for osd_id in node["osd_ids"]:
osd_path = "/var/lib/ceph/osd/{cluster}-{osd_id}".format(
cluster=n... | def test_ceph_volume_is_installed(self, node, host):
host.exists('ceph-volume')
@pytest.mark.lvm_scenario
def test_ceph_volume_systemd_is_installed(self, node, host):
host.exists('ceph-volume-systemd')
|
openstack/debtcollector | debtcollector/_utils.py | Python | apache-2.0 | 5,811 | 0 | # Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | he
# License for the specific language governing permissions and limitations
# under the License.
import functools
import inspect
import warnings
# See https://docs.python.org/3/library/builtins.html
_B | UILTIN_MODULES = ('builtins', 'exceptions')
_enabled = True
def deprecation(message, stacklevel=None, category=None):
"""Warns about some type of deprecation that has been (or will be) made.
This helper function makes it easier to interact with the warnings module
by standardizing the arguments that the ... |
alsrgv/tensorflow | tensorflow/python/compiler/tensorrt/test/int32_test.py | Python | apache-2.0 | 2,529 | 0.003559 | # Copyright 2018 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF... | ====================================================================
"""Test conversion of graphs involving INT32 tensors and operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.compiler.tensorrt.test im... |
Alkemic/webpage | module/portfolio/tests.py | Python | mit | 2,720 | 0 | # -*- coding:utf-8 -*-
from datetime import datetime, date
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from django.db.models.query import QuerySet
from module.portfolio.models import Entry, Company
class ViewsTestCase(TestCase):
fixtures = ... | elf):
"""Portfolio index page returns status code 200"""
response = self.client.get(self.portfolio_url)
self.assertEqual(response.status_code, 200)
self.assertInHTML(
'<h3>Ogradzamy.pl</h3>',
response.content
)
class ModelTestCase(TestCase):
fixtur... | self.assertIsInstance(entry.__unicode__(), unicode)
self.assertEqual(str(entry), "Ogradzamy.pl")
self.assertEqual(unicode(entry), "Ogradzamy.pl")
def test_company_str_unicode(self):
company = Company.objects.get(pk=1)
self.assertIsInstance(company.__str__(), unicode)
sel... |
brclark-usgs/flopy | flopy/utils/modpathfile.py | Python | bsd-3-clause | 20,645 | 0.001744 | """
Module to read MODPATH output files. The module contains two
important classes that can be accessed by the user.
* EndpointFile (ascii endpoint file)
* PathlineFile (ascii pathline file)
"""
import numpy as np
from ..utils.flopy_io import loadtxt
class PathlineFile():
"""
PathlineFile Class.
Par... | kijnames = ['k', 'i', 'j', 'particleid', 'particlegroup', 'linesegmentindex']
def __init__(self, filename, verbose=False):
"""
Class constructor.
"""
self.fname = filename
self.dtype, self.outdtype = | self._get_dtypes()
self._build_index()
self._data = loadtxt(self.file, dtype=self.dtype, skiprows=self.skiprows)
# set number of particle ids
self.nid = self._data['particleid'].max()
# convert layer, row, and column indices; particle id and group; and
# line segment ind... |
scrapinghub/scrapy | tests/test_downloadermiddleware_cookies.py | Python | bsd-3-clause | 6,842 | 0.003362 | from unittest import TestCase
import re
from scrapy.http import Response, Request
from scrapy.spider import Spider
from scrapy.contrib.downloadermiddleware.cookies import CookiesMiddleware
class CookiesMiddlewareTest(TestCase):
def assertCookieValEqual(self, first, second, msg=None):
cookievaleq = lambd... | ders = {'Set-Cookie': 'C1=value1; path=/'}
res = Response('http://scrapytest.org/', headers=headers)
assert self.mw.proce | ss_response(req, res, self.spider) is res
req2 = Request('http://scrapytest.org/sub1/')
assert self.mw.process_request(req2, self.spider) is None
self.assertCookieValEqual(req2.headers.get('Cookie'), "C1=value1; galleta=salada")
def test_cookiejar_key(self):
req = Request('http://... |
noironetworks/neutron | neutron/tests/unit/agent/l2/extensions/test_qos.py | Python | apache-2.0 | 22,770 | 0.000439 | # Copyright (c) 2015 Mellanox Technologies, Ltd
# 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
#
# U... | LimitRule)
def test__handle_update_create_rules_checks_should_apply_to_port(self):
self.egress_bandwidth_limit_rule.should_apply_to_port = mock.Mock(
return_value=False)
self.ingress_bandwidth_limit_rule.should_apply_to_port = mock.Mo | ck(
return_value=False)
self.driver.create(self.port, self.policy)
self.assertFalse(self.driver.create_bandwidth_limit.called)
self.egress_bandwidth_limit_rule.should_apply_to_port = mock.Mock(
return_value=True)
self.ingress_bandwidth_limit_rule.should_apply_to_... |
ktan2020/legacy-automation | win/Lib/test/test_pep277.py | Python | mit | 8,085 | 0.001484 | # Test the Unicode versions of normal file functions
# open, os.open, os.stat. os.listdir, os.rename, os.remove, os.mkdir, os.chdir, os.rmdir
import sys, os, unittest
from unicodedata import normalize
from test import test_support
filenames = [
'1_abc',
u'2_ascii',
u'3_Gr\xfc\xdf-Gott',
u'4_\... | code("utf-8"))
os.access(filename,os.R_OK)
os.remove(filename)
finally:
os.chdir(old | wd)
os.rmdir(dirname)
class UnicodeNFCFileTests(UnicodeFileTests):
normal_form = 'NFC'
class UnicodeNFDFileTests(UnicodeFileTests):
normal_form = 'NFD'
class UnicodeNFKCFileTests(UnicodeFileTests):
normal_form = 'NFKC'
class UnicodeNFKDFileTests(UnicodeFileTests):
no... |
Azure/azure-sdk-for-python | sdk/policyinsights/azure-mgmt-policyinsights/azure/mgmt/policyinsights/aio/operations/_policy_tracked_resources_operations.py | Python | mit | 19,738 | 0.004712 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | _top | = query_options.top
_filter = query_options.filter
management_groups_namespace = "Microsoft.Management"
policy_tracked_resources_resource = "default"
api_version = "2018-07-01-preview"
accept = "application/json"
def prepare_request(next_link=None):
# Con... |
carlohamalainen/imagetrove | develop/djangosettings.py | Python | bsd-2-clause | 573 | 0 |
import os.path
import sys
# | This is copied from mytardis.py in the project's root directory.
custom_settings = 'tardis.settings'
custom_settings_file = custom_settings.replace('.', '/') + '.py'
demo_settings = 'tardis.settings_changeme'
if os.path.isfile(custom_settings_file):
os.environ.setdefault("DJANGO_SETTINGS_MODULE", custom_settings)... | ult("DJANGO_SETTINGS_MODULE", demo_settings)
print('Using demo settings in "tardis/settings_changeme.py",'
' please add your own settings file, '
'"tardis/settings.py".')
|
janusnic/wagtail | wagtail/wagtailimages/models.py | Python | bsd-3-clause | 15,630 | 0.001791 | from __future__ import unicode_literals
import os.path
import hashlib
from contextlib import contextmanager
import warnings
from taggit.managers import TaggableManager
from willow.image import Image as WillowImage
from django.core.files import File
from django.core.exceptions import ImproperlyConfigured, ObjectDoes... | Rect.from_point(x, y, width, height)
def get_rendition(self, filter):
if not hasattr(filter, 'run'):
# assume we've been passed a filter spec string, rather than a Filter object
# TODO: keep an in-memory cache of filters, to avoid a db lookup
filter, created = Filter.obj... | :
rendition = self.renditions.get(
filter=filter,
focal_point_key=cache_key,
)
except ObjectDoesNotExist:
# Generate the rendition image
generated_image, output_format = filter.run(self, BytesIO())
# Generate filename
... |
gamecredits-project/electrum-client | plugins/btchipwallet.py | Python | gpl-3.0 | 23,308 | 0.003733 | from PyQt4.Qt import QApplication, QMessageBox, QDialog, QInputDialog, QLineEdit, QVBoxLayout, QLabel, QThread, SIGNAL
import PyQt4.QtCore as QtCore
from binascii import unhexlify
from binascii import hexlify
from struct import pack,unpack
from sys import stderr
from time import sleep
import electrum
from electrum_gui... | self | .wallet = wallet
self.wallet.plugin = self
if self.handler is None:
self.handler = BTChipCmdLineHandler()
@hook
def load_wallet(self, wallet, window):
self.wallet = wallet
self.wallet.plugin = self
if self.handler is None:
self.handler = BTChipQTH... |
thom-at-redhat/cfme_tests | cfme/tests/services/test_generic_service_catalogs.py | Python | gpl-2.0 | 6,331 | 0.00616 | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme.services.catalogs.catalog_item import CatalogItem
from cfme.automate.service_dialogs import ServiceDialog
from cfme.services.catalogs.catalog import Catalog
from cfme.services.catalogs.service_catalogs import ServiceCatalogs
from cfme.services.catalogs... | th error.expected(CandidateNotFound):
service_catalogs.order(catalog_item.catalog, catalog_item)
def test_se | rvice_circular_reference(catalog_item):
bundle_name = "first_" + fauxfactory.gen_alphanumeric()
catalog_bundle = CatalogBundle(name=bundle_name, description="catalog_bundle",
display_in=True, catalog=catalog_item.catalog, dialog=catalog_item.dialog)
catalog_bundle.create([catalog_item.nam... |
openstack/rally | rally/verification/utils.py | Python | apache-2.0 | 3,055 | 0 | # 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... | section)
for option, value in extra_options[section].items():
conf_object.set(section, option, value)
ret | urn conf_object
|
w1ll1am23/home-assistant | homeassistant/components/maxcube/climate.py | Python | apache-2.0 | 8,519 | 0.000822 | """Support for MAX! Thermostats via MAX! Cube."""
from __future__ import annotations
import logging
import socket
from maxcube.device import (
MAX_DEVICE_MODE_AUTOMATIC,
MAX_DEVICE_MODE_BOOST,
MAX_DEVICE_MODE_MANUAL,
MAX_DEVICE_MODE_VACATION,
)
from homeassistant.components.climate import ClimateEnti... | urn the maximum temperature."""
return self._device.max_temperature or MAX_TEMPERATURE
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
... | device.mode
if mode in [MAX_DEVICE_MODE_AUTOMATIC, MAX_DEVICE_MODE_BOOST]:
return HVAC_MODE_AUTO
if (
mode == MAX_DEVICE_MODE_MANUAL
and self._device.target_temperature == OFF_TEMPERATURE
):
return HVAC_MODE_OFF
return HVAC_MODE_HEAT
... |
LittleTodd/pythonWork | pythonTest.py | Python | gpl-3.0 | 141 | 0.028369 | teams = ['Milan','Inter','Juventus']
for team in teams:
print(team | .title() + " is a Seria A team")
print | ("My favourite team is " + teams[0]) |
napsternxg/gensim | gensim/models/ldamulticore.py | Python | gpl-3.0 | 16,688 | 0.004914 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Jan Zikes, Radim Rehurek
# Copyright (C) 2014 Radim Rehurek <me@radimrehurek.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""Online Latent Dirichlet Allocation (LDA) in Python, using all CPU cores to parallelize and speed up m... | odule allows both LDA model estimation from a training corpus and inference of topic dist | ribution on new,
unseen documents. The model can also be updated with new documents for online training.
The core estimation code is based on the `onlineldavb.py script
<https://github.com/blei-lab/onlineldavb/blob/master/onlineldavb.py>`_, by `Hoffman, Blei, Bach:
Online Learning for Latent Dirichlet Allocation, NIPS... |
ncbray/pystream | bin/tests/shape/test_shape_examples.py | Python | apache-2.0 | 8,509 | 0.032084 | # Copyright 2011 Nicholas Bray
#
# 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... | nExpr)
# xyn -> xy
argument = (self.xynRef, (self.tnExpr, self.ynExpr), None)
results | = |
mjj55409/cpq-exporter | config/settings/production.py | Python | mit | 7,354 | 0.001224 | # -*- coding: utf-8 -*-
"""
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.util... | INS', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True)
CSRF_COOKIE_SECURE = True
CSRF_COOKI... | FIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['mertisconsulting.com'])
# END SITE CONFIGURATIO... |
welliam/data-structures | src/graph.py | Python | mit | 5,049 | 0.000198 | # -*- coding: utf-8 -*-
"""Implement directed graph abstract data type."""
from __future__ import print_function
from .stack import Stack
from .queue import Queue
class Graph(object):
"""Implement a directed graph."""
def __init__(self):
"""Initialize a graph with no nodes or edges."""
self... | 1-1
/ \ / \
2-0 2-1 2- | 2 2-3''')
print('depth first ', g.depth_first_traversal('0-0'))
print('breadth first ', g.breadth_first_traversal('0-0'))
|
msempere/yacontracts | src/yacontracts.py | Python | mit | 3,410 | 0.003812 | """YAContrac module
"""
import inspect
from types import FunctionType, ListType, TupleType, StringType
def exec_validator(value, validator, error_message):
"""Run validation
Checks value against validator and returns error_message
in case of failure as a ValueError
"""
if not validator(value):
... | [("argument_1", lambda x: x > 0, 'Erro | r, argument_1 < 0 !'),
("argument_N", lambda x: isinstance(x, str), 'Error, not str !')]
returns:
(lambda x: isinstance(x, int), 'Return has to be an int')
"""
# validate args argument
if not isinstance(args, ListType):
raise ValueError('... |
Ebag333/Pyfa | eos/effects/shipsptoptimalbonusmf.py | Python | gpl-3.0 | 316 | 0.006329 | # shipSPTOptimalBonusMF
#
# Used by:
# Ship: Chremoas
type = "passive"
def handler(fit, ship, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Small Projectile Turret"),
"maxRange", ship.getModifiedItemAttr(" | shi | pBonusMF"), skill="Minmatar Frigate")
|
samuelmaudo/yepes | yepes/middleware/csrf_token.py | Python | bsd-3-clause | 1,653 | 0.00121 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django import VERSION as DJANGO_VERSION
from django.middleware.csrf import CsrfViewMiddleware
from django.middleware.csrf import _sanitize_token as sanitize_csrf_token
if DJANGO_VERSION < (1, 10):
from django.middleware.csrf import _get_new_csrf_... | ack_kwargs):
if getattr(request, 'csrf_processing_done', False):
return None
try:
cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
except KeyError:
# Generate token and store it in the request, so it's
# available to the view.
... | uest.META['CSRF_COOKIE'] = generate_csrf_token()
else:
csrf_token = sanitize_csrf_token(cookie_token)
if csrf_token != cookie_token:
# Cookie token needed to be replaced; the cookie
# needs to be reset.
request.csrf_cookie_needs_reset = Tru... |
maxtaco/okws | test/regtest/cases/44.py | Python | gpl-2.0 | 829 | 0.018094 | #
# Preliminary testing of regular expressions.
#
inputs = [ "aaabcccc", "abc", "aaacccc>", "abab", "aAaAbCcCcC" ]
d = [ { "val" : s } for s in inputs ]
regex = "r<a+b?c+\\>?>"
#
# for the last test case, add 0 so that the results gets coerced into
# an int. sneaky, i know!
| #
filedata = """
{$ locals { v : %s,
rxx : %s }
for (i, decorate (v)) {
print (i.iter + ": ")
if (match (rxx, i.val)) { print 1 }
elif (mat | ch (rxx, "i", i.val)) { print 2 }
else { print 0 }
print "\\n"
} $}
{$ locals { x : "XXaabccc>YY" } $}
%d: ${search(rxx,x) + 0}
""" % (d, regex, len (inputs))
results = [ 1, 1, 1, 0, 2, 1 ]
outcome = '\n'.join (["%d: %d" % (i, results[i])
for i in range (0, ... |
bizarrechaos/newsapi-client | news/newsconfig.py | Python | apache-2.0 | 1,209 | 0 | import ConfigParser
import sys
from os.path import expanduser, isfile
class NewsConfig(object):
"""handles reading, writing, and validating
the configuration for newsapi.org"""
def __init__(self, configpath=None, apikey=None):
super(NewsConfig, self).__init__()
self.section = 'newsapi.... | apikey = self.read_config('apikey')
else:
print '{0} does not exist'.format(self.configpath)
print 'create {0}, or use the -a flag'.format(self.configpath)
| sys.exit(1)
return apikey
def read_config(self, key):
parser = ConfigParser.SafeConfigParser()
parser.read(self.configpath)
return parser.get(self.section, key)
|
cwolferh/heat-scratch | heat/engine/resources/openstack/heat/remote_stack.py | Python | apache-2.0 | 11,589 | 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
# ... | 'a resource.'),
required=True,
update_allowed=True
),
TIMEOUT: properties.Schema(
properties.Schema.INTEGER,
| _('Number of minutes to wait for this stack creation.'),
update_allowed=True
),
PARAMETERS: properties.Schema(
properties.Schema.MAP,
_('Set of parameters passed to this stack.'),
default={},
update_allowed=True
),
}
attributes... |
jacklaag/rgb_wifi_python | led_on.py | Python | apache-2.0 | 355 | 0.019718 | import socket
def Main():
host = '192.168.178.60' # IP of the controller
port = 5577
s = socket.socket()
s.connect((host, port))
| s.send('EF0177'.decode('hex')) # connect
data = s.recv(1024)
s.send('CC2333'.decode('hex')) # send command (turn on in this | case)
s.close() # disconnect
if __name__ == '__main__':
Main() |
yunify/qingcloud-cli | qingcloud/cli/iaas_client/actions/snapshot/create_snapshots.py | Python | apache-2.0 | 2,277 | 0.004392 | # =========================================================================
# Copyright 2012-present Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the Licens... | n='store', type=int, default=0,
help='1 m | eans create full snapshot, 0 means determined by the system.')
parser.add_argument('-N', '--name', dest='snapshot_name',
action='store', type=str, default='',
help='short name of snapshot')
@classmethod
def build_directive(cls, options):
required_params = {'reso... |
skosukhin/spack | lib/spack/spack/test/sbang.py | Python | lgpl-2.1 | 6,406 | 0.001405 | ##############################################################################
# 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-64... | sbang_line
assert f.readline() == long_line
assert f.readline() == last | _line
def test_shebang_handles_non_writable_files(script_dir):
# make a file non-writable
st = os.stat(script_dir.long_shebang)
not_writable_mode = st.st_mode & ~stat.S_IWRITE
os.chmod(script_dir.long_shebang, not_writable_mode)
test_shebang_handling(script_dir)
st = os.stat(script_dir.long_... |
andyregan/scrape_argos | scrape_argos/settings.py | Python | mit | 478 | 0.004184 | # Scrapy settings for | scrape_argos project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'scrape_argos'
SPIDER_MODULES = ['scrape_argos.spiders']
NEWSPIDER_MODULE = 'scrape_argos.spiders'
# ... | omain.com)'
|
pcon/mpd-rest | mpdrest/webserverInit.py | Python | gpl-2.0 | 1,404 | 0.003561 | # Copyright 2011 Patrick Connelly
#
# This file is part of mpd-rest
#
# mpd-rest 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.
#
# Th... | Boston, MA 02110-1301, USA.
import cherrypy
import os.path
import sys
import mpdrest
from mpdrest.webserver import WebInterface
def initWebServer(options = {}):
options.setdefault('port', 8080)
options.setdefault('host', '0.0.0.0')
options.setdefault('web_root', '/')
options.setdefault('quiet', Fals... | sert isinstance(options['port'], int)
options_dict = {
'server.socket_port': options['port'],
'server.socket_host': options['host'],
}
cherrypy.config.update(options_dict)
config = {}
cherrypy.quickstart(WebInterface(), options['web_root'], config) |
south-coast-science/scs_core | src/scs_core/aqcsv/specification/country_iso.py | Python | mit | 1,163 | 0.00172 | """
Created on 4 Mar 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
AQCSV: ISO country codes
NB: initialisation is performed at the foot of this class
example:
{"numeric": 788, "name": "Tunisia", "iso": "TUN"}
https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
https://www.airnow.gov/
"""
from scs_c... | ----------------------------------------------------------------------------
class CountryISO(Country):
"""
classdocs
"""
_retrieved = {}
# ----------------------------------------------------------------------------------------------------------------
d | ef __init__(self, numeric, name, iso):
"""
Constructor
"""
super().__init__(numeric, name, iso)
# ----------------------------------------------------------------------------------------------------------------
@property
def pk(self):
return self.iso
# ----------... |
rvswift/BlastNFilter | build/lib/BlastNFilter/PreRelease/ParsePreRelease.py | Python | bsd-3-clause | 2,942 | 0.003399 | __author__ = 'robswift'
import sys
from collections import defaultdict
from filtering_sets import do_not_call
from BlastNFilter.Blast.Target import Target
def add_ligands(non_polymer):
"""
Remove undesirable residues from the non_polymer_file, and return a list of target objects.
:param non_polymer: absol... | )
target_list.append(target)
return target_list
def add_sequences(polymer, target_list):
# target_list will be populated if the weekly release contains docking competent ligands. If the list is not
# populated, then print an error and exit with error code 1
if not target_list:
prin... | t call filter\"'
sys.exit(1)
else:
file_handle = open(polymer,'r')
target_ids = set([x.get_pdb_id() for x in target_list])
for line in file_handle.readlines()[1:]:
words = line.split()
try:
pdb_id = words[0].lower()
chain_id = ... |
ritviksahajpal/pygeoutil | doc/conf.py | Python | mit | 10,031 | 0.005882 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pygeoutil documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 14 10:29:06 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# ... | ch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base n... | -------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. Li... |
NeCTAR-RC/cinder | cinder/api/v1/snapshots.py | Python | apache-2.0 | 8,175 | 0.000245 | # Copyright 2011 Justin Santa Barbara
# 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 requ... | metadata'),
dict):
d['metada | ta'] = snapshot['metadata']
else:
d['metadata'] = {}
return d
def make_snapshot(elem):
elem.set('id')
elem.set('status')
elem.set('size')
elem.set('created_at')
elem.set('display_name')
elem.set('display_description')
elem.set('volume_id')
elem.append(common.MetadataTem... |
NAMD/pypln.backend | pypln/backend/workers/tokenizer.py | Python | gpl-3.0 | 1,108 | 0.000903 | # coding: utf-8
#
# Copyright 2012 NAMD-EMAP-FGV
#
# This file is part of PyPLN. You can get more information at: http://pypln.org/.
#
# PyPLN 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 o... | from n | ltk import word_tokenize, sent_tokenize
from pypln.backend.celery_task import PyPLNTask
class Tokenizer(PyPLNTask):
def process(self, document):
text = document['text']
tokens = word_tokenize(text)
sentences = [word_tokenize(sent) for sent in sent_tokenize(text)]
return {'tokens'... |
ndokos/pbench | lib/pbench/test/unit/common/test_config.py | Python | gpl-3.0 | 2,638 | 0.001137 | """Test PbenchConfig class and objects
"""
import pytest
from pathlib import Path
from pbench import PbenchConfig
from pbench.common.exceptions import BadConfig
_config_path_prefix = Path("lib/pbench/test/unit/common/config")
class TestPbenchConfig:
def test_empty_config(self):
config = PbenchConfig(... | assert "43" == config.get(
"other", "barfoo"
), "Failed to fetch 'barfoo' from 'other' section"
assert isinstance(
config.files, list
| ), f"Unexpected object class for 'files', {config.files.__class__!r}"
def test_log_dir_provided(self):
config = PbenchConfig(_config_path_prefix / "logdir.cfg")
assert (
config.log_dir == "/srv/log/directory"
), f"Unexpected log directory, {config.log_dir!r}"
def te... |
pcmagic/stokes_flow | ecoli_in_pipe/tail_U.py | Python | mit | 9,601 | 0.002916 | # coding=utf-8
# 1. generate velocity and force nodes of sphere using MATLAB,
# 2. for each force node, get b, solve surrounding velocity boundary condition (pipe and cover, named boundary velocity) using formula from Liron's paper, save .mat file
# 3. read .mat file, for each boundary velocity, solve associated bounda... | ('%s_rota' % fileHandle, pick_M=False, mat_destroy=False)
print_single_ecoli_force_result(problem, part='tail', prefix='rota', **problem_kwargs)
problem.vtk_self('%s_rota' % fileHandle)
if save_vtk:
problem.vtk_velocity('%s_rota' % fileHandle)
return True
def self_rotate_tail(*... | s):
OptDB = PETSc.Options()
fileHandle = OptDB.getString('f', 'tail_U')
OptDB.setValue('f', fileHandle)
main_kwargs['fileHandle'] = fileHandle
field_range = np.array([[-3, -3, -3], [3, 3, 3]])
n_grid = np.array([1, 1, 1]) * OptDB.getInt('n_grid', 10)
main_kwargs['field_range'] = field_range
... |
zerolab/wagtail | wagtail/contrib/simple_translation/__init__.py | Python | bsd-3-clause | 233 | 0 | import djang | o
if django.VERSION >= (3, 2):
# The declaration is only needed for older Django versions
pass
else:
default_app_config = (
"wagtail.cont | rib.simple_translation.apps.SimpleTranslationAppConfig"
)
|
giosch/jarvis | transcribe.py | Python | gpl-3.0 | 2,358 | 0.004665 | #!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | uri."""
from google.cloud import speech
speech_client = speech.Client()
audio_sample = speech_client.sample(
content=None,
source_uri=gcs_uri,
encodi | ng='FLAC',
sample_rate_hertz=16000)
alternatives = audio_sample.recognize('it')
for alternative in alternatives:
print('Transcript: {}'.format(alternative.transcript))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argpars... |
lipis/life-line | run.py | Python | mit | 12,739 | 0.008556 | #!/usr/bin/env python
# coding: utf-8
from datetime import datetime
from distutils import spawn
import argparse
import json
import os
import platform
import shutil
import socket
import sys
import urllib
import urllib2
import main
from main import config
##############################################################... | L = 'https://www.google.com'
REQUIREMENTS_URL = 'http://docs.gae-init.appspot. | com/requirement/'
###############################################################################
# Helpers
###############################################################################
def print_out(script, filename=''):
timestamp = datetime.now().strftime('%H:%M:%S')
if not filename:
filename = '-' * 46
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.