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 |
|---|---|---|---|---|---|---|---|---|
nvoron23/python-weka-wrapper | tests/wekatests/plottests/experiments.py | Python | gpl-3.0 | 2,900 | 0.002759 | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# b... | re="Correlation coefficient", show_stdev=True, wait=False)
| plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False)
def suite():
"""
Returns the test suite.
:return: the test suite
:rtype: unittest.TestSuite
"""
return unittest.TestLoader().loadTestsFromTestCase(TestExperiments)
if __name__ == '__main__'... |
joke2k/faker | faker/providers/currency/es_ES/__init__.py | Python | mit | 6,293 | 0.000161 | from .. import Provider as CurrencyProvider
class Provider(CurrencyProvider):
# Format: (code, name)
currencies = (
("AED", "Dírham de los Emiratos Árabes Unidos"),
("AFN", "Afghaní"),
("ALL", "Lek albanés"),
("AMD", "Dram armenio"),
("ANG", "Florín de las Antillas Hola... | ("IDR", "Rupia indonesia"),
("ILS", "Séquel israelí"),
("NIS", "Nuevo Séquel israelí"),
("IMP", "Libra manesa"),
("INR", "Rupia india"),
("IQD", "Dinar iraquí"),
("IRR", "Rial iraní"),
("ISK", "Corona islandesa"),
("JEP", "Libra de Jersey"),
(... | ("KGS", "Som kirguís"),
("KHR", "Riel camboyano"),
("KMF", "Franco comorense"),
("KPW", "Won norcoreano"),
("KRW", "Krahn Occidental"),
("KWD", "Dinar kuwaití"),
("KYD", "Dólar de las islas Cayman"),
("KZT", "Tenge kazako"),
("LAK", "Kip laosiano"),
... |
matthewwardrop/formulaic | tests/parser/types/test_term.py | Python | mit | 1,044 | 0 | import pytest
from formulaic.parser.types import Factor, Term
class TestTerm:
@pytest.fixture
def term1(self):
return Term([Factor("c"), Factor("b")])
@pytest.fixture
def term2(self):
return Term([Factor("c"), Factor("d")])
@pytest.fixture
def term3(self):
return Ter... | assert term1 < term2
assert term2 < term3
assert term1 < term3
assert not (term3 < term | 1)
with pytest.raises(TypeError):
term1 < 1
def test_repr(self, term1):
assert repr(term1) == "b:c"
|
somic/paasta | paasta_tools/cleanup_chronos_jobs.py | Python | apache-2.0 | 8,610 | 0.002323 | #!/usr/bin/env python
# Copyright 2015-2016 Yelp 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 ... | = chronos_job_config.get_schedule_interval_in_seconds() or 0
except NoConfigurationForServiceError:
# If we can't get the job's config, default to cleanup after 1 day
interval = 0
if last_run_state != | chronos_tools.LastRunState.NotRun:
if ((datetime.datetime.now(dateutil.tz.tzutc()) -
dateutil.parser.parse(last_run_time)) >
max(datetime.timedelta(seconds=interval), datetime.timedelta(days=1))):
expired.append(job_name)
return expire... |
getefesto/efesto | setup.py | Python | gpl-3.0 | 1,723 | 0 | #!/usr/bin/env python
import io
import os
import sys
from efesto.Version import version
from setuptools import find_packages, setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sys.exit()
readme = io.open('README.md', 'r', enco... | ytest',
'pytest-moc | k',
'pytest-falcon'
],
setup_requires=['pytest-runner'],
install_requires=[
'falcon>=1.4.1',
'falcon-cors>=1.1.7',
'psycopg2-binary>=2.7.5',
'peewee>=3.7.1',
'click==6.7',
'colorama>=0.4.0',
'aratrum>=0.3.2',
'python-rapidjson>=0.6.3',
... |
michalliu/OpenWrt-Firefly-Libraries | staging_dir/host/lib/scons-2.3.1/SCons/Tool/sunf90.py | Python | gpl-2.0 | 2,198 | 0.003185 | """SCons.Tool.sunf90
Tool-specific initialization for sunf90, the Sun Studio F90 compiler.
The | re normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation
#
# Permission is hereby granted, free of ... | this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do ... |
JnyJny/GameOfLife | contrib/NCGameOfLife.py | Python | mit | 5,897 | 0.010853 | #!/usr/bin/env python3
'''Conway's Game of Life in a Curses Terminal Window
'''
import curses
import time
from GameOfLife import NumpyWorld
from GameOfLife import Patterns
from curses import ( COLOR_BLACK, COLOR_BLUE, COLOR_CYAN,
COLOR_GREEN, COLOR_MAGENTA, COLOR_RED,
COLOR... | break
self.handle_input()
t0 = time.time()
self.step()
self.draw()
self.w.refresh()
if self.interval:
cur | ses.napms(self.interval)
t1 = time.time()
self.gps = 1/(t1-t0)
except KeyboardInterrupt:
pass
def main(stdscr,argv):
w = CursesWorld(stdscr)
if len(argv) == 1:
raise ValueError("no patterns specified.")
for thing in argv[1:]:
... |
Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/chromium/src/testing/legion/process.py | Python | mit | 8,760 | 0.010046 | # Copyright 2015 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.
"""RPC compatible subprocess-type module.
This module defined both a task-side process class as well as a controller-side
process wrapper for easier access ... | key, timeout)
def Poll(self):
return self._rpc.subprocess. | Poll(self._key)
def GetPid(self):
return self._rpc.subprocess.GetPid(self._key)
class Process(object):
"""Implements a task-side non-blocking subprocess.
This non-blocking subprocess allows the caller to continue operating while
also able to interact with this subprocess based on a key returned to
the... |
edmorley/django | django/core/management/commands/makemessages.py | Python | bsd-3-clause | 27,345 | 0.001682 | import fnmatch
import glob
import os
import re
import sys
from functools import total_ordering
from itertools import dropwhile
import django
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.temp import NamedTemporaryFile
from django.core.management.base im... |
lines.append(li | ne)
msgs = '\n'.join(lines)
with open(potfile, 'a', encoding='utf-8') as fp:
fp.write(msgs)
class Command(BaseCommand):
help = (
"Runs over the entire source tree of the current directory and "
"pulls out all strings marked for translation. It creates (or updates) a message "
... |
jollychang/robotframework-appiumlibrary | AppiumLibrary/__init__.py | Python | apache-2.0 | 5,544 | 0.004509 | # -*- coding: utf-8 -*-
import os
from AppiumLibrary.keywords import *
from AppiumLibrary.version import VERSION
__version__ = VERSION
class AppiumLibrary(
_LoggingKeywords,
_RunOnFailureKeywords,
_ElementKeywords,
_ScreenshotKeywords,
_ApplicationManagementKeywords,
_WaitingK... | a locator is provided, it is matched against the key attributes
of the particular element type. For iOS and Android, key attribute is ``id`` for
all elements and locating elements is easy using just the ``id``. For example:
| Click Element id=my_element
New in AppiumLibrary 1.4, ``id`` and `... | else just use ``xpath`` locator as explained below.
For example:
| Click Element my_element
| Wait Until Page Contains Element //*[@type="android.widget.EditText"]
Appium additionally supports some of the [https://w3c.github.io/webdriver/webdriver-spec.html|Mobile JSON Wire Protocol] l... |
etingof/pysnmp | pysnmp/entity/observer.py | Python | bsd-2-clause | 2,572 | 0.000778 | #
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp import error
class MetaObserver(object):
"""This is a simple facility for exposing internal SNMP Engine
working details to pysnmp applicat... | self.__observers[execpoint] = []
self.__observers[execpoint].append(cbFun)
def unregisterObserver(self, cbFun=None):
if cbFun is None:
self.__observers.clear()
self._ | _contexts.clear()
else:
for execpoint in dict(self.__observers):
if cbFun in self.__observers[execpoint]:
self.__observers[execpoint].remove(cbFun)
if not self.__observers[execpoint]:
del self.__observers[execpoint]
def s... |
RishiRamraj/interviews | solutions/algorithms/bst.py | Python | mit | 667 | 0.004498 | '''
Problem:
Find the kth smallest element in a bst without using static/global variables.
'''
def find | (node, k, items=0):
# Base case.
if not node:
return items, None
# Decode the node.
left, value, right = node
# Check left.
index, result = find(left, k, items)
# Exit early.
if result:
return index, result
# Check this node.
next = index + 1
if next == k:... | 1, None), 2, (None, 3, None)), 4, ((None, 5, None), 5, (None, 6, None)))
#test = ((None, 1, None), 2, (None, 3, None))
print(find(test, 11))
|
laurentb/weboob | modules/ensap/__init__.py | Python | lgpl-3.0 | 885 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2017 Juliette Fourcot
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of th... | sion.
#
# This weboob module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more det | ails.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this weboob module. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from .module import EnsapModule
__all__ = ['EnsapModule']
|
jaekookang/useful_bits | Machine_Learning/RNN_LSTM/predict_character/rnn_char_windowing.py | Python | mit | 7,262 | 0.006063 |
# coding: utf-8
# # Simple Character-level Language Model using vanilla RNN
# 2017-04-21 jkang
# Python3.5
# TensorFlow1.0.1
#
# - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window)
# - input: 'hello_world_good_morning_see_you_hello_grea'
# ... | (x, y) is one example, it will create multiple examples with the length of window_size
x: (time_step) x (input_dim)
y: (time_step) x (output_dim)
x_out: (total_batch) x (batch_size) x ( | window_size) x (input_dim)
y_out: (total_batch) x (batch_size) x (window_size) x (output_dim)
total_batch x batch_size <= examples
'''
# (batch_size) x (window_size) x (dim)
# n_examples is calculated by sliding one character with window_size
n_examples = x.shape[0] - window_size + 1 # n_e... |
daviortega/bitk3 | docs/conf.py | Python | mit | 8,433 | 0.005336 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# bitk3 documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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
# autog... | if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = Fa | lse
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry p... |
ppokrovsky/pyvdp | demo/demo/urls.py | Python | mit | 2,820 | 0.002837 | from django.conf.urls import include, url
from demo.views import common
from demo.views.visadirect import fundstransfer, mvisa, reports, watchlist
from demo.views.pav import pav
from demo.views.dcas import cardinquiry
from demo.views.merchantsearch import search
from demo.views.paai.fundstransferattinq.cardattributes.... | sa_copp'),
url(r'^merchantpushpayments$', mvisa.mpp, name='vd_mvisa_mpp'),
])),
# Reports API
url(r'^reports$', reports.index, name='vd_reports'),
url(r'^reports/', include([
url(r'^transactiondata$', reports.transactiondata, name='vd_reports_transactiondata'),
... | , watchlist.index, name='vd_wl'),
url(r'^watchlist/', include([
url(r'^inquiry$', watchlist.inquiry, name='vd_wl_inquiry')
]))
])),
]
|
snakeego/pyactors | tests/test_forked_green_actors.py | Python | bsd-2-clause | 1,024 | 0.003906 | import sys
if '' not in sys.path:
sys.path.append('')
import time
import unittest
from pyactors.logs import file_logger
from pyactors.exceptions import EmptyInboxException
from tests import ForkedGreActor as TestActor
from multiprocessing import Manager
class ForkedGreenletActorTest(unittest.TestCase):
de... | ctor.start()
while actor.processing:
time.sleep(0.1)
actor.stop()
result = []
while True:
try:
result.append(actor.inbox.get())
except EmptyInboxException:
break
self.assertEqual(len(result), 10)
... | Equal(actor.processing, False)
self.assertEqual(actor.waiting, False)
if __name__ == '__main__':
unittest.main()
|
charles-vdulac/django-roa | examples/django_roa_client/forms.py | Python | bsd-3-clause | 432 | 0.002315 | from django import forms
from django_roa_client.models import RemotePage, RemotePageWithRelations
class TestForm(forms.Form):
test_fiel | d = forms.CharField()
remote_page = forms.ModelChoiceField(queryset=RemotePage.objects.all())
class | RemotePageForm(forms.ModelForm):
class Meta:
model = RemotePage
class RemotePageWithRelationsForm(forms.ModelForm):
class Meta:
model = RemotePageWithRelations
|
mozilla/olympia | src/olympia/amo/cron.py | Python | bsd-3-clause | 3,247 | 0.000924 | from datetime import datetime, timedelta
from django.core.files.storage import default_storage as storage
import olympia.core.logger
from olympia import amo
from olympia.activity.models import ActivityLog
from olympia.addons.models import Addon
from olympia.addons.tasks import delete_addons
from olympia.amo.utils imp... | # Delete stale FileUploads.
stale_uploads = FileUpload.objects.filter(created__lte=two_weeks_ago).order_by( | 'id')
for file_upload in stale_uploads:
log.info(
'[FileUpload:{uuid}] Removing file: {path}'.format(
uuid=file_upload.uuid, path=file_upload.path
)
)
if file_upload.path:
try:
storage.delete(file_upload.path)
ex... |
lbjay/cds-invenio | modules/websubmit/lib/functions/Check_Group.py | Python | gpl-2.0 | 2,200 | 0.010455 | ## This file is part of CDS Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
##
## CDS Invenio 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 (... | c.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
__revision__ = "$Id$"
import os
import re
from invenio.dbquery import run_sql
from invenio.websubmit_config import Inven | ioWebSubmitFunctionStop
def Check_Group(parameters, curdir, form, user_info=None):
"""
Check that a group exists.
Read from file "/curdir/Group"
If the group does not exist, switch to page 1, step 0
"""
#Path of file containing group
if os.path.exists("%s/%s" % (curdir,'Group')):
f... |
kisel/trex-core | scripts/external_libs/scapy-2.3.1/python3/scapy/layers/l2.py | Python | apache-2.0 | 17,955 | 0.017154 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
Classes and functions for layer 2 protocols.
"""
import os,struct,time
from scapy.base_classes import Net
from scapy... | mysummary(self):
return self.sprintf("%src% > %dst% (%type%)")
@classmeth | od
def dispatch_hook(cls, _pkt=None, *args, **kargs):
if _pkt and len(_pkt) >= 14:
if struct.unpack("!H", _pkt[12:14])[0] <= 1500:
return Dot3
return cls
class Dot3(Packet):
name = "802.3"
fields_desc = [ DestMACField("dst"),
MACField("src", ... |
chromium/chromium | chrome/test/enterprise/e2e/connector/realtime_reporting_bce/reporting_server.py | Python | bsd-3-clause | 1,846 | 0.003792 | # Copyright 2021 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.
import os
from googleapiclient.discovery import build
from google.oauth2 import service_account
class RealTimeReportingServer():
SCOPES = ['https://www.... | tkey.json')
credentials = service_account.Credentials.from_service_account_file(
filePath, scopes=self.SCOPES)
delegatedCreds = credentials.create_delegated(user_email)
return build('admin', 'reports_v1', credentials=delegatedCreds)
def lookupevents(self, eventName, startTime, deviceId):
co... | ,
customerId='C029rpj4z',
eventName=eventName,
startTime=startTime).execute()
activities = results.get('items', [])
for activity in activities:
for event in activity.get('events', []):
for parameter in event.get('parameters', []):
if parameter['name'] == 'DEVICE_I... |
hishivshah/WorldPop | code/create_zanzibar_boundary_map.py | Python | mit | 1,981 | 0.002524 | import logging
import mapnik
import xml.etree.ElementTree as ET
import os
import subprocess
import tempfile
# Set up logging
logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO)
# Parameters
shpPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-04-24/Zanzibar/Zanzibar.shp"
ep... | g / dLat
if dLong > dLat:
width = max_img_size
height = int(width / aspectRatio)
elif dLat > dLong:
height = max_img_s | ize
width = int(aspectRatio * height)
else:
width = max_img_size
height = max_img_size
# Create map
map = mapnik.Map(width, height)
map.append_style("boundariesStyle", style)
map.layers.append(layer)
map.zoom_all()
# Output to temporary postscript file
outPsPath = os.path.join(tempfile.gettempdir(), "Zanz... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/code/browser/tests/test_sourcepackagerecipebuild.py | Python | agpl-3.0 | 11,028 | 0.000091 | # Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for the source package recipe view classes and templates."""
__metaclass__ = type
from mechanize import LinkNotFoundError
from storm.locals import Store
from testtools.ma... | h(
owner=self.chef, name='cake', product=chocolate)
recipe = self.factory.makeSourcePackageRecipe(
owner=self.chef, distroseries=self.squirrel, name=u'cake_recipe',
description=u'This recipe builds a foo for disto bar, with my'
' Secret Squirrel changes.', branche... | =self.ppa)
build = self.factory.makeSourcePackageRecipeBuild(
recipe=recipe)
return build
def test_cancel_build(self):
"""An admin can cancel a build."""
queue = self.factory.makeSourcePackageRecipeBuildJob()
build = queue.specific_job.build
transaction.c... |
hfp/libxsmm | samples/deeplearning/tvm_cnnlayer/mb1_tuned_latest.py | Python | bsd-3-clause | 20,227 | 0.039996 | #!/usr/bin/env python3
###############################################################################
# Copyright (c) Intel Corporation - All rights reserved. #
# This file is part of the LIBXSMM library. #
# ... | mension is vectorized for AVX-512
'''
def convert_weight(w_np, in_channel, out_channel, kernel_height, kernel_width, vlen,W):
to_return = np.zeros((math.ceil(out_channel/vlen), math.ceil(in_channel/vlen),kernel_height, kernel_width,vlen,vlen), dtype = W.dtype)
for i in range(math.ceil(out_channel/vlen)):
... | kernel_width):
for m in range(vlen):
for n in range(vlen):
if i*vlen + n >= out_channel or j*vlen + m >= in_channel:
to_return[i,j,k,l,m,n] =float(0)
else:
to_return[i,j,k,l,m,n] = w_np[i*vlen + n,j*vlen+ m,k,l]
retur... |
tysonholub/twilio-python | twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py | Python | mit | 15,072 | 0.003715 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... | urn SubscribedTrackInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['participant_sid'],
)
def __repr__(self):
"""
Pro | vide a friendly representation
:returns: Machine friendly rep |
leeroybrun/heigvd-timetable-parser | setup.py | Python | mit | 604 | 0.036484 | #!/usr/bin/python
# coding=utf-8
from setuptools import setup, find_packages
setup(
name = "HEIGVD_TimetableParser",
version = "0.1",
packages = find_packages(),
install_r | equires = ['icalendar>=3.5', 'xlrd>=0.9.2'],
# metadata for upload to PyPI
author = "Leeroy Brun",
author_email = "leeroy.brun@gmail.com",
description = "Transforme un horaire au format XLS provenant de l'intranet du département FEE de la HEIG-VD en un fichier ICS.",
license = "MIT",
keywords =... | run/heigvd-timetable-parser",
)
|
willmcgugan/rich | tests/test_styled.py | Python | mit | 471 | 0.002123 | import io
from rich.console import Console
from rich. | measure import Measurement
from rich.styled import Styled
def test_styled():
styled_foo = Styled("foo", "on red")
console = Console(file=io.StringIO(), force_terminal=True, _environ={})
assert Measurement.get(console, console.options, styled_foo) == Measurement(3, 3)
console.print(styled_foo)
resu... | cted
|
puruckertom/ubertool | ubertool/terrplant/terrplant_functions.py | Python | unlicense | 20,304 | 0.006403 | from __future__ import division #brings in Python 3.0 mixed type calculation rules
import logging
import numpy as np
import pandas as pd
class TerrplantFunctions(object):
"""
Function class for Stir.
"""
def __init__(self):
"""Class representing the functions for Sip"""
super(Terrplan... | f spray(self):
"""
EEC for spray drift
"""
self.out_spray = self.application_rate * self.drift_fraction
return self.out_spray
def total_dry(self):
"""
EEC total for dry areas
"""
self.out_total_dry = self.out_run_ | dry + self.out_spray
return self.out_total_dry
def total_semi(self):
"""
EEC total for semi-aquatic areas
"""
self.out_total_semi = self.out_run_semi + self.out_spray
return self.out_total_semi
def nms_rq_dry(self):
"""
Risk Quotient for NON-LIST... |
rchrd2/django-cache-decorator | setup.py | Python | mit | 596 | 0.041946 | from setuptools import setup
version = '0.4'
setup(
name | = 'django-cache-decorator',
packages = ['django_cache_decorator'],
license = 'MIT',
version = version,
description = 'Easily add caching to functions within a django project.',
long_description=open('README.md').read(),
author = 'Richard Caceres',
author_email = 'me@rchrd.net',
url = 'ht... | ,'decorator'],
classifiers = [],
)
|
LuizArmesto/gastos_abertos | gastosabertos/contratos/views.py | Python | agpl-3.0 | 13,828 | 0.005496 | # -*- coding: utf-8 -*-
import os
import json
from sqlalchemy import and_, extract, func, desc
from datetime import datetime
from jinja2 import TemplateNotFound
from flask import Blueprint, render_template, send_from_directory, abort, request
from flask.ext.paginate import Pagination
from flask.ext import restful
fro... | citacao')
contratos_list_parser.add_argument('group_by', default='')
contratos_list_parser.add_argument('order_by', 'id')
contratos_list_parser.add_argu | ment('page', type=int, default=0)
contratos_list_parser.add_argument('per_page_num', type=int, default=100)
# Fields for ContratoAPI data marshal
contratos_fields = { 'id': fields.Integer()
, 'orgao': fields.String()
, 'data_assinatura': fields.DateTime(dt_format='iso8601')
... |
ATNF/askapsdp | Code/Base/py-accessor/current/askap/accessors/__init__.py | Python | gpl-2.0 | 991 | 0 | # Copyright (c) 2011 CSIRO
# Australia Telescope National Facility (ATNF)
# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
# PO Box 76, Epping NSW 1710, Australia
# atnf-enquiries@csiro.au
#
# This file is part of the ASKAP software distribution.
#
# The ASKAP software distribution is free softwar... | u 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 progra | m is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this pro... |
lealhugui/schema-analyser | app/server/api/migrations/0003_tablefield_inner_type.py | Python | mit | 467 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-09 13:44
from __future__ import unicode_literals
from django.db import migrations, m | odels
class Migration(migrations.Migration):
dependencies = [
('api', '0002_tablefield_allow_null'),
]
operations = [
migrations.AddField(
model_name='tablefield',
name='inner_type',
field=models.CharField(defa | ult='', max_length=250),
),
]
|
chaosmaker/pyload | module/plugins/accounts/RyushareCom.py | Python | gpl-3.0 | 742 | 0.001348 | # -*- coding: utf-8 -*-
from module.plugins.internal.XFSPAccount import XFSPAccount
class RyushareCom(XFSPAccount):
__name__ = "RyushareCom"
__version__ = "0.03"
__type__ = "account"
__description__ = """ryushare.com account plugin"""
__author_name__ = ("zoidberg", "trance4us")
__author_mail__... | n(self, user, data, req):
req.lastURL = "http://ryushare.com/login.python"
html = req.load("http://ryushare.com/login.python",
post={"login": user, "password": | data["password"], "op": "login"})
if 'Incorrect Login or Password' in html or '>Error<' in html:
self.wrongPassword()
|
bitmingw/hexomega | assets/HOJacMat.py | Python | mit | 2,566 | 0.011302 | from numpy import matrix
# integer Size; integer nPQ, Matrix G; Matrix B; Array U
def JacMat(Size, nPQ, G, B, U):
# Method Of Every Entry Of Jacbean Matrix
f = U.real
e = U.imag
JacMat = zeros(Size, Size)
def Hij(B, G, e, f):
return -B*e+Gf
def Nij(B, G, e, f):
retur... | ):
if m==n:
JacMat[m][n] = Hii(B[m][m], G[m][m], e[m], f[m])
else:
JacMat[m][n] = Hij(B[m][n], G[m][n], e[m], f[m])
for m in range(0, Size, 2): #N
for n in range(1, Size, 2):
if m==n:
JacMat[... | else:
JacMat[m][n] = Nij(B[m][n], G[m][n], e[m], f[m])
for m in range(1, Size, 2): #J
for n in range(0, nPQ*2, 2):
if m==n:
JacMat[m][n] = Jii(B[m][m], G[m][m], e[m], f[m])
else:
JacMat[m][n] = Jij(B[m]... |
rafaelnsantos/batfinancas | batfinancas/wsgi.py | Python | mit | 399 | 0 | """
WSGI config for batfinancas project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.c | ore.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "batfinancas.settings")
application = get_w | sgi_application()
|
zrax/moul-scripts | Python/xPodBahroSymbol.py | Python | gpl-3.0 | 6,228 | 0.006744 | # -*- coding: utf-8 -*-
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, 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 3... | .3% into a 56585 second
# day is 6394.105 seconds (56585 * 0.113). That gives us our base
# point for every other age that | needs the Bahro symbol.
kTimeWhenSymbolAppears = kDayLengthInSeconds * (float(SymbolAppears.value) / float(DayFrameSize.value))
#====================================
class xPodBahroSymbol(ptResponder):
###########################
def __init__(self):
ptResponder.__init__(self)
self.id = 5240
... |
tescalada/npyscreen-restructure | tests/testMonthbox.py | Python | bsd-2-clause | 337 | 0.011869 | #!/bin/env python
import npyscreen
class MainFm( | npyscreen.Form):
def create(self):
self.mb = self.add(npyscreen.MonthBox,
use_datetime = True)
class TestApp(npyscreen.NPSAppManaged):
def onStart(self):
s | elf.addForm("MAIN", MainFm)
if __name__ == "__main__":
A = TestApp()
A.run()
|
sridevikoushik31/nova | nova/virt/xenapi/vmops.py | Python | apache-2.0 | 88,390 | 0.000645 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright 2010 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
#
# ... | trOpt('region',
default=None,
help=_(' | Region compute host is in')),
cfg.StrOpt('ip_whitelist_file',
default=None,
help=_('File containing a list of IP addresses to whitelist '
'on managed hosts')),
cfg.StrOpt('max_snapshot_size',
default=0,
help=_('Maximum allowed numbe... |
richbs/django-record-collector | recollect/urls.py | Python | bsd-3-clause | 275 | 0.007273 | from django.conf.urls import patterns, url
urlpat | terns = patterns( | '',
url(r'^$', 'recollect.views.home', name='home'),
url(r'^albums$', 'recollect.views.albums', name='albums'),
url(r'^album/(?P<album_slug>[A-z0-9-]+)$', 'recollect.views.album', name='album'),
)
|
Geheimorganisation/sltv | sltv/ui/input/autoaudioinput.py | Python | gpl-2.0 | 1,172 | 0.000854 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Holoscópio Tecnologia
# Author: Luciana Fujii Pontello <luciana@holoscopio.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 Software Foundation; either version 2 of... | TNESS 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 Stree | t, Fifth Floor, Boston, MA 02110-1301 USA.
import gobject
import gtk
from sltv.settings import UI_DIR
from core import InputUI
class AutoAudioInputUI(InputUI):
def __init__(self):
InputUI.__init__(self)
def get_widget(self):
return None
def get_name(self):
return "AutoAudio"
... |
ericmjl/protein-interaction-network | proteingraph/features.py | Python | mit | 501 | 0 | """
Author: Eric J. Ma
License: MIT
A Python module that provides helper functions and variables for encoding amino
acid features in the protein interaction network. We encode features in order
to feed the data into the neural fingerprinting | software later on.
"""
amino_acids = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M | ",
"N",
"P",
"Q",
"R",
"S",
"T",
"V",
"W",
"X",
"Y",
"Z",
]
|
DanNixon/Sakuya | pc_client/sakuyaclient/NotificationSource.py | Python | apache-2.0 | 562 | 0.001779 | from abc import ABCMeta, abstractmethod
class NotificationSource():
"""
| Abstract class for all notification sources.
"""
__metaclass__ = ABCMeta
@abstractmethod
def poll(self):
"""
Used to get a set of changes between data retrieved in this call and the last.
"""
raise NotImplem | entedError('No concrete implementation!')
@abstractmethod
def name(self):
"""
Returns a unique name for the source type.
"""
raise NotImplementedError('No concrete implementation!')
|
matthew-brett/draft-statsmodels | scikits/statsmodels/sandbox/examples/ex_onewaygls.py | Python | bsd-3-clause | 4,198 | 0.010005 | # -*- coding: utf-8 -*-
"""Example: Test for equality of coefficients across groups/regressions
Created on Sat Mar 27 22:36:51 2010
Author: josef-pktd
"""
import numpy as np
from scipy import stats
#from numpy.testing import assert_almost_equal
import scikits.statsmodels as sm
from scikits.statsmodels.sandbox.regres... | oni correction)'
print ' * : reject at 5% uncorrected confidence level'
print 'Null hypothesis: all or pairwise coefficient are the same'
print 'Alternative hypothesis: all coefficients are different'
print '\nComparison with stats.f_oneway'
print stats.f_oneway(*[y[groupind==gr] for gr in re... | print res.lr_test()
print 'Null model: pooled all coefficients are the same across groups,'
print 'Alternative model: all coefficients are allowed to be different'
print 'not verified but looks close to f-test result'
print '\nOls parameters by group from individual, separate ols regressions'
for... |
anandpdoshi/erpnext | erpnext/setup/install.py | Python | agpl-3.0 | 1,780 | 0.024719 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
default_mail_footer = """<div style="padding: 7px; text-align: right; color: #888"><small>S | ent via
<a style="color: #888" href="http://erpnext | .org">ERPNext</a></div>"""
def after_install():
frappe.get_doc({'doctype': "Role", "role_name": "Analytics"}).insert()
set_single_defaults()
create_compact_item_print_custom_field()
from frappe.desk.page.setup_wizard.setup_wizard import add_all_roles_to
add_all_roles_to("Administrator")
frappe.db.commit()
def c... |
sparkslabs/kamaelia_ | Sketches/MPS/BugReports/FixTests/Kamaelia/Kamaelia/Apps/JsonRPC/BDJsonRPC.py | Python | apache-2.0 | 35,300 | 0.013059 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ve... | just return
return
if hasattr(function, '_callbacks_'): # 'response_callback'):
| for arg_name, response_callback in function._callbacks_.items():
name = function.__name__
self.callback_table[function][arg_name] = response_callback
print 'Added callback for method %s, argument %s' % (name, arg_name)
try:
# args by... |
xiaoyongaa/ALL | python基础2周/17猜年龄游戏.py | Python | apache-2.0 | 1,545 | 0.027353 | '''
笔记
for i in range(10):
#3次机会问一次
'''
age=22
c=0
while True:
if c<3:
cai=input("请输入要猜的年龄:")
if cai.isdigit(): #判断是否为整数
print("格式正确")
cai1=int(cai) #判断为整数把输入的变量变成int型
if cai1==age and c<3:
print | ("猜对了")
break
elif cai1>age and c<3:
print("猜大了")
c+=1
elif cai1<age and c<3:
print("猜小了")
c+=1
else: #判断是否为整数
print("输入格式不正确")
else:
p=input("次数用完,是否要继续,继续请按:yes,不想继续请... | 请输入要猜的年龄:")
if cai.isdigit(): #判断是否为整数
print("格式正确2")
cai1=int(cai) #判断为整数把输入的变量变成int型
if cai1==age and c<3:
print("猜对了")
break
elif cai1>age and c<3:
print("猜大了")
... |
cbcoutinho/learn_dg | tests/helpers.py | Python | bsd-2-clause | 4,156 | 0.001444 | import numpy as np
from ctypes import (
CDLL,
POINTER,
ARRAY,
c_void_p,
c_int,
byref,
c_double,
c_char,
c_char_p,
create_string_buffer,
)
from numpy.ctypeslib import ndpointer
import sys, os
prefix = {"win32": "lib"}.get(sys.platform, "lib")
extension = {"darwin": ".dylib", "wi... | c_int,
c_double,
c_double,
ndpointer(shape=(N + 1,), dtype="double", flags="F"),
]
f.restype = None
return f
def set_pascal_2D_quad_c_args(N):
"""
Assign arguements for full (quadrilateral) pascal lines
"""
f = libcore.pascal_2D_quad_c
f.argtypes = [
... |
ndpointer(shape=((N + 1) ** 2,), dtype="double", flags="F"),
]
f.restype = None
return f
def pascal_2D_single_row(N, x, y):
xs = np.array([np.power(x, N - ii) for ii in range(N + 1)])
ys = np.array([np.power(y, ii) for ii in range(N + 1)])
return xs * ys
def pascal_2D_post_row(N, i... |
mhbu50/erpnext | erpnext/crm/doctype/campaign/test_campaign.py | Python | gpl-3.0 | 167 | 0.005988 | # Copyrigh | t (c) 2021, Frappe Technologies Pvt. Ltd. and Contributors
# See license. | txt
# import frappe
import unittest
class TestCampaign(unittest.TestCase):
pass
|
w1ll1am23/home-assistant | tests/components/homekit_controller/specific_devices/test_koogeek_ls1.py | Python | apache-2.0 | 3,555 | 0.000281 | """Make sure that existing Koogeek LS1 support isn't broken."""
from datetime import timedelta
from unittest import mock
from aiohomekit.exceptions import AccessoryDisconnectedError, EncryptionError
from aiohomekit.testing import FakePairing
import pytest
from homeassistant.components.light import SUPPORT_BRIGHTNESS... | network connection drop.
See https://github.com/home-assistant/core/issues/18949
"""
accessories = await setup_accessories_from_file(hass, "koogeek_ls1.json")
config_entry, pairing = await setup_test_accessories(hass, accessories)
helper = Helper(
hass, "light.koogeek_ls1_20833f", pairing,... | t_value(False)
# Test that entity starts off in a known state
state = await helper.poll_and_get_state()
assert state.state == "off"
# Set light state on fake device to on
helper.characteristics[LIGHT_ON].set_value(True)
# Test that entity remains in the same state if there is a network error
... |
mwaskom/seaborn | seaborn/axisgrid.py | Python | bsd-3-clause | 87,264 | 0.000562 | from itertools import product
from inspect import signature
import warnings
from textwrap import dedent
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from ._core import VectorPlotter, variable_type, categorical_order
from . import utils
from .utils import _check_argum... | pace_needed
right = 1 - self._space_needed
# Place the subplot axes to give space for the legend
self._figure.subplots_adjust(right=right)
self._tight_layout_rect[2] = right
else:
# Draw a legend in the first axis
ax = self.axes.flat[0]
... | leg.set_title(title, prop={"size": title_size})
self._legend = leg
if adjust_subtitles:
adjust_legend_subtitles(leg)
return self
def _update_legend_data(self, ax):
"""Extract the legend data from an axes object and save it."""
data = {}
#... |
pmverdugo/fiware-validator | validator/tests/clients/test_chef_client.py | Python | apache-2.0 | 4,428 | 0.001807 | # -*- 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, ... | """Test a command execution in container"""
self.client.dc = self.m.CreateMockAnything()
self.client.container = "1234"
self.client.dc.exec_create(cmd='/bin/bash -c "mycommand"', container=u'1234').AndReturn("validcmd")
self.client.dc.exec_start("validcmd").AndReturn("OK")
... | nment"""
super(ChefClientTestCase, self).tearDown()
self.m.UnsetStubs()
self.m.ResetAll()
|
hatbot-team/hatbot | explanator/_explanator.py | Python | mit | 2,930 | 0 | import itertools
import random
from hb_res.explanation_source import sources_registry, ExplanationSource
__author__ = 'moskupols'
ALL_SOURCES = sources_registry.sources_registered()
ALL_SOURCES_NAMES_SET = frozenset(sources_registry.names_registered())
all_words_list = []
words_list_by_source_name = dict()
for s i... | lists = [words_list_by_source_name[name] for name in sources_names]
total = sum(map(len, lists))
rand = random.randrange(total)
upto = 0
for word_lis | t in lists:
upto += len(word_list)
if rand < upto:
return word_list[rand - upto] # yep, negative indexation
assert False, 'Shouldn\'t get here'
def explain_list(word, sources_names=None):
"""
Returns list of tuples (Explanations, asset_name)
"""
if word not in all_word... |
kapucko/bus-train-search | btsearch/exceptions.py | Python | apache-2.0 | 101 | 0.019802 | class DestinationNotFoundExceptio | n(Exception):
pass
class InvalidDateFormat(Exception):
pas | s |
RuralIndia/pari | pari/faces/migrations/0006_auto__add_field_face_district_id.py | Python | bsd-3-clause | 11,120 | 0.009083 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Face.district_id'
db.add_column(u'faces_face', 'district_... | ectionImage'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.model | s.fields.IntegerField', [], {'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank... |
iesugrace/pycmd | lib.py | Python | gpl-3.0 | 24,434 | 0.000941 | import sys
import os
import re
def human_size_to_byte(number):
"""
Convert number of these units to bytes, ignore case:
b : 512
kB : 1000
K : 1024
mB : 1000*1000
m : 1024*1024
MB : 1000*1000
M : 1024*1024
GB : 1000*1000*1000
G : 1024*1024*1024
TB : 1000*... | **7,
'yb' : 1000**8,
'y' : 1024**8,
}
unit = re.sub('^[0-9]+', '', number)
if unit:
unit = unit.lower()
assert unit in mapping.keys(), "wrong unit %s " % unit
amount = int(number[:-len(unit)])
return mapping[unit] * amount
else:
return int(number)... | scriptor may differ, this function can correct
it.
"""
cur = file.seek(0, 1)
file.seek(0, 2)
file.seek(cur)
def open_file(file):
if file == '-':
return os.fdopen(sys.stdin.fileno(), 'rb')
else:
return open(file, 'rb')
class Locator:
"""Search from the end of the file... |
darvid/hydrogen | hydrogen.py | Python | bsd-2-clause | 26,677 | 0 | # -*- coding: utf-8 -*-
"""
hydrogen
~~~~~~~~
Hydrogen is an extremely lightweight workflow enhancement tool for Python
| web applications, providing bower/npm-like functionality for both pip and
bower packages.
:author: David Gidwani <david.gidwani@gmail.com>
:license: BSD, see LICENSE for details
"""
import atexit
from collections import defaultdict
from functools import update_wrapper
import json
| import os
import re
import shutil
import sys
import tempfile
import yaml
import zipfile
import click
import envoy
from pathlib import Path, PurePath
from pathspec import GitIgnorePattern, PathSpec
from pip._vendor import pkg_resources
import requests
import rfc6266
import semver
__version__ = "0.0.1-alpha"
prog_nam... |
nburn42/tensorflow | tensorflow/contrib/autograph/converters/side_effect_guards.py | Python | apache-2.0 | 7,026 | 0.007543 | # Copyright 2016 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... | deps_guard = templates.replace(
template,
call=node.value,
aliased_guarded_args=aliased_guarded_args,
guarded_args=guarded_args)[-1]
else:
alias_map = {}
template = """
with ag__.utils.control_dependency_on | _returns(call):
pass
"""
control_deps_guard = templates.replace(template, call=node.value)[-1]
control_deps_guard.body = []
node = control_deps_guard
anno.setanno(node, anno.Basic.INDENT_BLOCK_REMAINDER,
(node.body, alias_map))
return node
# pyl... |
wenzheli/python_new | com/uva/network.py | Python | gpl-3.0 | 17,149 | 0.012595 | import random
from sets import Set
class Network(object):
"""
Network class represents the whole graph that we read from the
data file. Since we store all the edges ONLY, the size of this
information is much smaller due to the graph sparsity (in general,
around 0.1% of links are connected)
... | say edge,
it means either linked or non-link edge.
The class also contains lots of sampling methods that sampler can utilize.
This is great separation between different learners and data layer. By calling |
the function within this class, each learner can get different types of
data.
"""
def __init__(self, data, held_out_ratio):
"""
In this initialization step, we separate the whole data set
into training, validation and testing sets. Basically,
Training -> used for... |
MERegistro/meregistro | meregistro/apps/postitulos/models/Postitulo.py | Python | bsd-3-clause | 2,464 | 0.007323 | # -*- coding: utf-8 -*-
from django.db import models
from apps.postitulos.models.EstadoPostitulo import EstadoPostitulo
from apps.postitulos.models.TipoPostitulo import TipoPostitulo
from apps.postitulos.models.PostituloTipoNormativa import PostituloTipoNormativa
from apps.postitulos.models.CarreraPostitulo import Carr... | oEstado.objects.filter(postitulo = self).order_by('fecha', | 'id')
except:
estados = {}
return estados
"Algún título jurisdiccional está asociado al título?"
def asociado_carrera_postitulo_jurisdiccional(self):
from apps.postitulos.models.CarreraPostituloJurisdiccional import CarreraPostituloJurisdiccional
return CarreraPosti... |
ArteliaTelemac/PostTelemac | PostTelemac/meshlayerlibs/pyqtgraph/debug.py | Python | gpl-3.0 | 41,232 | 0.00827 | # -*- coding: utf-8 -*-
"""
debug.py - Functions to aid in debugging
Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more information.
"""
from __future__ import print_function
import sys, traceback, time, gc, re, types, weakref, inspect, os, cProfile, threading
from . import p... | Y TREE"
continue
else:
for p in tree:
refs.append(p+[r])
#seen[id(r)] = [maxLen, refs]
return refs
def objString(obj):
"""R | eturn a short but descriptive string for any object"""
try:
if type(obj) in [int, float]:
return str(obj)
elif isinstance(obj, dict):
if len(obj) > 5:
return "<dict {%s,...}>" % (",".join(list(obj.keys())[:5]))
else:
return "<dict {... |
classrank/ClassRank | classrank/grouch/grouch_util.py | Python | gpl-2.0 | 3,951 | 0.000253 | import datetime
import json
from classrank.database.wrapper import Query
"""add_to_database.py: adds courses from Grouch to the ClassRank DB."""
def add_to_database(grouch_output, db):
"""
Add courses from Grouch's output to a db.
Keyword arguments:
grouch_output -- the output of Grouch (the scrap... | (**school_dict).all()) != 0
def _course_in_database(course_dict, db, q):
"""Check if a course is in the database.
Keyword arguments:
course_dict -- | a dictionary specifying the course to check
db -- the db to search in
q -- the Query object used to query the database
Returns True if there are instances of course in database, False otherwise
"""
return len(q.query(db.course).filter_by(**course_dict).all()) != 0
|
airbnb/airflow | airflow/providers/cncf/kubernetes/hooks/kubernetes.py | Python | apache-2.0 | 9,757 | 0.002152 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | om airflow.exceptions import AirflowException
from airflow.hooks.base import BaseHook
def _load_body_to_dict(body):
try:
body_dict = yaml.safe_load(body)
except yaml.YAMLError as | e:
raise AirflowException("Exception when loading resource definition: %s\n" % e)
return body_dict
class KubernetesHook(BaseHook):
"""
Creates Kubernetes API connection.
- use in cluster configuration by using ``extra__kubernetes__in_cluster`` in connection
- use custom config by providi... |
signaldetect/messity | reader/receivers/core.py | Python | mit | 238 | 0 | """
Handling signals of the `core` app
"""
from django.dispatch import receiver
from core import signals
from reader import actions
@receiver(signals.app_link_ready)
def app_link_ready(sender, **kwargs):
actions.create_app_link() | ||
artefactual-labs/agentarchives | setup.py | Python | agpl-3.0 | 1,074 | 0.000931 | from setuptools import setup
setup(
name="agentarchives",
description="Clients to retrieve, add, and modify records from archival management systems",
url="https://github.com/artefactual-labs/agentarchives",
author="Artefactual Systems",
author_email="info@artefactual.com",
license="AGPL 3",
... | "Programming Language :: Python : | : 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
)
|
lanpa/tensorboardX | tensorboardX/beholder/beholder.py | Python | mit | 8,355 | 0.000838 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | output.'''
# pylint: disable=redefined-variable-type
shoul | d_record = config['is_recording']
if should_record:
if not self.is_recording:
self.is_recording = True
print('Starting recording using %s',
self.video_writer.current_output().name())
self.video_writer.write_frame(frame)
elif ... |
gwaldo/graphite-web | webapp/tests/test_readers_util.py | Python | apache-2.0 | 16,540 | 0.000665 | from .base import TestCase
import os
import shutil
import time
from django.conf import settings
import whisper
import gzip
from graphite.readers import WhisperReader, FetchInProgress, MultiReader, merge_with_cache
from graphite.wsgi import application # NOQA makes sure we have a working WSGI app
from graphite.node... | nd(None)
self.assertEqual(expected_values, values)
def test_merge_with_cache_with_different_step_sum(self):
# Data values from the Reader:
start = 1465844460 # (Mon Jun 13 19:01:00 UTC 2016)
window_size = 7200 # (2 hour)
step = 60 # (1 minute)
# F | ill in half the data. Nones for the rest.
values = range(0, window_size/2, step)
for i in range(0, window_size/2, step):
values.append(None)
# Generate data that would normally come from Carbon.
# Step will be different since that is what we are testing
cache_result... |
ChinaMassClouds/copenstack-server | openstack/src/nova-2014.2/nova/cells/weights/ram_by_instance_type.py | Python | gpl-2.0 | 1,971 | 0 | # Copyright (c) 2012-2013 Rackspace Hosting
# 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
#
# Unles... | way that spreads instances.
"""
from oslo.config import cfg
from nova.cells import weights
ram_weigher_opts = [
cfg.FloatOpt('ram_weight_multiplier',
default=10.0,
help='Multiplier used for weighing ram. Negative '
'numbers mean to stack vs... | _type requested."""
def weight_multiplier(self):
return CONF.cells.ram_weight_multiplier
def _weigh_object(self, cell, weight_properties):
"""Use the 'ram_free' for a particular instance_type advertised from a
child cell's capacity to compute a weight. We want to direct the
bu... |
Daishi1223/py-http-realip | http_realip/middlewares.py | Python | mit | 1,364 | 0.002933 | from django.conf import settings
from .func import (check_if_trusted,
get_from_X_FORWARDED_FOR as _get_from_xff,
get_from_X_REAL_IP)
trusted_list = (settings.REAL_IP_TRUSTED_LIST
if hasattr(settings, 'REAL_IP_TRUSTED_LIST')
else [])
def get_from_X_FO... | equest(self, request):
if not check_if_trusted(request.META['REMOTE_ADDR'], trusted_list):
# Only header from trusted ip can be used
return
for header_name in real_ip_headers:
try:
# Get the parsing function
func = func_map[header_name... | ue
# Parse the real ip
real_ip = func(header)
if real_ip:
request.META['REMOTE_ADDR'] = real_ip
break
|
HBEE/odoo-addons | project_analytic_integration/__openerp__.py | Python | agpl-3.0 | 1,908 | 0.002096 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#### | ##########################################################################
{
'name': 'Project and Analytic Account integration impprovements',
'version': '8.0.1.0.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Project and Analytic Account integration imp... |
skywalka/splunk-for-nagios | bin/livehostsdownstatus.py | Python | gpl-3.0 | 1,840 | 0.044565 | # Script to request hosts with DOWN status and total hosts by accessing MK Livestatus
# Required field to be passed to this script from Splunk: n/a
import socket,string,sys,re,splunk.Intersplunk,mklivestatus
results = []
try:
results,dummyresults,settings = splunk.Intersplunk.getOrganizedResults()
for r in ... | query = "".join(content)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((h, PORT))
except socket.error, (value,message):
if s:
s.close()
#Error: Could not open socket: connection refused (MK Livestatus not setup in xi... | Livestatus module not loaded?
s.close()
else:
livehosts2 = data.strip()
livehosts = livehosts2.split(";")
s.close()
livehostsdownind = int(livehosts[0])
livehoststotalind = int(livehosts[1])
livehostsdown = livehostsdown + livehostsdownind
livehoststotal = livehoststot... |
jpinedaf/pyspeckit | examples/example_pNH2D.py | Python | mit | 1,329 | 0.017306 | import pyspeckit
import os
from pyspeckit.spectrum.models | import nh2d
import numpy as np
import astropy.units as u
if not os.path.exists('p-nh2d_spec.fits'):
import astropy.utils.data as aud
from astropy.io import fits
f = aud.down | load_file('https://github.com/pyspeckit/pyspeckit-example-files/raw/master/p-nh2d_spec.fits')
with fits.open(f) as ff:
ff.writeto('p-nh2d_spec.fits')
# Load the spectrum
spec = pyspeckit.Spectrum('p-nh2d_spec.fits')
# Determine rms from line free section and load into cube
rms = np.std(spec.data[10:340])
... |
Serulab/Py4Bio | code/ch20/estimateintrons.py | Python | mit | 4,302 | 0.006044 | #!/usr/bin/env python
im | port argparse
import os
import sqlite3
from Bio import SeqIO, SeqRecord, Seq
from Bio.Align.Applications import ClustalwCommandline
from Bio.Blast import NCBIXML
from Bio.Blast.Applications import NcbiblastnCommandline as bn
from Bio import AlignIO
AT_DB_FILE = 'AT.db'
BLAST_EXE = '~/opt/ncbi-blast-2.6.0+/bin/blastn'... | '../../clustalw2'
def allgaps(seq):
"""Return a list with tuples containing all gap positions
and length. seq is a string."""
gaps = []
indash = False
for i, c in enumerate(seq):
if indash is False and c == '-':
c_ini = i
indash = True
dashn = 0
... |
rwl/PyCIM | CIM15/IEC61970/LoadModel/Season.py | Python | mit | 3,209 | 0.002805 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | {"name": "SeasonName"}
_refs = ["SeasonDayTypeSchedules"]
_many_refs = ["SeasonDayTypeSchedules"]
def getSeasonDayTypeSchedules(self):
"""Schedules that use this Season.
"""
| return self._SeasonDayTypeSchedules
def setSeasonDayTypeSchedules(self, value):
for x in self._SeasonDayTypeSchedules:
x.Season = None
for y in value:
y._Season = self
self._SeasonDayTypeSchedules = value
SeasonDayTypeSchedules = property(getSeasonDayTyp... |
Twinstar2/Python_Master_scripts | data_mining/extract_all_targz_in_dir.py | Python | mit | 2,292 | 0.004363 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import shutil
import urllib2
from contextlib import closing
from os.path import basename
import gzip
import tarfile
# argparse for information
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--directory", help="input dire... | try:
| with gzip.open((os.path.join(dirpath, file)), 'rb') as f:
file_content = f.read()
extracted_file = open((os.path.join(dirpath, os.path.splitext(file)[0])), 'w')
extracted_file.write(file_content)
extracted_file.close()
# ... |
vleo/vleo-notebook | test_python/multiprocessing/test_multiprocessing.py | Python | gpl-3.0 | 811 | 0.014797 | from multiprocessing import Process,Queue
import os
class TestMP:
def __init__(self,n):
self.n = n
@staticmethod
def worker(q):
"""worker function"""
# print('worker',*args)
# print("ppid= {} pid= {}".format(os.getppid(),os.getpid()))
q.put([1,'x',(os.getpid(),[])])
... | rn
def main(self):
if __name__ == '__main__':
jobs = []
for i in | range(self.n):
q = Queue()
p = Process(target=self.worker,args=(q,))
jobs.append((p,q))
p.start()
for i in range(self.n):
j=jobs.pop(0)
j[0].join()
msg = j[1].get()
print("job no ... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/db/backends/oracle/base.py | Python | artistic-2.0 | 24,995 | 0.00164 | """
Oracle database backend for Django.
Requires cx_Oracle: http://cx-oracle.sourceforge.net/
"""
from __future__ import unicode_literals
import datetime
import decimal
import os
import platform
import sys
import warnings
from django.conf import settings
from django.db import utils
from django.db.backends.base.base ... | on
# or the result of a bilateral transformation).
# In those cases, special characters for LIKE operators (e.g. \, *, _) should be
# escaped on database side.
#
# Note: we use str.format() here for readability as '%' is used as a wildcard for
# the LIKE operator.
pattern_esc = r"R | EPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')"
_pattern_ops = {
'contains': "'%%' || {} || '%%'",
'icontains': "'%%' || UPPER({}) || '%%'",
'startswith': "{} || '%%'",
'istartswith': "UPPER({}) || '%%'",
'endswith': "'%%' || {}",
'iendswith': "'%%' |... |
rohitranjan1991/home-assistant | homeassistant/components/screenlogic/services.py | Python | mit | 3,148 | 0.001906 | """Services for ScreenLogic integration."""
import logging
from screenlogicpy import ScreenLogicError
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassi... | unload_screenlogic_services(hass: HomeAssistant):
"""Unload services for the ScreenLogic integration."""
if hass.data[DOMAIN]:
# There is still another config entry for this domain, don't remove services.
return
| if not hass.services.has_service(DOMAIN, SERVICE_SET_COLOR_MODE):
return
_LOGGER.info("Unloading ScreenLogic Services")
hass.services.async_remove(domain=DOMAIN, service=SERVICE_SET_COLOR_MODE)
|
ddico/odoo | addons/website_event/models/website.py | Python | agpl-3.0 | 491 | 0.004073 | # -*- coding: utf-8 -*-
# Part of Odo | o. See LICENSE file for full copyright and licensing details.
from odoo import models, _
from odoo.addons.http_routing.models.ir_http import url_for
class Website(models.Model):
_inherit = "website"
def get_suggested_controllers(self):
suggested_controllers = super(Website, self).get_suggested_contr... | vents'), url_for('/event'), 'website_event'))
return suggested_controllers
|
drimer/NetControl | netcontrol/test/util/test_singleton.py | Python | gpl-2.0 | 593 | 0.001686 | from unittest import Tes | tCase
from netcontrol.util import singleton
@singleton
class SingletonClass(object):
pass
@singleton
class SingletonClassWithAttributes(object):
@classmethod
def setup_attributes(cls):
cls.value = 1
class SingletonTest(TestCase):
def test_that_only_instance_is_created(self):
obj_o... | that_instance_is_created_using_setup_method(self):
obj = SingletonClassWithAttributes()
self.assertEqual(1, obj.value)
|
jumoconnect/openjumo | jumodjango/etc/credit_card_fields.py | Python | mit | 4,687 | 0.00256 | import re
from datetime import date
from calendar import monthrange, IllegalMonthError
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
# from - https://github.com/bryanchow/django-creditcard-fields
CREDIT_CARD_RE = r'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][... | et(forms.MultiWidget):
"""
Widget containing two select boxes for selecting the month and year.
"""
def decompress(self, value):
return [value.month, value.year] if value else [None, None]
def format_output(self, rendered_widgets):
return u'<div class="expirydatefield">%s</div>' % ... | alueField):
"""
Form field that validates credit card expiry dates.
"""
default_error_messages = {
'invalid_month': _(u'Please enter a valid month.'),
'invalid_year': _(u'Please enter a valid year.'),
'date_passed': _(u'This expiry date has passed.'),
}
def __init__(sel... |
FrostyX/tracer | tracer/resources/processes.py | Python | gpl-2.0 | 9,071 | 0.026127 | #-*- coding: utf-8 -*-
# processes.py
# Module providing informations about processes
#
# Copyright (C) 2016 Jakub Kadlcik
#
# 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, or (at your... | "
# User who run the process can be deleted
try:
return super(Process, self).username()
except KeyError:
return None
def children(self, recursive=False):
"""The collection of process's children. Ea | ch of them casted from ``psutil.Process``
to tracer ``Process``."""
children = super(Process, self).children(recursive)
return ProcessesCollection([Process(child.pid) for child in children])
@property
def exe(self):
"""The absolute path to process executable. Cleaned from arbitrary strings
which appears on... |
xfire/guppy | test/doctest_assertions.py | Python | gpl-2.0 | 3,440 | 0 | #!/usr/bin/env python
#
# vim:syntax=python:sw=4:ts=4:expandtab
"""
test hasAttributes()
---------------------
>>> from guppy import hasAttributes
>>> class Foo(object):
... def __init__(self):
... self.a = 23
... self.b = 42
>>> hasAttributes('a')(Foo())
True... | rotocol)(FooBar())
False
>>> implementProtocol(AllProtocol)(FooBar())
False
>>> implementProtocol(SpamEggsProtocol)(SpamEggs())
True
>>> implementProtocol | (FooBarProtocol)(SpamEggs())
False
>>> implementProtocol(AllProtocol)(SpamEggs())
False
>>> implementProtocol(SpamEggsProtocol)(All())
True
>>> implementProtocol(FooBarProtocol)(All())
True
>>> implementProtocol((SpamEggsProtocol, FooBarProtocol))(All())
True
>>> implementProtoc... |
ella/django-ratings | tests/example_project/settings/config.py | Python | bsd-3-clause | 1,465 | 0.004778 | from tempfile im | port gettempdir
from os.path import join, dirname
import example_project
ADMINS = (
)
MANAGERS = ADMINS
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DISABLE_CACHE_TEMPLATE = DEBUG
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = join(gettempdir(), 'django_ratings_example_project.db')
TEST_DATABASE_NAME =joi | n(gettempdir(), 'test_django_ratings_example_project.db')
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
TIME_ZONE = 'Europe/Prague'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
# Make this unique, and don't share it with anybody.
SECRET_KEY = '88b-01f^x4lh$-s5-hdccnicekg07)n... |
ajkerr0/kappa | kappa/plot.py | Python | mit | 16,060 | 0.022167 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 22 14:18:45 2016
@author: Alex Kerr
Define functions that draw molecule objects.
"""
import copy
from itertools import cycle
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from .molecule import ... | """
plt.sca(ax)
posList = molecule.posList
length = len(molecule)
for bond in molecule.bondList:
i,j = bond
plt.plot([posList[i][0],posList[j][0]],
[posList[i][1],posList[j][1]],
color='k', zorder=-1, linewidth=linewidth)
cLis... | st[count]]])
plt.scatter(posList[:,0],posList[:,1],s=1.5*radList[molecule.zList]*size_scale,c=cList,
edgecolors='k')
if indices:
for index, pos in enumerate(molecule.posList):
plt.annotate(index, (pos[0]+.1, pos[1]+.1), color='b', fontsize=10)
... |
petxo/clitellum | clitellum/endpoints/channels/reconnectiontimers.py | Python | gpl-3.0 | 3,471 | 0.007779 | from time import sleep
import math
__author__ = 'sergio'
## @package clitellum.endpoints.channels.reconnectiontimers
# Este paquete contiene las clases para los temporizadores de reconexion
#
## Metodo factoria que crea una instancia de un temporizador
# instantaneo
def CreateInstantTimer():
return Instant | ReconnectionTimer()
## Metodo factoria que crea una instancia de un temporizador
# logaritmico
def CreateLogarithmicTimer():
return LogarithmicReconnec | tionTimer()
## Metodo factoria que crear una instancia de un temporizador de tiempo constante
def CreateConstantTimer(waiting_time=5):
return ConstantReconnectionTimer(waiting_time=waiting_time)
## Crea una temporizador en funcion del tipo especificado
# @param type Tipo de temporizador "Instant", "Logarithmic"
... |
qbuat/rootpy | examples/stats/plot_quantiles.py | Python | gpl-3.0 | 1,944 | 0.002058 | #!/usr/bin/env python
"""
=================================================
Draw a Quantile-Quantile Plot and Confidence Band
=================================================
This is an example of drawing a quantile-quantile plot with a confidence level
(CL) band.
"""
print __doc__
import ROOT
from rootpy.interactive... | tmargin=0.05,
textsize=20)
leg.Draw()
pad = c.cd(2)
gr = qqgraph(h1, h2)
gr.xaxis.title = h1.title
gr.yaxis.title = h2.title
gr.fillcolor = 17
gr.fillstyle = 'solid'
gr.linecolor = 17
gr.markercolor = 'darkred'
gr.markerstyle = 20
gr.title = "QQ with CL"
gr.Draw("ap")
x_min = gr.GetXaxis().GetXmin()
x_... | is().GetXmax()
gr.Draw('a3')
gr.Draw('Xp same')
# a straight line y=x to be a reference
f_dia = ROOT.TF1("f_dia", "x",
h1.GetXaxis().GetXmin(),
h1.GetXaxis().GetXmax())
f_dia.SetLineColor(9)
f_dia.SetLineWidth(2)
f_dia.SetLineStyle(2)
f_dia.Draw("same")
leg = Legend(3, pad=pad, leftm... |
thebarbershopper/Empire | lib/modules/lateral_movement/invoke_psexec.py | Python | bsd-3-clause | 5,198 | 0.012697 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-PsExec',
'Author': ['@harmj0y'],
'Description': ('Executes a stager on remote hosts using PsExec type functionality.'),
'Background' : Tru... | 'Description' : 'User-agent strin | g to use for the staging request (default, none, or other).',
'Required' : False,
'Value' : 'default'
},
'Proxy' : {
'Description' : 'Proxy to use for request (default, none, or other).',
'Required' : Fal... |
mandawilson/cbioportal | core/src/test/scripts/system_tests_validate_data.py | Python | agpl-3.0 | 11,621 | 0.001807 | #!/usr/bin/env python3
'''
Copyright (c) 2016 The Hyve B.V.
This code is licensed under the GNU Affero General Public License (AGPL),
version 3, or (at your option) any later version.
'''
import unittest
import logging
import tempfile
import os
import shutil
import time
import difflib
from importer import validateDa... | args = validateData.interface(args)
# Execute main function with arguments provided through sy | s.argv
exit_status = validateData.main_validate(args)
self.assertEqual(0, exit_status)
self.assertFileGenerated(out_file_name,
'test_data/study_es_0/result_report.html')
def test_portal_mismatch(self):
'''Test if validation fails when data contradict... |
nooperpudd/pulsar | examples/calculator/tests.py | Python | bsd-3-clause | 9,018 | 0.000887 | '''Tests the RPC "calculator" example.'''
import unittest
import types
from pulsar import send
from pulsar.apps import rpc, http
from pulsar.apps.test import dont_run_with_thread
from .manage import server, Root, Calculator
class TestRpcOnThread(unittest.TestCase):
app_cfg = None
concurrency = 'thread'
... | d, batch_response in enumerate(batch_generator):
self.assertI | n(ind, (0, 1))
if call_id1 == batch_response.id:
self.assertEqual(batch_response.result, 'pong')
self.assertIsNone(batch_response.exception)
elif call_id2 == batch_response.id:
self.assertEqual(batch_response.result, 2)
self.assertI... |
Jeff-Tian/mybnb | Python27/Lib/bsddb/test/test_all.py | Python | apache-2.0 | 19,765 | 0.011131 | """Run all test cases.
"""
import sys
import os
import unittest
try:
# For Pythons w/distutils pybsddb
import bsddb3 as bsddb
except ImportError:
# For Python 2.3
import bsddb
if sys.version_info[0] >= 3 :
charset = "iso8859-1" # Full 8 bit
class logcursor_py3k(object) :
... | ext")()
return self._fix(v)
next = __next__
def previous(self) :
v = self._dbcursor.previous()
return self._fix(v)
def last(self) :
v = self._dbcursor.last()
return self._fix(v)
def set(self, k) :
i | f isinstance(k, str) :
k = bytes(k, charset)
v = self._dbcursor.set(k)
return self._fix(v)
def set_recno(self, num) :
v = self._dbcursor.set_recno(num)
return self._fix(v)
def set_range(self, k, dlen=-1, doff=-1) :
i... |
huyx/icall | setup.py | Python | lgpl-3.0 | 1,026 | 0.024366 | # -*- coding: utf-8 -*-
from distutils.core import setup
import os.path
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Library or Lesser General Public Lice... | oftware Development :: Li | braries :: Python Modules",
]
def read(fname):
fname = os.path.join(os.path.dirname(__file__), fname)
return open(fname).read().strip()
def read_files(*fnames):
return '\r\n\r\n\r\n'.join(map(read, fnames))
setup(
name = 'icall',
version = '0.3.4',
py_modules = ['icall'],
description ... |
GoogleCloudPlatform/grpc-gcp-python | firestore/examples/end2end/src/Write.py | Python | apache-2.0 | 2,967 | 0.013482 | #! /usr/bin/python
import sys
import os
import json
import grpc
import time
import subprocess
from google.oauth2 import service_account
import google.oauth2.credentials
import google.auth.transport.requests
import google.auth.transport.grpc
from google.firestore.v1beta1 import firestore_pb2
from google.firestore.v1be... | yield msg
def generate_messages(database, writes, stream_id, stream_token):
# writes can be an array and append to the messages, so it can write multiple Write
# here just write one as example
messages = [
firestore_pb2.WriteRequest(database=database, writes = []),
firestore_... | = stream_token)
]
for msg in messages:
yield msg
def main():
fl = os.path.dirname(os.path.abspath(__file__))
fn = os.path.join(fl, 'grpc.json')
with open(fn) as grpc_file:
item = json.load(grpc_file)
creds = item["grpc"]["Write"]["credentials"]
... |
autodefrost/sandbox | python/test_rel_import/package1/subpackage2/module1h.py | Python | apache-2.0 | 88 | 0.011364 | from ..subpackage1 import module1g
def func1h():
print('1h')
module1g.fu | nc1g()
| |
astraw/PyUniversalLibrary | examples/ulai01.py | Python | bsd-3-clause | 1,869 | 0 | # Copyright (c) 2005, California Institute of Technology
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# * Redistributions of source code must retain the above copyright
# notice, th... | chnol | ogy nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior
# written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMI... |
carlohamalainen/volgenmodel-nipype | new_data_to_atlas_space.py | Python | bsd-3-clause | 4,566 | 0 | #!/usr/bin/env python3
import os
import os.path
from nipype.interfaces.utility import IdentityInterface, Function
from nipype.interfaces.io import SelectFiles, DataSink, DataGrabber
from nipype.pipeline.engine import Workflow, Node, MapNode
from nipype.interfaces.minc import Resample, BigAverage, VolSymm
import argpars... | ed=True
)
parser.add_argument(
"--xfm_pattern",
type=str,
required=True
)
parser.add_argument(
"--source_dir",
type=str,
required=True
)
parser.add_argument(
| "--source_pattern",
type=str,
required=True
)
parser.add_argument(
"--atlas_dir",
type=str,
required=True
)
parser.add_argument(
"--atlas_pattern",
type=str,
required=True
)
parser.add_argument(
"--work_dir",
... |
south-coast-science/scs_core | src/scs_core/data/queue_report.py | Python | mit | 4,239 | 0.006841 | """
Created on 26 Aug 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from collections import OrderedDict
from enum import Enum
from scs_core.data.json import JSONReport
# --------------------------------------------------------------------------------------------------------------------
class... | --------------------------------------------------
def __str__(self, *args, **kwargs):
return "QueueReport:{length:%s, client_state:%s, publish_success:%s}" % \
(self.length, self.client_state, self.publish_success)
# ---------------------- | ----------------------------------------------------------------------------------------------
class ClientStatus(Enum):
"""
classdocs
"""
NONE = 0
INHIBITED = 1
WAITING = 2
CONNECTING = 3
CONNECTED = 4
# -----------------------------------... |
arokem/nipy | nipy/labs/utils/tests/test_misc.py | Python | bsd-3-clause | 2,093 | 0.010511 | #!/usr/bin/env python
import numpy as np
from scipy import special
from ..routines import median, mahalanobis, gamln, psi
from nose.tools import assert_true
from numpy.testing import assert_almost_equal, assert_equal, TestCase
class TestAll(TestCase):
def test_median(self):
x = np.random.rand(100)
... | lg.inv(Aa[:,:,i,j]), x[:,i,j]))
f_mah = (mahalanobis(x, Aa))[i,j]
assert_true(np.allclose(mah, f_mah))
def test_gamln(self): |
for x in (0.01+100*np.random.random(50)):
scipy_gamln = special.gammaln(x)
my_gamln = gamln(x)
assert_almost_equal(scipy_gamln, my_gamln)
def test_psi(self):
for x in (0.01+100*np.random.random(50)):
scipy_psi = special.psi(x)
my_psi = ps... |
CroceRossaItaliana/jorvik | anagrafica/migrations/0047_auto_20170525_2011.py | Python | gpl-3.0 | 865 | 0.001156 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-05-25 20:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('anagrafica', '0046_delega_stato'),
]
operations = [
migrations.AlterIndexTogether(
... | ', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('tipo', 'oggetto_tipo', 'oggetto_id'), ('persona', 'inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'stato'), ('persona', 'stato'), ('persona', 'inizio', 'fine'), ('inizio', 'fine', 'tipo'), ('pe | rsona', 'inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('persona', 'tipo'), ('oggetto_tipo', 'oggetto_id'), ('inizio', 'fine', 'stato'), ('inizio', 'fine')]),
),
]
|
davivcgarcia/wttd-15 | eventex/core/tests/test_models_speaker_contact.py | Python | gpl-3.0 | 3,199 | 0 | # coding: utf-8
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be use... | ntact.
"""
contact = Contact.objects.create(
speaker=self.speaker,
kind='E',
value='henrique@bastos.net'
)
self.assertEqual(1, contact.pk)
def test_phone(self):
"""
| Speaker should have email contact.
"""
contact = Contact.objects.create(
speaker=self.speaker,
kind='P',
value='21-987654321'
)
self.assertEqual(1, contact.pk)
def test_fax(self):
"""
Speaker should have email contact.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.