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 |
|---|---|---|---|---|---|---|---|---|
rdobson/xva-tools | pyxva/cmd/tests/test_xva.py | Python | gpl-3.0 | 924 | 0 | import unittest
import os
from mock import MagicMock, patch
| from pyxva.cmd import xva
class TestXVAUpdate(unittest.TestCase):
| OVA_XML = "data/ova.xml"
@patch("pyxva.cmd.xva.extract_xva")
def setUp(self, mock_extract):
ova_xml_path = "%s/%s" % (
os.path.dirname(os.path.realpath(__file__)),
self.OVA_XML
)
with open(ova_xml_path, 'r') as fh:
ova_data = fh.read()
m... |
hosiet/ustcbbs-archiver | exec.py | Python | mit | 125 | 0.008403 | #!/usr/bin/env python3
# 作者:hosiet
import os
import sys
| import sqlite3
import config
import reques | ts
import urllib
|
jimklo/LRSignature | src/setup.py | Python | apache-2.0 | 1,114 | 0.007181 | '''
Copyright 2011 SRI International
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, softw... | 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.
Created on May 11, 2011
@author: jklo
'''
from | setuptools import setup, find_packages
setup(
name='LRSignature',
version='0.1.14',
author='Jim Klo',
author_email="jim.klo@sri.com",
url = "https://github.com/jimklo/LRSignature",
description='Learning Registry resource data digital signature management',
packages=find_packages(),
lon... |
renoirb/browsercompat | webplatformcompat/serializers.py | Python | mpl-2.0 | 17,212 | 0 | # -*- coding: utf-8 -*-
"""API Serializers"""
from collections import OrderedDict
from django.db.models import CharField
from django.contrib.auth.models import User
from rest_framework.serializers import (
CurrentUserDefa | ult, DateTimeField, IntegerField,
ModelSerializer, SerializerMethodField, ValidationError)
from sortedm2m.fields import SortedManyToManyField
from . import fields
from .drf_fields import (
CurrentHistoryField, HistoricalObjectField, HistoryField,
MPTTRelationField, OptionalCharField, OptionalIntegerField,
... | ls import (
Browser, Feature, Maturity, Section, Specification, Support, Version)
from .validators import VersionAndStatusValidator
def omit_some(source_list, *omitted):
"""Return a list with some items omitted"""
for item in omitted:
assert item in source_list, '%r not in %r' % (item, source_list... |
zestrada/nova-cs498cc | nova/db/sqlalchemy/migrate_repo/versions/175_add_project_user_id_to_volume_usage_cache.py | Python | apache-2.0 | 1,735 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | instance_id = Column('instance_uuid', String(36))
pr | oject_id = Column('project_id', String(36))
user_id = Column('user_id', String(36))
volume_usage_cache.create_column(instance_id)
volume_usage_cache.create_column(project_id)
volume_usage_cache.create_column(user_id)
def downgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
... |
bregman-arie/ansible | lib/ansible/modules/network/eos/eos_banner.py | Python | gpl-3.0 | 6,270 | 0.001276 | #!/usr/bin/python
#
# 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 distribut... | if module.params['banner'] == 'login':
banner_response_key = 'loginBanner'
else:
banner_response_key = 'motd'
if isinstance(output[0], dict) and banner_respo | nse_key in output[0].keys():
obj['text'] = output[0]
else:
obj['text'] = output[0]
obj['state'] = 'present'
return obj
def map_params_to_obj(module):
text = module.params['text']
if text:
text = str(text).strip()
return {
'banner': module.pa... |
expectocode/Telethon | telethon_generator/parsers/tlobject/tlobject.py | Python | mit | 5,137 | 0 | import re
import struct
import zlib
from ...utils import snake_to_camel_case
# https://github.com/telegramdesktop/tdesktop/blob/4bf66cb6e93f3965b40084771b595e93d0b11bcd/Telegram/SourceFiles/codegen/scheme/codegen_scheme.py#L57-L62
WHITELISTED_MISMATCHING_IDS = {
# 0 represents any layer
0: {'channel', # Sinc... | ' ' + ' '.join([repr(arg) for arg in self.args])
else:
args = ''
return '{}{}{} = {}'.format(self.fu | llname, hex_id, args, self.result)
def infer_id(self):
representation = self.__repr__(ignore_id=True)
representation = representation\
.replace(':bytes ', ':string ')\
.replace('?bytes ', '?string ')\
.replace('<', ' ').replace('>', '')\
.replace('{',... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/lepl/lexer/lines/monitor.py | Python | agpl-3.0 | 3,018 | 0.001988 |
# The contents of this file are subject to the Mozilla Public License
# (MPL) Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# b... | y deleting the
# provisions above and replace them with the notice and other provisions
# required by the LGPL License. If you do not delete the provisions
# above, a recipient may use your version of this file under either the
# MPL or the LGPL License.
'''
Support the stack-scoped tracking of indent level blocks.
'... | itor, LogMixin):
'''
This tracks the current indent level (in number of spaces). It is
read by `Line` and updated by `Block`.
'''
def __init__(self, start=0):
'''
start is the initial indent (in spaces).
'''
super(BlockMonitor, self).__init__()
self.__st... |
elaeon/dsignature | creacion_firma/migrations/0011_auto_20150323_1736.py | Python | gpl-3.0 | 461 | 0 | # -*- codi | ng: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('creacion_firma', '0010_userdocumentsign_fecha'),
]
operations = [
migrations.AlterField(
model_name='userdocumentsign',
... | now_add=True),
preserve_default=True,
),
]
|
sffjunkie/home-assistant | homeassistant/components/hvac/__init__.py | Python | mit | 14,456 | 0 | """
Provides functionality to interact with hvacs.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/hvac/
"""
import logging
import os
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.config import load_yaml_config_f... | , away_mode, entity_id=None):
"""Turn all or specified | hvac away mode on."""
data = {
ATTR_AWAY_MODE: away_mode
}
if entity_id:
data[ATTR_ENTITY_ID] = entity_id
hass.services.call(DOMAIN, SERVICE_SET_AWAY_MODE, data)
def set_aux_heat(hass, aux_heat, entity_id=None):
"""Turn all or specified hvac auxillary heater on."""
data = {
... |
google/pymql | emql/adapters/search.py | Python | apache-2.0 | 5,119 | 0.001563 | # 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 agreed to in writing, ... | args[name] = value
if 'limit' not in args:
args['limit'] = MQL_LIMIT # plug-in default MQL limit
if 'score' in params:
matches = me.get_session().relevance_query(tid, format='ac', **args)
guids = ['#' + match['guid'] for match in matches]
... | :
matches = me.get_session().relevance_query(tid, format='guids', **args)
guids = ['#' + guid for guid in matches]
if guids:
result['guid|='] = guids
else:
result['guid|='] = ['#00000000000000000000000000000000']
if 'score' in params:
... |
SkiftCreative/docker-gunicorn-examples | flask/app/app.py | Python | mit | 319 | 0 | from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return 'Flask is running on gunicorn!'
@app.route('/data')
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
ret | urn jsonify(data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port | =5000)
|
ClearCorp-dev/odoo-costa-rica | l10n_cr_hr_ins_csv_generator/__openerp__.py | Python | agpl-3.0 | 1,898 | 0.007376 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute... | U 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" : 'Costa Rica INS csv Generator',
"version" : '1.0',
"author" : 'ClearCorp',
'complexity': 'normal',
"description": """
Module build for the generation of custom files to upload information to the INS systems
""",
"category": 'Human Resources'... |
rmyers/dtrove | dtrove/views.py | Python | mit | 3,803 | 0 |
import json
import logging
import uuid
from django.core.cache import caches
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
CACHE = caches['default']
LOG = logging.getLogger()
SERVICE_CATALOG = {
"access": {
"serviceCatalog": [
{
"end... | [],
"OS-DCF:diskConfig": "MANUAL",
"id": ser | ver_id,
"links": [],
"adminPass": "aabbccddeeff"
}
}
return HttpResponse(json.dumps(server),
content_type="application/json")
elif request.method == 'GET':
_, server_id = path.split('/')... |
jpmunic/udest | watson_examples/personality_insights_v3.py | Python | mit | 669 | 0.001495 | import | json
from os.path import join, dirname
from watson_developer_cloud import PersonalityInsightsV3
"""
The example returns a JSON response whose content is the same as that in
../resource | s/personality-v3-expect2.txt
"""
personality_insights = PersonalityInsightsV3(
version='2016-10-20',
username='YOUR SERVICE USERNAME',
password='YOUR SERVICE PASSWORD')
with open(join(dirname(__file__), '../resources/personality-v3.json')) as profile_json:
profile = personality_insights.profile(
... |
lotube/lotube | lotube/users/views_api_xml.py | Python | mit | 223 | 0 | from core.mixins import XMLFromJSONView
from .view | s_api_json import UserListJSON, UserDetailJSON
class UserListXML(XMLFromJSONView, UserListJSON):
pass
class UserDetailXML(XMLFromJSONView, UserDetailJSON):
| pass
|
gpotter2/scapy | scapy/contrib/automotive/scanner/executor.py | Python | gpl-2.0 | 12,631 | 0 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Nils Weiss <nils@we155.de>
# This program is published under a GPLv2 license
# scapy.contrib.description = AutomotiveTestCaseExecutor base class
# scapy.contrib.status = library
import abc
import time
from it... | lf.stat | e_graph.add_edge(edge, tf)
if isinstance(test_case, TestCaseGenerator):
new_test_case = test_case.get_generated_test_case()
if new_test_case:
log_interactive.debug("Testcase generated %s", new_test_case)
self.configuration.add_test_case(new_test_case)
... |
dennyreiter/pypints | taps/forms.py | Python | gpl-3.0 | 1,775 | 0.006761 | from django import forms
from django.db.models import Q
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Button, Submit, MultiField
from crispy_forms.bootstrap import FormActions, InlineRadios
#from beers.models import Beer
from .models import Tap
from kegs.models import Keg
f... | ter(Q(active=True),
Q(pk=self.instance.keg_id) | ~Q(kegstatus__in=('SERVING',' | NEEDS_PARTS','NEEDS_REPAIRS','NEEDS_CLEANING'))
)
self.fields['beer'].queryset = Beer.objects.filter(active=True)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_c... |
magfest/ubersystem | alembic/versions/771555241255_initial_migration.py | Python | agpl-3.0 | 3,407 | 0.012328 | """Initial migration
Revision ID: 771555241255
Revises: 73b22ccbe472
Create Date: 2017-04-24 09:15:59.549855
"""
# revision identifiers, used by Alembic.
revision = '771555241255'
down_revision = '73b22ccbe472'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
import residue
t... | requests_attendee_id_attendee')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_hotel_requests')),
sa.UniqueConstraint('attendee_id', name=op.f('uq_hotel_requests_attendee_id'))
)
op.create_table('room_assignment',
sa.Column('id', residue.UUID(), nullable=False),
sa.Column('room_id', residue.UUID(... | ignment_attendee_id_attendee')),
sa.ForeignKeyConstraint(['room_id'], ['room.id'], name=op.f('fk_room_assignment_room_id_room')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_room_assignment'))
)
if is_sqlite:
with op.batch_alter_table('attendee', reflect_kwargs=sqlite_reflect_kwargs) as batch_o... |
bane138/nonhumanuser | nonhumanuser/admin.py | Python | mit | 103 | 0.019417 | admin.a | utodiscover()
flatpages.register()
urlpatterns += [ url(r'^admin/', include(admin.site. | urls)), ] |
ty-a/pytybot | tybot.py | Python | gpl-3.0 | 15,523 | 0.051601 | ##########################################################################
# PyTyBot - A MediaWiki wrapper for use on wikis.
# Copyright (C) 2012 TyA <tya.wiki@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 publishe... | "format":"json",
"token":self.tokens["undelete"]
}
response = self.postToWiki(data)
try:
print(response["error"]["code"])
return False
except:
return True
def block(self,target,summary='',expiry="infinite"):
"""
| Blocks users via the API
:param target (str): The user to block
:param summary (str): The block summary
:param expiry (str): Expiry timestamp or relative time. (Default: infinite)
:returns: boolean based on success
"""
data = {
"action":"block",
"user":target,
"reason":summary,
"expiry":expiry... |
willemneal/Docky | lib/pygments/tests/test_cmdline.py | Python | mit | 8,892 | 0.000337 | # -*- coding: utf-8 -*-
"""
Command line test
~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import print_function
import io
import os
import re
import sys
import tempfile
import unittest
import support... | e>foo, bar=baz=,</title>' in o)
def test_F_opt(self):
filename = TESTFILE
o = self.check_success('-Fhighlight:tokentype=Name.Blubb,'
| 'names=TESTFILE filename',
'-fhtml', filename)
self.assertTrue('<span class="n-Blubb' in o)
def test_H_opt(self):
o = self.check_success('-H', 'formatter', 'html')
self.assertTrue('HTML' in o)
o = self.check_success('-H', ... |
nyuphys/DataMaster | example/lab.py | Python | mit | 2,511 | 0.008761 | # -*- coding: utf-8 -*-
#############################################################
# 1. Imports
#############################################################
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#############################################################
# 2. ... | x = np.linspace(5, 31, 1000)
plt.plot(x, m*x + b, 'c--')
plt.errorbar(x=(current * 1e3), y=voltage, xerr=(dI * 1e3), yerr=dV, fmt='r.', ecolor='k', a | lpha=0.5)
plt.xlabel('Current ($mA$)')
plt.ylabel('Voltage ($V$)')
def get_resistance():
m, b, sy, sm, sb, r = lsq(current, voltage)
# Resistance is the slope m; its uncertainty sm is already computed by lsq()
return (m, sm)
|
maxpumperla/elephas | tests/mllib/test_adapter.py | Python | mit | 570 | 0 | import numpy as np
from elephas.mllib.adapter import *
from pyspark.mllib.linalg import Matrices, Vectors
def test_to_matrix():
x = np.ones((4, 2))
mat = to_matrix(x)
assert mat.numRows == 4
assert mat.numCols == 2
def test_from_matrix():
mat = M | atrices.dense(1, 2, [13, 37])
x = from_matrix(mat)
assert x.shape == (1, 2)
| def test_from_vector():
x = np.ones((3,))
vector = to_vector(x)
assert len(vector) == 3
def test_to_vector():
vector = Vectors.dense([4, 2])
x = from_vector(vector)
assert x.shape == (2,)
|
lafranceinsoumise/api-django | agir/api/test_runner.py | Python | agpl-3.0 | 1,140 | 0 | import shutil
import tempfile
from django.test import override_settings
from django.test.runner import DiscoverRunner
from .celery import app
class TempMediaMixin(object):
"Mixin to create MEDIA_ROOT in temp and tear down when complete."
def setup_test_environment(self):
"Create temp directory and u... | )
self.media_settings_overrider = override_settings(
MEDIA_ROOT=self._temp_media,
DEFAULT_FILE_STORAGE="django.core.files.storage.FileSystemS | torage",
)
self.media_settings_overrider.enable()
def teardown_test_environment(self):
"Delete temp storage."
super(TempMediaMixin, self).teardown_test_environment()
shutil.rmtree(self._temp_media, ignore_errors=True)
self.media_settings_overrider.disable()
class T... |
proevo/pythondotorg | nominations/forms.py | Python | apache-2.0 | 1,948 | 0.002567 | from django import forms
from django.utils.safestring import mark_safe
from markupfield.widgets import MarkupTextarea
from .models import Nomination
class NominationForm(forms.ModelForm):
class Meta:
| model = Nomination
fields = (
"name",
"email",
"previous_board_service",
"employer",
"other_affiliations",
"nomination_statement",
)
widgets = {
"nomination_statement": MarkupTextarea()
} # , "sel... | help_texts = {
"name": "Name of the person you are nominating.",
"email": "Email address for the person you are nominating.",
"previous_board_service": "Has the person previously served on the PSF Board? If so what year(s)? Otherwise 'New board member'.",
"employe... |
goedzo/PokemonGo-Bot | pokemongo_bot/cell_workers/heal_pokemon.py | Python | mit | 11,496 | 0.002001 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from datetime import datetime, timedelta
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot import inventory
from pokemongo_bot.item_list import Item
... | 'name': pokemon.name
}
)
if item == Item.ITEM_REVIVE.value:
pokemon.hp = int(pokemon.hp_max / 2)
| self.to_heal.append(pokemon)
else:
# Set pokemon as revived
pokemon.hp = pokemon.hp_max
return True
else:
self.emit_event(
'revived_pokemon',
... |
nwjs/nw.js | test/sanity/issue5730-add-node-in-permissions/test.py | Python | mit | 1,183 | 0.002536 | import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
testdir = os.path.dirname(os.path.abspath(__file__))
chrome_options.add_argument('nwapp=' + testdir)
driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_optio... | e'
prin | t ret2
print 'show request normatl value'
print ret1
break
except selenium.common.exceptions.NoSuchElementException:
pass
time.sleep(1)
timeout = timeout - 1
if timeout <= 0:
raise Exception('Timeout when waiting fo... |
leppa/home-assistant | homeassistant/components/axis/camera.py | Python | apache-2.0 | 3,117 | 0 | """Support for Axis camera streaming."""
from homeassistant.components.camera import SUPPORT_STREAM
from homeassistant.components.mjpeg.camera import (
CONF_MJPEG_URL,
CONF_STILL_IMAGE_URL,
MjpegCamera,
filter_urllib3_logging,
)
from homeassistant.const import (
CONF_AUTHENTICATION,
CONF_DEVICE... | USERNAME: config_entry.data[CONF_DEVICE][CONF_USERNAME],
CONF_PASSWORD: config_entry.data[CONF_DEVICE][CONF_PASSWORD],
CONF_MJPEG_URL: AXIS_VID | EO.format(
config_entry.data[CONF_DEVICE][CONF_HOST],
config_entry.data[CONF_DEVICE][CONF_PORT],
),
CONF_STILL_IMAGE_URL: AXIS_IMAGE.format(
config_entry.data[CONF_DEVICE][CONF_HOST],
config_entry.data[CONF_DEVICE][CONF_PORT],
),
CONF_AUTHE... |
ISISComputingGroup/EPICS-inst_servers | BlockServer/test_modules/test_active_config_holder.py | Python | bsd-3-clause | 26,201 | 0.002901 | # This file is part of the ISIS IBEX application.
# Copyright (C) 2012-2016 Science & Technology Facilities Council.
# All rights reserved.
#
# This program is distributed in the hope that it will be useful.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License... | to the Configuration object.
# We are testing that ActiveConfigServerManager correctly interfaces with Configuration, not testing the
# functionality of Configuration, which is done in Configuration's own suite of tests.
class TestActiveConfigHolderSequence(unittest.TestCase):
def setUp(self):
# Note: ... | hive = Mock()
self.mock_archive.update_archiver = Mock()
self.mock_file_manager = MockConfigurationFileManager()
self.active_config_holder = self.create_active_config_holder()
def create_active_config_holder(self):
config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)... |
QiJune/Paddle | python/paddle/fluid/tests/unittests/testsuite.py | Python | apache-2.0 | 7,265 | 0.000275 | # Copyright (c) 2018 PaddlePaddle 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 app... | 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 __futur | e__ import print_function
import numpy as np
import paddle.fluid.core as core
from paddle.fluid.op import Operator
def create_op(scope, op_type, inputs, outputs, attrs):
kwargs = dict()
op_maker = core.op_proto_and_checker_maker
op_role_attr_name = op_maker.kOpRoleAttrName()
if op_role_attr_name n... |
robinson96/GRAPE | vine/updateView.py | Python | bsd-3-clause | 20,286 | 0.007691 | import os
import shutil
import addSubproject
import option
import utility
import grapeGit as git
import grapeConfig
import grapeMenu
import checkout
# update your custom sparse checkout view
class UpdateView(option.Option):
"""
grape uv - Updates your active submodules and ensures you are on a consistent ... | branch does not exist).
[default: .grapeconfig.post-checkout.syncWithOrigin]
--add=<project> Submodule or subproject to add to the workspace. Can be defined multiple t | imes.
--remove=<project> Submodule or subproject to remove from the workspace. Can be defined multiple times.
"""
def __init__(self):
super(UpdateView, self).__init__()
self._key = "uv"
self._section = "Workspace"
self._pushBranch = False
self._skipPush = F... |
Symmetry-Innovations-Pty-Ltd/Python-2.7-for-QNX6.5.0-x86 | usr/pkg/lib/python2.7/collections.py | Python | mit | 25,363 | 0.002287 | __all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDict']
# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
# They should however be considered an integral part of collections.py.
from _abcoll import *
import _abcoll
__all__ += _abcoll.__all__
from _collections import deque, ... | # Deleting an existing item uses self.__map to find th | e link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link_prev, link_next, key = self.__map.pop(key)
link_prev[NEXT] = link_next
link_next[PREV] = link_prev
def __iter__(self):
'od.__iter__() <==> iter(od)'... |
ARM-software/lisa | lisa/tests/staging/utilclamp.py | Python | apache-2.0 | 14,119 | 0.000425 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2020, Arm Limited and contributors.
#
# 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
#
# ... | uency import Frequency | Analysis
from lisa.analysis.load_tracking import LoadTrackingAnalysis
from lisa.datautils import df_refit_index
from lisa.pelt import PELT_SCALE
from lisa.tests.base import ResultBundle, TestBundle, RTATestBundle, TestMetric
from lisa.wlgen.rta import RTAPhase, PeriodicWload
from lisa.notebook import plot_signal
clas... |
noironetworks/neutron | neutron/tests/unit/objects/test_subnet.py | Python | apache-2.0 | 10,392 | 0.000289 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | se, self).setUp()
self.update_obj_fields(
{'subnet_id': lambda: self._create_test_subnet_id()})
class SubnetObjectIfaceTest | Case(obj_test_base.BaseObjectIfaceTestCase):
_test_class = subnet.Subnet
def setUp(self):
super(SubnetObjectIfaceTestCase, self).setUp()
self.pager_map[subnet.DNSNameServer.obj_name()] = (
obj_base.Pager(sorts=[('order', True)]))
# Base class will mock those out only when r... |
poiesisconsulting/openerp-restaurant | epn/epn.py | Python | agpl-3.0 | 2,129 | 0.008455 |
# -*- 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 GN... | logging.getLogger(__name__)
class epn_pos_statements(osv.osv):
_inherit = 'account.bank.statement.line'
_columns = {
'signature': fields.binary("Signature",help="This signature provided with the payment"),
'epn_info': fields.text('EPN Credit-Card Info', help="EPN Credit-Card Payment Informatio... | }
class epn_pos_order(osv.osv):
_inherit = 'pos.order'
def _payment_fields(self,ui_paymentline):
fields = super(epn_pos_order,self)._payment_fields(ui_paymentline)
fields['signature'] = ui_paymentline.get('signature',False)
fields['epn_info'] = ui_paymentline.get('epn_info','')
... |
RoyalTS/econ-python-environment | .mywaflib/waflib/Tools/c_preproc.py | Python | bsd-3-clause | 27,412 | 0.03524 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
"""
C/C++ preprocessor for finding dependencies
Reasons for using the Waf preprocessor by default
#. Some c/c++ extensions (Qt) require a custom preprocessor for obtaining the dependencies (.moc files)
#. Not all compilers provide .d files for ob... | cters"""
NUM | = 'i'
"""Number token"""
OP = 'O'
"""Operator token"""
IDENT = 'T'
"""Identifier token"""
STR = 's'
"""String token"""
CHAR = 'c'
"""Character token"""
tok_types = [NUM, STR, IDENT, OP]
"""Token types"""
exp_types = [
r"""0[xX](?P<hex>[a-fA-F0-9]+)(?P<qual1>[uUlL]*)|L*?'(?P<char>(\\.|[^\\'])+)'|(?P<n1>\... |
divio/django-filer | tests/test_models.py | Python | bsd-3-clause | 12,044 | 0.001744 | import os
from django.conf import settings
from django.core.files import File as DjangoFile
from django.forms.models import modelform_factory
from django.test import TestCase
from tests.helpers import (
create_clipboard_item, create_folder_structure, create_image,
create_superuser,
)
from filer import settin... | ler_settings.FILER_PRIVATEMEDIA_STORAGE.location))
self.assertEqual(len(image.icons), len(filer_settings.FILER_ADMIN_ICON_SIZES))
def test_deleting_files(self):
# Note: this first test case fails deep inside
# easy-thumbnails thumbnail generation with a segmentation fault
# (which p... | if the previous test case had the create_filer_image() call
# - under python 3.x
# - once out of 3-4 runs
# It happens on completely different systems (locally and on Travis).
# Current tearDown() does not help, nor does cleaning up temp directory
# nor django cache.
# ... |
blackball/an-test6 | util/imageutils.py | Python | gpl-2.0 | 1,081 | 0.037003 | import numpy
def write_pnm_to(img, f, maxval=255):
if len(img.shape) == 1:
raise 'write_pnm: img is one-dimensional: must be 2 or 3.'
elif len(img.shape) == 2:
#pnmtype = 'G'
pnmcode = 5
(h,w) = img.shape
elif len(img.shape) == 3:
(h,w,planes) = img.shape
#pnmtype = 'P'
pnmcode = 6
if planes != 3:
... | imensions.'
if img.max() > maxval:
print 'write_pnm: Some pixel values are > maxval (%i): clipping them.' % maxval
if img.min() < 0:
print 'write_pnm: Some pixel values are < 0: clipping them.'
cli | pped = img.clip(0, maxval)
maxval = int(maxval)
if maxval > 65535:
raise 'write_pnm: maxval must be <= 65535'
if maxval < 0:
raise 'write_pnm: maxval must be positive'
f.write('P%i %i %i %i ' % (pnmcode, w, h, maxval))
if maxval <= 255:
f.write(img.astype(numpy.uint8).data)
else:
f.write(img.astype(nump... |
danielsamuels/working-on | working_on/apps/site/models.py | Python | mit | 205 | 0 | from cms.models import HtmlField
from cms.apps.pages.models import ContentBase
# class Cont | ent(ContentBase):
# content_primary = HtmlField(
# "primary content",
# blank=True
# ) | |
DavidTingley/ephys-processing-pipeline | installation/klustaviewa-0.3.0/klustaviewa/control/tests/test_processor.py | Python | gpl-3.0 | 1,236 | 0.005663 | """Unit tests for controller module."""
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os
import numpy as np
from klustaviewa.control.processor import Processor
from kwiklib.dat... |
xmlfile = os.path.join(dir, 'test.xml')
l = KlustersLoader(filename=xmlfile)
c = Processor(l)
return (l, c)
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
def t | est_processor():
l, p = load()
l.close()
|
vinodc/evernote | src/evernote/edam/notestore/ttypes.py | Python | bsd-2-clause | 89,345 | 0.016095 | #
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
import evernote.edam.userstore.ttypes
import evernote.edam.type.ttypes
import evernote.edam.error.ttypes
import evernote.edam.limits.ttypes
from thrift.transport import TTransport
from thrif... | is no more recent information.
</dd>
<dt>notes</dt>
<dd>
| If present, this is a list of non-expunged notes that
have a USN in this chunk. This will include notes that are "deleted"
but not expunged (i.e. in the trash). The notes will include their list
of tags and resources, but the resource content and recognition data
will not be supplied.
</dd... |
azumimuo/family-xbmc-addon | plugin.video.specto/resources/lib/resolvers/cloudmailru.py | Python | gpl-2.0 | 1,296 | 0.01466 | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
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 b | e 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 program. If not, see <http://www.gnu... |
akoskaaa/imfp | imfp/subscriptions/tests/test_models.py | Python | mit | 1,766 | 0.003964 |
from django.test.testcases import TestCase
from mock import patch, Mock
from imfp.subscriptions.models import Subscription
__all__ = ['CreateSubscriptionTestCase', 'RemoveSubscriptionTestCase']
class SubscriptionOperationsTestBase(TestCase):
def setUp(self):
self.mock_event = Mock(id=1)
self.mo... | ock_user.id, self.mock_event.id)
self.assertEquals(result, None)
# TODO figure this out.
#def test_create_subscription_success(self):
# with patch('imfp.subscriptions.models.get_or_none'):
# with patch('imfp.subscriptions.models.create') as mock_create:
# with patch('i | mfp.subscriptions.models.save'):
# mock_create.return_value = self.mock_subscription
# result = self.subscription_manager.create_subscription(self.mock_user.id, self.mock_event.id)
# self.assertNotEquals(result, None)
class RemoveSubscriptionTestCase(SubscriptionOperations... |
marianotepper/dask | dask/distributed/scheduler.py | Python | bsd-3-clause | 24,150 | 0.000621 | from __future__ import print_function
import zmq
import socket
import dill
import uuid
from collections import defaultdict
import itertools
from multiprocessing.pool import ThreadPool
import random
from datetime import datetime
from threading import Thread, Lock
from contextlib import contextmanager
import traceback
i... | : self._get_collection,
'close': self._close}
# Away we go!
log(self.address_to_workers, 'Start')
self._listen_to_workers_thread = Thread(target=self._listen_to_workers)
self._listen_to_worker | s_thread.start()
self._listen_to_clients_thread = Thread(target=self._listen_to_clients)
self._listen_to_clients_thread.start()
if block:
self.block()
def _listen_to_workers(self):
""" Event loop: Listen to worker router """
while self.status != 'closed':
... |
LaoZhongGu/kbengine | kbe/src/lib/python/Lib/ctypes/test/test_structures.py | Python | lgpl-3.0 | 15,782 | 0.002344 | import unittest
from ctypes import *
from struct import calcsize
import _testcapi
class SubclassesTest(unittest.TestCase):
def test_subclass(self):
class X(Structure):
_fields_ = [("a", c_int)]
class Y(X):
_fields_ = [("b", c_int)]
class Z(X):
pass
... | sertEqual((sizeof(X), code),
(calcsize("%c" % (code)), code))
def test_struct_alignment(self):
class X(Structure):
_fields_ = [("x", c_char * 3)]
self.assertEqual(alignment(X), calcsize("s"))
| self.assertEqual(sizeof(X), calcsize("3s"))
class Y(Structure):
_fields_ = [("x", c_char * 3),
("y", c_int)]
self.assertEqual(alignment(Y), calcsize("i"))
self.assertEqual(sizeof(Y), calcsize("3si"))
class SI(Structure):
_fields_ =... |
slaporte/qualityvis | orange_scripts/project_setup.py | Python | gpl-3.0 | 321 | 0.009346 | """
Load this into a Python Script widget (does not have
to be connected to any other widgets), and set the
project directory to the location of the git repo.
Hit execute and enjoy!
"""
PRO | JECT_DIR = '/home/mahmoud/work/qualityvis'
import sys
sys.path.append(PROJECT_DIR)
sys.path.append(PROJ | ECT_DIR+'/orange_scripts') |
AlexEKoren/grumpy | compiler/block_test.py | Python | apache-2.0 | 10,530 | 0.002757 | # coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | r'CheckLocal\b.*foo')
self.assertRegexpMatches(self._ResolveName(func1_block, 'bar'),
r'ResolveGlobal\b.*bar')
self.assertRegexpMatches(self._ResolveName(func1_bl | ock, 'baz'),
r'ResolveGlobal\b.*baz')
self.assertRegexpMatches(self._ResolveName(func2_block, 'foo'),
r'CheckLocal\b.*foo')
self.assertRegexpMatches(self._ResolveName(func2_block, 'bar'),
r'CheckLocal\b.*bar')
self.assert... |
windyer/windyer_blog | windyer_blog/wsgi.py | Python | bsd-3-clause | 395 | 0 | """
WSGI config for mysite 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.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_ | MODULE", "windyer_blog.settings")
application = get_wsgi_application()
|
miguelinux/vbox | src/VBox/Main/webservice/samples/python/clienttest.py | Python | gpl-2.0 | 4,520 | 0.006195 | #!/usr/bin/python
#
# Copyright (C) 2012 Oracle Corporation
#
# This file is part of VirtualBox Open Source Edition (OSE), as
# available from http://www.virtualbox.org. This file is free software;
# you can redistribute it and/or modify it under the terms of the GNU
# General Public License (GPL) as published by the F... | 's current display resolution + bit depth + position
screenNum = 0 # From first screen
(screenW, screenH, screenBPP, screenX, screenY, _) = display.getScreenResolution(screenNum)
print " Display (%d): %dx%d, %d BPP at %d,%d" %(screenN | um, screenW, screenH, screenBPP, screenX, screenY)
# We're done -- don't forget to unlock the machine!
session.unlockMachine()
except Exception, e:
print "Errror [%s]: %s" %(mach.name, str(e))
traceback.print_exc()
# Call destructor and delete wrapp... |
MyRobotLab/pyrobotlab | home/kwatters/harry/gestures/InMoovApps/Rock_Paper_Scissors/rock.py | Python | apache-2.0 | 1,243 | 0.132743 | def rock():
fullspeed()
i01.moveHead(90,90)
i01.moveArm("left",70,90,80,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.setHeadSpeed(.8,.8)
i01.moveHead(60,107)
i01.moveArm("left",49,90,75,10)
i01.mo... |
i01.moveArm("left",80,90,85,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.setHeadSpeed(.8,.8)
i01.moveHead(60,107)
i01.moveArm("left",49,90,75,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left"... | 0,90,90,10)
i01.moveArm("right",20,85,10,20)
i01.moveHand("left",130,180,180,180,180,90)
i01.moveHand("right",50,90,90,90,100,90)
sleep(.5)
i01.setHeadSpeed(.8,.8)
i01.moveHead(60,107)
i01.moveArm("left",45,90,75,10)
i01.moveArm("right",20,80,20,20)
i01.moveHand("left",130,180,180,180,180,80)... |
nvenayak/impact | impact/core/__init__.py | Python | gpl-3.0 | 276 | 0.007246 | from .TrialIdentifier import *
from .AnalyteData import TimeCourse, TimePoint, Substrate, Product, Biomass, Reporter, FitParameter
from .SingleTrial import SingleTrial
from .ReplicateTri | al import ReplicateT | rial
from .Experiment import Experiment
from .settings import settings |
ctuning/ck-env | soft/plugin.openme.ctuning/customize.py | Python | bsd-3-clause | 2,895 | 0.02418 | #
# Collective Knowledge (individual environment - setup)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
##############################################################################
# setup envir... | if win=='yes':
if remote=='yes' or mingw=='yes':
dext='.so'
else:
dext='.dll'
else:
dext='.so'
r = ck.access({'action': 'lib_path_export_script', 'module_uoa': | 'os', 'host_os_dict': host_d,
'dynamic_lib_path': cus.get('path_lib','')})
if r['return']>0: return r
s += r['script']
cus['dynamic_plugin']='plugin-openme-ctuning-1.5'+dext
env[envp+'_DYNAMIC_NAME']=cus.get('dynamic_plugin','')
return {'return':0, 'bat':s}
|
jilljenn/tryalgo | tryalgo/eulerian_tour.py | Python | mit | 4,665 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Eulerian cycle
jill-jênn vie et christoph dürr - 2015-2020
"""
import random
from tryalgo.graph import write_graph
# snip{ eulerian_tour_undirected
def eulerian_tour_undirected(graph):
"""Eulerian tour on an undirected graph
:param graph: directed graph... | pend to path from start
node = neighbor # move on
while R:
Q.append(R.pop()) # add to Q the discovered cycle R
P.append(start) # resulting path P is extended
return P
# snip}
def write_cycle(filename, graph, cycle, directed):
""... | ted: describes the graph
:param cycle: tour as a vertex list
:returns: nothing
:complexity: `O(|V|^2 + |E|)`
"""
n = len(graph)
weight = [[float('inf')] * n for _ in range(n)]
for r in range(1, len(cycle)):
weight[cycle[r-1]][cycle[r]] = r
if not directed:
... |
losalamos/Pavilion | PAV/modules/helperutilities.py | Python | bsd-3-clause | 3,253 | 0.011989 | #!python
# ###################################################################
#
# Disclaimer and Notice of Copyright
# ==================================
#
# Copyright (c) 2015, Los Alamos National Security, LLC
# All rights reserved.
#
# Copyright 2015. Los Alamos National Security, LLC.
# This software was... | ):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
| else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
|
klmitch/glance | glance/common/client.py | Python | apache-2.0 | 23,213 | 0 | # Copyright 2010-2011 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... |
self.host = host
| self.port = port or self.DEFAULT_PORT
self.timeout = timeout
# A value of '0' implies never timeout
if timeout == 0:
self.timeout = None
self.use_ssl = use_ssl
self.auth_token = auth_token
self.creds = creds or {}
self.connection = None
self.co... |
wemanuel/smry | smry/server-auth/ls/google-cloud-sdk/lib/googlecloudsdk/compute/subcommands/target_https_proxies/describe.py | Python | apache-2.0 | 917 | 0.007634 | # Copyright 2014 Google Inc. All Rights Reserved.
"""Command for describing target HTTP | S proxies."""
from googlecloudsdk.compute.lib import base_classes
class Describe(base_classes.GlobalDescriber):
"""Display detailed information about a target HTTPS proxy."""
@staticmethod
def Args(parser):
cli = Describe.GetCLIGenerator()
base_classes.GlobalDescriber.Args(
parser, 'compute.tar... | HttpsProxies')
@property
def service(self):
return self.compute.targetHttpsProxies
@property
def resource_type(self):
return 'targetHttpsProxies'
Describe.detailed_help = {
'brief': 'Display detailed information about a target HTTPS proxy',
'DESCRIPTION': """\
*{command}* displays al... |
jolene-esposito/osf.io | website/mails.py | Python | apache-2.0 | 7,045 | 0.002413 | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_pre... | ', mails.CONFIRM_EMAIL, user=user)
"""
import os
import logging
from mako.lookup import TemplateLookup, Template
from framework.email import tasks
from website import settings
logger = logging.getLogger(__name__)
EMAIL_TEMPLATES_DIR = os.path.join(settings.TEMPLATES_PATH, 'emails')
|
_tpl_lookup = TemplateLookup(
directories=[EMAIL_TEMPLATES_DIR],
)
TXT_EXT = '.txt.mako'
HTML_EXT = '.html.mako'
class Mail(object):
"""An email object.
:param str tpl_prefix: The template name prefix.
:param str subject: The subject of the email.
"""
def __init__(self, tpl_prefix, subject... |
ahu-odoo/odoo | addons/account/partner.py | Python | agpl-3.0 | 15,435 | 0.00596 | # -*- 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... | ntext.copy()
ctx['all_fiscalyear'] = True
query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx)
cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit)
FROM account_move_line l
| LEFT JOIN account_account a ON (l.account_id=a.id)
WHERE a.type IN ('receivable','payable')
AND l.partner_id IN %s
AND l.reconcile_id IS NULL
AND """ + query + """
GROUP BY l.partner_id, a.type
... |
kantel/Virtuelle-Wunderkammer | sources/treepy/tree.py | Python | mit | 680 | 0.016176 | import pygame, math
pygame.init()
window = pygame.display.set_mode((600, 600))
pygame.display.set_c | aption("Fractal Tree")
screen = pygame.display.get_surface()
def drawTree(x1, y1, angle, depth):
if depth:
x2 = x1 + int(math.cos(math.radians(angle)) * d | epth * 10.0)
y2 = y1 + int(math.sin(math.radians(angle)) * depth * 10.0)
pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)
drawTree(x2, y2, angle - 20, depth - 1)
drawTree(x2, y2, angle + 20, depth - 1)
def input(event):
if event.type == pygame.QUIT:
exit(0)
... |
yubang/wechat_sdk | wechat_sdk.py | Python | apache-2.0 | 11,004 | 0.00281 | # coding:UTF-8
"""
微信公众号相关操作封装
@author: yubang
@version: 1.0
2016年02月11日
"""
from xml.dom.minidom import Document
import requests
import json
import urllib
import time
request_timeout = 10
def __fetch_url(url, is_get=True, post_data=None):
"""
发送一个GET请求
:param url: 要请求的url
:param is_get: 是否是GET请... |
"""
将一条长链接转成短链接
:param access_token: 微信access_token
:param source_url: 源网址
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"action": 'long2short', 'long_url': source_url})
return re... | :param access_token: 微信access_token
:param expire_seconds: 二维码过期时间
:param scene_id: 场景值ID
:return:
"""
target_url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % access_token
result = __get_data_use_api(target_url, False, {"expire_seconds": expire_seconds, "action_info": ... |
weidel-p/nest-simulator | pynest/nest/tests/test_glif_cond.py | Python | gpl-2.0 | 7,258 | 0 | # -*- coding: utf-8 -*-
#
# test_glif_cond.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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,... | ailable')
class GLIFCONDTestCase(unittest.TestCase):
def setUp(self):
"""
Clean up and initialize NEST before each test.
"""
msd = 123456
self.resol = 0.01
nest.ResetKernel()
N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
pyrngs = [np.ran... | 'grng_seed': msd + N_vp,
'rng_seeds': range(msd + N_vp + 1,
msd + 2 * N_vp + 1)})
def simulate_w_stim(self, model_params):
"""
Runs a one second simulation with different types of input stimulation.
Return... |
Brett-D/cs494program | echoclient.py | Python | gpl-2.0 | 3,368 | 0.058492 | #!/usr/bin/env python
"""
Written by Brett Dunscomb
This is the game client for the game manhunt
The object of the game is to move into the space occupied by the other player
"""
import socket
import select
import sys
import os
import time
data = 'hello'
move = 'up'
host = 'localhost'
port = 50000
size = 1024
#game ... | game.conn.close()
quit()
if playerlock[0] == "2" and playerlock[1] == "N":
#data = game.conn.recv(size)
updateLoc(xpos,ypos)
print "two players connected"
move = raw_input("Enter Movement(up,down,left,right,quit):")
game.conn.send("m" + move) #sends movement command
... | updateLoc(xpos,ypos)
#print playerlock
print "waiting for player"
time.sleep(1)
except socket.error, (value,message):
if game.conn:
game.conn.close()
print "Server error: " + message
sys.exit(1)
finally:
game.conn.close()
|
Cocosoft/bitcoin | qa/rpc-tests/rpcnamedargs.py | Python | mit | 1,437 | 0.004175 | #!/usr/bin/env python3
# Copyright (c) 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.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_eq... | ert_equal(node.echo(arg1=1), [None, 1])
assert_equal(node.echo(arg9=None), [None]*10)
assert_equal(node.echo(arg0=0,ar | g3=3,arg9=9), [0] + [None]*2 + [3] + [None]*5 + [9])
if __name__ == '__main__':
NamedArgumentTest().main()
|
ARudiuk/mne-python | mne/commands/mne_show_fiff.py | Python | bsd-3-clause | 485 | 0 | #!/usr/bin/env python
"""Show the contents of a FIFF file
You can do for example:
$ mne show_fiff test_raw.fif
"""
# Authors : Eric Larson, PhD
import sys
import mne
def run():
parser = mne.command | s.utils.get_optparser(
__file__, usage='mne show_fiff <file>')
options, args = parser.parse_args()
if len(args) != 1:
parser.print_help()
sys.exit(1)
print(mne.io.show_fiff(args[0]))
is_main = (__name__ == '__main__')
if is_main:
run()
| |
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_rich_string03.py | Python | bsd-2-clause | 1,229 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | ted by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'rich_string03.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.e | xp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
bold = ... |
AntSharesSDK/antshares-python | sdk/AntShares/IO/BinaryWriter.py | Python | apache-2.0 | 2,641 | 0.001515 | # -*- coding:utf-8 -*-
"""
Description:
Binary Writer |
Usage:
from AntShares.IO.BinaryWriter import BinaryWriter
"""
import struct
import binascii
class BinaryWriter(object):
"""docstring for BinaryWriter"""
def __init__(self, stream):
super(BinaryWriter, self).__init__()
self.stream = stream
def writeByte(self, value):
self.st... | value = binascii.unhexlify(value)
except TypeError:
pass
self.stream.write(value)
def pack(self, fmt, data):
return self.writeBytes(struct.pack(fmt, data))
def writeChar(self, value):
return self.pack('c', value)
def writeInt8(self, value):
return s... |
simonzhangsm/voltdb | tools/vmc_stats_emulator.py | Python | agpl-3.0 | 4,874 | 0.012926 | #!/usr/bin/env python2.6
# This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to... | ds(content)['status'],"Unknown status")
print "%s %s Request# %d - | Error getting %s\n\thttp_status=%s\tresponse=%s" % (ts(), tid, i, a, response['status'], statusstring)
err_ct += 1
except AttributeError:
err_ct += 1
if err_ct >= max_errors:
if pause_on_error:
raw_input("Press any key to c... |
elbow-jason/flask-meta | flask_meta/appmeta/controllers/form_page.py | Python | mit | 402 | 0.007463 | from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound
form_page = Blueprint('form_page', __name__,
template_folder='templat | es')
@form_page.route('/<page>')
def show(page):
try:
form = AppForms.query.filter_by(name=page).first()
return render_template( | 'form.html', form=form)
except TemplateNotFound:
abort(404) |
vied12/superdesk | server/superdesk/media/media_operations.py | Python | agpl-3.0 | 3,953 | 0.000759 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
i... | k.lower(), decode_val(v)) for k, v in metadata.items())
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
exc... | return process_image(content, type)
if type in ('audio', 'video'):
return process_video(content, type)
return {}
def process_video(content, type):
content.seek(0)
meta = video_meta(content)
content.seek(0)
return meta
def process_image(content, type):
content.seek(0)
m... |
magfest/ubersystem | alembic/versions/53b71e7c45b5_add_fields_for_mivs_show_info_checklist_.py | Python | agpl-3.0 | 1,940 | 0.005155 | """Add fields for MIVS show_info checklist item
Revision ID: 53b71e7c45b5
Revises: ad26fcaafb78
Create Date: 2019-11-25 19:37:15.322579
"""
|
# revision identifiers, used by Alembic.
revision = '53b71e7c45b5'
down_revision = 'ad26fcaafb78'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
try:
is_sqlite = op.get_context().dialect.name == 'sqlite'
except Exception:
is_sqlite = False
if is_sqlite:
op.get_c... | imezone('utc', current_timestamp)"
def sqlite_column_reflect_listener(inspector, table, column_info):
"""Adds parenthesis around SQLite datetime defaults for utcnow."""
if column_info['default'] == "datetime('now', 'utc')":
column_info['default'] = utcnow_server_default
sqlite_reflect_kwargs = {
'... |
TylerKirby/cltk | cltk/tests/test_nlp/test_phonology.py | Python | mit | 40,764 | 0.003701 | """Test cltk.phonology."""
__author__ = ['Jack Duff <jmunroeduff@gmail.com>', "Clément Besnier <clemsciences@aol.com>"]
__license__ = 'MIT License. See LICENSE.'
import unicodedata
from cltk.phonology.arabic.romanization import transliterate as AarabicTransliterate
from cltk.phonology.greek import transcription as gr... | t the Latin Library corpus reader filter"""
@classmethod
def setUpClass(self):
self.greek_transcriber = grc.Transcriber("Attic", "Probert")
s | elf.latin_transcriber = lat.Transcriber("Classical", "Allen")
"""greek.transcription"""
def test_greek_refresh(self):
"""Test the Word class's `_refresh` method in Greek."""
test_word = grc.Word("pʰór.miŋks", grc.GREEK["Attic"]["Probert"])
test_word._refresh()
contexts = [test_w... |
myriadrf/pyLMS7002M | pyLMS7002M/__init__.py | Python | apache-2.0 | 115 | 0.043478 | __version_ | _="1.1.0"
from LMS7002_EVB import *
from LimeSDR import *
from LimeSDRMini import *
from QSpark import *
| |
CrashenX/auto-grader | src/auto-grade.py | Python | agpl-3.0 | 9,526 | 0.010708 | #!/usr/bin/env python
# Mininet Automatic Testing Tool (Prototype)
# Copyright (C) 2013 Jesse J. Cook
# This program 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, either version 3 of the
# License, o... | dest='hostname'
, default='mininet'
, help='hostname for the libvirt test domain'
)
return parser.parse_args()
def ssh_connect( hos | tname
, port=22
, username="mininet"
, keyfile="~/.ssh/id_rsa"
):
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect( hostname = hostname
... |
aswolf/unbiased-pscale | code/Fei2007_fit.py | Python | mit | 9,689 | 0.023222 | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as optimization
from MGD_func import MGD_PowerLaw
#define functions here
def lsqfun(p_eos,volume,temperature,Natom,P):
resid_scl = MGD_PowerLaw(volume, temperature, p_eos,Natom) - P
return resid_scl
def fitfun(p_eos,volu... | resid_scl = (MGD_PowerLaw(volume, tem | perature, p_eos,Natom) - P)/error
return resid_scl
#V0, gamma0 and theta0 are fixed here.
def lsqfun_Fixed(p_fit, p_fix ,volume,temperature,Natom,P):
pall = [p_fix[0],p_fit[0],p_fit[1],p_fix[1], p_fix[2],p_fit[2]]
resid_scl = MGD_PowerLaw(volume, temperature, pall,Natom) - P
return resid_scl
def lsqfun_Fixedfit(p... |
mwales/education | InteractivePython/asteroids.py | Python | gpl-2.0 | 25,069 | 0.011568 | # program template for Spaceship
import simplegui
import math
import random
# globals for user interface
WIDTH = 800
HEIGHT = 600
score = 0
lives = 3
time = 0
game_mode = 0 # 0 = splash screen, 1 = game mode, 2 = game over
ANGULAR_ACCEL_SCALAR = math.pi / 800.0
ANGULAR_FRICTION = 0.95
LINEAR_ACCEL_SCALAR = 0.25
LINEA... | ang)]
def vector_to_angle(v):
return math.atan2(v[0],v[1])
def vector_scale(vec, scale):
return [vec[0] * scale, vec[1] * scale]
def vector_add(vec1, vec2):
return [vec1[0] + vec2[0], vec1[1] + vec2[1]]
def dist(p,q):
return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2)
def smallRockExplode(roc... | (0,0),
random.random() * 2 * math.pi,
0,
explosion_image,
explosion_info,
explosion_sound,
relSize = 0.3)
return explodeObj
... |
nikitamarchenko/open-kilda | services/topology-engine/queue-engine/tests/smoke-tests/create-multi-path-topology.py | Python | apache-2.0 | 779 | 0 | #!/usr/bin/python
# Copyright 2017 Telstra Open Source
#
# 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 appl... | 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 clean_topology | import cleanup
from create_topology import create_topo
print "\n -- "
cleanup()
create_topo('multi-path-topology.json')
print "\n -- "
|
tomasstorck/diatomas | blender/asdriver_nofil.py | Python | mit | 1,371 | 0.010941 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Driver for ecoli.py
import os, re, time, subprocess
iterModDiv = 1
dirPathList = ["/home/tomas/documenten/modelling/diatomas_symlink/results/as_low_bridging_seed2"]
for d in dirPathList:
print(time.strftime('%H:%M:%S ') + d)
dAbs = d + "/output"
fileList = [... | )
if not int(re.match('g(\d{4})r(\d{4}).mat',f).group(2))%iterModDiv == 0:
# relaxation iteration (YYYY in filename gXXXXrYYYY.mat) % iterModulusDivider == 0
continue
fAbs = dAbs + "/" + f
callStr = ["blender", "--background", "--python", "as_nofil.py", "--", fAbs] ... | stdout = stdout.decode()
if 'Error' in stdout:
print("#####################################")
print(stdout)
print("#####################################")
|
Polarcraft/KbveBot | commands/help.py | Python | gpl-2.0 | 1,867 | 0.002142 | # Copyright (C) 2013-2015 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Fox Wilson
#
# 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 ve... | argument only")
elif not is_registered(msg):
send("Not a module.")
else:
doc = get_command(msg).get_doc()
if doc is None:
send("No documentation found.")
else:
for line in doc.splitlines():
| send(line.format(command=cmdchar + msg))
else:
modules = sorted(get_commands())
cmdlist = (' %s' % cmdchar).join(modules)
send('Commands: %s%s' % (cmdchar, cmdlist), target=args['nick'], ignore_length=True)
send('%shelp <command> for more info on a command.' % cmdc... |
drcoms/drcom-generic | latest-wired.py | Python | agpl-3.0 | 18,049 | 0.016473 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import struct
import time
import hashlib
import sys
import os
import random
import traceback
# CONFIG
server = "192.168.100.150"
username = ""
password = ""
host_name = "LIYUANYUAN"
host_os = "8089D"
host_ip = "10.30.22.17"
PRIMARY_DNS = "114.114.114.114"
dh... | packet, (svr, 61440))
data, address = s.recvfrom(1024)
log('[keep-alive2] recv1',data.encode('hex'))
if da | ta.startswith('\x07\x00\x28\x00') or data.startswith('\x07' + chr(svr_num) + '\x28\x00'):
break
elif data[0] == '\x07' and data[2] == '\x10':
log('[keep-alive2] recv file, resending..')
svr_num = svr_num + 1
# packet = keep_alive_package_builder(svr_num,dump(ran)... |
caio2k/RIDE | src/robotide/lib/robot/libraries/dialogs_jy.py | Python | apache-2.0 | 3,458 | 0 | # Copyright 2008-2015 Nokia Solutions and 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 applicable l... | er(pane.focus_listener)
dialog.show()
while dialog.isShowing():
time.sleep(0.2)
dialog.dispose()
def _get_value(self, pane):
value = pane.getInputValue()
return value if value != UNINITIALIZED_VALUE else None
clas | s MessageDialog(_SwingDialog):
def __init__(self, message):
pane = WrappedOptionPane(message, PLAIN_MESSAGE, DEFAULT_OPTION)
_SwingDialog.__init__(self, pane)
class InputDialog(_SwingDialog):
def __init__(self, message, default, hidden=False):
self._input_field = JPasswordField() if ... |
Fenugreek/tamarind | calendar.py | Python | gpl-3.0 | 11,719 | 0.008789 | """
Track valid dates, number of days between them, etc.
"""
import re
import datetime, time
import numpy
from . import logging
def today():
"""Return system date in YYYYMMDD."""
return time.strftime('%Y%m%d')
def decimalize(dates):
"""
Convert '20020930' to 2002.75.
"""
if numpy.isscalar(... | date
| else: return self.search_date(date, 1)
def previous_valid(self, date):
"""If given date is in calendar, return it; otherwise return closest
earlier date in the calendar."""
date = str(date)
if date in self.date: return date
else: return self.search_date(date, 0)
... |
tboyce1/home-assistant | homeassistant/components/hassio/http.py | Python | apache-2.0 | 4,916 | 0.00061 | """HTTP Support for Hass.io."""
import asyncio
import logging
import os
import re
from typing import Dict, Union
import aiohttp
from aiohttp import web
from aiohttp.hdrs import CONTENT_LENGTH, CONTENT_TYPE
from aiohttp.web_exceptions import HTTPBadGateway
import async_timeout
from homeassistant.components.http import... | nt.read()
return web.Respons | e(
content_type=client.content_type, status=client.status, body=body
)
# Stream response
response = web.StreamResponse(status=client.status, headers=client.headers)
response.content_type = client.content_type
await response.prepare(re... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.5/django/contrib/localflavor/pe/pe_region.py | Python | bsd-3-clause | 854 | 0 | # -*- coding: utf-8 -*-
"""
A list of Peru regions as `choices` in a formfield.
This exists in this standalone file so that it's only imported into memory
when explicitly needed.
"""
from __future__ import unicode_literals
REG | ION_CHOICES = (
('AMA', 'Amazonas'),
('ANC', 'Ancash'),
('APU', 'Apurímac'),
('ARE', 'Arequipa'),
('AYA', 'Ayacucho'),
('CAJ', 'Cajamarca'),
('CAL', 'Callao'),
('CUS', 'Cusco'),
('HUV', 'Huancavelica'),
('HUC', 'Huánuco'),
('ICA', 'Ica'),
('JUN', 'Junín'),
('LAL', 'La... | o'),
('PIU', 'Piura'),
('PUN', 'Puno'),
('SAM', 'San Martín'),
('TAC', 'Tacna'),
('TUM', 'Tumbes'),
('UCA', 'Ucayali'),
)
|
meteorfox/PerfKitBenchmarker | perfkitbenchmarker/providers/gcp/gcp_bigtable.py | Python | apache-2.0 | 3,117 | 0.003529 | # Copyright 2016 PerfKitBenchmarker 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 appli... | cloudCommand(self, 'beta', 'bigtable', 'instances', 'list')
cmd.flags['format'] = 'json'
cmd.flags['project'] = self.project
# The zone flag makes this command fail.
cmd.flags['zone'] = []
stdout, stderr, retcode = cmd.Issue(suppress_warning=True)
if retcode != 0:
# This is not ideal, as w... | he table isn't there, but because we can't figure out whether
# it is there. This behavior is consistent without other
# _Exists methods.
logging.error('Unable to list GCP Bigtable instances. Return code %s '
'STDOUT: %s\nSTDERR: %s', retcode, stdout, stderr)
return False
... |
berquist/cclib | cclib/parser/gamessukparser.py | Python | bsd-3-clause | 30,330 | 0.002209 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2020, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Parser for GAMESS-UK output files"""
import re
import numpy
from cclib.parser import logfileparser
from cclib.parse... | *****************
# * basis selected is sto sto3g *
# ****************************************
#
# *******************************************************************************
# * ... | atomic coordinates number of *
# * charge x y z shells *
# * *
# *************************************... |
pystruct/pystruct | setup.py | Python | bsd-2-clause | 1,928 | 0 | from setuptools import setup
from setuptools.extension import Extension
import numpy as np
import os
if os.path.exists('MANIFEST'):
os.remove('MANIFEST')
include_dirs = [np.get_include()]
setup(name="pystruct",
version="0.3.2",
install_requires=["ad3", "numpy"],
packages=['pystruct', 'pystruct... |
'Intended Audience :: Developers',
'License :: OSI Approved',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
... | 'Operating System :: Unix',
'Operating System :: MacOS',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: ... |
nesdis/djongo | tests/django_tests/tests/v21/tests/context_processors/urls.py | Python | agpl-3.0 | 173 | 0 | from django.conf.urls import url
from . impo | rt views
urlpatterns = [
url(r'^request_att | rs/$', views.request_processor),
url(r'^debug/$', views.debug_processor),
]
|
cheddarfinancial/quarry-platform | chassis/database.py | Python | bsd-3-clause | 7,076 | 0.006218 | # Standard Library
import datetime
import json
# Third Party
import mixingboard
from sqlalchemy import create_engine, types, event, exc, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool i... | odels.jobhistory import JobHistory
from models.notification import Notification
from models.query import Query
from models.rawdataset impor | t RawDataset
from models.user import User
from models.workflow import Workflow
from models.token import Token
Base.metadata.create_all(bind=engine)
##
# Json TYPE BECAUSE SQLALCHEMY IS RETARDED
##
class JsonEncodedObj(types.TypeDecorator):
"""Represents an immutable structure as a json-encoded s... |
veltzer/demos-python | src/examples/short/gzip/same_content_different_files.py | Python | gpl-3.0 | 1,827 | 0.001095 | #!/usr/bin/env python
"""
This example shows that two activations of the gzip library to compress files
actually produce files with different md5 signatures.
The reason for this is the filename, date and compression levels.
You can control this by uding the GzipFil | e object which has more
parameters. This is not yet demonstrated in this demo.
References:
- http://stackoverflow.com/questions/28213912/python-md5-hashes-of-same-gzipped-file-are-inconsistent
"""
import gzip
import hashlib
f_name = '/etc/passwd'
output_template = '/tmp/test{}.gz'
def digest(filename: str) -> str:... | , 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
return md5.hexdigest()
block_size = 4096
print("The default way - non identical outputs")
for x in range(0, 3):
input_handle = open(f_name, 'rb')
output_filename = output_template.format(x)
my_zip =... |
KiChjang/servo | tests/wpt/web-platform-tests/service-workers/service-worker/resources/fetch-access-control.py | Python | mpl-2.0 | 5,045 | 0.006343 | import base64
import json
import os
import six
from wptserve.utils import isomorphic_decode, isomorphic_encode
def decodebytes(s):
if six.PY3:
return base64.decodebytes(six.ensure_binary(s))
return base64.decodestring(s)
def main(request, response):
headers = []
headers.append((b'X-ServiceWo... | quest.GET[query]))
if b"ACEHeaders" in request.GET:
headers.append((b"Access-Control-Expose-Headers", request.GET[b"ACEHeaders"]))
if (b"Auth" in reques | t.GET and not request.auth.username) or b"AuthFail" in request.GET:
status = 401
headers.append((b'WWW-Authenticate', b'Basic realm="Restricted"'))
body = b'Authentication canceled'
return status, headers, body
if b"PNGIMAGE" in request.GET:
headers.append((b"Content-Type", ... |
nanocell/lsync | python/boto/auth.py | Python | gpl-3.0 | 24,702 | 0.000648 | # Copyright 2010 Google Inc.
# Copyright (c) 2011 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2011, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without re... | access_key, b64_hmac))
class HmacAuthV2Handler(AuthHandler, HmacKeys):
"""
Implements the simplified HMAC authorization used by CloudFront.
"""
capability = ['hmac-v2', 'cloudfront']
def __init__(self, host, config, provider):
AuthHandler.__init__(self, host, config, provider)
Hma... | provider):
super(HmacAuthV2Handler, self).update_provider(provider)
self._hmac_256 = None
def add_auth(self, http_request, **kwargs):
headers = http_request.headers
if 'Date' not in headers:
headers['Date'] = formatdate(usegmt=True)
b64_hmac = self.sign_string(... |
stepanvanecek/failover_test_framework | source/infrastructure/main.py | Python | gpl-3.0 | 2,430 | 0.003704 | #!/usr/bin/python
import os
import sys
import commentjson
import time
import json
import datetime
from parse_input import check_config_struc | ture
from build_nova import build_infrastructure, wait_for_spawn
from url_requests import test_infrastructure
import subprocess
### MAIN
| if __name__ == "__main__":
if len(sys.argv) > 4:
configFile = sys.argv[4]
else:
print "No config file specified. Using 'config_example.json'"
configFile = 'config_example.json'
try:
with open(sys.argv[3] + "/config_files/" + configFile) as json_data_file:
try:
... |
dotKom/onlineweb4 | apps/profiles/appconfig.py | Python | mit | 333 | 0 | from django.apps import AppConfig
class ProfilesConfig(AppConfig):
name = 'apps.profiles'
verbose_name = | 'Profiles'
def ready(self):
super(ProfilesConfig, self).ready()
from reversion import revisions as reversion
from apps.profiles.model | s import Privacy
reversion.register(Privacy)
|
levilucio/SyVOLT | UMLRT2Kiltera_MM/PortConnector.py | Python | mit | 3,839 | 0.029435 | """
__PortConnector.py_____________________________________________________
Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY)
Author: gehan
Modified: Sat Aug 30 18:23:4 | 0 2014
_______________________________________________________________________
"""
fro | m ASGNode import *
from ATOM3Type import *
from ATOM3String import *
from graph_PortConnector import *
class PortConnector(ASGNode, ATOM3Type):
def __init__(self, parent = None):
ASGNode.__init__(self)
ATOM3Type.__init__(self)
self.superTypes = ['NamedElement', 'MetaModelElement_S']
self.g... |
DronMDF/laweb | lawe/migrations/0007_auto_20170423_1937.py | Python | apache-2.0 | 1,029 | 0.029258 | # -*- coding: u | tf-8 -*-
# Generated by Django 1.10 on 2017-04-23 19:37
''' Миграция '''
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
''' Добавляем опциональные поля '''
dependencies = [
('lawe', '0006_remove_account_unit'),
]
operations = [
migrati... | length=200, verbose_name='Основная группа'),
),
migrations.AlterField(
model_name='account',
name='name',
field=models.CharField(blank=True, max_length=200, verbose_name='Название'),
),
migrations.AlterField(
model_name='account',
name='subgroup',
field=models.CharField(blank=True, max_length=... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractBLNovelObsession.py | Python | bsd-3-clause | 854 | 0.0363 | def extractBLNovelObsession(item):
"""
'BL Novel Obsession'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
if 'Feng | Mang' in item['tags']:
return buildReleaseMessageWithType(item, 'Feng Mang', vol, chp, frag=frag, postfix=postfix)
tagmap = [
('Deceive', 'Deceive', 'translated'),
('Feng Mang', 'Feng Mang', 'translated'),
('15P 7H 6SM', '15P 7H 6SM', ... | uildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
wcmitchell/insights-core | insights/combiners/tests/test_user_namespaces.py | Python | apache-2.0 | 4,522 | 0 | from ..user_namespaces import UserNamespaces
from ...parsers.cmdline import CmdLine
from ...parsers.grub_conf import Grub2Config
from ...tests import context_wrap
ENABLE_TOK_A = '''
user_namespaces.enable=1
'''.strip() # noqa
ENABLE_TOK_B = '''
user-namespaces.enable=1
'''.strip() # noqa
CMDLINE = '''
BOOT_IMAGE=/... | l7.x86_64) 7.3 (Maipo)' --class red --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-514.el7.x86_64-advanced-9727cab4-12c2-41a8-9527-9644df34e586' {{
load_video
set gfxpayload=keep
insmod gzio
insmod part_gpt
insmod xfs
set roo... | [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt2 --hint-efi=hd0,gpt2 --hint-baremetal=ahci0,gpt2 d80fa96c-ffa1-4894-9282-aeda37f0befe
else
search --no-floppy --fs-uuid --set=root d80fa96c-ffa1-4894-9282-aeda37f0befe
fi
... |
cmtm/networkx | networkx/algorithms/shortest_paths/tests/test_astar.py | Python | bsd-3-clause | 5,022 | 0 | from nose.tools import assert_equal
from nose.tools import assert_raises
from nose.tools import raises
from math import sqrt
from random import random, choice
import networkx as nx
from networkx.utils import pairwise
def dist(a, b):
"""Returns the Euclidean distance between points `a` and `b`."""
return sqr... | on 2 is | dropped, this test can be simplified
# by replacing `Unorderable()` by `object()`.
class Unorderable(object):
def __le__(self):
raise NotImplemented
def __ge__(self):
raise NotImplemented
# Create the cycle graph on four nodes, with node... |
uDeviceX/uDeviceX | pre/uconf/src/uconf.py | Python | gpl-2.0 | 20,089 | 0.0001 | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evalu... | (BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)' | ),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.