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 |
|---|---|---|---|---|---|---|---|---|
nitely/Spirit | spirit/comment/like/tags.py | Python | mit | 306 | 0 | # -*- coding: utf-8 -*-
from ...core.tags.registry import register
from .forms import LikeForm
@register.inclusion_tag('spirit/comment/like/_form.html')
def render_like_form(comme | nt, l | ike, next=None):
form = LikeForm()
return {'form': form, 'comment_id': comment.pk, 'like': like, 'next': next}
|
lyarwood/virt-deploy | virtdeploy/drivers/libvirt.py | Python | gpl-2.0 | 12,400 | 0 | #
# Copyright 2015 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... |
execute(('qemu-img', 'create', '-f', 'qcow2', '-b', base, image),
cwd=repository)
hostname = 'vm-{0}'.format(vmid)
| domainname = _get_network_domainname(net)
if domainname is None:
fqdn = hostname
else:
fqdn = '{0}.{1}'.format(hostname, domainname)
if kwargs['password'] is None:
kwargs['password'] = random_password()
password_string = 'password:{0}'.format(kwar... |
iulian787/spack | var/spack/repos/builtin/packages/perl-devel-globaldestruction/package.py | Python | lgpl-2.1 | 641 | 0.00624 | # Copyright 2013-2020 Lawrence Livermore National Security, | LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PerlDevelGlobaldestruction(PerlPackage):
"""Makes Perl's global destruction less tricky to deal with"""
homepage = "http://search.cpan.org/~haarg... | Destruction-0.14.tar.gz"
version('0.14', sha256='34b8a5f29991311468fe6913cadaba75fd5d2b0b3ee3bb41fe5b53efab9154ab')
|
SouthForkResearch/CHaMP_Metrics | tools/auxmetrics/metriclib/coverMetrics.py | Python | gpl-3.0 | 9,707 | 0.003709 | from lib.loghelper import Logger
import numpy as np
def visitCoverMetrics(visitMetrics, visitobj):
visit = vi | sitobj['visit']
riparianStructures = visitobj['riparianStructures']
percentBigTreeCover(visitMetrics, riparianStructures)
percentCanopyNoCover(visitMetrics, riparianStructures)
percentGroundCover(visitMetrics, riparianStructures)
percentGroundCoverNoCover(visitMetrics, riparianStructures)
perce... | rcentConiferousCover(visitMetrics, visit, riparianStructures)
def percentConiferousCover(visitMetrics, visit, riparianStructures):
if visit["iterationID"] == 1:
visitMetrics["PercentConiferousCover"] = getConiferousScore2011(riparianStructures)
else:
visitMetrics["PercentConiferousCover"] = ge... |
jimi-c/ansible | contrib/inventory/ec2.py | Python | gpl-3.0 | 72,916 | 0.002373 | #!/usr/bin/env python
'''
EC2 external inventory script
=================================
Generates inventory that Ansible can understand by making API request to
AWS EC2 using the Boto library.
NOTE: This script assumes Ansible is being executed where the environment
variables needed for Boto have already been set:... | ec2_security_group_ids
- ec2_security_group_names
- ec2_shutdown_state
- ec2_sourceDestCheck
- ec2_spot_instance_request_id
- ec2_state
- ec2_state_code
- ec2_state_reason
- ec2_status
- ec2_subnet_id
- ec2_tenancy
- ec2_virtualization_ty | pe
- ec2_vpc_id
These variables are pulled out of a boto.ec2.instance object. There is a lack of
consistency with variable spellings (camelCase and underscores) since this
just loops through all variables the object exposes. It is preferred to use the
ones with underscores when multiple exist.
In addition, if an ins... |
meteoswiss-mdr/precipattractor | pymodules/time_tools_attractor.py | Python | gpl-3.0 | 12,112 | 0.011311 | #!/usr/bin/env python
'''
Module to perform various time operations.
Documentation convention from https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
07.07.2016
Loris Foresti
'''
from __future__ import division
from __future__ import print_function
import datetime
import numpy as np... | Get Julian day from datetime object.
Parameters
----------
timeDate : datetime
Datetime object
Returns
-------
julianDay: int
Julian day
'''
julianDay = timeDate.timetuple().tm_yday
return(julianDay)
def parse_datetime(timeDate):
'''... | me object
Returns
-------
year: int
Year
yearStr: str
Year string in YY
julianDay: int
Julian day
julianDayStr: str
Julian day string JJJ
'''
year = timeDate.year
yearStr = str(year)[2:4]
julianDay = get_julianday(timeDate)
... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/pandas/tests/test_rplot.py | Python | artistic-2.0 | 11,560 | 0.001298 | # -*- coding: utf-8 -*-
from pandas.compat import range
import pandas.util.testing as tm
from pandas import read_csv
import os
import nose
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
import pandas.tools.rplot as rplot
def curpath():
pth, _ = os.path.split(os.path.abspath(__file__))... | r2)
self.assertTrue(isinstance(layer2.aes['size'], rplot.ScaleSize))
self.assertTrue(isinstance(layer2.aes['shape'], rplot.ScaleShape))
self.assertEqual(layer2.aes['size'], layer1.aes['size'])
for key in layer2.aes.keys():
if key != 'size' and key != 'shape':
... | palWidth',
size=rplot.ScaleSize('PetalLength'))
layer3 = rplot.GeomPolyFit(2)
result = rplot.sequence_layers([layer1, layer2, layer3])
self.assertEqual(len(result), 3)
last = result[-1]
self.assertEqual(last.aes['x'], 'SepalLength')
self.a... |
mvs-live/metaverse | test/test-rpc-v3/TestCase/Account/batch_account.py | Python | agpl-3.0 | 2,352 | 0.006378 | from utils import common, database
from TestCase.MVSTestCase import *
class TestAccount(MVSTestCaseBase):
roles = ()
need_mine = False
def test_0_new_account(self):
'''create new account * 5000'''
account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username()
... | 0, message)
def test_1_new_address(self): |
'''new address for Zac'''
max_duration = 0.01
avg_duration = 0.002
round = 5000
Zac.create()
account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username()
try:
origin_payload_size = database.get_payload_size(account_table... |
ubiquitypress/rua | src/submission/logic.py | Python | gpl-2.0 | 2,061 | 0 | from django.core.exceptions import PermissionDenied
from core.models import Author, Editor
def copy_author_to_submission(user, book):
author = Author(
first_name=user.first_name,
middle_name=user.profile.middle_name,
last_name=user.last_name,
salutation=user.profile.salutation,
... | ()
book.author.add(author)
return author
def copy_editor_to_submission(user, book):
editor = Editor(
first_name=user.first_name,
middle_name=user.profile.middle_name,
last_name=user.last_name,
salutation=user.profile.salutation,
institution=user.profile.institution... | ment=user.profile.department,
country=user.profile.country,
author_email=user.email,
biography=user.profile.biography,
orcid=user.profile.orcid,
twitter=user.profile.twitter,
linkedin=user.profile.linkedin,
facebook=user.profile.facebook,
)
editor.save()
... |
hubert667/AIR | build/scripts-2.7/learning-experiment.py | Python | gpl-3.0 | 860 | 0.002326 | #!/usr/bin/python
# This file is part of L | erot.
#
# Lerot is free software: you can redistribute it and/or modify
# it under the ter | ms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Lerot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS... |
geopython/pywps | pywps/processing/job.py | Python | mit | 4,609 | 0.001519 | ##################################################################
# Copyright 2018 Open Source Geospatial Foundation and others #
# licensed under MIT, Please consult LICENSE.txt for details #
##################################################################
import os
import tempfile
import pywps.configuratio... | ocess, wps_request, wps_response):
self.process = process
self.method = '_run_process'
self.wps_request = wps_request
self.wps_response = wps_response
@property
def name(self):
return self.process.identifier
@property
def workdir(self):
return self.proce... |
return self.process.uuid
@property
def json(self):
"""Return JSON encoded representation of the request
"""
obj = {
'process': self.process.json,
'wps_request': self.wps_request.json,
}
return json.dumps(obj, allow_nan=False)
@class... |
bsmithyman/galoshes | setup.py | Python | mit | 1,497 | 0.032732 | '''Galoshes
'''
from distutils.core import setup
from setuptools import find_packages
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Topic :: Scientific/Engineer... | install_requires = ['numpy>=1.7',
'future',
],
author = 'Brendan Smithyman',
author_email = 'brendan@bitsmithy.net',
description = 'galoshes',
long_description = LONG_DESCRIPTION,
lic | ense = 'MIT',
keywords = 'dictionary class attribute',
url = 'https://github.com/bsmithyman/galoshes',
download_url = 'https://github.com/bsmithyman/galoshes',
classifiers = CLASSIFIERS,
platforms = ['Windows', 'Linux', 'Solaris', 'Mac OS-X', 'Unix'],
use_2to3 = False,
)
|
seagatesoft/dateparser | tests/test_languages.py | Python | bsd-3-clause | 18,881 | 0.0024 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from nose_parameterized import parameterized, param
from dateparser.languages import default_language_loader, Language
from dateparser.languages.detection import AutoDetectLanguage, ExactLanguages
from tests import BaseTestCase
class TestBundledLanguag... | param('ar', "منذ 2 ساعات", "ago 2 hour"),
param('ar', "منذ ساعتين", "ago 2 hour"),
# Polish
param('pl', "2 godz.", "2 hour"),
param('pl', "Wczoraj o 07:40", "1 day 07:40"),
param('pl', "Poniedziałek 8:10 pm", "monday 8:10 pm"),
# Vietnamese
param(' | vi', "2 tuần 3 ngày", "2 week 3 day"),
param('vi', "21 giờ trước", "21 hour ago"),
param('vi', "Hôm qua 08:16", "1 day 08:16"),
param('vi', "Hôm nay 15:39", "0 day 15:39"),
#French
param('fr', u"Il y a moins d'une minute", "ago 1 minute"),
param('fr', u"Il y a moins de 30... |
haxwithaxe/ddp | examples/xrproxy_server.py | Python | bsd-3-clause | 11,364 | 0.027455 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#########################################################################
# Copyright/License Notice (BSD License) #
#########################################################################
###################################################... | T OF THE USE #
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #
#########################################################################
from danlog import DanLo | g
from ddp import *
import os
import pickle
import sys
import xmlrpclib
from xml.dom import minidom
###########
# Globals #
###########
client_callsign = ""
log = DanLog("XRProxyServer")
#############
# Constants #
#############
ALLOW_UNSIGNED_PACKETS = False
BACKEND_DATAMODE = "PSK500R"
BACKEND_HOSTNAME = "local... |
qedi-r/home-assistant | homeassistant/components/conversation/agent.py | Python | apache-2.0 | 714 | 0 | """Agent foundation for conversation integration."""
from abc import ABC, abstractmethod
from typing import Optional
from homeassistant.helpers import intent
class AbstractConversationAgent(ABC):
"""Abstract conversation agent."""
@property
def attribution(self):
"""Return the attributio | n."""
return None
async def async_get_onboarding(self):
"""Get onboard data."""
return None
async def async_set_onboarding(self, shown):
"""Set onboard data."""
return True
@abstractmethod
async def async_process(
self, text: str, conversation_id: Optio... | nse:
"""Process a sentence."""
|
smmribeiro/intellij-community | python/testData/quickFixes/PyRemoveUnusedLocalQuickFixTest/withOneTarget_after.py | Python | apache-2.0 | 56 | 0.017857 | def main():
| with open('file.txt'):
pri | nt(42) |
rdthomson/set09103 | src/LPHW/ex5.py | Python | gpl-3.0 | 596 | 0.008389 | my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # Inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_tee | th = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy"
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His t | eeth are usually %s depending on the coffee." % my_teeth
# this line is tricky, try to get it exactly right
print" If I add %d, %d and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
|
rfhk/awo-custom | sale_line_quant_extended/models/stock_move.py | Python | lgpl-3.0 | 10,584 | 0.005574 | # -*- coding: utf-8 -*-
# Copyright 2015-2017 Quartile Limted
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api, _
class StockMove(models.Model):
_inherit = "stock.move"
pick_partner_id = fields.Many2one(
related='picking_id.partner_id',
... | ' + name
res.append((line.id, name))
return res
@api.multi
@api.depends('quant_ids', 'reserved_quant_ids', 'lot_id')
def _g | et_quant_info(self):
for m in self:
if m.quant_ids:
m.quant_lot_id = m.quant_ids[0].lot_id and \
m.quant_ids[0].lot_id.id
m.quant_owner_id = m.quant_ids[0].owner_id and \
m.quant_ids[0].owner_id.id
elif m.reserved_qu... |
oblique-labs/pyVM | rpython/translator/backendopt/escape.py | Python | mit | 12,552 | 0.001514 | from rpython.flowspace.model import Variable
from rpython.rtyper.lltypesystem import lltype
from rpython.translator.simplify import get_graph
from rpython.tool.uid import uid
class CreationPoint(object):
def __init__(self, creation_method, TYPE, op=None):
self.escapes = False
self.returns = False
... | onst, Variable):
varstate = VarState()
else:
| if var_or_const not in self.constant_cps:
crep = CreationPoint("constant", var_or_const.concretetype)
self.constant_cps[var_or_const] = crep
else:
crep = self.constant_cps[var_or_const]
varstate = VarState(crep)
self.varstates[v... |
stbenjam/katello-agent | src/setup.py | Python | gpl-2.0 | 1,603 | 0.001871 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU Lesser General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (LGPLv2) or (at your option) any later version.
# There is NO WARRANTY for thi... | ted version of python')
requires = [
]
setup(
name='katello-agent',
version='0.1',
description='Katello Agent',
author='Jeff Ortel',
author_email='jortel@redhat.com',
url='',
license='GPLv2+',
packages=find_packages(),
scripts = [
],
include_package_data=False,
data_fil... | opic :: Content Management and Delivery',
'Topic :: Software Development :: Libraries :: Python Modules',
'Intended Audience :: Developers',
'Development Status :: 3 - Alpha',
],
install_requires=requires,
)
|
satish-suradkar/pyresttest | pyresttest/testapp/testapp/urls.py | Python | apache-2.0 | 535 | 0 | from django.conf.urls import patterns, include, url
from testapp.api import PersonResource
from django.contrib | import admin
admin.autodiscover()
person_resource = PersonResource()
urlpatterns = patterns('',
| # Examples:
# url(r'^$', 'testapp.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
(r'^api/', include(person_resource.urls))
)
|
oseemann/cvsreview | app/urls.py | Python | gpl-3.0 | 1,023 | 0.006843 | # vim:set tabstop=3 shiftwidth=3 expandtab:
# vim:set autoindent smarttab nowrap:
from django.conf.urls.defaults import *
import settings
urlpatterns = patterns('',
(r'^$', | 'webreview.views.index'),
(r'^skip/(?P<skip>.*)$', 'webreview.views.changes'),
(r'^diff/(?P<change_id>.*)/html$', 'webreview.views.diffhtml'),
(r'^addmodule$', 'webreview.views.addmodule'),
(r'^login$', 'webreview.views.login'),
... | 'webreview.views.index'),
(r'^changes/(?P<filter>.*)/(?P<filter_id>\d+)/skip/(?P<skip>\d*)$', 'webreview.views.changes'),
(r'^changes/(?P<filter>.*)/(?P<filter_id>\d+)$', 'webreview.views.changes'),
(r'^static/(?P<path>.*)$', 'django.views.static.se... |
adwiputra/LUMENS-repo | processing/r/RAlgorithm.py | Python | gpl-2.0 | 22,835 | 0.001927 | # -*- coding: utf-8 -*-
"""
***************************************************************************
RAlgorithm.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
****************************... | line.replace('#', '')
if line.lower().strip().startswith('report'):
| self.report = True
self.addOutput(OutputHTML(RAlgorithm.KNITR_REPORT, 'HTML Report'))
return
if line.lower().strip().startswith('showplots'):
self.showPlots = True
self.addOutput(OutputHTML(RAlgorithm.RPLOTS, 'R Plots'))
return
if line.low... |
qiyuangong/leetcode | python/422_Valid_Word_Square.py | Python | mit | 805 | 0.001242 | class Solution(object):
def validWordSquare(self, words):
"""
:t | ype words: List[str]
:rtype: bool
"""
if words is None or len(words) == 0:
return True
ls = len(words)
for i in range(ls):
for j in range(1, len(words[i])):
if j >= ls:
return False
if i >= len(words[j]):... | if words[i][j] != words[j][i]:
return False
return True
# def validWordSquare(self, words):
# # https://discuss.leetcode.com/topic/63423/1-liner-python/2
# # The map(None, ...) transposes the "matrix", filling missing spots with None
# return map(None, *words) =... |
yeti-platform/yeti | plugins/feeds/public/threatfox.py | Python | apache-2.0 | 2,925 | 0 | import logging
from datetime import timedelta
from core import Feed
import pandas as pd
from core.observables import Ip, Observable
from core.errors import ObservableValidationError
class ThreatFox(Feed):
default_values = {
"frequency": timedelta(hours=1),
"name": "ThreatFox",
"source": "... | level
value = None
obs = None
try:
if "ip" in ioc_type:
value, port = ioc_value.split(":")
context["port"] = port
obs = Ip.get_or_create(value=value)
else:
obs = Observable.add_text(ioc_value)
excep... | ng.error(e)
return
if obs:
obs.add_context(context)
obs.add_source(self.name)
if tags:
obs.tag(tags)
if malware_printable:
obs.tags
|
arlewis/arl_galbase | single_cutout_test_newmethod.py | Python | mit | 18,179 | 0.004951 | import astropy.io.fits as pyfits
import astropy.wcs as pywcs
import os, sys, time
import numpy as np
from pdb import set_trace
import montage_wrapper as montage
import shutil
import gal_data
import config
import glob
from scipy.ndimage.interpolation import zoom
#_TOP_DIR = '/data/tycho/0/leroy.42/allsky/'
#_INDEX_DIR... | :
im = counts2jy_galex(im, nuv_toab, pix_as)
if not os.path.exists(int_outfiles[i]):
# | im -= np.mean(im)
pyfits.writeto(int_outfiles[i], im, hdr)
if not os.path.exists(wt_outfiles[i]):
pyfits.writeto(wt_outfiles[i], wt, whdr)
else:
continue
return converted_dir, converted_dir
def counts2jy_galex(counts, cal, pix_as):
# first con... |
john-wang-metro/metro-openerp | bug_fix/ir_mail_server.py | Python | agpl-3.0 | 25,985 | 0.005118 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2011-2012 OpenERP S.A (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | return header_text_ascii if header_text_ascii\
else Header(header_text_utf8, 'utf-8')
def encode_header_param(param_text):
"""Returns | an appropriate RFC2047 encoded representation of the given
header parameter value, suitable for direct assignation as the
param value (e.g. via Message.set_param() or Message.add_header())
RFC2822 assumes that headers contain only 7-bit characters,
so we ensure it is the case, using RFC2047... |
ruchee/vimrc | vimfiles/bundle/vim-python/submodules/pylint/tests/functional/s/stop_iteration_inside_generator.py | Python | mit | 3,242 | 0.005552 | """
Test that no StopIteration is raised inside a generator
"""
# pylint: disable=missing-docstring,invalid-name,import-error, try-except-raise, wrong-import-position,not-callable,raise-missing-from
import asyncio
class RebornStopIteration(StopIteration):
"""
A class inheriting from StopIteration exception
... | e():
# https://github.com/PyCQA/pylint/issues/1779
yield from iter()
raise asyncio.TimeoutError()
# https://github.com/PyCQA/pylint/issues/1830
def gen_next_with_sentinel():
yield next([], 42) # No bad return
from itertools import count
# https://github.com/PyCQA/pylint/issue | s/2158
def generator_using_next():
counter = count()
number = next(counter)
yield number * 2
# pylint: disable=no-self-use,too-few-public-methods
class SomeClassWithNext:
def next(self):
return iter([1, 2, 3])
def some_gen(self):
for value in self.next():
yield value
... |
SEA000/uw-empathica | empathica/gluon/contrib/pysimplesoap/server.py | Python | mit | 17,610 | 0.005849 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in t... | ix()
if DEBUG: print "dispatch method", name
function, returns_types, args_types, doc = self.methods[name]
# de-serialize parameters (if type definitions given)
if args_types:
args = method. | children().unmarshall(args_types)
elif args_types is None:
args = {'request':method} # send raw request
else:
args = {} # no parameters
soap_fault_code = 'Server'
# execute function
ret = function(**args)
if DEBUG: ... |
xesscorp/skidl | skidl/libs/analog_devices_sklib.py | Python | mit | 14,637 | 0.042768 | from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
analog_devices = SchLib(tool=SKIDL).add_parts(*[
Part(name='AD623AN',dest=TEMPLATE,tool=SKIDL,keywords='ad623 instumentation amplifier dip-8',description='Single Supply, Rail to Rail, Instumentation Amplifier, RoHS, DIP-8',ref_pr... | =Pin.PASSIVE,do_erc=True),
Pin(num='3',name='Rg',func=Pin.PASSIVE,do_erc=True),
Pin(num='4',name='+',do_erc=True),
Pin(num='5',name='Vs-',func=P | in.PWRIN,do_erc=True),
Pin(num='6',name='Ref',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='~',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='Vs+',func=Pin.PWRIN,do_erc=True)]),
Part(name='AD8422ARZ',dest=TEMPLATE,tool=SKIDL,keywords='ad8429 instumentation amplifier soic-... |
tchellomello/home-assistant | homeassistant/components/homematicip_cloud/climate.py | Python | apache-2.0 | 11,473 | 0.000697 | """Support for HomematicIP Cloud climate devices."""
import logging
from typing import Any, Dict, List, Optional, Union
from homematicip.aio.device import AsyncHeatingThermostat, AsyncHeatingThermostatCompact
from homematicip.aio.group import AsyncHeatingGroup
from homematicip.base.enums import AbsenceType
from homema... | return
if self._device.boostMode and preset_mode != PRESET_BOOST:
await self._device.set_boost(False)
if preset_mode == PRESET_BOOST:
await self._device.set_boost()
if preset_mode in self._devic | e_profile_names:
profile_idx = self._get_profile_idx_by_name(preset_mode)
if self._device.controlMode != HMIP_AUTOMATIC_CM:
await self.async_set_hvac_mode(HVAC_MODE_AUTO)
await self._device.set_active_profile(profile_idx)
@property
def |
VanyaDNDZ/django-sybase-backend | sqlsybase_server/pyodbc/compiler.py | Python | unlicense | 10,019 | 0.003394 | from django.db.models.sql import compiler
from datetime import datetime
import re
from django.db.models.base import Model
REV_ODIR = {
'ASC': 'DESC',
'DESC': 'ASC'
}
SQL_SERVER_8_LIMIT_QUERY = \
"""SELECT *
FROM (
SELECT TOP %(limit)s *
FROM (
%(orig_sql)s
ORDER BY %(ord)s
) AS %(table)s
ORDER... | ps.bulk_insert_sql(fields, len(values)))
return [(" ".join(resu | lt), tuple([v for val in values for v in val]))]
else:
return [
(" ".join(result + ["VALUES (%s)" % ", ".join(p)]), vals)
for p, vals in zip(placeholders, params)
]
class SQLDeleteCompiler(compiler.SQLDeleteCompiler, SQLCompiler):
pass
class SQLUpda... |
lorenyu/project-euler | problem-036.py | Python | mit | 813 | 0.00615 | problem = """
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base | 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zero | s.)
"""
def is_palindromic(s):
return s[:len(s)/2] == s[:(len(s)-1)/2:-1]
def decimal2binary(num):
x = ''
while num > 0:
x = str(num % 2) + x
num /= 2
return x
double_base_palindromes = set()
for num in range(1000):
p1 = int(str(num) + str(num)[-2::-1])
p2 = int(str(num) + st... |
suyashphadtare/vestasi-erp-1 | erpnext/erpnext/accounts/doctype/sales_invoice/pos.py | Python | agpl-3.0 | 1,595 | 0.022571 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
@frappe.whitelist()
def get_items(price_list, sales_or_purchase, item=None, item_group=None):
condition = ""
args = {"price_list": p... | db.sql("""select name, item_code from `tabSerial No` where
name=%s""", (barcode_serial_no), as_dict=1)
if not item_code:
input_via = "barcode"
item_code = frappe.db.sql("""select name from | `tabItem` where barcode=%s""",
(barcode_serial_no), as_dict=1)
if item_code:
return item_code, input_via
else:
frappe.throw(frappe._("Invalid Barcode or Serial No"))
@frappe.whitelist()
def get_mode_of_payment():
return frappe.get_list("Mode of Payment")
|
ecino/compassion-switzerland | sponsorship_switzerland/models/correspondence.py | Python | agpl-3.0 | 583 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) | 2019 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Samy Bucher <samy.bucher@outlook.com>
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import models
from odoo imp... | 'Gift')
|
undertherain/vsmlib | vsmlib/benchmarks/__main__.py | Python | apache-2.0 | 70 | 0 | fr | om .evaluate_all import main
if __name | __ == "__main__":
main()
|
plotly/plotly.py | packages/python/plotly/codegen/__init__.py | Python | mit | 11,939 | 0.00067 | import json
import os
import os.path as opath
import shutil
import subprocess
from codegen.datatypes import build_datatype_py, write_datatype_py
from codegen.compatibility import (
write_deprecated_datatypes,
write_graph_objs_graph_objs,
DEPRECATED_DATATYPES,
)
from codegen.figure import write_figure_class... | he
end of the array, so this can be used to add a watermark annotation or a
logo image, for example. To omit one of these items on the plot, make
an item with matching `templateitemname` and `visible: false`.""",
}
layout["template"] = template
# Renam | e concentrationscales to colorscale to match conventions
items = plotly_schema["traces"]["sankey"]["attributes"]["link"]["colorscales"][
"items"
]
if "concentrationscales" in items:
items["colorscale"] = items.pop("concentrationscales")
def perform_codegen():
# Set root codegen output... |
saltstack/salt | salt/states/grains.py | Python | apache-2.0 | 15,945 | 0.001568 | """
Manage grains on the minion
===========================
This state allows for grains to be set.
Grains set or altered with this module are stored in the 'grains'
file on the minions, By default, this file is located at: ``/etc/salt/grains``
.. note::
This does **NOT** override any grains set in the minion con... | if __opts__["test"]:
ret["result"] = None
if existing is _non_existent:
ret["comment"] = "Grain {} is set to be added".format(name)
| ret["changes"] = {"new": name}
else:
ret["comment"] = "Grain {} is set to be changed".format(name)
ret["changes"] = {"changed": {name: value}}
return ret
ret = __salt__["grains.set"](name, value, force=force)
if ret["result"] is True and ret["changes"] != {}:
... |
marrow/monitor.collector | marrow/monitor/collector/ext/load.py | Python | mit | 1,855 | 0.012412 | # encoding: utf-8
import os
import subprocess
import mongoengine as db
def generic_backend():
"""Allow Python to handle the details of load average discovery.
This is the fastest method, but may not be portable everywhere.
Testing on a Linux 2.6.35 Rackspace Cloud server: 17µsec.
"""
... | ition(': ')[2].strip().split(' ', 3)[:3]]
_map = {'generic': generic_backend, 'linux': linux_backend, 'posix': posix_backend, None: generic_backend}
class LoadMixIn(object):
load = db.ListField(db.FloatField, verbose_name="Load Average", default=list)
class | LoadExtension(object):
def __init__(self, config):
super(LoadExtension, self).__init__()
# TODO: Standard trifecta.
self.backend = _map[config.get('backend')]
@property
def mixin(self):
return LoadMixIn
def start(self):
pass
def stop(se... |
drfreemayn/ml-testing | sex-dice/GIFImage.py | Python | gpl-2.0 | 5,891 | 0.006451 | """GIFImage by Matthew Roe"""
import Image
import pygame
from pygame.locals import *
import time
class GIFImage(object):
def __init__(self, filename):
self.filename = filename
self.image = Image.open(filename)
self.frames = []
self.get_frames()
self.cur = 0
self.p... | lename)
new.running = self.running
new.breakpoint = self.breakpoint
new.startpoint = self.startpoint
new.cur = self.cur
new.ptime = self.ptime
new.reversed = self.reversed
return new
##def main():
## pygame.init()
## screen = pygame. | display.set_mode((640, 480))
##
## hulk = GIFImage("hulk.gif")
## football = GIFImage("football.gif")
## hulk2 = hulk.copy()
## hulk2.reverse()
## hulk3 = hulk.copy()
## hulk3.set_bounds(0, 2)
## spiderman = GIFImage("spiderman7.gif")
##
## while 1:
## for event in pygame.event.get():
## ... |
TonyJenkins/cfs2160-python | 04classes/Bank/bank_account.py | Python | unlicense | 1,282 | 0.0117 | #!/usr/bin/env python3
# bank_account.py
#
# Simple Bank Account class example.
#
# AMJ
# 2017-04-01
from random import randint
class BankAccount:
def __init__ (self, account_holder, has_overdraft):
self.account_number = self.generate_account_number ()
self.account_holder = account_holder
... | eactivate (self):
self.is_activ | e = False
def activate (self):
self.is_active = True
def generate_account_number (self):
s = ''
for i in range (9):
s += str (randint (0, 9))
return s
def __str__ (self):
return "Account: {:} Holder: {:} Balance: {:}".format (self.account_number, self.... |
pobear/django-xadmin | xadmin/util.py | Python | bsd-3-clause | 19,558 | 0.001534 | import django
from django.db import models
from django.db.models.sql.query import LOOKUP_SEP
from django.db.models.deletion import Collector
# from django.db.models.related import RelatedObject
from django.db.models.fields.related import ForeignObjectRel as RelatedObject
from django.forms.forms import pretty_name
from ... | uld also be deleted. ``objs``
must be a homogenous iterable of objects (e.g. a QuerySet).
Returns a nested list of strings suitable for display in the
template with the ``unordered_list`` filter.
"""
collector = NestedObjects(using=using)
collector.collect(objs)
perms_needed = set()
d... | at_callback(obj):
has_admin = obj.__class__ in admin_site._registry
opts = obj._meta
if has_admin:
admin_url = reverse('%s:%s_%s_change'
% (admin_site.name,
opts.app_label,
opts.obj... |
brchiu/tensorflow | tensorflow/python/ops/image_ops_test.py | Python | apache-2.0 | 165,524 | 0.007812 | # Copyright 2015 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... | ayscale_to_rgb(x_tf)
y_tf = self.evaluate(y)
self.assertAllEqual(y_tf, y_np)
# 3-D input with no batch dimension.
x_np = np.array([[1, 2]], dtype=np.uint8).reshape([1, 2, 1])
y_np = | np.array([[1, 1, 1], [2, 2, 2]], dtype=np.uint8).reshape([1, 2, 3])
with self.test_session(use_gpu=True):
x_tf = constant_op.constant(x_np, shape=x_np.shape)
y = image_ops.grayscale_to_rgb(x_tf)
y_tf = self.evaluate(y)
self.assertAllEqual(y_tf, y_np)
def testShapeInference(self):
# S... |
endlessm/chromium-browser | third_party/catapult/dashboard/dashboard/pinpoint/models/evaluators/job_serializer.py | Python | bsd-3-clause | 10,578 | 0.005105 | # Copyright 2019 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.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import itertools
from dashboard.pinpoint.model... | tasks import performance_bisection
from dashboard.pinpoint.models.tasks import read_value
from dashboard.pinpoint.models.tasks import run_test
class Serializer(evaluators.DispatchByTaskType):
"""Serializes a task graph asso | ciated with a job.
This Serializer follows the same API contract of an Evaluator, which applies
specific transformations based on the type of a task in the graph.
The end state of the context argument is a mapping with the following schema:
{
'comparison_mode': <string>
'metric': <string>
... |
yotchang4s/cafebabepy | src/main/python/idlelib/outwin.py | Python | bsd-3-clause | 4,385 | 0.000456 | import re
from tkinter import *
import tkinter.messagebox as tkMessageBox
from idlelib.editor import EditorWindow
from idlelib import iomenu
class OutputWindow(EditorWindow):
"""An editor window that can serve as an output file.
Also the future base class for the Python shell window.
This class has no... | tomize EditorWindow
def ispythonsource(self, filename):
# No colorization needed
return 0
def short_title(self):
return "Output"
def maybesave(self):
# Override base class method -- don't ask any questions
if self.get_saved():
return "yes"
else:... | return "no"
# Act as output file
def write(self, s, tags=(), mark="insert"):
if isinstance(s, (bytes, bytes)):
s = s.decode(iomenu.encoding, "replace")
self.text.insert(mark, s, tags)
self.text.see(mark)
self.text.update()
return len(s)
def wr... |
sunlightlabs/openstates | scrapers/nc/__init__.py | Python | gpl-3.0 | 12,386 | 0.000242 | import lxml
from utils import State
from .people import NCPersonScraper
from .bills import NCBillScraper
# from .committees import NCCommitteeScraper
class NorthCarolina(State):
scrapers = {
"people": NCPersonScraper,
# 'committees': NCCommitteeScraper,
"bills": NCBillScraper,
}
l... | 11",
},
{
"_scraped_name": "2008 Extra Session",
"classification": "special",
"identifier": "2007E2",
"name": "2008 | Extra Session",
"start_date": "2008-03-20",
"end_date": "2008-03-20",
},
{
"_scraped_name": "2009-2010 Session",
"classification": "primary",
"identifier": "2009",
"name": "2009-2010 Session",
|
RRCKI/panda-server | pandaserver/brokerage/broker_util.py | Python | apache-2.0 | 16,126 | 0.014015 | import re
import urllib
import time
import sys
import types
import datetime
import commands
import xml.dom.minidom
from config import panda_config
from pandalogger.LogWrapper import LogWrapper
from pandalogger.PandaLogger import PandaLogger
_log = PandaLogger().getLogger('broker_util')
# curl class
class _Curl:
... | es)
# append LFNs
if res | != None and len(res) != 0:
for resLFN in res:
outStr += '%s ' % resLFN
# close cursor
dbCur.close()
# close connection
dbConn.close()
except:
type, value, traceBack = sys.exc_info()
_log.error("_getPFNFromMySQL : %s %s %s" ... |
ellisonbg/altair | tools/generate_schema_wrapper.py | Python | bsd-3-clause | 18,648 | 0.001448 | """Generate a schema wrapper from a schema"""
import copy
import os
import sys
import json
from os.path import abspath, join, dirname
import textwrap
from urllib import request
import m2r
# import schemapi from here
sys.path.insert(0, abspath(dirname(__file__)))
from schemapi import codegen
from schemapi.codegen imp... | ion]
return SCHEMA_URL_TEMPLATE.format(library=library, version=version)
def download_schemafile(library, version, schemapath):
url = schema_url(library, version)
filename = os.path.join(schemapath, '{lib | rary}-schema.json'.format(library=library))
request.urlretrieve(url, filename)
return filename
def copy_schemapi_util():
"""
Copy the schemapi utility and its test file into altair/utils/
"""
# copy the schemapi utility file
source_path = abspath(join(dirname(__file__), 'schemapi', 'schema... |
EEEManchester/Food-Computer | Software/MQTT Test GUI/MQTT_GUI/main.py | Python | mit | 7,742 | 0.005425 | from MQTT_UI import Ui_MainWindow #Generated by Qt Designer
from PyQt4 import QtCore, QtGui #for gui
import paho.mqtt.client as mqtt #for mqtt
import sys #for exit
class StartQT4(QtGui.QMainWindow):
client1 = mqtt.Client() #for raspberry pi
client2 = mqtt.Client() #for simple mqtt test
def __init__(self, ... | lish(str(self.ui.lineEdit_3.text()), 'D')
def pushButton_5(self):
self.client1.publish(str(self.ui.lineEdit_3.text()), 'E')
def pushButton_6(self):
self.client1.publish(str(self.ui.lineEdit_3.text()), 'F')
def pushButton_7(self):
self.client1.publish(str(self.ui.lineEdit_3.text())... | self.ui.lineEdit_3.text()), 'I')
def pushButton_10(self):
self.client1.publish(str(self.ui.lineEdit_3.text()), 'J')
def pushButton_11(self):
self.client1.publish(str(self.ui.lineEdit_3.text()), 'K')
def pushButton_12(self):
self.client1.publish(str(self.ui.lineEdit_3.text()), 'L')... |
danielpronych/pyramid-doxygen | pyramid/tests/test_util.py | Python | bsd-2-clause | 21,474 | 0.001537 | import unittest
from pyramid.compat import PY3
class Test_InstancePropertyMixin(unittest.TestCase):
def _makeOne(self):
cls = self._getTargetClass()
class Foo(cls):
pass
return Foo()
def _getTargetClass(self):
from pyramid.util import InstancePropertyMixin
r... | elf):
wos = self._makeOne()
reg = Dummy()
wos.add(reg)
self.assertEqual(list(wos), [reg])
self.assertTrue(reg in wos)
self.assertEqual(wos.last, reg)
def test_add_multiple_items(se | lf):
wos = self._makeOne()
reg1 = Dummy()
reg2 = Dummy()
wos.add(reg1)
wos.add(reg2)
self.assertEqual(len(wos), 2)
self.assertEqual(list(wos), [reg1, reg2])
self.assertTrue(reg1 in wos)
self.assertTrue(reg2 in wos)
self.assertEqual(wos.last... |
vladikoff/fxa-mochitest | tests/config/mozharness/marionette.py | Python | mpl-2.0 | 2,925 | 0.000342 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
config = {
"suite_definitions": {
"gaiatest_desktop": {
"options": [
"--restart"... | "run_filename": "",
"testsdir": ""
},
"marionette_emulator": {
"options": [
"--type=%(type)s",
"--log-raw=%(raw_log_file)s",
"--logcat-dir=%(logcat_dir)s",
"--emulator=% | (emulator)s",
"--homedir=%(homedir)s",
"--symbols-path=%(symbols_path)s"
],
"run_filename": "",
"testsdir": ""
},
"webapi_desktop": {
"options": [],
"run_filename": "",
"testsdir": ""
},
... |
ncharles/ncf | tools/ncf.py | Python | gpl-3.0 | 6,835 | 0.016971 | # This is a Python module containing functions to parse and analyze ncf components
# This module is designed to run on the latest major versions of the most popular
# server OSes (Debian, Red Hat/CentOS, Ubuntu, SLES, ...)
# At the time of writing (November 2013) these are Debian 7, Red Hat/CentOS 6,
# Ubuntu 12.04 LT... | # Sanity check: if more than one bundle, this is a weird file and I'm quitting
bundle_count = 0
for bundle in promises['bundles']:
if bundle['bundleType'] == "agent":
bundle_count += 1
if bundle_count > 1:
raise Exception("There is not exactly one bundle in this file, aborting")
# Sanity check... | promises['bundles'][0]['bundleType'] != 'agent':
raise Exception("This bundle if not a bundle agent, aborting")
methods_promises = [promiseType for promiseType in promises['bundles'][0]['promiseTypes'] if promiseType['name']=="methods"]
methods = []
if len(methods_promises) >= 1:
methods = methods_promis... |
palindromed/data-structures2 | src/doubly_linked.py | Python | mit | 4,501 | 0 | # _*_ encoding: utf-8 _*_
"""Demonstrate doubly-linked list in python."""
from linked_list import Node
class DoublyLinked(object):
"""Implement a doubly-linked list from a singly-linked list."""
def __init__(self, val=None):
"""Initialize the list."""
self.head = object()
self._mark =... | ibuteError:
raise IndexError
return cur.get_data()
def remove(self, value):
"""Remove the first occurrence of value in the list."""
previous_node = None
current_node = self.head
while current_node.get_data() is not value:
previous_node = curre... | if current_node.get_data() is None:
break
if current_node.get_data() == value:
previous_node.set_next(current_node.get_next())
else:
print('Not Found')
class DoubleNode(object):
"""Double Node constructor for doubly linked list."""
def __init__(self, d... |
jtwhite79/pyemu | pyemu/mat/__init__.py | Python | bsd-3-clause | 301 | 0.006645 | """Th | is module contains classes for handling matrices in a linear algebra setting.
The primary objects are the `Matrix` and `Cov`. These objects overload most numerical
operators to autoalign the elements based on row and column names."""
from .mat_handler import Matrix, Cov, Jco, concat, save_co | o
|
missyjcat/pythonexercises | basic/list1.py | Python | apache-2.0 | 3,070 | 0.011726 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic list exercises
# Fill in the code for the functions below. main() is already set ... | est(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
print
print 'front_x'
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
test(front_x(['ccc', 'bbb', 'aaa', '... | le', 'mix'])
print
print 'sort_last'
test(sort_last([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(sort_last([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
if __name__ == ... |
TargetHolding/pyspark-cassandra | python/pyspark_cassandra/streaming.py | Python | apache-2.0 | 2,902 | 0.002757 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
| # You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in | writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pyspark_cassandra.util import as_java_object, as_... |
angadpc/Alexa-Project- | twilio/rest/api/v2010/account/message/feedback.py | Python | mit | 5,676 | 0.001409 | # coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page i... | operty
def date_created(self):
"""
:returns: The date_created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date_updated
:rtype | : datetime
"""
return self._properties['date_updated']
@property
def uri(self):
"""
:returns: The uri
:rtype: unicode
"""
return self._properties['uri']
def __repr__(self):
"""
Provide a friendly representation
:returns: Mach... |
macosforge/ccs-calendarserver | twistedcaldav/datafilters/filter.py | Python | apache-2.0 | 3,318 | 0.000603 | ##
# Copyright (c) 2009-2017 Apple 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 by applicable l... | "
Merge the old iCalendar object into the new iCalendar data using the request information.
@param icalnew: new iCalendar object to merge data into
@type icalnew: L{Component}
@param icalold: old iCalendar data to merge data from
@type icalold: L{Component}
"""
r... | ndar(self, ical):
# If we were passed a string, parse it out as a Component
if isinstance(ical, str):
try:
ical = iComponent.fromString(ical)
except ValueError:
raise ValueError("Not a calendar: %r" % (ical,))
if ical is None or ical.name... |
aikramer2/spaCy | spacy/lang/en/__init__.py | Python | mit | 1,389 | 0.00216 | # coding: utf8
from __future__ import unicode_literals
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .norm_exceptions import NORM_EXCEPTIONS
from .tag_map import TAG_MAP
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .morph_rules import MORPH_RULES
from .lemmatizer import LEMMA_... | iterators import SYNTAX_ITER | ATORS
from ..tokenizer_exceptions import BASE_EXCEPTIONS
from ..norm_exceptions import BASE_NORMS
from ...language import Language
from ...attrs import LANG, NORM
from ...util import update_exc, add_lookups
def _return_en(_):
return 'en'
class EnglishDefaults(Language.Defaults):
lex_attr_getters = dict(Langu... |
warvariuc/mykde | packages/__init__.py | Python | bsd-3-clause | 301 | 0 | import myk | de
class ActionPackage(mykde.ActionPackage):
author = 'Victor Varvaryuk <victor.varvariuc@gmail.com>'
version = 2
description = """
TODO:
xnview - unpack to ~/apps/ and create .desktop file in Graphics category
clip2net
galaxy icons libreoffice, enter ke | y behavior in calc
"""
|
eayunstack/python-neutronclient | neutronclient/neutron/v2_0/qos/bandwidth_limit_rule.py | Python | apache-2.0 | 3,455 | 0 | # Copyright 2015 Huawei Technologies India Pvt Ltd, 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
... | WIDTH_LIMIT_RULE_RESOURCE
def add_known_arguments(self, parser):
super(CreateQoSBandwidthLimitRule, self).add_known_arguments(parser)
add_bandwidth_limit_arguments(par | ser)
def args2body(self, parsed_args):
body = {}
update_bandwidth_limit_args2body(parsed_args, body)
return {self.resource: body}
class ListQoSBandwidthLimitRules(qos_rule.QosRuleMixin,
neutronv20.ListCommand):
"""List all qos bandwidth limit rules bel... |
rbaumg/trac | contrib/workflow/migrate_original_to_basic.py | Python | bsd-3-clause | 1,456 | 0.000687 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2019 Edgewall Software
# Copyright (C) 2007 Eli Carter <retracile@gmail.com>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also availab... |
trac_env.db_transaction("""
UP | DATE ticket SET status = 'accepted' WHERE status = 'assigned'
""")
if __name__ == '__main__':
main()
|
apache/incubator-allura | ForgeTracker/forgetracker/tests/unit/test_ticket_model.py | Python | apache-2.0 | 14,297 | 0.00028 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (t... | in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITH | OUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from pylons import tmpl_context as c
from datetime import datetime
import urllib2
from ming.orm.ormsession import ThreadLocal... |
lesscomplex/HomeSec | lock/buzz_anm.py | Python | agpl-3.0 | 2,986 | 0.081045 | import RPi.GPIO as GPIO
import time
buzzer_pin = 27
notes = {
'B0' : 31,
'C1' : 33, 'CS1' : 35,
'D1' : 37, 'DS1' : 39,
'EB1' : 39,
'E1' : 41,
'F1' : 44, 'FS1' : 46,
'G1' : 49, 'GS1' : 52,
'A1' : 55, 'AS1' : 58,
'BB1' : 58,
'B1' : 62,
'C2' : 65, 'CS2' : 69,
'D2' : 73, 'DS2' : 78,
'EB2' : 78,
'E2' : 82,
... | 5' : 932,
'B5' : 988,
'C6' : 1047, 'CS6' : 1109,
'D6' : 1175, 'DS6' : 1245,
'EB6' : 1245,
'E6' : 1319,
'F6' : 1397, 'FS6' : 1480,
'G6' : 1568, 'GS6' : 1661,
'A6' : 1760, 'AS6' : 1865,
'BB6' : 1865,
'B6' : 1976,
'C7' : 2093, 'CS7' : 2217,
'D7' : 2349, 'DS7' : 2489,
'EB7' : 2489,
'E7' : 2637,
'F7' : 2794, ... | ['F4'],notes['A4'],notes['G4'],notes['C4'],
]
anmeldung_tempo = [
0.25,0.25,0.25,0.35,
]
def buzz(frequency, length): #create the function "buzz" and feed it the pitch and duration)
if(frequency==0):
time.sleep(length)
return
period = 1.0 / frequency #in physics, the period (sec/cyc) is the inverse of th... |
danieltalsky/gp-code-test | books.py | Python | unlicense | 1,974 | 0.003546 | #!/usr/bin/env python
"""
books.py
reads a list of books from an input file and returns them filtered and sorted
features
- iterates through records without holding the entire dataset in memory, allowing for large datasets
- uses SQLite for storage and retrieval
"""
import os
import argparse
import sqlite3
f... | e,
help='show a subset of books, looks for the argument as a substring of any of the fields')
parser.add_argument('--year', action='store_true', default=False,
help="sort the books by year, ascending inst | ead of default sort")
parser.add_argument('--reverse', action='store_true', default=False,
help='reverse sort')
args = parser.parse_args()
# Read files and populate book list
sqlite3_connection = sqlite3.Connection(SQLITE3_DB_FILE);
book_list = BookList(sqlite3_connection)
for parse_type, file_path... |
mhbu50/erpnext | erpnext/portal/doctype/homepage/homepage.py | Python | gpl-3.0 | 801 | 0.021223 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe.website.utils import delete_page_cache
class Homepage(Document):
def validate(self):
if not self.description:
self.descrip... | ite': 1}, limit=3):
doc = frappe.get_doc('Item', d.name)
if not doc.route:
# set missing route
doc.save()
self.append('products', dic | t(item_code=d.name,
item_name=d.item_name, description=d.description, image=d.image))
|
QuantumQuadrate/CsPyController | python/exp_functional_waveforms/hybridChop.py | Python | lgpl-3.0 | 469 | 0.036247 | def choppedRO(t,period=2e-3,RO_onoff=[0,.5],Trap_onoff=[.5,1]):
'''
period: time in ms
RO_onoff: tuple containing [on,off] as a percentage of | period
Trap_onoff: tuple containing [on,off] as a | percentage of period
'''
D2_switch(t,0)
vODT_switch(t,0)
D2_switch(t+RO_onoff[0]*period,1)
D2_switch(t+RO_onoff[1]*period,0)
vODT_switch(t+Trap_onoff[0]*period,1)
vODT_switch(t+Trap_onoff[1]*period,0)
return t+period |
leecannon/trending | trending/count.py | Python | mit | 4,854 | 0.004738 | # Copyright (c) 2016 Lee Cannon
# Licensed under the MIT License, see included LICENSE File
from collections import Counter
from .filter import at_trigrams, with_words
def count_trigrams(interactions: list, minimum: int = 1, n: int = None, include_unknown: bool = False) -> list:
"""Returns the n most common trig... | _to_ignore: list=None) -> list:
"""Returns the n most common words in the interactions given.
:param interactions: The interactions to check.
:type interactions: list
:param min | imum: Ignore words that occur less than equal to minimum. Defaults to 1
:type minimum: int
:param n: The maximum number of words to return, defaults to None which returns all.
:type n: int
:param additional_words_to_ignore: List of additional words to ignore
:type additional_words_to_ignore: list
... |
Tepira/binwalk | src/binwalk/core/smart.py | Python | mit | 12,128 | 0.002803 | # "Smart" parser for handling libmagic signature results. Specifically, this implements
# support for binwalk's custom libmagic signature extensions (keyword tags, string processing,
# false positive detection, etc).
import re
import binwalk.core.module
from binwalk.core.compat import *
from binwalk.core.common import... | arg = ''
safe_data = self.safe_string(data)
| if tag.tag in safe_data:
arg = safe_data.split(tag.tag)[1].split(tag.TAG_DELIM_END)[0]
return (data, arg)
def get_math_arg(self, data, tag):
'''
Retrieves the argument for keywords that specifiy mathematical e |
ljx0305/ice | allTests.py | Python | gpl-2.0 | 476 | 0.006303 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included | in this distribution.
#
# ***************************** | *****************************************
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "scripts"))
from Util import runTests
runTests() |
huaiping/pandora | membership/urls.py | Python | mit | 324 | 0 | from django.conf.urls import url
from . import views
urlpa | tterns = [
url(r'^$', views.index, name='index'),
url(r'^login/$', views.login, name='login'),
url(r'^register/$', views.register, name='register'),
url(r'^logout/$', views.logout, name='logout'),
| url(r'^plaza/$', views.plaza, name='plaza'),
]
|
SkySchermer/uweclang | uweclang/plain/clean.py | Python | mit | 7,350 | 0.000954 | # -*- coding: utf-8 -*-
"""UWEC Language Tools student corpus module
Provides functions for processing student corpus data.
"""
# Python 3 forward compatability imports.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_liter... | rns the punctuation density of the given text.
Arguments:
text (str): The input text.
punctuation (str): A regex pattern for matching punctuation characters.
Defaults to r'[,.!?:;\\/]'.
Returns:
(float): The density of p | untuation in the text.
"""
if len(text) == 0:
return 0
words = re.sub(r'\W', ' ', text).split()
puncs = float(sum([len(re.findall(punctuation, x)) for x in text]))
return (puncs / len(words)) if len(words) > 0 else 0.0
def capitalization_density(text):
"""Returns the word-starting ca... |
yaybu/touchdown | touchdown/tests/fixtures/ssh_connection.py | Python | apache-2.0 | 2,710 | 0.000369 | # Copyright 2016 Isotoma Limited
#
# 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... | lass DummyServer(paramiko.ServerInterface):
def get_allowed_auths(self, username):
return "publickey,password"
def check_auth_password(self, username, password | ):
return paramiko.AUTH_SUCCESSFUL
def check_auth_publickey(self, username, key):
return paramiko.AUTH_SUCCESSFUL
def check_channel_request(self, kind, chanid):
return paramiko.OPEN_SUCCEEDED
def check_channel_exec_request(self, channel, command):
return True
def chec... |
flp9001/eveggie | config/settings/base.py | Python | mit | 10,190 | 0.001865 | """
Django settings for eveggie project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import environ
ROOT_DIR = environ.Path(__file__) - 3 # (eveggie/config/se... | s.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = str(APPS_DIR('media'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# URL Configuration
# -------------------- | ----------------------------------------------------------
ROOT_URLCONF = 'config.urls'
# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = 'config.wsgi.application'
# PASSWORD STORAGE SETTINGS
# ------------------------------------------------------------------------------
... |
shobhitmishra/CodingProblems | LeetCode/Session3/mincut.py | Python | mit | 600 | 0.005 | class Solution:
def minCut(self, s: str) -> int:
cut = [0] * (len(s) + 1)
cut[0] = -1
ispal = []
for _ in range(len(s)):
ispal.append([False] * len(s))
for i in range(len(s)):
mincut = i
for j in range(i+1):
# if i ... | if s[i] == s[j] and (i-j <= 2 or ispal[j+1][i-1]):
ispal[j][i] = True
mincut = min(mincut, cut[j] + 1)
cut[i+1] = mincut
return cut[-1]
ob = Solution()
s = "aabbaa"
print(ob.minCut(s)) | |
TxDOT/python | standalone/AdminPrefix_Resourcer_v1.py | Python | mit | 3,702 | 0.006753 |
#
#
#March 2014
#Adam Breznicky - TxDOT TPP - Mapping Group
#
#This is an independent script which requires a single parameter designating a directory.
#The script will walk through each subfol | der and file within the designated directory, identifying the MXD files
#and re-sourcing the Comanche database connections to utilize the new 'Admin' prefix
#
#
#
#
#import modules
import arcpy, os
#variables
directory = ""
def re_source_admin():
#issue list
issues = []
#walk through each directory
... | "\\")[-1]
dbsuffix = specDir.split(".")[-1]
if dbsuffix == "gdb" or dbsuffix == "mdb" or dbsuffix == "tbx":
pass
else:
for n in files:
#identify the mxds
if str(n).split(".")[-1] == "mxd":
print "working on: " + str(os.p... |
ajbouh/tfi | src/tfi/parse/docstring.py | Python | mit | 17,890 | 0.000671 | # -*- coding: utf-8 -*-
"""
sphinx.ext.napoleon.docstring
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Classes for docstring parsing and formatting.
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import collections
import inspect
import re
# from ... |
'todo': self._parse_generic_section,
} # type: Dict[unicode, Callable]
self._sections = {
name: value
for name, value in [*self._entry_sections.items(), *self._freeform_sections.items()]
}
self._parsed_dicts = {
name: []
for... |
def lines(self):
# type: () -> List[unicode]
"""Return the parsed lines of the docstring in reStructuredText format.
Returns
-------
list(str)
The lines of the docstring in a list.
"""
return self._parsed_lines
def result(self):
# ... |
EnduranceIndia/ratelimitd | Policies/SaslSenderDomainPolicy.py | Python | apache-2.0 | 3,282 | 0.004875 | """
Copyright 2015 Sai Gopal
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
dist... | ES OR | CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from Logger import Logger
from ProfileLookup import ProfileLookup
from RedisConn import RedisConn
class SaslSenderDomainPolicy:
"""
This class provides sasl... |
zygmuntz/numer.ai | validate_lr.py | Python | bsd-3-clause | 3,382 | 0.041987 | #!/usr/bin/env python
"Load data, create the validation split, optionally scale data, train a linear model, evaluate"
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import Normalizer, PolynomialFeatures
from sklearn.preprocessing import MaxAbsScaler, MinMaxScaler, StandardScaler... | .45%
StandardScaler(copy=True, with_mean=True, with_std=True)
AUC: 53.52%, accuracy: 52.42%
Normalizer(copy=True, norm='l1')
AUC: 53.16%, accuracy: 53.19%
Normalizer(copy=True, norm='l2')
AUC: 52.92%, accuracy: 53.20%
Normalizer(copy=True, norm='max')
AUC: 53.02%, accuracy: 52.66%
PolynomialFeatures(degree=2, incl... | ler', MinMaxScaler(copy=True, feature_range=(0, 1)))])
AUC: 53.62%, accuracy: 53.04%
""" |
Aclz/Tentacles | python3/app/backend/maintree.py | Python | gpl-2.0 | 10,439 | 0.003172 | from flask import request, jsonify
from sql_classes import UrlList, Acl, UserGroup, User, Role
def _node_base_and_rest(path):
"""
Returns a tuple: (the substring of a path after the last nodeSeparator, the preceding path before it)
If 'base' includes its own baseSeparator - return only a string after it
... | , UserGroup.id.label('usergroup_id'),
UserGroup.distinguishedName).join(UserGroup).\
filter(User.id == current_user_properties['user_object']['id'], User.hidden == 0).all()
Session.remove()
# Future tree
user_tree = []
# Place each user on a tree
for query_result_row in qu... | user_object = {
'id': query_result_row.user_id,
'distinguishedName': query_result_row.distinguishedName,
'status': query_result_row.status,
'cn': query_result_row.cn
}
_place_user_onto_tree(user_object, user_tree, user_groups)
user_tree = {
... |
XKNX/xknx | xknx/io/gateway_scanner.py | Python | mit | 9,132 | 0.000986 | """
GatewayScanner is an abstraction for searching for KNX/IP devices on the local network.
* It walks through all network interfaces
* and sends UDP multicast search requests
* it returns the first found device
"""
from __future__ import annotations
import asyncio
from functools import partial
import logging
from ty... | .xknx,
(ip_addr, 0),
(se | lf.xknx.multicast_group, self.xknx.multicast_port),
multicast=True,
)
udp_transport.register_callback(
partial(self._response_rec_callback, interface=interface),
[KNXIPServiceType.SEARCH_RESPONSE],
)
await udp_transport.connect()
self._udp_tr... |
w1ll1am23/home-assistant | homeassistant/components/homeassistant/triggers/state.py | Python | apache-2.0 | 6,291 | 0.000795 | """Offer state listening automation rules."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
import voluptuous as vol
from homeassistant import exceptions
from homeassistant.const import CONF_ATTRIBUTE, CONF_FOR, CONF_PLATFORM, MATCH_ALL
from homeassistant.cor... | ld_value == new_value)
):
return
@callback
def call_action():
"""Call action with right context."""
hass.async_run_hass_job(
job,
{
"trigger": {
"platform": platform_type,
... | _state": to_s,
"for": time_delta if not time_delta else period[entity],
"attribute": attribute,
"description": f"state of {entity}",
"id": trigger_id,
}
},
event.context,
... |
andr-04/Telethon | telethon/network/__init__.py | Python | mit | 191 | 0 | from | .mtproto_plain_sender import MtProtoPlainSender
from .authenticator import do_authentication
from .mtproto_sender import MtProtoSender
from .connection import Connection, | ConnectionMode
|
SkyZH/ddcm-word-count | wordcount/test/const.py | Python | bsd-3-clause | 119 | 0 | url = "https | ://skyzh.github.io/social-network-site/1.html"
html_path = "wordcount/test/data/social.html"
devel = False
| |
rboman/progs | apps/fractal/cpp_qt/run.py | Python | apache-2.0 | 179 | 0 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
from build import *
addroot()
| import pytools.build as b |
b.build()
b.run('qtfract')
|
flavoi/diventi | diventi/blog/migrations/0008_auto_20190411_0806.py | Python | apache-2.0 | 574 | 0 | # Generated by Django 2.1.7 on 2019-04-11 06:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0 | 007_auto_20180526_1702'),
]
operations = [
migrations.AlterField(
model_name='article',
name='image | ',
field=models.URLField(blank=True, verbose_name='image'),
),
migrations.AlterField(
model_name='blogcover',
name='image',
field=models.URLField(blank=True, verbose_name='image'),
),
]
|
harshkothari410/snn-image-segmentation | imageSeg.py | Python | mit | 4,893 | 0.02943 | from genetic import *
from image import *
from snn import *
import math, random
import numpy
def convert_binary(data, w, h, t):
ans = [[0 for x in xrange(w)] for x in xrange(h)]
for x in xrange(h):
for y in xrange(w):
if data[x][y] > t:
ans[x][y] = 1
else:
ans[x][y] = 0
return ans
def convert_mat(... | image
pixel, w, h = imageread('test8.jpg' | )
# convert to snn
pixel_mat = snn_response(pixel, w, h, 10, 0.05)
d=3
def weight(x1,y1,x,y):
w = 10*math.exp(- ( ( math.pow((x1-x),2)+math.pow((y1-y),2) + math.pow(pixel[x1][y1]-pixel[x][y],2 )/d ) ) )
return w
def second_layer_locality():
second_layer = [[0 for x in xrange(w+2)] for x in xrange(h+2)]
for x ... |
plasmashadow/training-python | time/sorted-list.py | Python | gpl-2.0 | 1,566 | 0.02235 | # -----------------------------------------------------------
# compares the creation of sorted lists using the python
# bisect module, and the "usual" way
#o
# (C) 2015 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email frank.hofmann@efho.de
# --------------------------------------------... | d fill with 200000 randomized integers
sortedNumbers = []
for element in range(200000):
# choose a number between 0 and 1000
newNumber = random.randint(0, 1000)
# add number to list
#print ("adding %i to list ... " %newNumber)
so | rtedNumbers.append(newNumber)
# sort the list in-place
sortedNumbers.sort()
return
def sortListBisect():
# define empty list, and fill with 200000 randomized integers
sortedNumbers = []
for element in range(200000):
# choose a number between 0 and 1000
newNumber = random.randint(0, 1000)
#print ("adding ... |
linvictor88/vse-lbaas-driver | quantum/plugins/linuxbridge/agent/linuxbridge_quantum_agent.py | Python | apache-2.0 | 29,895 | 0 | #!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Cisco Systems, 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
#
# ... | eady exists."""
interface = self.get_subinterface_name(physical_interface, vlan_id)
if not self.device_exists(interface):
LOG.debug(_("Creating subinterface %(interface) | s for "
"VLAN %(vlan_id)s on interface "
"%(physical_interface)s"),
{'interface': interface, 'vlan_id': vlan_id,
'physical_interface': physical_interface})
if utils.execute(['ip', 'link', 'add', 'link',
... |
ypid-bot/check_mk | web/htdocs/table.py | Python | gpl-2.0 | 15,132 | 0.005155 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | eaders" : kwargs.get("omit_headers", False),
"searchable" : kwargs.get("searchable", True),
| "sortable" : kwargs.get("sortable", True),
"next_header" : None,
"output_format" : kwargs.get("output_format", "html"), # possible: html, csv, fetch
}
if kwargs.get("empty_text"):
table["empty_text"] = kwargs["empty_text"]
else:
table["empty_text"] = _("No ... |
policycompass/policycompass-services | apps/referencepool/management/commands/harvest.py | Python | agpl-3.0 | 2,610 | 0.001149 | from django.core.management.base import BaseCommand
from django.db.utils import IntegrityError
from apps.referencepool.models import *
import requests
import json
import os
__author__ = 'fki'
class Command(BaseCommand):
help = 'Harvest external resources to fill the Reference Pool'
def handle(self, *args, *... | '.')
url = 'http://' + name
r = ExternalResource(title=name, url=url, api_url=url)
r.save()
except IntegrityError:
pass
def _file_to_json(self, rel_path):
dir = os.pat | h.dirname(__file__)
abs_path = os.path.join(dir, rel_path)
with open(abs_path, "r") as file:
data = json.load(file)
return data
|
iLotus/googleads-adsensehost-examples | python/v4.x/get_all_ad_units_for_publisher.py | Python | apache-2.0 | 2,497 | 0.005607 | #!/usr/bin/python
#
# Copyright 2012 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 required b... | ad_unit['status']))
request = service.accounts().adunits().list_next(request, res | ult)
else:
print 'No ad units were found.'
break
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
|
ElBell/VTDairyDB | manage.py | Python | gpl-3.0 | 10,171 | 0.005309 | import sys, os
from main import app
from flask_script import Manager, Server, Command, Option
from flask_security.utils import encrypt_password
from models import db, populate_db, StatusData, GrowthData, LifeData, GrowthDataAverages
from main import app
import random
from datetime import date, datetime
import pandas
f... | if life.bwt is None:
life.bwt = row['BWt']
life.dob = row['Birthdate']
life.breed = row['Brd']
life.estimate = True if type(row['Estimate']) is unicode else False
db.session.commit()
growth_data_old | .columns = pandas.MultiIndex.from_tuples([(c[:-1], c[-1]) for c in growth_data_old.columns])
for row_name, row in tqdm(growth_data_old.iterrows()):
row = row.where((pandas.notnull(row)), None)
for date_name, weight_data in row.unstack().iterrows():
weight = weight_data['W... |
vfiebig/rpaas | tests/test_storage.py | Python | bsd-3-clause | 5,053 | 0.000396 | # coding: utf-8
# Copyright 2015 rpaas authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import unittest
from rpaas import plan, storage
class MongoDBStorageTestCase(unittest.TestCase):
def setUp(self):
self.storage = st... | self.assertEqual(p.to_dict(), got_plan.to_dict())
def test_store_plan_duplicate(self):
p = plan.Plan(name="small", description="small thing",
config={"serviceofferingid": "abcdef123"})
with self.assertRaises(storage.DuplicateError):
self.storage.store_plan(p)
... | te_plan(self):
p = plan.Plan(name="super_huge", description="very huge thing",
config={"serviceofferingid": "abcdef123"})
self.storage.store_plan(p)
self.storage.update_plan(p.name, description="wat?",
config={"serviceofferingid": "abcdef123... |
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/vest/shared_vest_s03.py | Python | mit | 450 | 0.046667 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/vest/shared_vest_s03.iff"
result.attribute_template_id = ... | ,"vest_s03")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS | ####
return result |
writefaruq/lionface-app | django/contrib/staticfiles/handlers.py | Python | bsd-3-clause | 2,733 | 0.001098 | import urllib
from urlparse import urlparse
from django.conf import settings
from django.core.handlers.wsgi import WSGIHandler
from django.contrib.staticfiles import utils
from django.contrib.staticfiles.views import serve
class StaticFilesHandler(WSGIHandler):
"""
WSG | I middleware that intercepts calls to the static files directory, as
defined by the STATICFILES_URL setting, and serves those files.
"""
def __init__(self, applicatio | n, media_dir=None):
self.application = application
if media_dir:
self.media_dir = media_dir
else:
self.media_dir = self.get_media_dir()
self.media_url = urlparse(self.get_media_url())
if settings.DEBUG:
utils.check_settings()
s... |
capless/kev | kev/backends/__init__.py | Python | gpl-3.0 | 3,810 | 0.003412 | import json
import hashlib
import uuid
import datetime
from valley.exceptions import ValidationException
from kev.utils import get_doc_type
from kev.query import SortingParam
class DocDB(object):
db_class = None
indexer_class = None
backend_id = None
doc_id_string = '{doc_id}:id:{backend_id}:{class_n... | alue(doc.get(key))
if prop.unique:
self.check_unique(doc_obj, key, raw_value)
value = prop.get_db_value(raw_value)
doc[key] = value
| doc['_doc_type'] = get_doc_type(doc_obj.__class__)
return doc
def _save(self, doc_obj):
doc = self.prep_doc(doc_obj)
if '_id' not in doc:
self.create_pk(doc_obj,doc)
doc['_id'] = doc_obj._id
return (doc_obj, doc)
def get_id_list(self, filters_list):
... |
dwhswenson/mdtraj | mdtraj/reporters/hdf5reporter.py | Python | lgpl-2.1 | 4,749 | 0.000632 | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
#
# Authors: Robert McGibbon
# Contributors:
#
# MDTraj is free software: y... | rajectoryFile
Either an open HDF5TrajecoryFile object to write to, or a string
specifying the filename of a new HDF5 file to save the trajectory to.
reportInterval : int
The interval (in time steps) at which to write frames.
coordinates : bool
Whether to write the coordinates to ... | file.
cell : bool
Whether to write the current unit cell dimensions to the file.
potentialEnergy : bool
Whether to write the potential energy to the file.
kineticEnergy : bool
Whether to write the kinetic energy to the file.
temperature : bool
Whether to write the instan... |
nagareproject/core | doc/conf.py | Python | bsd-3-clause | 5,554 | 0.001801 | # -*- coding: utf-8 -*-
#
# Nagare documentation build configuration file, created by
# sphinx-quickstart on Fri Sep 29 15:07:51 2017.
#
# 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
# autogenerated file.
#
# Al... | modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.p | ath.abspath to make it absolute, like shown here.
#
#import os
#import sys
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension ... |
gomex/docker-zabbix | docker_service/__init__.py | Python | gpl-3.0 | 148 | 0.006757 | def main():
"""Instantiate a DockerStats object and collect stats."""
print('Docker Service Module')
if __ | name__ = | = '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.