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 |
|---|---|---|---|---|---|---|---|---|
SunPower/pvfactors | pvfactors/tests/test_geometry/test_timeseries.py | Python | bsd-3-clause | 13,582 | 0 | import os
from pvfactors.geometry.timeseries import TsPointCoords, TsLineCoords
from pvfactors.geometry.pvrow import TsPVRow
from pvfactors.geometry.pvground import TsGround, TsGroundElement
import pandas as pd
import numpy as np
from pvfactors.geometry.pvrow import PVRow
from pvfactors.geometry.base import \
BaseS... | back_surface = (pvrow.back.list_segments[1].illum_co | llection
.list_surfaces[0])
n_vector_front = front_surface.n_vector
n_vector_back = back_surface.n_vector
expected_n_vec_front = np.array([-0.68404029, 1.87938524])
np.testing.assert_allclose(n_vector_front, expected_n_vec_front)
np.testing.assert_allclose(n_vector_back, - expect... |
azaghal/ansible | test/units/plugins/connection/test_local.py | Python | gpl-3.0 | 1,355 | 0.001476 | #
# (c) 2020 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | t
from ansible.plugins.connection import local
from ansible.playbook.play_context import PlayContext
class TestLocalConne | ctionClass(unittest.TestCase):
def test_local_connection_module(self):
play_context = PlayContext()
play_context.prompt = (
'[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: '
)
in_stream = StringIO()
self.assertIsInstance(local.Connection(play... |
louistin/thinkstation | a_byte_of_python/unit_15_standard_library/compress_test.py | Python | mit | 207 | 0 | #!/usr/bin/pyth | on
# _*_ coding: utf-8 _*_
import zlib
s = b'witch which has which witches wrist watch'
print len(s)
t = zlib.compress(s)
print len(t)
print t
print zlib.decompress(t)
print zlib.crc | 32(s)
|
CalthorpeAnalytics/urbanfootprint | footprint/main/management/commands/create_datadump.py | Python | gpl-3.0 | 4,014 | 0.005232 |
# UrbanFootprint v1.5
# Copyright (C) 2017 Calthorpe Analytics
#
# This file is part of UrbanFootprint version 1.5
#
# UrbanFootprint is distributed under the terms of the GNU General
# Public License version 3, as published by the Free Software Foundation. This
# code is distributed WITHOUT ANY WARRANTY, without impl... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License v3 for more details; see <http://www.gnu.org/licenses/>.
import pwd
import shlex
import subprocess
from optparse import make_option
import os
from distutils import spawn
from django.conf import settings
from django.core.manag... | word_loaded
class Command(BaseCommand):
args = '<destination_folder> (optional - if not specified use settings.py option)'
help = 'Creates a data dump'
# I hate having to use optparse. We should be using argparse.
# When https://code.djangoproject.com/ticket/19973 gets fixed, we can
# use the new... |
rahulunair/nova | nova/api/openstack/compute/limits.py | Python | apache-2.0 | 3,590 | 0 | # Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | 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 nova.api.openstack.api_version_request \
import MAX_IMAGE_META_PROXY_API_VERSION
from nova.api.openstack.api_version_request \
impo... | WITHOUT_IMAGE_META_PROXY_API_VERSION
from nova.api.openstack.api_version_request \
import MIN_WITHOUT_PROXY_API_SUPPORT_VERSION
from nova.api.openstack.compute.schemas import limits
from nova.api.openstack.compute.views import limits as limits_views
from nova.api.openstack import wsgi
from nova.api import validatio... |
GenericStudent/home-assistant | homeassistant/components/openweathermap/config_flow.py | Python | apache-2.0 | 4,415 | 0.00068 | """Config flow for OpenWeatherMap."""
from pyowm import OWM
from pyowm.exceptions.api_call_error import APICallError
from pyowm.exceptions.api_response_error import UnauthorizedError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import (
CONF_API_KEY,
CONF_LATITUDE,... | fig[CONF_LANGUAGE] = DEFAULT_LANGUAGE
return await self.async_step_user(config)
class OpenWeatherMapOptionsFlow(config_entries.OptionsFlow):
"""Handle options."""
def __init__(self, config_entry):
"""Initialize options flow."""
self.config_entry = config_entry
async def async_ste... | urn self.async_create_entry(title="", data=user_input)
return self.async_show_form(
step_id="init",
data_schema=self._get_options_schema(),
)
def _get_options_schema(self):
return vol.Schema(
{
vol.Optional(
CONF_MODE,... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/aio/operations/_network_interfaces_operations.py | Python | mit | 64,200 | 0.005109 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | rm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class NetworkInterfacesOperations:
| """NetworkInterfacesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.netwo... |
Digilent/u-boot-digilent | tools/binman/etype/x86_reset16.py | Python | gpl-2.0 | 1,018 | 0.000982 | # SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Entry-type module for the 16-bit x86 | reset code for U-Boot
#
from binman.entry import Entry
from binman.etype.blob import Entry_blob
class Entry_x86_reset16(Entry_blob):
"""x86 16-bit reset code for U-Boot
Properties / Entry arguments:
- filename: Filename of u-boot-x86-reset16.bin (default
'u-boot-x86-reset16.bin')
x86... | et CONFIG_RESET_VEC_LOC. The code is responsible
for jumping to the x86-start16 code, which continues execution.
For 64-bit U-Boot, the 'x86_reset16_spl' entry type is used instead.
"""
def __init__(self, section, etype, node):
super().__init__(section, etype, node)
def GetDefaultFilename(... |
xahhy/Django-vod | vodmanagement/models.py | Python | lgpl-3.0 | 14,356 | 0.002854 | import logging
import os
import datetime
import six
import humanfriendly
from pathlib import Path
from django.db import models
from django.utils.html import format_html
from django.utils.encoding import uri_to_iri
from django.core.management import call_command
from django.utils.safestring import mark_safe
from django.... | """
print('save image')
return "%s/%s" % (new_id, filename)
def upload_image_location(instance, filename):
VodModel = instance.__class__
if VodModel.objects.count() is not 0:
new_id = VodModel.objects.order_by("id").last().id + 1
else:
new_id = 0
folder = instance.save_path
... | '_' + folder
return "%s/images/%s/%s" % (category, new_id, filename)
def upload_record_image_location(instance, filename):
return "%s/images/%s" % (settings.RECORD_MEDIA_FOLDER, filename)
def default_description(instance):
default = instance.title
print(default)
return 'The %s description' % def... |
pymedusa/SickRage | medusa/server/api/v2/auth.py | Python | gpl-3.0 | 2,962 | 0.001013 | # coding=utf-8
"""Request handler for authentication."""
from __future__ import unicode_literals
import logging
import random
import string
import time
from builtins import range
import jwt
from medusa import app, helpers, notifiers
from medusa.logger.adapters.style import BraceAdapter
from medusa.server.api.v2.base... | gin(error='Invalid credentials')
return self._login(submitted_exp)
def _login(self, exp=86400):
self.set_header('Content-Type', 'application/json')
if app.NOTIFY_ON_LOGIN and not helpers.is_ip_private(self.request.remote_ip):
notifiers.notify_login(self.request.remote_ip)
... | ime.time())
return self._ok(data={
'token': jwt.encode({
'iss': 'Medusa ' + text_type(app.APP_VERSION),
'iat': time_now,
# @TODO: The jti should be saved so we can revoke tokens
'jti': ''.join(random.choice(string.ascii_letters + string... |
optimizely/tcollector | tcollector.py | Python | lgpl-3.0 | 53,880 | 0.001188 | #!/usr/bin/python
# This file is part of tcollector.
# Copyright (C) 2010 The tcollector Authors.
#
# 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 of the License, or (a... | urn
# iterate for each line we have
while self.buffer:
idx = self.buffer.find('\n')
if idx == -1:
break
# one full line is now found and we can pull it out of the buffer
line = self.buffer[0:idx].strip()
if line:
... | ime.time())
self.buffer = self.buffer[idx+1:]
def collect(self):
"""Reads input from the collector and returns the lines up to whomever
is calling us. This is a generator that returns a line as it
becomes available."""
while self.proc is not None:
sel... |
kevinhughes27/TensorKart | record.py | Python | mit | 6,952 | 0.008631 | #!/usr/bin/env python
import numpy as np
import os
import shutil
import mss
import matplotlib
matplotlib.use('TkAgg')
from datetime import datetime
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigCanvas
from PIL import ImageTk, Image
import sys
PY3_OR_LATER... | xists - i.e. may be saving over data
if os.path.exists(self.outputDir):
# overwrite the data, yes/no?
if tkMessageBox.askyesno(tit | le='Warning!', message='Output Directory Exists - Overwrite Data?', parent=self.root):
# delete & re-make the dir:
shutil.rmtree(self.outputDir)
os.mkdir(self.outputDir)
# answer was 'no', so do not overwrite the data
else:
... |
seankelly/buildbot | master/buildbot/scripts/trycmd.py | Python | gpl-2.0 | 903 | 0 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | R PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from... | t.Try(config)
t.run()
return 0
|
ppb/ppb-vector | tests/test_member_access.py | Python | artistic-2.0 | 444 | 0 | from hypothesis import gi | ven
from ppb_vector import Vector
from utils import floats, vectors
@given(x=floats(), y=floats())
def test_class_member_access(x: float, y: float):
v = Vector(x, y)
assert v.x == x
assert v.y == y
@given(v=vectors())
def test_index_access(v: Vector):
assert v[0] == v.x
assert v[1] == v.y
@gi... | ssert v["y"] == v.y
|
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/sparse/linalg/isolve/lsmr.py | Python | mit | 15,126 | 0.000463 | """
Copyright (C) 2010 David Fong and Michael Saunders
LSMR us | es an iterative method.
07 Jun 2010: Documentation updated
03 Jun 2010: First release version in Python
David Chin-lung Fong clfong@stanford.edu
Institute for Computational and Mathematical Engineering
Stanford University
Michael Saunders saunders@stanford.edu
Systems Optimization Laborator... | py import zeros, infty, atleast_1d
from numpy.linalg import norm
from math import sqrt
from scipy.sparse.linalg.interface import aslinearoperator
from .lsqr import _sym_ortho
def lsmr(A, b, damp=0.0, atol=1e-6, btol=1e-6, conlim=1e8,
maxiter=None, show=False, x0=None):
"""Iterative solver for least-squa... |
lecaoquochung/ddnb.django | tests/staticfiles_tests/storage.py | Python | bsd-3-clause | 660 | 0 | from datetime import datetime
from django.core.files import storage
from django.contrib.staticfiles.storag | e import CachedStaticFilesStorage
class DummyStorage(storage.Storage):
"""
A storage class that does implement modified_time() but raises
NotImplementedError when calling
"""
def _save(self, name, content):
return 'dummy'
def delete(self, name):
pass
def exists(self, name... | lesStorage):
def file_hash(self, name, content=None):
return 'deploy12345'
|
diagonalwalnut/Experience | lrs/util/req_validate.py | Python | apache-2.0 | 32,206 | 0.006334 | import json
import urllib2
from isodate.isodatetime import parse_datetime
from isodate.isoerror import ISO8601Error
from django.conf import settings
from util import validate_uuid, convert_to_dict, get_agent_ifp
from Authorization import auth
from StatementValidator import StatementValidator
from ..models import Sta... | == | 'Group':
contains_account = len([x for m in stmt['authority']['member'] for x in m.keys() if 'account' in x]) > 0
if contains_account:
for agent in stmt['authority']['member']:
if 'account' in agent:
... |
avsm/xen-unstable | tools/python/xen/xend/XendConstants.py | Python | gpl-2.0 | 3,953 | 0.012396 | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... | SLOT = 0x100
#
# tmem
#
TMEM_CONTROL = 0
TMEM_NEW_POOL = 1
TMEM_DESTROY_POOL = 2
TMEM_NEW_PAGE = 3
TMEM_PUT_PAGE = 4
TMEM_GET_PAGE = 5
TMEM_FLUSH_PAGE = 6
TMEM_FLUSH_OBJECT = 7
TMEM_READ = 8
TMEM_WRITE | = 9
TMEM_XCHG = 10
TMEMC_THAW = 0
TMEMC_FREEZE = 1
TMEMC_FLUSH = 2
TMEMC_DESTROY = 3
TMEMC_LIST = 4
TMEMC_SET_WEIGHT = 5
TMEMC_SET_CAP = 6
TMEMC_SET_COMPRESS = 7
|
slashk/prowl.alfredworkflow | prowl_alfred.py | Python | apache-2.0 | 1,835 | 0.00545 | # Copyright 2013 Ken Pepple <ken@pepple.info>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | and limitations
# under the License.
import alfred_utils as utils
import requests
PROWL_URL = "https://api.prowlapp.com/publicapi/"
DEFAULT_PRIORITY = 0
VALID_PRIORITIES = [-2, -1, 0, 1, 2]
def get_api_key():
return utils.get_config('apikey')
def get_priority_key():
try:
p = utils.get_config('pri... | turn p
def verify_apikey(apikey):
parameters = {'apikey': apikey}
r = requests.post(PROWL_URL + "verify", params=parameters)
return r.ok
def save_api_key(apikey):
utils.save_config('apikey',apikey)
def send_prowl(description, application="Alfred", event="event", priority=0):
try:
apikey =... |
Vaidyanath/tempest | tempest/api/object_storage/test_container_sync_middleware.py | Python | apache-2.0 | 1,985 | 0 | # Copyright(c)2015 NTT corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un | less required by a | pplicable 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 tempest.... |
saukrIppl/seahub | thirdpart/openpyxl-2.3.0-py2.7.egg/openpyxl/formatting/__init__.py | Python | apache-2.0 | 144 | 0 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from .formatting import | ConditionalFormatting
from .rule | import Rule
|
anchore/anchore-engine | tests/unit/anchore_engine/auth/test_common.py | Python | apache-2.0 | 3,612 | 0.001661 | import json
import time
import pytest
from anchore_engine.auth.common import (
get_creds_by_registry,
get_docker_registry_userpw,
registry_record_matches,
)
_test_username = "tonystark"
_test_password = "potts"
_test_registry_meta = {
"authorizationToken": "{}:{}".format(_test_username, _test_passwor... | ("docker.io/myus | er/myrepo", "docker.io", "myuser/myrepo2"),
],
)
def test_registry_record_matches_non(registry_record_str, registry, repository):
assert not registry_record_matches(registry_record_str, registry, repository)
|
simondlevy/ISCPP | Chapter08/sumton.py | Python | gpl-3.0 | 926 | 0.006479 | #!/usr/bin/env python3
"""
sumton.py : compute the sum of 0 through N
Copyright (C) Simon D. Levy 2016
This file is part of ISCPP.
ISCPP 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... | ributed 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 Lesser General Public License
a | long with this code. If not, see <http:#www.gnu.org/licenses/>.
"""
def sumToN(n):
res = 0
for k in range(0,n+1):
res = res + k
return res
if __name__ == "__main__":
"""
Example
"""
print(sumToN(5))
|
sevein/archivematica | src/MCPClient/lib/clientScripts/generateDIPFromAIPGenerateDIP.py | Python | agpl-3.0 | 2,681 | 0.002611 | #!/usr/bin/env python2
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, ... |
# Archivematica 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
# alon... | h@artefactual.com>
from __future__ import print_function
import os
import sys
import shutil
import django
django.setup()
# dashboard
from main.models import Job, SIP
# archivematicaCommon
from custom_handlers import get_script_logger
from databaseFunctions import createSIP
if __name__ == '__main__':
logger = ge... |
ESS-LLP/erpnext | erpnext/projects/doctype/task/task.py | Python | gpl-3.0 | 12,175 | 0.026201 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import json
import frappe
from frappe import _, throw
from frappe.desk.form.assign_to import clear, close_all_assignments
from frappe.model.mapper imp... | k, "is_template"):
parent_task_format = """<a href="#Form/Task/{0}">{0}</a>""".format(self.parent_task)
frappe.throw(_("Parent Task {0} is not a Template Task").format(parent_task_format | ))
def validate_depends_on_tasks(self):
if self.depends_on:
for task in self.depends_on:
if not frappe.db.get_value("Task", task.task, "is_template"):
dependent_task_format = """<a href="#Form/Task/{0}">{0}</a>""".format(task.task)
frappe.throw(_("Dependent Task {0} is not a Template Task").format(... |
belangeo/pyo | pyo/examples/sequencing/01_starttime_duration.py | Python | lgpl-3.0 | 1,118 | 0.002683 | #!/usr/bin/env python
# encoding: utf-8
"""
Show how to use `dur` and `delay` parameters of play() and out()
methods to sequence events over time.
"""
from pyo import *
import random
s = Server(duplex=0).b | oot()
num = 70
freqs = [random.uniform(100, 1000) for i in range(num)]
start1 = [i * 0.5 for i in range(num)]
fade1 = Fader([1] * num, 1, 5, mul=0.03).play(dur=5, delay=start1)
a = SineLoop(freqs, feedback=0.05, mul=fade1).out(dur=5, delay=start1)
start2 = 30
dur2 = 40
snds = [
"../snds/alum1.wav",
"../snds/a... | av",
"../snds/alum3.wav",
"../snds/alum4.wav",
]
tabs = SndTable(snds)
fade2 = Fader(0.05, 10, dur2, mul=0.7).play(dur=dur2, delay=start2)
b = Beat(time=0.125, w1=[90, 30, 30, 20], w2=[30, 90, 50, 40], w3=[0, 30, 30, 40], poly=1).play(dur=dur2, delay=start2)
out = TrigEnv(b, tabs, b["dur"], mul=b["amp"] * fade2... |
emotrix/Emotrix | emotrix/HeadsetTester.py | Python | bsd-2-clause | 529 | 0 | # -*- coding: utf-8 -*-
from Headset import Headset
import logging
import time
puerto = 'COM3'
headset = Headset(logging.INFO)
t | ry:
headset.connect(puerto, 115200)
except Exception, e:
raise e
print "Is conected? " + str(headset.isConnected())
print "-----------------------------------------"
headset.startReading(persist_data=True)
time.sleep(5)
headset.stopReading()
headset.closePort()
| print "-----------------------------------------"
print "Is conected? " + str(headset.isConnected())
print headset.getStatus()
|
KevinHoo/new-file-pro | commands/NewFileBase.py | Python | gpl-3.0 | 3,250 | 0.029231 | import sublime
import sublime_plugin
import re
import os
import datetime
TMLP_DIR = 'templates'
KEY_SYNTAX = 'syntax'
KEY_FILE_EXT = 'extension'
IS_GTE_ST3 = int(sublime.version()) >= 3000
PACKAGE_NAME = 'new-file-pro'
PACKAGES_PATH = sublime.packages_path()
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
cla... | ngs = self.get_settings()
format = settings.get('date_format', '%Y-%m-%d')
date = datetime.datetime.now().strftime(format)
if not IS_GTE_ST3:
code = code.decode('utf8') # for st2 && Chinese characters
code = code.replace('${date}', date)
attr = settings.get('attr', {})
for key in attr:
code = code.re... | e) and hasattr(win, 'extract_variables'):
variables = win.extract_variables()
for key in ['project_base_name', 'project_path', 'platform']:
code = code.replace('${%s}' % key, variables.get(key, ''))
code = re.sub(r"(?<!\\)\${(?!\d)", '\${', code)
return code
def open_file(self, path, mode='r'):
fp = ... |
scaramallion/pynetdicom | pynetdicom/apps/movescu/movescu.py | Python | mit | 11,001 | 0.000364 | #!/usr/bin/env python
"""A QR Move SCU application.
For sending Query/Retrieve (QR) C-MOVE requests to a QR Move SCP.
"""
import argparse
import sys
from pynetdicom import (
AE,
evt,
QueryRetrievePresentationContexts,
AllStoragePresentationContexts,
)
from pynetdicom.apps.common import setup_logging,... | )
net_opts.add_argument(
"-aec",
"--called-aet",
metavar="[a]etitle",
help="set called AE title of peer (default: ANY-SCP)",
type=str,
default="ANY-SCP",
)
net_opts.add_argument(
"-aem",
"--move-aet",
metavar="[a]etitle",
help... | default: STORESCP)",
type=str,
default="STORESCP",
)
net_opts.add_argument(
"-ta",
"--acse-timeout",
metavar="[s]econds",
help="timeout for ACSE messages (default: 30 s)",
type=float,
default=30,
)
net_opts.add_argument(
"-td",
... |
veratulips/OMOOC2py | _src/exCodesHardWay/ex41.py | Python | mit | 4,337 | 0.027669 | from sys import exit
from random import randint
def death():
quips = ["You died. You kinda suck at this.",
"Your mom would be proud. If she were smarter.",
"Such a luser.",
"I have a small puppy that's better at this."]
print quips[randint(0,len(quips)-1)]
exit(1)
def princess_lives_here():
print "Y... | '
elif feed_it == "throw it in":
print "The Koi wiggles, then leaps into the air to eat the cake."
print "You can see it's happy, it then grunts, thrashes..."
print "and finally rolls over and poops a magic diamond into the air"
print "at your feet."
return 'bear_with_sword'
else:
print "The Koi gets an... | ord walks in."
print '"Hey! That\' my diamond! Where\'d you get that!?"'
print "It holds its paw out and looks at you."
give_it = raw_input("> ")
if give_it == "give it":
print "The bear swipes at your hand to grab the diamond and"
print "rips your hand off in the process. It then looks at"
print 'y... |
sasha-gitg/python-aiplatform | google/cloud/aiplatform_v1beta1/services/specialist_pool_service/client.py | Python | apache-2.0 | 37,342 | 0.001767 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | r, Type[SpecialistPoolServiceTransport]]
_transport_registry["grpc"] = SpecialistPoolServiceGrpcTransport
_transport_registry["grpc_asyncio"] = SpecialistPoolServiceGrpcAsyncIOTransport
def get_transport_class(
cls, label: str = None,
) -> Type[SpecialistPoolServiceTransport]:
"""Return... | propriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
... |
acsone/bank-statement-import | account_bank_statement_import_ofx/__openerp__.py | Python | agpl-3.0 | 534 | 0 | # -*- coding: utf-8 -*-
{
'name': 'Import OFX Bank Statement',
'category': 'Banking addons',
'version': '8.0.1.0.1',
'license': 'AGPL-3',
'author': 'OpenERP SA,'
'Odoo Community Association (OCA)',
'website': 'https://github.com/OCA/bank-statement-import',
'depends': [
... | t_bank_statement_import'
],
'demo': [
'demo/demo_data.xml',
],
'external_dependencies': {
'python': ['ofxparse'],
},
'a | uto_install': False,
'installable': True,
}
|
snegovick/bcam | bcam/events.py | Python | gpl-3.0 | 31,621 | 0.004744 | from __future__ import absolute_import, division, print_function
import pygtk
pygtk.require('2.0')
import gtk, gobject, cairo
import time
import sys
import imp
import os
from bcam.loader_dxf import DXFLoader
from bcam.loader_excellon import ExcellonLoader
from bcam.tool_operation import TOResult
from bcam.tool_op_dri... | ,
self.ee.update_paths_list: [self.update_paths_list],
self.ee.path_list_selection_changed: [self.path_list_selection_changed],
self.ee.exact_follow_tool_click: [self.exact_follow_tool_click],
self.ee.offset_follow | _tool_click: [self.offset_follow_tool_click],
self.ee.pocket_tool_click: [self.pocket_tool_click],
self.ee.update_tool_operations_list: [self.update_tool_operations_list],
self.ee.tool_operations_list_selection_changed: [self.tool_operations_list_selection_changed],
self.... |
uwosh/uwosh.emergency.client | uwosh/emergency/client/interfaces.py | Python | gpl-2.0 | 228 | 0.008772 | from zope.interface import Interface, Attribute
from zope import schema
from uwosh.emergency.clien | t.config import mf as _
class IUWOs | hEmergencyClientLayer(Interface):
"""Marker interface that defines a browser layer
""" |
airbnb/kafka | tests/kafkatest/services/monitor/jmx.py | Python | apache-2.0 | 5,768 | 0.003814 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | &" % self.jmx_tool_ | err_log
self.logger.debug("%s: Start JmxTool %d command: %s" % (node.account, idx, cmd))
node.account.ssh(cmd, allow_fail=False)
wait_until(lambda: self._jmx_has_output(node), timeout_sec=10, backoff_sec=.5, err_msg="%s: Jmx tool took too long to start" % node.account)
self.started[idx-... |
shobhitmittal/textract | docs/conf.py | Python | mit | 8,694 | 0.005866 | # -*- coding: utf-8 -*-
#
# textract documentation build configuration file, created by
# sphinx-quickstart on Fri Jul 4 11:09:09 2014.
#
# 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.
#
# ... | e encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'textract'
copyright = u'2014, Dean Malmgren'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, al... | tags.
release = textract.VERSION
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as th... |
mamaddeveloper/teleadmin | tools/imageQueryParser.py | Python | mit | 1,079 | 0 | import random
class ImageQueryParser:
def __init__(self):
pass
def parse(self, query_string):
tab = query_string.split(" ")
last = tab[-1].lower()
is_random = False
index = 0
if last.startswith("-"):
if last == "-r":
| is_random = True
tab.pop()
else:
try:
index = int(last[1:])
tab.pop()
except ValueError:
pass
query_string = " ".join(tab)
return ImageQuery(query_string, is_random, inde... | ss ImageQuery:
def __init__(self, query, is_random, index):
self.__query = query
self.__is_random = is_random
self.__index = index
def query(self):
return self.__query
def is_random(self):
return self.__is_random
def next_index(self):
if self.is_random(... |
gcrisis/ardupilot | Tools/autotest/param_metadata/param.py | Python | gpl-3.0 | 5,433 | 0.024664 |
class Parameter(object):
def __init__(self, name):
self.name = name
class Vehicle(object):
def __init__(self, name, path):
self.name = name
self.path = path
self.params = []
class Library(object):
def __init__(self, name):
self.name = name
self.params = [... | is too cumbersome for most users
# angle
'deg' : 'degrees' , # Not SI, but is some situations more user-friendly than radians
'deg/s' : 'degrees per second' , # Not SI, but is some situations more user-friendly than radians
'cdeg' | : 'centidegrees' , # Not SI, but is some situations more user-friendly than radians
'cdeg/s' : 'centidegrees per second', # Not SI, but is some situations more user-friendly than radians
'cdeg/s/s': 'centidegrees per square second' , # Not SI, but is some situations more use... |
dongweiming/web_develop | chapter3/section4/consts.py | Python | gpl-3.0 | 170 | 0 | # coding=utf-8
HOSTNAME = | 'localhost'
DATABASE = 'r'
USERNAME = 'web'
PASSWORD = 'web'
DB_URI = 'mysql://{}:{}@{}/{}'.format(
USERNAME, PASSWORD, HOSTNAME, DATABAS | E)
|
django-wodnas/django-tinymce | tinymce/views.py | Python | mit | 4,440 | 0.001802 | # Copyright (c) 2008 Joost Cassee
# Licensed under the terms of the MIT License (see LICENSE.txt)
import logging
from django.core import urlresolvers
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.utils import simplejs... | tors.csrf import csrf_exempt
def textareas_js(request, name, lang=None):
"""
Returns a HttpResponse whose content is a Javscript file. The template
is loaded from 'tinymce/<name>_textareas.js' or
'<name>/tinymce_textareas.js'. Optionally, the lang argument sets the
content lan | guage.
"""
template_files = (
'tinymce/%s_textareas.js' % name,
'%s/tinymce_textareas.js' % name,
)
template = loader.select_template(template_files)
vars = get_language_config(lang)
vars['content_language'] = lang
context = RequestContext(request, vars)
return HttpResp... |
JaeGyu/PythonEx_1 | p200_048.py | Python | mit | 497 | 0 | '''
mode | de | sc
r 또는 rt | 텍스트 모드로 읽기
w 또는 wt | 텍스트 모드로 쓰기
a 또는 at | 텍스트 모드로 파일 마지막에 추가하기
rb | 바이너리 모드로 읽기
wb | 바이너리 모드로 쓰기
ab | 바이 | 너리 모드로 파일 마지막에 추가하기
'''
f = open("./py200_sample.txt", "w")
f.write("abcd")
f.close()
r = open("./py200_sample.txt", "r")
print("-" * 60)
print(r.readline())
r.close()
|
karllessard/tensorflow | tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/structured_output.py | Python | apache-2.0 | 5,614 | 0.015497 | # Copyright 2019 The TensorFlow Auth | ors. 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 | y 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.
# =====================... |
TGITS/programming-workouts | exercism/python/series/series_test.py | Python | mit | 1,747 | 0.000572 | import unittest
from series import slices
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0
class SeriesTest(unittest.TestCase):
def test_slices_of_one_from_one(self):
self.assertEqual(slices("1", 1), ["1"])
def test_slices_of_one_from_two(self):
self.asse | rtEqual(slices("12", 1), ["1", "2"])
def test_slices_of_two(self):
self.assertEqual(slices("35", 2), ["35"])
def test_slices_of_two_overlap(self):
self.assertEqual(slices("9142", 2), ["91", "14", "42"])
def test_slices_can_include_duplicates(self):
self.assertEqual(slices("777777"... | ", "777"])
def test_slices_of_a_long_series(self):
self.assertEqual(
slices("918493904243", 5),
["91849", "18493", "84939", "49390", "93904", "39042", "90424", "04243"],
)
def test_slice_length_is_too_large(self):
with self.assertRaisesWithMessage(ValueError):
... |
photoninger/ansible | lib/ansible/plugins/action/win_reboot.py | Python | gpl-3.0 | 8,292 | 0.0041 | # (c) 2016, Matt Davis <mdavis@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.errors import AnsibleErro... | ay_sec', self.DEFAULT_PRE_REBOOT_DELAY))
|
if self._task.args.get('post_reboot_delay') is not None:
post_reboot_delay = int(self._task.args.get('post_reboot_delay', self.DEFAULT_POST_REBOOT_DELAY))
else:
post_reboot_delay = int(self._task.args.get('post_reboot_delay_sec', self.DEFAULT_POST_REBOOT_DELAY))
test_co... |
mahmutf/dupeguru | core/engine.py | Python | gpl-3.0 | 18,745 | 0.002401 | # Created By: Virgil Dupras
# Created On: 2006/01/29
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-... | `.
"""
COMMON_WORD_THRESHOLD = 50
LIMIT = 5000000
j = j.start_subjob(2)
sj = j.start_subjob(2)
for o in objects:
if not hasattr(o, "words"):
o.words = getwords(o.name)
word_dict = build_word_dict(objects, sj)
reduce_common_words(word_dict, COMMON_WORD_THRESHOLD)
i... | ags = []
if we |
alex/pyechonest | examples/try_new_things.py | Python | bsd-3-clause | 6,593 | 0.005764 | #!/usr/bin/env python
# encoding: utf-8
"""
Copyright (c) 2010 The Echo Nest. All rights reserved.
Created by Tyler Williams on 2010-09-01
# 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; eithe... | le_plist:
fout.wr | ite("%s - %s \t %s\n" % tupe)
logger.info("all done!")
sys.exit(0) |
SasView/sasview | src/sas/qtgui/UnitTesting/SquishTestSuites/suite_sasview_qt/tst_Resolution/test.py | Python | bsd-3-clause | 3,434 | 0.009027 | # -* | - coding: utf-8 -*-
def main():
startApplication("sasview")
c | lickTab(waitForObject(":FittingWidgetUI.tabFitting_QTabWidget_2"), "Resolution")
test.compare(waitForObjectExists(":groupBox_4.cbSmearing_QComboBox").currentIndex, 0)
test.compare(str(waitForObjectExists(":groupBox_4.cbSmearing_QComboBox").currentText), "None")
test.compare(waitForObjectExists(":groupBox_4.... |
ARMmbed/yotta_osx_installer | workspace/lib/python2.7/site-packages/pip/_vendor/lockfile/sqlitelockfile.py | Python | apache-2.0 | 5,540 | 0.000722 | from __future__ import absolute_import, division
import time
import os
try:
unicode
except NameError:
unicode = str
from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked
class SQLiteLockFile(LockBase):
"Demonstrate SQL-based locking."
testdb = None
def __init__(self, path, t... | SQLiteLockFile.testdb = testdb
import sqlite3
self.connection = sqlite3.connect(SQLiteLockFile.testdb)
c = self.connection.cursor()
try:
c.execute | ("create table locks"
"("
" lock_file varchar(32),"
" unique_name varchar(32)"
")")
except sqlite3.OperationalError:
pass
else:
self.connection.commit()
import atexit
... |
bbusemeyer/busempyer | drivers/gen_json.py | Python | gpl-2.0 | 653 | 0.018377 | #!/usr/bin/python
imp | ort json
import sys
import data_processing as dp
from mython import NumpyToListEncoder
from subprocess import check_output
from imp import reload
reload(dp)
# Neat way of calling:
# find . -name '*_metadata.json' > rootlist
# python gen_json.py $(< rootlist) &> gen_json.out
files = sys.argv[1:]
roots = [f.replace('_... | '.join(root.split('/')[:-1])
outfn = loc+"/record.json"
print("Outputting to %s..."%outfn)
with open(outfn,'w') as outf:
json.dump(data,outf,cls=NumpyToListEncoder)
|
AndyLamperski/lemkelcp | lemkelcp/lemkelcp.py | Python | mit | 5,431 | 0.02228 | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y =... | d]
elif v == self.Z:
ppos = self.wPos[ind]
else:
ppos = None
| return ppos
def pivot(self,pos):
ppos = self.partnerPos(pos)
if ppos is not None:
self.swapColumns(pos,ppos)
self.swapColumns(pos,-2)
return True
else:
self.swapColumns(pos,-2)
return False
d... |
niubileme/shadowsocks-manyuser | shadowsocks/config.py | Python | apache-2.0 | 805 | 0.016149 | import logging
#Config
MYSQL_HOST = '127.0.0.1'
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_PASS = 'oppzk'
MYSQL_DB = 'SSMM'
MANAGE_PASS = 'passwd'
#if you want manage in other server you should set this value to global ip
MANAGE_BIND_IP = '127.0.0.1'
#make sure this port is idle
MANAGE_PORT = 10001
PANEL_VERSION = ... | pv6 '[::]'
#if you want bind all of ipv4 if '0.0.0.0'
#if you want bind all of if only '4.4.4.4'
SS_BIND_IP = '0.0.0.0'
SS_METHOD = 'rc4-md5'
#LOG CONFIG
LOG_ENABLE = False
LOG_LEVEL = logging.DEBUG
LOG_FILE = '/var | /log/shadowsocks.log'
|
shenqicang/openmc | tests/test_particle_restart_eigval/results.py | Python | mit | 1,055 | 0.008531 | #!/usr/bin/env python
import sys
# import particle restart
sys.path.append('../../src/utils')
import particle_restart as pr
# read in particle restart file
if len(sys.argv) > 1:
p = pr.Particle(sys.argv[1])
else:
p = pr.Particle('particle_12_842.binary')
# set up ou | tput string
outstr = ''
# write out properties
outstr += 'current batch:\n'
outstr += "{0:12.6E}\n".format(p.current_batch)
outstr += 'current gen:\n'
outstr += "{0:12.6E}\n".format(p.current_gen)
outstr += 'particle id:\n'
outstr += "{0:12.6E}\n".format(p.id)
outstr += 'run mode:\n'
outstr += "{0:12.6E}\n".format(p... | tr += 'particle xyz:\n'
outstr += "{0:12.6E} {1:12.6E} {2:12.6E}\n".format(p.xyz[0],p.xyz[1],p.xyz[2])
outstr += 'particle uvw:\n'
outstr += "{0:12.6E} {1:12.6E} {2:12.6E}\n".format(p.uvw[0],p.uvw[1],p.uvw[2])
# write results to file
with open('results_test.dat','w') as fh:
fh.write(outstr)
|
codesyntax/Products.zorionagurra | Products/zorionagurra/browser/portlet.py | Python | gpl-2.0 | 1,398 | 0.004292 | __version__ = '$Id$'
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.CMFCore.utils import getToolByName
from DateTime import DateTime
class LastZorionagurrak(BrowserView):
def getLastZorionagurrak(self, num=5):
context = aq_inner(self.context)
today ... | num - todaybrainnumber
tomorrowbrains = pcal(portal_type='Zorionagurra',
| review_state='published',
getDate={'query':(todayend,),
'range':'min'},
sort_on='getDate',
sort_limit=tomorrowbrainnumber)
retur... |
luzi82/HiSocial | HiPubIface/test/000_basic/src/hipubiface_test_basic.py | Python | gpl-3.0 | 4,370 | 0.019908 | import unittest
import os
import hiframe
import hipubiface_test_basic_plugin._hiframe
MY_ABSOLUTE_PATH = os.path.abspath(__file__)
MY_ABSOLUTE_PARENT = os.path.dirname(MY_ABSOLUTE_PATH)
HIPUBIFACE_PATH = os.path.dirname(os.path.dirname(os.path.dirname(MY_ABSOLUTE_PARENT)))
HIPUBIFACE_SRC_PATH = HIPUBIFACE_PATH+"/src"... | rtEqual(r["value"],c[0].lower())
#
# r = hipubiface.call("base", "guest_ping", {"txt_value":c[1].lower()})
# self.check_ok(r)
# self.assertEqual(r["type"],"value")
# self.assertEqual(r["value"],c[0].lower())
#
# def test_guest_ping_fail(self):
# cv = ["a... | "-99999999",
# "9999999",
# "999999999"
# ]
# for c in cv :
# r = hipubiface.call("base", "guest_ping", {"txt_value":c})
# self.assertTrue(r != None)
# self.assertTrue(isinstance(r,dict))
# self.assertEqual(r[hipubiface.RESULT_... |
scoky/pytools | curve/ks_test.py | Python | mit | 2,158 | 0.008341 | #!/usr/bin/env python
import os
import sys
import argparse
import traceback
sys.path.insert(1, os.path.join(os.path.dirname(__file__), os.pardir))
from toollib.group import Group,UnsortedInputGrouper
import scipy.stats as ss
class KSGroup(Group):
def __init__(self, tup):
super(KSGroup, self).__init__(tup)... | args.delimiter if args.delimiter != None else ' '
if len(self.tup) > 0:
args.outfile.write(jdelim.join(self.tup) + jdelim)
args.outfile.write(jdelim.join(map(str, ss.kstest(self.samples, args.distf, args=args.params))) + '\n')
if __name__ == "__main__":
# set up command line args
pa... | description='Compare the request distributions of all clients')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
parser.add_argument('-s', '--source', d... |
morelab/labman_ud | labman_ud/entities/news/models.py | Python | gpl-3.0 | 3,999 | 0.003251 |
from django.db import models
from django.template.defaultfilters import slugify
from datetime import datetime
from redactor.fields import RedactorField
from management.post_tweet import post_tweet
### News
####################################################################################################
cla... | erson = models.ForeignKey('persons.Person')
news = models.ForeignKey('News')
class Meta:
verbose | _name = u'Person related to News piece'
verbose_name_plural = u'People related to News pieces'
### EventRelatedToNews
####################################################################################################
class EventRelatedToNews(models.Model):
event = models.ForeignKey('events.Event')... |
ZzCalvinzZ/picturepay | picture/views.py | Python | mit | 5,543 | 0.027242 | from PIL import Image
import stripe
import datetime
from django.shortcuts import render, redirect
from django.views.generic import TemplateView, View, FormView
from django.core.urlresolvers import reverse_lazy, reverse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_dec... | r(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
self.picture = Settings.objects.first().picture
business = settings.PAYPAL_EMAIL
paypal_options = {
"business | ": business,
"amount": request.session.get('payment_note').get('number'),
"invoice": request.session.get('payment_note').get('url'),
"custom": request.session.get('payment_note').get('name'),
"item_name": "Pixel Reveal",
# "invoice": "unique-invoice-id",
"notify_url": request.build_absolute_uri(revers... |
crc5464/groupme-bot | src/markov.py | Python | gpl-3.0 | 6,551 | 0.003817 | import startbot, stats, os, re, random, sys
import utils
MARKOV_LENGTH = 2
#majority of the code taken from https://github.com/hrs/markov-sentence-generator
#changes made: allowed it to hook up from the text gotten directly from messages
#changed it to be encompassed in a class structure. Made minor changes to make ... | them into mapping
for first, followset in self.tempMapping.items():
total = sum(followset | .values())
# Normalizing here:
self.mapping[first] = dict([(k, v / total) for k, v in followset.items()])
# Returns the next word in the sentence (chosen randomly),
# given the previous ones.
def next(self, prevList):
sum = 0.0
retval = ""
index = random.rand... |
CroceRossaItaliana/jorvik | survey/migrations/0001_initial.py | Python | gpl-3.0 | 2,602 | 0.003459 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2018-12 | -04 15:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('anagrafica', '0049_auto_20181028_1639'),
]
operations = [
migrations.CreateModel(
... | lse, verbose_name='ID')),
('text', models.CharField(max_length=255)),
('is_active', models.BooleanField(default=True)),
('required', models.BooleanField(default=True, verbose_name='Obbligatorio')),
],
options={
'verbose_name': 'Doma... |
michaupl/wordtester | src/tests/WordTableModelTests.py | Python | apache-2.0 | 2,079 | 0.005291 | #-*- coding: utf-8 -*-
import unittest
from top.WordTableModel import WordTableModel
class WordTableModelTestsTestCase(unittest.TestCase):
def setUp(self):
self.model = WordTableModel()
self.model.load("dotestow.pkl")
def testLoading(self):
assert len(self.model.words) == 5, "incorre... | self.model.exportWords("exportTest.txt")
modelFh = open("dotestow.txt")
testFh = open("exportTest.txt")
modelText = modelFh.read | ()
testText = testFh.read()
assert modelText == testText, "incorrect export"
modelFh.close()
testFh.close()
import os
os.remove("exportTest.txt")
def testImport(self):
self.model.words.clearWords()
self.model.importWords("dotestow.txt")
self.t... |
mikar/projects | various/word_possibilities.py | Python | mit | 1,021 | 0.007835 | #!/usr/bin/env python2
# Print out the 2^n possibilities of a word with the length n
import unittest
from itertools import product, permutations
def word_variations(s):
| try:
if not len(s): return
lower, upper = s.lower(), s.upper()
except:
return
# Since number strings won't produce cartesian values with lower/upper,
# we use itertools.permutations.
if lower == upper:
pairs = permutations(lower)
else:
pairs = product(*zip(l... | lass WordTest(unittest.TestCase):
def _test(self, s, expected):
result = word_variations(s)
self.assertEqual(len(result), expected)
def test_basecase(self):
self._test("hello", 32)
def test_int(self):
self._test("123", 6)
def test_empty(self):
self.ass... |
defcube/django-south | south/tests/logic.py | Python | apache-2.0 | 32,253 | 0.002263 | import unittest
from collections import deque
import datetime
import sys
import os
import StringIO
from south import exceptions
from south.migration import migrate_app
from south.migration.base import all_migrations, Migration, Migrations
from south.migration.utils import depends, dfs, flatten, get_app_label
from sou... | ird']
self.assert | True(F1.is_before(F2))
self.assertTrue(F1.is_before(F3))
self.assertTrue(F2.is_before(F3))
self.assertEqual(O3.is_before(O1), False)
self.assertEqual(O3.is_before(O2), False)
self.assertEqual(O2.is_before(O2), False)
self.assertEqual(O2.is_before(O1), False)
self.... |
yephper/django | tests/syndication_tests/feeds.py | Python | bsd-3-clause | 6,128 | 0.000653 | from __future__ import unicode_literals
from django.contrib.syndication import views
from django.utils import feedgenerator
from django.utils.timezone import get_fixed_timezone
from .models import Article, Entry
class TestRss2Feed(views.Feed):
title = 'My blog'
description = 'A more thorough desc... | ello.png', 0, 'image/png'),
feedgenerator.Enclosure('http://example.com/goodbye.png', 0, 'image/png'),
]
class TemplateFeed | (TestRss2Feed):
"""
A feed to test defining item titles and descriptions with templates.
"""
title_template = 'syndication/title.html'
description_template = 'syndication/description.html'
# Defining a template overrides any item_title definition
def item_title(self):
retur... |
inductivekickback/ev3 | ev3/direct_command.py | Python | mit | 72,705 | 0.011361 | """A simple interface for executing bytecodes over a Bluetooth serial port.
From the lms2012 source code documentation:
Beside running user programs the VM is able to execute direct commands from
the Communication Module. In fact direct commands are small programs that
consist of regular byte codes and they are execu... | llllll Local variables [0..MAX_COMMAND_LOCALS]
Byte 7 - n: Byte codes
Direct Command response Bytes:
------------------------------
Byte 0 - 1: Reply size
Byte 2 - 3: Message counter
Byte 4: ReplyType
Byte 5 - n: Respon | se buffer (global variable values)
"""
import ev3
import message
MAX_CMD_LEN = 1019 # The size of the brick's txBuf is 1024 bytes but
# the header requires 5 bytes.
MAX_STR_LEN = 255
MAX_VERSION_STR_LEN = 64
MAX_LOCAL_VARIABLE_BYTES = 0xFFFFFFFF
MAX_NAME_STR_LEN = 64
MOTOR_MI... |
rgarcia-herrera/vectores | vectores.py | Python | gpl-3.0 | 446 | 0.006726 | from vectores_oo import Vector
x = input('vector U componente X= ')
y = input('vector U componente X= ')
U = Vector(x,y)
m = input('vector V magnitud= ')
a = input('vector V angulo= ')
V = Vector(m=m, a=a)
E = input('Escalar= ')
print "U=%s" % U
print "V=%s" % V
print 'UxE=%s' % U.x_escalar(E)
print 'VxE=%s'... | oPunto(V)
print '|UxV|=%s' % U.Modulo_ProductoCruz(V)
| |
vtungn/HackaPanzer | Sprite.py | Python | mit | 2,212 | 0.007233 | # -*- coding: utf-8 -*-
import os
import pygame
from pygame.locals import *
class Sprite(pygame.sprite.Sprite):
def __init__(self,SpriteName):
pygame.sprite.Sprite.__init__(self)
self.Name = SpriteName
self.rect = 0
self.image = 0
def getRect(self):
return self.rect
... | d return them as a list
def images_at(self, rects):
"Loads multiple images, supply a list of coordinates"
return [self.image_at(rect) for rec | t in rects], rect
# Load a whole strip of images
def load_strip(self, rect, image_count, colorkey = None):
"Loads a strip of images and returns them as a list"
tups = [(rect[0]+rect[2]*x, rect[1], rect[2], rect[3])
for x in range(image_count)]
return self.images_at(tups, ... |
omf2097/pyomftools | omftools/pyshadowdive/palette_mapping.py | Python | mit | 1,335 | 0 | from validx import Dict, List
from .protos import DataObject
from .pale | tte import Palette
from .utils.parser import BinaryParser
from .utils.validator import UInt8
from .utils.types import Remappings, Remapping
class PaletteMapping(DataObject):
__slots__ = (
"colors",
"remaps",
)
schema = Dict({"colors": Palette.schema, "remaps": List(List(UInt8))})
def... | ()
self.remaps: Remappings = []
def remap(self, remap_id: int) -> Palette:
return self.colors.remap(self.remaps[remap_id])
def read(self, parser: BinaryParser):
self.colors = Palette().read(parser)
for k in range(0, 19):
remap: Remapping = []
for m in ra... |
craneworks/python-pyroute2 | pyroute2/netlink/rtnl/errmsg.py | Python | apache-2.0 | 155 | 0 | from pyroute2.netlink import nlmsg
class errmsg(nlmsg):
'''
Custom message type
Error ersatz-message
'''
f | ields = (('co | de', 'i'), )
|
MarxMustermann/OfMiceAndMechs | src/itemFolder/obsolete/chemical.py | Python | gpl-3.0 | 1,571 | 0 | import src
class Chemical(src.items.Item):
type = "Chemical"
def __init__(self):
super().__init__(display=src.canvas.displayChars.fireCrystals)
self.name = "chemical"
self.composition = b"cccccggggg"
def apply(self, character):
import hashlib
results = []
... | elif tmp == "switch":
self.mix(character)
elif tmp == "shift":
self.shift()
test = hashlib.sha256(self.composition[0:9])
character.addMessage(counter)
| result = int(test.digest()[-1])
result2 = int(test.digest()[-2])
if result < 15:
character.addMessage(test.digest())
character.addMessage(result)
character.addMessage(result2)
break
counter += 1
# character.ad... |
nlgcoin/guldencoin-official | contrib/zmq/zmq_sub3.4.py | Python | mit | 3,273 | 0.001833 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
ZMQ example using python3's asyncio
Bitcoin should be started with the command line argument... | tes an infinite loop. An
alternative is to wrap the contents of `handle` inside `while True`.
The `@asyncio.coroutine` decorator and the `yield from` syntax found here
was introduced in python 3.4 and has been deprecated in favor of the `async`
and `await` keywords respectively.
A blocking exampl... | it history:
https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py
"""
import binascii
import asyncio
import zmq
import zmq.asyncio
import signal
import struct
import sys
if not (sys.version_info.major >= 3 and sys.version_info.minor >= 4):
print("This example ... |
mdurrant-b3/acos-client | acos_client/v21/slb/template/persistence.py | Python | apache-2.0 | 2,180 | 0 | # Copyright 2014, Doug Wiegley, A10 Networks.
#
# 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 appli... | x), {'name': name},
**kwargs)
def exists(self, name, **kwargs):
try:
self.get(name, **kwargs)
return True
except acos_errors.NotFound:
return False
def create(self, name, **kwargs):
self._post(("%s.create" % self.prefix), se... | lass CookiePersistence(BasePersistence):
def __init__(self, client):
self.pers_type = 'cookie'
super(CookiePersistence, self).__init__(client)
def get_params(self, name):
return {
"cookie_persistence_template": {
"name": name
}
}
class ... |
AttorneyOnlineVidya/tsuserver3 | server/ban_manager.py | Python | agpl-3.0 | 2,392 | 0.001254 | # tsuserver3, an Attorney Online server
#
# Copyright (C) 2016 argoneus <argoneuscze@gmail.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 3 of the License, or
# (at your o... | icense for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import ipaddress
import json
import yaml
from server.exceptions import ServerError
class | BanManager:
def __init__(self):
self.bans = {}
self.load_banlist()
self.hdid_exempt = {}
self.load_hdidexceptions()
def load_banlist(self):
try:
with open('storage/banlist.json', 'r') as banlist_file:
self.bans = json.load(banlist_file)
... |
Willem23/mbed | workspace_tools/export/__init__.py | Python | apache-2.0 | 4,602 | 0.004129 | """
mbed SDK
Copyright (c) 2011-2013 ARM 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 wr... | version of the mbed library</a>.
"""
def online_build_url_resolver(url):
# TODO: Retrieve the path and name of an online library build URL
return {'path':'', 'name':''}
def export(project_path, project_name, ide, target, destination='/tmp/',
tempdir=No | ne, clean=True, extra_symbols=None, build_url_resolver=online_build_url_resolver):
# Convention: we are using capitals for toolchain and target names
if target is not None:
target = target.upper()
if tempdir is None:
tempdir = tempfile.mkdtemp()
if ide is None:
# Simply copy ev... |
lino-framework/noi | lino_noi/lib/noi/user_types.py | Python | bsd-2-clause | 3,072 | 0.002604 | # -*- coding: UTF-8 -*-
# Copyright 2015-2021 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
"""
Defines a set of user roles and fills
:class:`lino.modlib.users.choicelists.UserTypes`.
This is used as the :attr:`user_types_module
<lino.core.site.Site.user_types_module>` ... | ommentsReader):
"""
A **Developer** is a trusted user who has s | igned an NDA, has access to client contacts.
Is able to make service reports as well as manage tickets.
"""
pass
class SiteAdmin(SiteAdmin, Developer, OfficeStaff, VotesStaff, ContactsStaff, CommentsStaff, ProductsStaff, LedgerStaff):
"""
Can do everything.
"""
# class Anonymous(CommentsRead... |
ULHPC/modules | easybuild/easybuild-easyblocks/easybuild/easyblocks/s/suitesparse.py | Python | mit | 7,433 | 0.002422 | ##
# Copyright 2009-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | t the e | nd
if cfgvars:
try:
f = open(fp, "a")
f.write("# lines below added automatically by EasyBuild")
for (var, val) in cfgvars.items():
f.write("%s = %s\n" % (var, val))
f.close()
except IOError, err:
... |
seakers/daphne_brain | example_problem/explorer/urls.py | Python | mit | 208 | 0 | from django.urls import path
from . import views
urlpatterns = [
path('start-ga', views.StartGA.as_view()),
p | ath('stop-ga', views.StopGA.as_view()),
path('check-ga', views.CheckGA.as_view()) | ,
]
|
madecoste/swarming | appengine/isolate/tests/stats_test.py | Python | apache-2.0 | 3,366 | 0.006239 | #!/usr/bin/env python
# Copyright 2014 The Swarming Authors. All rights reserved.
# Use of this source code is governed by the Apache v2.0 license that can be
# found in the LICENSE file.
import datetime
import sys
import unittest
import test_env
test_env.setup_test_env()
# From components/third_party/
import webtes... | ed = [
{
'contains_lookups': 0,
'contains_requests': 0,
'downloads': 0,
'downloads_bytes': 0,
'failures': 0,
'key': datetime.datetime(2010, 1, 2, 3, 4),
'other_requests': 0,
'requests': 1,
'uploads': 0,
'uploads_bytes': 0,
},
... | ected, actual)
def test_store(self):
expected = {
'uploads': 1,
'uploads_bytes': 2048,
}
self._test_handler('/store', expected)
def test_return(self):
expected = {
'downloads': 1,
'downloads_bytes': 4096,
}
self._test_handler('/return', expected)
def test_lookup(... |
nvbn/django-socialregistration | socialregistration/urls.py | Python | mit | 4,237 | 0.006372 | """
Updated on 19.12.2009
@author: alen, pinda
"""
from django.conf import settings
from django.conf.urls.defaults import *
from socialregistration.utils import OpenID, OAuthClient, OAuthTwitter, OAuthLinkedin
urlpatterns = patterns('',
url('^setup/$', 'socialregistration.views.setup',
name='socialregi... | dict(
consumer_key=settings.LINKEDIN_CONSUMER_KEY,
| secret_key=settings.LINKEDIN_CONSUMER_SECRET_KEY,
request_token_url=settings.LINKEDIN_REQUEST_TOKEN_URL,
access_token_url=settings.LINKEDIN_ACCESS_TOKEN_URL,
authorization_url=settings.LINKEDIN_AUTHORIZATION_URL,
callback_url='linkedin',
... |
aliyun/aliyun-oss-python-sdk | oss2/compat.py | Python | mit | 2,283 | 0.001447 | # -*- coding: utf-8 -*-
"""
兼容Python版本
"""
import sys
is_py2 = (sys.version_info[0] == 2)
is_py3 = (sys.version_info[0] == 3)
is_py33 = (sys.version_info[0] == 3 and sys.version_info[1] == 3)
try:
import simplejson as json
except (ImportError, SyntaxError):
import json
if is_py2:
from urllib import q... | ytes;其他则原样返回"""
if isinstance(data, str):
return data.encode(encoding='utf-8')
else:
return data
def to_string(data):
"""若输入为bytes,则认为是utf-8编码,并返回str"""
if isinstance(data, bytes):
return data.decode('utf-8')
else:
return data
... | tes。"""
return to_string(data)
def stringify(input):
return input
builtin_str = str
bytes = bytes
str = str
|
Callek/build-relengapi-slaveloan | relengapi/blueprints/slaveloan/slave_mappings.py | Python | mpl-2.0 | 3,163 | 0 | # 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/.
import re
# Todo this mapping REALLY need | s a non-hardcoded home
_slave_type = {
"bld-linux64-ec2": [
re.compile("^bld-centos6-hp-"),
re.com | pile("^bld-linux64-ec2-"),
re.compile("^bld-linux64-ix-"),
re.compile("^b-linux64-ix-"),
re.compile("^bld-linux64-spot-"),
re.compile("^b-linux64-hp-"),
re.compile("^try-linux64-spot-"),
],
"bld-lion-r5": [
re.compile("^bld-lion-r5-"),
],
"b-2008-i... |
yiwen-luo/LeetCode | Python/can-place-flowers.py | Python | mit | 1,263 | 0.003167 | # Time: O(n)
# Space: O(1)
# Suppose you have a long flowerbed in which some of the plots are planted and some are not.
# However, flowers cannot be planted in adjacent plots - they would compete for water
# and both would die.
#
# Given a flowerbed (represented as an array containing 0 and 1,
# where 0 means empty a... | violating the no-adjacent-flowers rule.
#
# Example 1:
# Input: flowerbed = [1,0,0,0,1 | ], n = 1
# Output: True
# Example 2:
# Input: flowerbed = [1,0,0,0,1], n = 2
# Output: False
# Note:
# The input array won't violate no-adjacent-flowers rule.
# The input array size is in the range of [1, 20000].
# n is a non-negative integer which won't exceed the input array size.
class Solution(object):
def can... |
gangadhar-kadam/sapphite_lib | core/doctype/customize_form/customize_form.py | Python | mit | 8,959 | 0.041299 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# MIT License. See license.txt
from __future__ import unicode_literals
"""
Customize Form is a Single DocType used to mask the Property Setter
Thus providing a better UI from user perspective
"""
import webnotes
from webnotes.utils import cstr
class DocType:
... | d to be deleted
"""
# Check if property has changed compared to when it was loaded
if new_d.fields.get(prop) != ref_d.fields.get(prop) \
and not \
( \
new_d.fields.get(prop) in [None, 0] \
and ref_d.fields.get(prop) in [None, 0] \
) and not \
( \
new_d.fields.get(prop) in [None, ''] \
and ref... | .fields[prop]))
# Check if the new property is same as that in original doctype
# If yes, we need to delete the property setter entry
for dt_d in dt_doclist:
if dt_d.name == ref_d.name \
and (new_d.fields.get(prop) == dt_d.fields.get(prop) \
or \
( \
new_d.fields.get(prop) in [None, 0] \
... |
googleinterns/adversarial-0th-order-optimization | discretezoo/loss/semantic_similarity.py | Python | apache-2.0 | 9,072 | 0.003307 | """
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
d... | = tf.math.reduce_s | um(
original_sentences_embedded, axis=1)
adversarial_sentences_reduced = tf.math.reduce_sum(
adversarial_sentences_embedded, axis=1)
difference_vector = tf.math.subtract(original_sentences_reduced,
adversarial_sentences_reduced)
distance = tf.n... |
torgartor21/solar | solar/solar/system_log/tasks.py | Python | apache-2.0 | 1,007 | 0 | # Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | o 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 solar.orchestration.runner import app
from solar.system_log.operations import set_error, move_to_commited
__all__ = ['error_logitem', 'commit_logitem']
@app.task(na... |
far-far-away-science/hab-v2 | software/ax25-utils/code_generation_v2.py | Python | gpl-3.0 | 2,693 | 0.004827 | import numpy
import data_generator
class Generator:
def __init__(self):
self.combinations = data_generator.generateAllByteToAx25DataCombinations()
self.frameSeparatorOne = data_generator.calculateNewAx25DataFromOldImpl(1, 0, 0x7E, False)
self.frameSeparatorZero = data_generator.calculateNew... | astBitWasZero, newLastBitGiventLastBitWasZero, newDataGiventLast | BitWasOne, newLastBitGiventLastBitWasOne, newDataNumberOfBits, newNumberOfOnes) in self.combinations:
text += ' {' + '{:>3}'.format(newDataGiventLastBitWasZero) + ', ' + '{:>2}'.format(newDataNumberOfBits) + ', ' + '{:>2}'.format(newNumberOfOnes) + '}, ' + \
'// idx = ' + '{:0>4}'.forma... |
Foxugly/MyTaxAccountant | scripts/move_document.py | Python | agpl-3.0 | 504 | 0.003968 | from documents.models import Document
| from categories.models import Category
import os
def move_doc(doc_id, cat_id):
doc = Document.objects.get(pk=int(doc_id))
old_cat = doc.refer_category
new_ | cat = Category.objects.get(pk=int(cat_id))
for p in doc.pages.all():
cmd = "mv " + p.get_absolute_path() + " " + new_cat.get_absolute_path() + "/"
os.system(cmd)
doc.refer_category = new_cat
doc.save()
old_cat.documents.remove(doc)
new_cat.documents.add(doc)
|
mitmproxy/mitmproxy | test/mitmproxy/contentviews/test_msgpack.py | Python | mit | 1,392 | 0.000718 | from hypothesis import given
from hypothesis.strategies import binary
from msgpack import packb
from mitmproxy.contentviews import msgpack
from . import full_eval
def msgpack_encode(content):
return packb(content, use | _bin_type=True)
def test_parse_msgpack():
assert msgpack.parse_msgpack(msgpack_encode({"foo": 1}))
assert msg | pack.parse_msgpack(b"aoesuteoahu") is msgpack.PARSE_ERROR
assert msgpack.parse_msgpack(msgpack_encode({"foo": "\xe4\xb8\x96\xe7\x95\x8c"}))
def test_format_msgpack():
assert list(msgpack.format_msgpack({
"data": [
"str",
42,
True,
False,
None... |
johnoneil/arib | arib/read.py | Python | apache-2.0 | 2,368 | 0.022382 | # vim: set ts=2 expandtab:
'''
Module: read.py
Desc: unpack data from binary files
Author: John O'Neil
Email: oneil.john@gmail.com
DATE: Thursday, March 13th 2014
'''
import struct
DEBUG = False
class EOFError(Exception):
""" Custom exception raised when we read to EOF
"""
pass
def split_buffer(length, buf):
... | t.unpack('>Q', _f)[0]
def buffer(f, s | ize):
'''Read N bytes from either a file or list
'''
if isinstance(f, list):
n, f = split_buffer(size, f)
return ''.join(n)
else:
_f = f.read(size)
if len(_f) < size:
raise EOFError()
return _f
|
queria/my-tempest | tempest/api/compute/admin/test_simple_tenant_usage_negative.py | Python | apache-2.0 | 2,656 | 0 | # Copyright 2013 NEC Corporation
# 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 ... | ms = {'start': self.start,
'end': self.end}
self.assertRaises(exceptions.NotFound,
self.adm_client.get_tenant_usage,
'', params)
|
@test.attr(type=['negative', 'gate'])
def test_get_usage_tenant_with_invalid_date(self):
# Get usage for tenant with invalid date
params = {'start': self.end,
'end': self.start}
self.assertRaises(exceptions.BadRequest,
self.adm_client.get_tena... |
barentsen/surveytools | surveytools/tests/test_footprint.py | Python | mit | 2,130 | 0.002817 | """Tests the surveytools.footprint module."""
import numpy as np
from surveytools.footprint import VphasFootprint, VphasOffset
def test_vphas_offset_coordinates():
"""Test the offset pattern, which is expected to equal
ra -0, dec +0 arcsec for the "a" pointing;
ra -588, dec +660 arcsec for the "b" pointin... | et."""
assert VphasOffset('1122a').ima | ge_filenames['ha'] == 'o20120330_00032.fit'
assert VphasOffset('1122b').image_filenames['ha'] == 'o20120330_00034.fit'
assert VphasOffset('1122c').image_filenames['ha'] == 'o20120330_00033.fit'
assert VphasOffset('1842a').image_filenames['r'] == 'o20130314_00061.fit'
assert VphasOffset('1842b').image_fi... |
agoravoting/agora-tools | import_election_csv.py | Python | agpl-3.0 | 18,685 | 0.005516 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of agora-tools.
# Copyright (C) 2014-2016 Agora Voting SL <agora@agoravoting.com>
# agora-tools is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software... | return s == "TRUE"
def parse_extra(q):
val = dict(
(key.replace("extra: ", ""), value)
for key, value in q.items() if key.startswith("extra: ")
)
if "success_screen__hide_download_ballot_ticket" in val:
val["success_screen__hide_download_ballot_ticket"] | = parse_bool(
val["success_screen__hide_download_ballot_ticket"]
)
if "shuffle_category_list" in val:
val["shuffle_category_list"] = parse_list(val["shuffle_category_list"])
if "shuffle_categories" in val:
val["shuffle_categories"] = parse_bool(val["shuffle_categories"])
if "shuffle_al... |
jmesteve/saas3 | openerp/addons/base_report_designer/base_report_designer.py | Python | agpl-3.0 | 3,471 | 0.007491 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | .xsl'),'rb')
if file_type=='odt':
fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb')
report = self.pool['ir.action | s.report.xml'].write(cr, uid, [report_id], {
'report_sxw_content': base64.decodestring(file_sxw),
'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read())),
})
return True
def report_get(self, cr, uid, report_id, context=None):
if context is None:
cont... |
sixu05202004/newsmeme | newsmeme/newsmeme/models/posts.py | Python | bsd-3-clause | 10,746 | 0.000279 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from datetime import datetime
from werkzeug import cached_property
from flask import url_for, Markup
from flask.ext.sqlalchemy import BaseQuery
from flask.ext.principal import Permission, UserNeed, Denial
from newsmeme.extensions import db
from newsmeme.h... | by(Post.num_comments.desc(),
Post.sc | ore.desc(),
Post.id.desc())
def public(self):
return self.filter(Post.access == Post.PUBLIC)
def restricted(self, user=None):
"""
Returns posts filtered for a) public posts b) posts authored by
the user or c) posts authored by friends
"""
... |
tensorflow/agents | tf_agents/policies/random_py_policy_test.py | Python | apache-2.0 | 5,609 | 0.001783 | # coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | p = time_step.restart(observation=np.array([1]))
def testGeneratesActions(self):
action_spec = [
array_spec.BoundedArr | aySpec((2, 3), np.int32, -10, 10),
array_spec.BoundedArraySpec((1, 2), np.int32, -10, 10)
]
policy = random_py_policy.RandomPyPolicy(
time_step_spec=self._time_step_spec, action_spec=action_spec)
action_step = policy.action(self._time_step)
tf.nest.assert_same_structure(action_spec, act... |
DasIch/editor | prototypes/regex/tests.py | Python | bsd-3-clause | 17,417 | 0.000172 | # coding: utf-8
"""
regex.tests
~~~~~~~~~~~
:copyright: 2012 by Daniel Neuhäuser
:license: BSD, see LICENSE.rst
"""
from unittest import TestCase
from itertools import izip
from contextlib import contextmanager
from regex.parser import (
parse, ParserError, Parser, DEFAULT_ALPHABET, DEFAULT_LANGUA... | n: ]"
)
self.assertEqual(
exception.annotation,
(
u"[a-]\n"
u" ^"
)
)
def test_any(self):
parser = Parser(DEFAULT_LANGUAGE, alphabet=frozenset(u"ab"))
self.assertEqual(
parser.parse(u"."),
... | regex
self.ast = parse(regex)
@property
def nfa(self):
if not hasattr(self, "_nfa"):
self._nfa = self.ast.to_nfa()
return self._nfa
@property
def dfa(self):
if not hasattr(self, "_dfa"):
self._dfa = self.ast.to_dfa()
return self._dfa
... |
ilv/gettor | gettor/smtp.py | Python | bsd-3-clause | 17,953 | 0.000501 | # -*- coding: utf-8 -*-
#
# This file is part of GetTor, a Tor Browser distribution system.
#
# :authors: Israel Leiva <ilv@riseup.net>
# see also AUTHORS file
#
# :copyright: (c) 2008-2014, The Tor Project, Inc.
# (c) 2014, Israel Leiva
#
# :license: This is Free Software. See LICENSE for lic... | g, addr):
"""Parse the email received.
Get the locale and parse the text for the rest of the info.
:param: msg (string) the content of the email to be parsed.
:param: addr (string) the address of the recipient (i.e. us).
:return: (list) 4-tuple with locale, os and type o | f request.
"""
req = self._parse_text(msg)
lc = self._get_lc(addr)
supported_lc = self.core.get_supported_lc()
if lc in supported_lc:
req['lc'] = lc
else:
req['lc'] = 'en'
return req
def _parse_text(self, msg):
"""Parse the ... |
yuxng/Deep_ISM | ISM/lib/ism/config.py | Python | mit | 10,824 | 0.001663 | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Fast R-CNN config system.
This file specifies default config option... | EED = 3
# A small number that's used many times
__C.EPS = 1e-14
# Root directory of project
__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))
# Place outputs under an experiments directory
__C.EXP_DIR = 'default'
# Use GPU implementation of non-maximum suppression
__C.USE_GPU_NMS = True
# Def... | _output_dir(imdb, net):
"""Return the directory where experimental artifacts are placed.
A canonical path is built using the name from an imdb and a network
(if not None).
"""
path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))
if net is None:
return path
el... |
EArmour/pyfibot | pyfibot/modules/module_spotify.py | Python | bsd-3-clause | 1,777 | 0.005627 | """
Parse spotify URLs
"""
from __future__ import unicode_l | iterals
import re
import logging
log = logging.getLogger('spotify')
def handle_privmsg(bot, user, channel, args):
"""Grab Spotify URLs from the messages and handle them"""
m = re.match(".*(http:\/\/open.spotify.com\/|spotify:)(?P<item>album|artist|track|user[:\/]\S+[:\/]playlist)[:\/](?P<id>[a-zA-Z0-9]+)\/?... | ).split('/')
item[0] += 's'
if item[0] == 'users':
# All playlists seem to return 401 at the time, even the public ones
return None
apiurl = "https://api.spotify.com/v1/%s/%s" % ('/'.join(item), spotify_id)
r = bot.get_url(apiurl)
if r.status_code != 200:
if r.status_code n... |
hunch/hunch-gift-app | django/contrib/comments/templatetags/comments.py | Python | mit | 12,178 | 0.006077 | from django import template
from django.template.loader import render_to_string
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib import comments
from django.utils.encoding import smart_unicode
register = template.Library()
class BaseCommentNode(t... | ents/form.html"
]
context.push()
formstr = render_to_string(template_search_list, {"form" : self.get_form(context)}, context)
context.pop()
return formstr
else:
return ''
class RenderCommentListNode(CommentListNode):
"""Rende... | rse render_comment_list and return a Node."""
tokens = token.contents.split()
if tokens[1] != 'for':
raise template.TemplateSyntaxError("Second argument in %r tag must be 'for'" % tokens[0])
# {% render_comment_list for obj %}
if len(tokens) == 3:
return c... |
wangjiezhe/FetchNovels | novel/sources/quanben5.py | Python | gpl-3.0 | 612 | 0 | #!/usr/bin/env pyth | on
# -*- coding: utf-8 -*-
from novel import serial, utils
BAS | E_URL = 'http://www.quanben5.com/n/{}/xiaoshuo.html'
class Quanben5(serial.SerialNovel):
def __init__(self, tid):
super().__init__(utils.base_to_url(BASE_URL, tid), '#content',
intro_sel='.description',
chap_type=serial.ChapterType.path,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.