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
igroen/homebrew
homebrew/homebrew.py
Python
isc
2,053
0.000974
import asyncio import subprocess from collections import defaultdict from .cache import uses_cache from .printer import print_overview class HomeBrew: __slots__ = ("_installed", "_uses") def __init__(self): self.update() def update(self): self._installed = self._get_installed() ...
et_installed(self): result = subprocess.check_output(["brew", "list", "--formula"]) installed = result.split() return [r.deco
de() for r in installed] @uses_cache def _get_uses(self): tasks = [self._get_uses_for_package(package) for package in self._installed] tasks_result, _ = asyncio.run(asyncio.wait(tasks)) return dict(task_result.result() for task_result in tasks_result) async def _get_uses_for_packa...
appleseedhq/cortex
test/IECore/Object.py
Python
bsd-3-clause
6,383
0.04465
########################################################################## # # Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
urn False group = IECore.CompoundObject() objectClasses = filter(objectDerived, map(lambda x: getattr(IECore, x), dir(IECore))) notCreated = [] notCasted = [] for c in objectClasses: tId = IECore.Object.typeIdFromTypeName( c.__name__ ) try: obj = IECore.Object.create(tId) except: notCreated....
oup["object"] = obj except: notCasted.append(c) errors = "" if len( notCreated ) : errors += "The following classes could not be created from Object.create() function: " + str( notCreated ) + "\n" if len( notCasted ): errors += "The following classes could not be casted to ObjectPtr:" + str( notCa...
heddle317/moto
moto/core/responses.py
Python
apache-2.0
22,064
0.000453
from __future__ import unicode_literals import datetime import json import logging import re import pytz from moto.core.exceptions import DryRunClientError from jinja2 import Environment, DictLoader, TemplateNotFound import six from six.moves.urllib.parse import parse_qs, urlparse import xmltodict from pkg_resource...
ram(param_name) if val is not None: return int(val) return if_none def _get_bool_param(self, param_name, if_none=None): val = self._get_param(param_name) if val
is not None: if val.lower() == 'true': return True elif val.lower() == 'false': return False return if_none def _get_multi_param(self, param_prefix): """ Given a querystring of ?LaunchConfigurationNames.member.1=my-test-1&LaunchConfigu...
silly-wacky-3-town-toon/SOURCE-COD
otp/otpbase/Settings.py
Python
apache-2.0
893
0.00224
import collections import json import os class Settings(collections.MutableMapping): def __init__(self, filename): self.filename = filename self.store = {} self.read() def read(self): if os.path.exists(self.filename): with open(self.filename, 'r') as f: ...
separators=(',', ': ')) def __setitem__(self, key, value): self.store[key] = value self.write() def __delitem__(self, key): del self.store[key] self.write() def __getitem__(self, key): return self.store[key] def __iter__(self
): return iter(self.store) def __len__(self): return len(self.store)
feist/pcs
pcs_test/tools/command_env/config_http_files.py
Python
gpl-2.0
4,688
0
import base64 import json from pcs_test.tools.command_env.mock_node_communicator import ( place_multinode_call, ) class FilesShortcuts: def __init__(self, calls): self.__calls = calls def put_files( self, node_labels=None, pcmk_authkey=None, corosync_authkey=None,...
True, ) output_data[file_id] = written_output_dict if corosync_authke
y: file_id = "corosync authkey" input_data[file_id] = dict( data=base64.b64encode(corosync_authkey).decode("utf-8"), type="corosync_authkey", rewrite_existing=True, ) output_data[file_id] = written_output_dict if co...
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_email/imaplib_fetch_raw.py
Python
apache-2.0
243
0
import imaplib import pprint import imaplib_connect ima
plib.Debug = 4 with imapli
b_connect.open_connection() as c: c.select('INBOX', readonly=True) typ, msg_data = c.fetch('1', '(BODY.PEEK[HEADER] FLAGS)') pprint.pprint(msg_data)
SilverWingedSeraph/pyparens
parens/eval.py
Python
mit
4,263
0.000704
# eval.py # Python Lisp EVALuation function import importlib from .common import Symbol, List from .env import global_env def get_var(x, env): " Look up a variable in the env. If it's not there, look it up globally. " try: val = env[x] except KeyError: try: val = globals()[x]...
: # const. literal return x # OK, x is a list, but is it
empty? elif len(x) == 0: return [] # It isn't empty... maybe it's a special form. # Dot extraction special form elif x[0] == '.': return dot_extraction(x, env) # Conditional special form elif x[0] == 'if': try: # With an alt clause (_, test, cons...
HelloLily/hellolily
lily/utils/migrations/0016_remove_historylistitem.py
Python
agpl-3.0
606
0
# -*- coding: utf-8
-*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('utils', '0015_auto_20161121_1831'), ('notes', '0010_remove_polymorphic_cleanup') ] operations = [ migrations.RemoveField( model_nam...
ame='tenant', ), migrations.DeleteModel( name='HistoryListItem', ), ]
tgquintela/pySpatialTools
pySpatialTools/Retrieve/collectionretrievers.py
Python
mit
13,968
0.001432
""" CollectionRetrievers -------------------- Wrapper of retrievers with a customed api oriented to interact properly with spatial descriptor models. This module contains the main class to mamage all retrievers without entering in low-level programming. As the FeaturesRetriever there are a requisit to have all the ret...
################ ########################################################################### def _format_retrievers(sel
f, retrievers): """Format the retrievers. Parameters ---------- retrievers: list, pst.BaseRetriever the retrievers we want to input to that manager. """ if type(retrievers) == list: self.retrievers += retrievers elif retrievers.__name__ =...
AhmadHamzeei/Amir-Accounting
amir/setting.py
Python
gpl-3.0
27,685
0.006502
import gtk import os import gobject import class_subject import upgrade import database import dbconfig import subjects from share import share from helpers import get_builder, comboInsertItems config = share.config class Setting(gobject.GObject): def __init__(self): gobject.GObject.__init__(self) ...
e.get_iter_from_string(path) self.liststore.set(self.active_iter, column, False) self.liststore.set(iter, column, True) self.active_iter = iter def selectDbFile(self, sender): self.filechooser.set_action(gtk.FILE_CHOOSER_ACTION_OP
EN) self.filechooser.set_current_folder (os.path.dirname (config.db.dbfile)) result = self.filechooser.run() if result == gtk.RESPONSE_OK: self.filename.set_text(self.filechooser.get_filename()) self.filechooser.hide() # def selectOldDatabase(self, sender): # ...
PHSCRC/boxbot
hardware/distance.py
Python
mit
1,344
0.00372
import os, math try: from .adc import * except SystemError: from adc import * from bisect import bisect_right, bisect_left class InterpolatedDistance(ADC4): def __init__(self, profiles, ad
dr, **kwargs): super().__init__(addr, fn="distance", **kwargs) self.__mm = [] self.__v = []
for i in profiles: i.sort(key=lambda x: -x[0]) repacked = tuple(zip(*i)) self.__mm.append(repacked[0]) self.__v.append(repacked[1]) def process_reading(self, reading, pin): v = super().process_reading(reading, pin) try: v = v ...
WUJISHANXIA/wujishanxia
bootcamp/activities/models.py
Python
mit
8,027
0
from __future__ import unicode_literals import json from django.db.models.functions import TruncMonth, TruncDay from django.db.models import Count from django.contrib.auth.models import User from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.html import escape...
self.question.pk, escape(self.get_summary(self.question.title)) ) elif self.notification_type == self.ACCEPTED_ANSWER: return self._ACCEPTED_ANSWER_TEMPLATE.format( escape(self.from_user.username), escape(self.from_user...
self.answer.question.pk, escape(self.get_summary(self.answer.description)) ) elif self.notification_type == self.EDITED_ARTICLE: return self._EDITED_ARTICLE_TEMPLATE.format( escape(self.from_user.username), escape(self.from_user.profile...
tsdmgz/ansible
test/runner/lib/sanity/rstcheck.py
Python
gpl-3.0
2,126
0.002352
"""Sanity test using rstcheck.""" from __future__ import absolute_import, print_function import os from lib.sanity import ( SanitySingleVersion, SanityMessage, SanityFailure, SanitySuccess, SanitySkipped, ) from lib.util import ( SubprocessError, run_command, parse_to_dict, find_e...
(SanitySingleVersion): """Sanity test using rstcheck.""" def test(self, args, targets): """ :type args: SanityConfig :type targets: SanityTargets :rtype: SanityResult """ with open('test/sanity/rstcheck/ignore-substitutions.txt', 'r') as ignore_fd: ign...
'.rst',)) if not paths: return SanitySkipped(self.name) cmd = [ 'python%s' % args.python_version, find_executable('rstcheck'), '--report', 'warning', '--ignore-substitutions', ','.join(ignore_substitutions), ] + paths try: ...
siye1982/kafkey
app/main/__init__.py
Python
bsd-2-clause
848
0.001238
# -*- coding:utf-8 -*- import socket # 判断是否是ip:port def
is_ip_port(ip_port): ip_port_arr = ip_port.split(':') if len(ip_port_arr) != 2 or isinstance(ip_port_arr[1], int): return False return is_internal_ip(ip_port_arr[0]) # 判断是否是内网ip def is_internal_ip(ip): if not check_ip(ip): return False ip = ip_into_int(ip)
net_a = ip_into_int('10.255.255.255') >> 24 net_b = ip_into_int('172.31.255.255') >> 20 net_c = ip_into_int('192.168.255.255') >> 16 return ip >> 24 == net_a or ip >> 20 == net_b or ip >> 16 == net_c # 将ip转成int def ip_into_int(ip): return reduce(lambda x, y: (x << 8) + y, map(int, ip.split('.'))) #...
nirizr/rematch
server/collab/migrations/0002_auto_20181104_0545.py
Python
gpl-3.0
713
0.002805
# Generated by Django 2.1.2 on 2018-11-04 05:45 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('collab', '0001_initial'), ] operations = [ migrations.AddField( model_name='instance', ...
s.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ),
migrations.AddField( model_name='match', name='created', field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now), preserve_default=False, ), ]
luiscape/hdx-monitor-sql-collect
app/functions/manage_queue.py
Python
mit
1,180
0.010169
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Function to manage the Redis Queue. In summary this function either (a) starts a new queue if no jobs are pending (b) fetches statistics from a running queue (c) cancels a queue and starts again This function was designed to be called directly by the routes so that ...
''' Gets status of queue. ''' queue = Queue(connection=Redis(host=REDIS_HOST), name=queue_id) result = { 'message': 'Queue `{name}` has {n} jobs that are being processed.'.format(name=queue_id, n=queue.count), 'empty': queue.is_empty(), 'count': queue.count, 'ids': queue.get_job_ids() } r...
sult = { 'success': True, 'message': 'Cleaned {n} jobs successfully from `{name}`.'.format(n=queue.empty(), name=queue_id) } return result
c3cashdesk/c6sh
src/postix/core/migrations/0057_itemsupplypack_itemsupplypacklog.py
Python
agpl-3.0
2,025
0.003951
# Generated by Django 2.1.4 on 2018-12-20 13:04 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0056_auto_20181207_1404'), ] operations = [ migrations.CreateModel...
oreignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='core.ItemMovement', verbose_name='Associated item movement')), ('supply_pack', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='logs', to='core.ItemSupplyPack'))
, ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='item_supply_logs', to=settings.AUTH_USER_MODEL, verbose_name='User issuing movement')), ], ), ]
spulec/moto
moto/dynamodb2/models/dynamo_type.py
Python
apache-2.0
8,167
0.002204
from moto.dynamodb2.comparisons import get_comparison_func from moto.dynamodb2.exceptions import IncorrectDataType from moto.dynamodb2.models.utilities import bytesize class DDBType(object): """ Official documentation at https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeValue.html ...
if key.upper() == key } @classmethod def get_human_type(cls, abbreviated_type): """ Args: abbreviated_type(str): An attribute of DDBType Returns: str: The human readable form of the DDBType. """ return cls._human_type_mapping.get(abbre...
type) class DynamoType(object): """ http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModelDataTypes """ def __init__(self, type_as_dict): if type(type_as_dict) == DynamoType: self.type = type_as_dict.type self.value = type_as_dict.valu...
ctgk/BayesianNetwork
test/math/test_divide.py
Python
mit
637
0
import unittest import numpy as np import bayesnet as bn class TestDivide(unittest.TestCase): def test_divide(self): x = bn.Parame
ter(10.) z = x / 2 self.assertEqual(z.value, 5) z.backward() self.assertEqual(x.grad, 0.5) x = np.random.rand(5, 10, 3) y = np.random.rand(10, 1) p = bn.Parameter(y
) z = x / p self.assertTrue((z.value == x / y).all()) z.backward(np.ones((5, 10, 3))) d = np.sum(-x / y ** 2, axis=0).sum(axis=1, keepdims=True) self.assertTrue((p.grad == d).all()) if __name__ == '__main__': unittest.main()
mwcraig/conda-build
conda_build/jinja_context.py
Python
bsd-3-clause
1,276
0.004702
''' Created on Jan 16, 2014 @author: sean ''' from __
future__ import absolute_import, division, print_function import json import os from conda.compat import PY3 from .environ import get_dict as get_environ _setuptools_data = None def load_setuptools(setup_file='setup.py'): global _setuptools_data if _setuptools_data is None: _setuptools_data = {} ...
.path.append('.') #Patch setuptools setuptools_setup = setuptools.setup setuptools.setup = setup exec(open(setup_file).read()) setuptools.setup = setuptools_setup del sys.path[-1] return _setuptools_data def load_npm(): # json module expects bytes in Python 2 an...
Valeureux/wezer-exchange
__unreviewed__/website_community_template/__openerp__.py
Python
agpl-3.0
1,583
0
# -*- coding: utf-8 -*- # # # Website Marketplace # Copyright (C) 2014 Valeureux Group (<http://Valeureux.com>). # # 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 ve...
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # { 'name': 'Website Community Templa...
'auth_signup', 'website', 'website_marketplace', 'website_blog' ], 'data': [ 'views/assets.xml', 'views/snippets.xml', 'views/templates/404.xml', 'views/templates/layout.xml', 'views/templates/login.xml', 'views/templates/login_layout...
metacloud/molecule
test/unit/command/init/test_role.py
Python
mit
5,090
0
# Copyright (c) 2015-2018 Cisco 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 restriction, including without limitation the # rights to use, copy, modify, merge...
mission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNE...
HERA-Team/librarian
alembic/env.py
Python
bsd-2-clause
1,321
0.002271
# -*- mode: python; coding: utf-8 -*- # Copyright 2016 the HERA Collaboration # Licensed under the 2-clause BSD License. """This script is some boilerplate needed by Alembic to do its fancy database migration stuff. """ # A hack so that we can get the librarian_server module. import sys sys.path.insert(0, '.') fro...
. """ url = app.config['SQLALCHEMY_DATABASE_URI'] context.configure( url=url, target_metadata=target_metadata, literal_binds=True ) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode -- us...
as connection: context.configure( connection=connection, target_metadata=target_metadata ) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
CSC-IT-Center-for-Science/pouta-blueprints
migrations/versions/37s5rj356547_.py
Python
mit
611
0.00982
"""empty message Revision ID: 37s5rj356547 Revises: j4d9g3scvf4s Create Date: 2019-02-20 16:45:34.186981 """ # revision identifiers, used by Alembic. revision = '37s5rj356547' down_revision = 'j4d9g3scvf4s' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - ...
### commands auto generated by Alembic - please adjust! ### op.drop_column('users', 'group_quota')
### end Alembic commands ###
deadbok/wp-passwd-reset-vestacp
change-wp-conf-secrets.py
Python
mit
4,552
0.026588
# -*- coding: utf-8 -*- """ Update the secrets in a Wordpress configuration file. MIT License Copyright (c) 2016 Martin Bo Kristensen Grønholdt Permission is her
eby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to ...
luded in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LI...
gnufede/tddgoat
tddgoat/lists/models.py
Python
mit
87
0.022989
from django.db import models
class Item(models.Model): text = models.TextField()
jcu-eresearch/jcu.dc24.ingesterapi
jcudc24ingesterapi/schemas/tests.py
Python
bsd-3-clause
962
0.006237
import unittest from jcudc24ingesterapi.schemas.metadata_schemas import DataEntryMetadataSchema from jcudc24ingesterapi.schemas.data_types import * class TestSchemas(unittest.TestCase): def test_valid_schemas(self): """Test that the schema creation APIs properly validate the schemas as they are con...
ntryMetadataSchema() good_schema.addAttr(Double("attr1")) good_schema.addAttr(String("attr2")) bad_schema = DataEntryMetadataSchema() self.assertRaises(ValueError, bad_schema.addAttr, str) def test_data_types(self): pass class TestDataTypes(unittest.TestCas...
Error, Double, "") self.assertRaises(ValueError, Double, "dfkj dfjk") self.assertRaises(ValueError, Double, "1dfkjdfjk") Double("validname") if __name__ == '__main__': unittest.main()
hatwar/buyback-erpnext
erpnext/setup/page/setup_wizard/setup_wizard.py
Python
agpl-3.0
17,916
0.029917
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json, copy from frappe.utils import cstr, flt, getdate, strip from frappe import _ from frappe.utils.file_manager import save_file from ...
if isinstance(value, basestring): args[key] = strip(value) return args def update_user_name(args): if args.get("email"): ar
gs['name'] = args.get("email") _mute_emails, frappe.flags.mute_emails = frappe.flags.mute_emails, True doc = frappe.get_doc({ "doctype":"User", "email": args.get("email"), "first_name": args.get("first_name"), "last_name": args.get("last_name") }) doc.flags.no_welcome_mail = True doc.insert() f...
christophelec/github3.py
tests/integration/test_notifications.py
Python
bsd-3-clause
1,512
0
"""Integration test for Notifications.""" import github3 from .helper import IntegrationHelper class TestThread(IntegrationHelper): """Integration test for methods on Test class""" def test_subscription(self): """Show that a user can retrieve notifications for repository""" self.token_log
in() cassette_name = self.cassette_name("subscription") with self.recorder.use_cassette(cassette_name): repository = self.gh.repository('sigmavirus24', 'github3.py') threads = list(repository.notifications(all=True)) assert len(threads) > 0 thread = thread...
github3.notifications.Subscription) class TestSubscription(IntegrationHelper): """Integration test for methods on Test class""" def test_set(self): """Show that user can successful set subscription""" self.token_login() cassette_name = self.cassette_name("set") ...
zhengbomo/python_practice
project/Lagou/Downloader.py
Python
mit
2,671
0.001139
#!/usr/bin/python # -*- coding:utf-8 -*- import os import shutil import hashlib import urllib import urllib2 class Downloader(object): def __init__(self): pass @staticmethod def get_html(url, data, folder): file_url = url + data file_url = file_url.encode('UTF-8') file_...
Request(url) try: response = urllib2.urlopen(request, data) return response.read() except Exception, e: print str(e) return None @staticmethod def __get_file_content(url, folder): path = Downloader.__get_file_path(url, folder) if ...
): file_object = open(path) try: return file_object.read() finally: file_object.close() return None @staticmethod def __cache_url(url, html, folder): path = Downloader.__get_file_path(url, folder) output = open(path, 'w...
mutirri/bokeh
bokeh/models/plots.py
Python
bsd-3-clause
15,027
0.001331
""" Models for representing top-level plot objects. """ from __future__ import absolute_import from six import string_types from ..enums import Location from ..mixins import LineProps, TextProps from ..plot_object import PlotObject from ..properties import Bool, Int, String, Color, Enum, Auto, Instance, Either, List...
"seconds since epoch" instead of formatted dates. """) y_mapper_ty
pe = Either(Auto, String, help=""" What kind of mapper to use to convert y-coordina
acq4/acq4
acq4/devices/NiDAQ/resample_test.py
Python
mit
4,804
0.030183
# -*- coding: utf-8 -*- from __future__ import print_function import sys import time import numpy as np from pyqtgraph import PlotWindow from six.moves import zip sys.path.append('
../../util') sys.path.append('../..') from .nidaq import NiDAQ from pyqtgraph.functions import mkPen, mkColor pw = PlotWindow() time.clock() sr = 100000 dur = 2.0 data = np
.zeros(int(sr*dur)) dlen = len(data) xVals = np.linspace(0, dur, dlen) data += np.random.normal(size=dlen) + 20. data[round(dlen*0.102):round(dlen*0.3)] += 20 data[round(dlen*0.3):round(dlen*0.5)] += 30 data[round(dlen*0.4)]+= 1000 data += np.sin(xVals*40677*2.0*np.pi)*4. #data = sin(linspace(0, dur, sr*dur)* linspace...
mindprince/test-infra
experiment/generate_tests.py
Python
apache-2.0
11,228
0.000267
#!/usr/bin/env python # Copyright 2017 The Kubernetes 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
6 fields in job name', self.job_name) image = self.images[fields[3]] k8s_version = self.k8s_versions[fields[4][3:]] test_suite = self.test_suites[fields[5]] # envs are disallowed in node e2e tests. if 'envs' in self.common or 'envs' in image or 'envs' in test_suite: ...
s = [] args.extend(get_args(self.job_name, self.common)) args.extend(get_args(self.job_name, image)) args.extend(get_args(self.job_name, test_suite)) # Generates job config. job_config = self.__get_job_def(args) # Generates prow config. prow_config = self.__get_pr...
studiocoop/maya-coop
scripts/coopReplaceMayaEnvironment.py
Python
unlicense
2,170
0.006912
''' @name: coopReplaceMayaEnvironment.py @repository: https://github.com/studiocoop/maya @version: 1.0 @license: UNLICENCE @author: Santiago Montesdeoca [artineering.io] @summary: replaces the existing Maya.env with a template which has to be in the same directory a...
t maya.cmds as cmds import userPrefs as prefs #find environment directory scriptsDir = os.path.abspath(cmds.int
ernalVar(usd=True)) envDir = os.path.dirname(scriptsDir) #hide unnecessary shelves shelvesDict = prefs.unnecessaryShelvesForAnim #Maya creates all default shelves in prefs only after each has been opened (initialized) for shelf in shelvesDict: try: mel.eval('jumpToNamedShelf("{0}");'.format(shelf)) exc...
tsl143/addons-server
src/olympia/files/tests/test_models.py
Python
bsd-3-clause
56,292
0
# -*- coding: utf-8 -*- import hashlib import json import os import tempfile import zipfile from datetime import datetime from django import forms from django.core.files.storage import default_storage as storage from django.conf import settings from django.test.utils import override_settings import mock import pytest...
f.version.delete() assert storage.exists(f.file_path) finally: if storage.exists(f.file_path): storage.delete
(f.file_path) def test_delete_file_path(self): f = File.objects.get(pk=67442) self.check_delete(f, f.file_path) def test_delete_no_file(self): # test that the file object can be deleted without the file # being present file = File.objects.get(pk=74797) filename ...
sergiocorreia/panflute
setup.py
Python
bsd-3-clause
4,886
0.000614
"""A pythonic alternative to pandocfilters See: https://github.com/sergiocorreia/panflute """ from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: ...
python_requires='>=3.6', # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=[ 'click >=6,<...
yyaml >=3,<7', ], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,pypi] extras_require={ 'dev': [ 'configparser', 'coverage', 'f...
Evlos/rwbypress
app.py
Python
gpl-2.0
726
0.001377
#!/usr/bin/python # -*- coding: utf-8 -*- # RedisPress.alpha # --- # Database: Redis # Framework: Tornado import
sys import raven.contrib.tornado import tornado.httpserver import tornado.ioloop import project.app.application if __name__ == '__main__': if len(sys.argv) == 2: port = sys.argv[1] else: port = 24400 sentry_key = '56b95038ef7849d7bfbfc735d2ee50e1:64c853d4c58947b5a8b663ca7ac2c8b1' app =...
pp.sentry_client = raven.contrib.tornado.AsyncSentryClient( 'http://' + sentry_key + '@lin.eternalelf.com/sentry/7', ) srv = tornado.httpserver.HTTPServer(app) srv.listen(int(port)) tornado.ioloop.IOLoop.instance().start()
forslund/mycroft-core
mycroft/tts/espeak_tts.py
Python
apache-2.0
2,379
0
# Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
one) """
# Create Argument String for Espeak arguments = ['espeak', '-v', self.lang + '+' + self.voice] amplitude = self.config.get('amplitude') if amplitude: arguments.append('-a '+amplitude) gap = self.config.get('gap') if gap: arguments.append('-g '+gap...
nharraud/invenio-jsonschemas
invenio_jsonschemas/errors.py
Python
gpl-2.0
2,330
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
stributed
in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to...
kbrebanov/atlantic-python
atlantic/atlantic.py
Python
mit
549
0.001821
from .utils import Atl
anticBase from .image import AtlanticImage from .plan import AtlanticPlan from .server import AtlanticServer from .sshkey import AtlanticSSHKey class Atlantic(AtlanticBase): def __init__(self, access_key, private_key): AtlanticBase.__init__(self, access_key, private_key) self.image = AtlanticImage(...
key) self.plan = AtlanticPlan(access_key, private_key) self.server = AtlanticServer(access_key, private_key) self.sshkey = AtlanticSSHKey(access_key, private_key)
TAJaroszewski/lma_contrail_monitoring
deployment_scripts/puppet/modules/lma_contrail_monitoring/files/scripts/check-api-contrail-9081.py
Python
apache-2.0
4,630
0.000216
# !/usr/bin/python # # Copyright 2016 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 ...
ugin [verbose]: %s' % (plugin_name, msg)) def payload(): config = ConfigParser.RawConfigParser() config.read(CONF_FILE) API = OSAPI(config) payload = API.check_api(url, "contrail") return payload def payload_callback():
log_verbose('Read callback called') value = payload() # log_verbose( # 'Sending value: %s.%s=%s' % (plugin_name, '-'.join([val.plugin, val.type]), value)) val = collectd.Values( plugin=plugin_name, # metric source plugin_instance=plugin_instance, type=plugin_type, ...
CINPLA/exana
exana/tests/_test_baysian_latency.py
Python
gpl-3.0
3,442
0.003196
import pytest import elephant import neo import quantities as pq import numpy as np def test_baysian(): from exana.stimulus import baysian_latency, generate_salt_trials from exana.misc import concatenate_spiketrains from elephant.spike_train_generation import homogeneous_poisson_process as hpp np.rand...
spiketrain_trials(spike_train=spike_train, epoch=epoch) from elephant.statistics import time_histogram t_start = trials[0].t_start.rescale('s') t_stop = trials[0].t_stop.rescale('s') binsize = (abs(t_start)+abs(t_stop))/float(100) time_hist = time_histogram(trials, binsize, t_start=t_start, ...
np.arange(t_start.magnitude, t_stop.magnitude, binsize.magnitude) count_data = time_hist.magnitude trace = baysian_latency(count_data) return count_data, trace if __name__ == '__main__': import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt count_data, trace = test_...
legordian/ROOTPWA
pyInterface/scripts/convertTreeToEvt.py
Python
gpl-3.0
3,620
0.024862
#!/usr/bin/env python import argparse import os import sys import math import pyRootPwa import pyRootPwa.core def writeParticleToFile (outFile, particleName, particleMomentum): if pyRootPwa.core.particleDataTable.isInTable(particleName): partProperties = pyRootPwa.core.particleDataTable.entry(particleName) char...
ath to the RootPwa input file") parser.add_argument("outputFileName", help="The path to the ASCII evt output file") parser.add_argument("-p", "--particleDataTable", help="The path of particleDataTable file (default: '$ROOTPWA/particleData/particleDataTable.txt')", default='$ROOTPWA/particleData/p...
leDataTable.txt') args = parser.parse_args() printWarn = pyRootPwa.utils.printWarn printErr = pyRootPwa.utils.printErr printSucc = pyRootPwa.utils.printSucc ROOT = pyRootPwa.ROOT pdtPath = os.path.expandvars(args.particleDataTable) if not pyRootPwa.core.particleDataTable.instance.readFile(pdtPath): printErr...
arthurdejong/python-stdnum
stdnum/nl/postcode.py
Python
lgpl-2.1
2,481
0
# postcode.py - functions for handling Dutch postal codes # # Copyright (C) 2013 Arthur de Jong # # This library 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 2.1 of the License, or (...
the correct format. This currently does not check whether the code corr
esponds to a real address.""" number = compact(number) match = _postcode_re.search(number) if not match: raise InvalidFormat() if match.group('pt2') in _postcode_blacklist: raise InvalidComponent() return '%s %s' % (match.group('pt1'), match.group('pt2')) def is_valid(number): ...
psnj/petl
petl/test/io/test_sources.py
Python
mit
3,696
0
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import gzip import bz2 import zipfile from tempfile import NamedTemporaryFile from petl.compat import PY2 from petl.test.helpers import ieq, eq_ import petl as etl from petl.io.sources import MemorySource, PopenSource, ZipSourc...
if not PY2: expect = expect.encode('ascii') eq_
(expect, actual) def test_memorysource_2(): data = 'foo,bar\r\na,1\r\nb,2\r\nc,2\r\n' if not PY2: data = data.encode('ascii') actual = etl.fromcsv(MemorySource(data)) expect = (('foo', 'bar'), ('a', '1'), ('b', '2'), ('c', '2')) ieq(expect, actual...
Nano1994/freenos
site_scons/iso.py
Python
gpl-3.0
2,428
0.01771
# # Copyright (C) 2009 Niek Linnenbank # # This program is free softw
are: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free S
oftware Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License ...
lesina/Hack70
env/bin/player.py
Python
gpl-3.0
2,194
0
#!/home/oleg/Web/Hack70/env/bin/python3 # # The Python Imaging Library # $Id$ # from __future__ import print_function try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys # -------------------------------------------------------------------- # an im...
] del self.im[0] self.image.paste(im) except IndexError: return # end of list else: try: im = self.im im.seek(im.tell() + 1)
self.image.paste(im) except EOFError: return # end of file try: duration = im.info["duration"] except KeyError: duration = 100 self.after(duration, self.next) self.update_idletasks() # -----------------------------------...
KT26/PythonCourse
3. Working with lists/17.py
Python
mit
397
0.012594
# Created by PyCharm Pro Edition # User: Kaushik Talukdar
# Date: 30-03-17 # Time: 11:35 PM # tuple can't be modified but the variable holding a tuple can be assigned new values # basically changing the tuple cars = ["bmw", "rollsroyce", "audi", "ferrari"] print(cars) cars = ["bmw", "koenigsegg", "audi", "ferrari"] p...
rs)
oVirt/ovirt-node-dbus-backend
src/log.py
Python
gpl-3.0
2,690
0.000372
#!/usr/bin/python # -*- coding: utf-8 -*- # # log.py - Copyright (C) 2015 Red Hat, Inc. # Written by Ryan Barry <rbarry@redhat.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; version 2 of...
': 'INFO', 'formatter': 'standard', 'class': 'logging.StreamHandler' } }, 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False } } }) def configure_lo
gging(debug=False): log_config = DEBUG_LOGGING if debug else LOGGING logging.config.dictConfig(log_config) def getLogger(name=None): if not getLogger._logger: if not logging.getLogger().handlers: configure_logging() getLogger._logger = logging.getLogger() fullname = ".".joi...
dkruchinin/spdemo
walkers/bfs.py
Python
bsd-3-clause
1,065
0
from core.cell import CellStatus from walkers.basic import BasicWalker class BFSWalker(BasicWalker): ""
" Breadth first search algorithm. """ def __init__(self, graph, src_cell, dst_cell, use_diags): super(BFSWalker, self).__init__(graph, src_cell, dst_cell, use_diags) self._queue = [self._src_cell] self._finished = False def finished(self): return self._finished def...
._queue) == 0: self._finished = True if self._finished: return while len(self._queue) > 0: cur_cell = self._queue.pop(0) cur_cell.status = CellStatus.Visited if cur_cell == self._dst_cell: self._finished = True ...
inspyration/odoo
addons/crm/report/crm_phonecall_report.py
Python
agpl-3.0
3,856
0.007002
# -*- 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 Affero General Public License as # published by the Free Software...
coolhacks/python-hacks
examples/pyHacks/TwistedChat.py
Python
mit
1,269
0.034673
from twisted.internet.protocol import Factory from twisted.protocols.ba
sic import LineReceiver from twisted.internet import reactor class NonAnonChat(LineReceiver): def __
init__(self, protocols): self.users = {'john':'john', 'adastra':'adastra'} self.userName = None self.userLogged = False self.protocols = protocols def connectionMade(self): self.sendLine('Your Username: ') def connectionLost(self, reason): for protocol in self.protocols: if protocol != self: prot...
andmos/ansible
lib/ansible/module_utils/docker/common.py
Python
gpl-3.0
37,096
0.002237
# # Copyright 2016 Red Hat | Ansible # # 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. # # ...
r(exc)
HAS_DOCKER_PY = False # The next 2 imports ``docker.models`` and ``docker.ssladapter`` are used # to ensure the user does not have both ``docker`` and ``docker-py`` modules # installed, as they utilize the same namespace are are incompatible try: # docker import docker.models # noqa: F401 HAS_DOCKER_M...
Mariaanisimova/pythonintask
INBa/2015/Ionova_A_K/task_2_8.py
Python
apache-2.0
579
0.047887
# Задача 2
. Вариант 8. #Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Лао-Цзы. Не забудьте о том, что автор должен быть упомянут на отдельной строке. # Ionova A. K. #30.04.2016 print("Нельзя обожествлять бесов.\n\t\t\t\t\t\t\t\tЛао-цзы") input("Наж...
TER для выхода.")
ewiseblatt/spinnaker
testing/citest/tests/bake_and_deploy_test.py
Python
apache-2.0
30,181
0.004374
# Copyright 2015 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 applicable law or a...
les to archive: somedir/vim_2:7.4.052-1ubuntu3_amd64.deb # # # PYTHONPATH=$CITEST_ROOT/testing/cites
t \ # python $CITEST_ROOT/testing/citest/tests/bake_and_deploy_test.py \ # --gce_ssh_passphrase_file=$PASSPHRASE_FILE \ # --gce_project=$PROJECT \ # --gce_zone=$ZONE \ # --gce_instance=$INSTANCE \ # --jenkins_master=$JENKINS_MASTER \ # --jenkins_url=$JENKINS_URL \ # --jenkins_auth_path=$...
longyangking/AlphaGomoku
alphagomoku/Config.py
Python
lgpl-2.1
401
0.082294
from enum import Enum # ChessBoard Info ChessBoardHeight = 10 ChessBoardWidth = 10 # Role Info Roles = {'Human':
0,'Computer':1,'Sel
f_A':2,'Self_B':3, 'Eva_base':4, 'Eva_new':5} # Chess Info ChessInfo = {'Human':-1,'Computer':1,'Self_A':1,'Self_B':-1, 'Eva_base':1, 'Eva_new':-1} # Victory Info Victories = {'Human':-1,'Computer':1,"NoOneWin":0,'Self_A':1, 'Self_B':-1, 'Eva_base':1, 'Eva_new':-1}
if1live/wireless-latency-benchmark
benchmark/udp_server.py
Python
mit
877
0.009122
#!/usr/bin/env python #-*- coding: utf-8 -*- import common import SocketServer import sys class UDPEchoHandler(SocketServer.BaseRequestHandler): """ This class works similar to the TCP handler class, except that self.request consists of a pair of data and client socket, and since there is no conne...
t_address) print "{} wrote:".format(self.client_address[0]), data def main():
if not common.validate_server_argv(): return -1 HOST = "0.0.0.0" server = SocketServer.UDPServer((HOST, common.SOCKET_PORT), UDPEchoHandler) server.serve_forever() if __name__ == '__main__': main()
jmread/cerebro
cerebro/DE.py
Python
gpl-3.0
5,119
0.017191
from numpy import * from Mapper import Mapper from kNN import kNN from MLP import MLPbp from functions import sigmoid, linear from RLS import RLS def jump_size(e,grad_e,t): return e * clip(grad_e + 1.,0.,1.) def project(h,w_origin,jump=0.2,N=100): ''' USE THIS ONE FOR MAD_0.py ''' N_i = h.N_i ...
# (the current self.x (set of weights) produced the result 'y' (e.g., error) in the last round) ################################################################################################ if self.burn_in > 0
: # not enough points on map yet self.h.update(self.w,y) self.burn_in = self.burn_in - 1 return project(self.h,zeros(self.w.shape),1.,N=1) yp = self.h.predict(self.w.reshape(1,-1)) delta = (y - yp) y_ = yp + self.learn_rate * delta #print...
kyhau/reko
reko/rekognition.py
Python
mit
4,130
0.001211
import boto3 DEFAULTS = { "region_name": "ap-southeast-2" # Sydney } def status_code(ret): return ret["ResponseMetadata"]["HTTPStatusCode"] class Rekognition(): def __init__(self, profile, region=DEFAULTS["region_name"]): self.profile = profile self.region_name = region self.cl...
rint("Confidence: {}".format(face["Confidence"])) return ret["Faces"] print(status_code(ret)) return [] def create_collection(self, collection_id): try: ret = self.client.create_collection(CollectionId=collection_id) print(ret)
return True except Exception as e: print(e) return False def delete_collection(self, collection_id): try: ret = self.client.delete_collection(CollectionId=collection_id) print(ret) return True except Exception as e: p...
tokibito/django-edamame
example/note/models.py
Python
mit
186
0
from django.db import models class Note(models.Model): title
= models.CharField(max_length=100) text
= models.TextField() created = models.DateTimeField(auto_now_add=True)
DarthMaulware/EquationGroupLeaks
Leak #1 - Equation Group Cyber Weapons Auction - Invitation/EQGRP-Free-File/Firewall/SCRIPTS/fw_wrapper/tunnel.py
Python
unlicense
32,118
0.026807
import bananaglee import tools import shelve import fw_logging import os import sys import cmd import subprocess import shlex import ConfigParser import logging class Tunnel(cmd.Cmd): def __init__(self,sfile,logger): cmd.Cmd.__init__(self) self.prompt = 'Tunnel>>' #shelve file self.sfile = sfile #set u...
Num: attk_int |') self.logger.info(' -------------------------Firewall-------------------------') self.logger.info(' | Iface Num: tgt_int ^')
self.logger.info(' v |') self.logger.info(' Firewall to Target Packet Target to Firewall Packet') self.logger.info(' Source IP : tgt_source Source IP : rtn_tgt_source') ...
Architektor/PySnip
venv/lib/python2.7/site-packages/twisted/trial/itrial.py
Python
gpl-3.0
6,853
0.003502
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Interfaces for Trial. Maintainer: Jonathan Lange """ from __future__ import division, absolute_import import zope.interface as zi from zope.interface import Attribute class ITestCase(zi.Interface): """ The interface that a test ca...
"" def printErrors(): """ Deprecated in Twisted 8.0, use L{done} instead. Present the errors that have occ
urred during the test run. This method will be called after all tests have been run. """ def write(string): """ Deprecated in Twisted 8.0, use L{done} instead. Display a string to the user, without appending a new line. """ def writeln(string): """ ...
googleapis/python-dlp
samples/generated_samples/dlp_v2_generated_dlp_service_list_stored_info_types_sync.py
Python
apache-2.0
1,491
0.000671
# -*- coding: utf-8 -*- # Copyright 2022 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...
for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for ListStoredInfoTypes # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modificati
ons to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-dlp # [START dlp_v2_generated_DlpService_ListStoredInfoTypes_sync] from google.cloud import dlp_v2 def sample_list_stored_info_types(): # Create a client cli...
takara9/watson_chatbot
weather_report/load3_db_weather.py
Python
epl-1.0
1,717
0.00975
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Cloudant のデータベース作成 # # Copyright (C) 2016 International Business Machines Corporation # and others. All Rights Reserved. # ...
cloudant.result import Result, ResultByKey, QueryResult from cloudant.query import Query #import cloudant # Cloudant認証情報の取得 f = open('cloudant_credentia
ls_id.json', 'r') cred = json.load(f) f.close() print cred # データベース名の取得 f = open('database_name.json', 'r') dbn = json.load(f) f.close() print dbn['name'] client = Cloudant(cred['credentials']['username'], cred['credentials']['password'], url=cred['credentials']['url']) # Conne...
Placeware/ThisPlace
thisplace.py
Python
mit
8,967
0.003903
""" thisplace: Human-readable addresses for every 3x3m square on the earth's surface. The simplest way to use this module are the `four_words` and `decode` functions. For more see `WordHasher`. """ import random import geohash def get_words(fname): lines = open(fname) words = [] for word in lines: ...
shorter list with only 4096 words GOOGLE_4096WORDS = get_words("words/google-ngram-list-4096") # current best list for the three word hash WORDNET_LEMMAS = get_words("words/wordnet-list") # Human friendly word list, taken directly from humanhash project # these are the best words but there are not enough of # them so ...
rtist', 'asparagus', 'aspen', 'august', 'autumn', 'avocado', 'bacon', 'bakerloo', 'batman', 'beer', 'berlin', 'beryllium', 'black', 'blossom', 'blue', 'bluebird', 'bravo', 'bulldog', 'burger', 'butter', 'california', 'carbon', 'cardinal', 'carolina', 'carpet', 'cat', 'ceiling', 'charlie'...
HoangNguyenHuy/SocialNetwork
src/SocialNetwork_API/models/timestamped.py
Python
mit
262
0.007634
from django.db import models from django.util
s import timezone class TimeStampedModel(models.Model): created_at = models.DateTimeField(default=timezone.now) updated_at
= models.DateTimeField(default=timezone.now) class Meta: abstract = True
bacher09/xrcon
xrcon/client.py
Python
lgpl-3.0
6,417
0
import socket import time from functools import wraps import six from .utils import ( rcon_nosecure_packet, rcon_secure_time_packet, rcon_secure_challenge_packet, parse_challenge_response, parse_rcon_response, parse_server_addr, parse_status_packet, Player, CHALLENGE_PACKET, CHAL...
= self.RCON_SECURE_TIME: self.soc
k.send(rcon_secure_time_packet(self.password, command)) elif self.secure_rcon == self.RCON_SECURE_CHALLENGE: challenge = self.getchallenge() self.sock.send(rcon_secure_challenge_packet(self.password, challenge, command)) els...
astrofrog/ginga
ginga/gtkw/plugins/Catalogs.py
Python
bsd-3-clause
31,943
0.003131
# # Catalogs.py -- Catalogs plugin for fits viewer # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # from ginga.misc import Bunch, Future from ginga.gtkw import FitsImag...
self.catalog_server_params = None self.tooltips = self.fv.w.tooltips def build_gui(self, container, future=None): vbox1 = gtk.VBox() self.msgFont = pango.FontDescription("Sans 12") tw = gtk.TextView() tw.set_wrap_mode(gtk.WRAP_WORD) tw.set_left_margin(4) t...
ht_margin(4) tw.modify_font(self.msgFont) self.tw = tw fr = gtk.Frame(" Instructions ") fr.set_shadow_type(gtk.SHADOW_ETCHED_OUT) fr.set_label_align(0.1, 0.5) fr.add(tw) vbox1.pack_start(fr, padding=4, fill=True, expand=False) nb = gtk.Notebook()...
KrisCheng/HackerPractice
Python/module/urllibDemo.py
Python
mit
326
0
# !/usr/bin/env python3 # -*- coding: utf-8 -*- from urllib import request # URL抓取 with request.urlopen('https://api.douban.com/v2/book/2129650') as f: data = f.read() print('Status:', f.status, f.reason) for k, v in f.getheaders(): print('%s :
%s' % (k, v)) print(
'Data:', data.decode('utf-8'))
BRiDGEIris/cgs-apps
code/apps/variants/src/variants/serializers.py
Python
apache-2.0
32,788
0.00549
from rest_framework import serializers from variants.models import * from beeswax.design import hql_query from beeswax.server import dbms from beeswax.server.dbms import get_query_server_config from hbase.api import HbaseApi from converters import * from models import * import time import os import json import threadin...
mple_id']) if not 'collection_status' in current_sample: current_samp
le['collection_status'] = '' status = str(current_sample['collection_status']) if not 'sample_type' in current_sample: current_sample['sample_type'] = '' sample_type = str(current_sample['sample_type']) if not 'biological_contaminatio...
ryfeus/lambda-packs
pytorch/source/numpy/core/memmap.py
Python
mit
11,612
0.000775
from __future__ import division, absolute_import, print_function import numpy as np from .numeric import uint8, ndarray, dtype from numpy.compat import ( long, basestring, os_fspath, contextlib_nullcontext, is_pathlib_path ) from numpy.core.overrides import set_module __all__ = ['memmap'] dtypedescr = dtype vali...
Attributes ---------- filename : str or pathlib.Path instance Path to the mapped file. offset : int Offset position in the file. mode : str File mode. Methods ------- flush Flush any changes in memory to file on
disk. When you delete a memmap object, flush is called first to write changes to disk before removing the object. See also -------- lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file. Notes ----- The memmap object can be used anywhere an ndarray is accepted...
anjianshi/flask-restful-extend
flask_restful_extend/reqparse_fixed_type.py
Python
mit
425
0.011765
# -*- coding: utf-8 -*- fr
om datetime import datetime, date import six def fix_number(target_type): return lambda value: None if isinstance(value, (str, six.text_type)) and len(value) == 0 else target_type(value) fixed_datetime = lambda time_str: datetime.strptime(time_str, '%Y-%m-%d
%H:%M:%S') fixed_date = lambda time_str: date.fromtimestamp(time_str) fixed_int = fix_number(int) fixed_float = fix_number(float)
erja-gp/openthread
tools/harness-automation/cases/reed_5_7_2.py
Python
bsd-3-clause
1,872
0.001603
#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
ROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSS...
port HarnessCase class REED_5_7_2(HarnessCase): role = HarnessCase.ROLE_REED case = '5 7 2' golden_devices_required = 16 def on_dialog(self, dialog, title): pass if __name__ == '__main__': unittest.main()
gnuvet/gnuvet
gtable.py
Python
gpl-3.0
37,590
0.004363
# -*- coding: utf-8 -*- """Strict unflexible table constructor: The hand-knitted table for GnuVet. Provides html formatting in cells. First set_headers if required, then append_row and set_alignment, finally adjust rows2contents if appropriate. Setting headers after filling table deletes all table entries. Optionall...
rollArea class Gcell(QLabel): """Table cell.""" clicked = pyqtSignal(object) rightclicked = pyqtSignal(object) # is QPoint selectable = True entry = False data =
None children = 0 def __init__(self, parent=None, txt='', col=None, data=None): super(Gcell, self).__init__(parent) self.setAttribute(55) # Qt.WA_DeleteOnClose # parent normally gtable.table, of that gtable, of that gtable.parent # in case of additional cells (create_cell):...
ecino/compassion-switzerland
mobile_app_switzerland/controllers/__init__.py
Python
agpl-3.0
389
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2019 Compassion CH
(http://www.compassion.ch) # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from . import re
gistration_controller
licongyu95/learning_python
core_python_programming/cap10/cap10.py
Python
unlicense
487
0.01848
#!/usr/bin/env python #encoding=utf-8 import os try: f = file('blah','r') except IOError,e: print 'could not open file:',e def safe_float(obj): try: return float(obj) exce
pt ValueError: pass ccfile = N
one log = file('log.txt','w+') try: ccfile = file('card.txt','r') txns = ccfile.readlines() ccfile.close() except IOError: log.write('no txns this month%s' % os.linesep) finally: log.close() if ccfile: ccfile.close()
MobileCloudNetworking/epcaas
bundle/wsgi/DNSaaSClient.py
Python
apache-2.0
13,958
0.002866
# Copyright 2014 Copyright (c) 2013-2015, OneSource, Portugal. # 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/license...
_data: record data :param token: Token :param kwargs: Priority for the record :return: Status 1 for success, or a description of error """ if record_type in ['A', 'AAAA', 'TXT', 'MX', 'PTR', 'SRV', 'NS', 'CNAME', 'SPF', 'SSHFP', 'NAPTR']: json_record = '' ...
record_name = '' json_record = {'domain_name': domain_name, 'record_name': record_name, 'record_type': record_type, 'data': record_data, 'priority': int(priority)} elif record_type in ['SRV', 'NAPTR']: if 'priority' in k...
ktsaou/netdata
collectors/python.d.plugin/python_modules/pyyaml3/composer.py
Python
gpl-3.0
4,912
0.003664
# SPDX-License-Identifier: MIT __all__ = ['Composer', 'ComposerError'] from .error import MarkedYAMLError from .events import * from .nodes import * class ComposerError(MarkedYAMLError): pass class Composer: def __init__(self): self.anchors = {} def check_node(self): # Drop the STREAM-...
while not self.check_event(SequenceEndEvent): node.value.append(self.compose_node(node, index)) index += 1 end_event = self.get_event() node.end_mark = end_event.end_mark return node def compose_mapping_node(self, anchor): start_event = self.get_event...
'!': tag = self.resolve(MappingNode, None, start_event.implicit) node = MappingNode(tag, [], start_event.start_mark, None, flow_style=start_event.flow_style) if anchor is not None: self.anchors[anchor] = node while not self.check_event(Mapp...
eleme/polaris
polaris/server.py
Python
mit
3,719
0
""" polaris.server ~~~~~~~~~~~~~~ :copyright: (c) 2013 Eleme, http://polaris.eleme.io :license: MIT Polaris app server. """ import hashlib import os.path from flask import Flask as _Flask from werkzeug.datastructures import ImmutableDict from werkzeug.utils import import_string __all__ = ['crea...
me] = import_string(path) app.config["source"] = {} app.config["category"] = {} for name, cfg in app.config["SOURCES"].items(): source = app.config["ext"][cfg["ext"]](**cfg["params"]) app.config["source"][name] = source app.config["category"][name] = source.c
ategory register_jinja(app) return app def register_jinja(app): app._assets = app.config.get('ASSETS', {}) def static_url(filename): if app.testing: return filename if filename in app._assets: return app._assets[filename] filepath = os.path.join(app....
otfried/cs101
code/files/planets4.py
Python
gpl-3.0
213
0.018779
f = open("data/planetsc.txt", "r") earth = 0 for line in f: planet = line.strip().low
er() if planet[0] == "#": continue earth += 1 if planet == "earth": break print "Earth is planet #%d" % eart
h
memorycoin/asm2mmc
asm2mmc/__init__.py
Python
mit
49
0.020408
# -*- coding: utf8 -*- from de
code import decod
e
kyubifire/softlayer-python
tests/CLI/modules/file_tests.py
Python
mit
28,087
0.000392
""" SoftLayer.tests.CLI.modules.file_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import exceptions from SoftLayer import testing import json import mock class FileTests(testing.TestCase): def test_access_list(self): result = ...
'--ip-address-id=192', '--ip-address=192.3.2.1', '--subnet-id=200']) self.assert_no_fail(result) def test_volume_list(self): result = self.run_command(['file', 'volume-list']) self.assert_no_fail(result) ...
'ip_addr': '127.0.0.1', 'storage_type': 'ENDURANCE', 'username': 'user', 'active_transactions': None, 'mount_addr': '127.0.0.1:/TEST', 'rep_partner_count': None }], json.loads(result.output)) @mock.patch...
qilicun/python
python2/diveintopythonzh-cn-5.4b/zh_cn/makerealworddoc.py
Python
gpl-3.0
2,374
0.029486
#coding=gbk """Convert HTML page to Word 97 document This script is used during the build process of "Dive Into Python" (http://diveintopython.org/) to create the downloadable Word 97 version of the book (http://diveintopython.org/diveintopython.doc) Looks for 2 arguments on the command line. The first argument is t...
atch("Word.Application
") try: worddoc = word.Documents.Open(FileName=infile) try: worddoc.TablesOfContents.Add(Range=word.ActiveWindow.Selection.Range, \ RightAlignPageNumbers=1, \ UseHeadingStyles=1, \ UpperHeadingLevel=1, \ LowerHeadingLevel=2, \ IncludePageNumbers=1, \ ...
raultron/ivs_sim
python/5points_gradientdescent.py
Python
mit
5,075
0.040197
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Aug 4 11:52:11 2017 @author: lracuna """ from vision.camera import * from vision.plane import Plane import vision.error_functions as ef import gdescent.hpoints_gradient5 as gd5 from ippe import homo2d ## CREATE A SIMULATED CAMERA cam = Camera() cam.s...
00001 #condition number norm gradient = gd5.create_gradient(metric='condition_number') #gradient = gd5.create_gradient(metric='volker_metric') #gradient = gd5.create_gradient(metric='pnorm_condition_number') objectPoin
ts_des = pl.get_points() alpha=0.2 imagePoints_des = np.array(cam.project(objectPoints_des, False)) objectPoints_list = list() imagePoints_list = list() transfer_error_list = list() condition_number_list = list() normalized_condition_number_list = list() new_objectPoints = objectPoints_des for i in range(1000): obj...
AsgerPetersen/QGIS
python/plugins/processing/algs/qgis/SumLines.py
Python
gpl-2.0
5,242
0.001908
# -*- coding: utf-8 -*- """ *************************************************************************** SumLines.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************************...
T'))) self.addOutput(OutputVector(self.OUTPUT, self.tr('Line length'))) def processAlgorithm(self, progress): lineLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.LINES)) polyLayer = dataobjects.getObjectFromUri(self.getParameterValue(self.POLYGONS)) lengthFieldName...
yLayer.dataProvider() (idxLength, fieldList) = vector.findOrCreateField(polyLayer, polyLayer.pendingFields(), lengthFieldName) (idxCount, fieldList) = vector.findOrCreateField(polyLayer, fieldList, ...
wangybgit/Chameleon
hostapd-OpenWrt/tests/hwsim/test_rfkill.py
Python
apache-2.0
6,236
0.003688
# rfkill tests # Copyright (c) 2014, Jouni Malinen <j@w1.fi> # # This software may be distributed under the terms of the BSD license. # See README for more details. import logging logger = logging.getLogger() import time import hostapd from hostapd import HostapdGlobal import hwsim_utils from wpasupplicant import Wpa...
finally: rfk.unblock() def test_rfkill_autogo(dev, apdev): """rfkill block/unblock for autonomous P2P GO""" rfk0 = get_rfkill(dev[0]) rfk1 = get_rfkill(dev[1]) dev[0].p2p_start_go() dev[1].request("SET p2p_no_group_iface 0") dev[1].p2p_start_go() try: logger.info("rfkill...
ise Exception("Group removal not reported") if "reason=UNAVAILABLE" not in ev: raise Exception("Unexpected group removal reason: " + ev) if "FAIL" not in dev[0].request("P2P_LISTEN 1"): raise Exception("P2P_LISTEN accepted unexpectedly") if "FAIL" not in dev[0].request("P...
tic-ull/defensatfc-proto
tfc_webapps/packages/suds-timestamp/suds/xsd/sxbasic.py
Python
agpl-3.0
31,569
0.00529
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will ...
ry = TypeQuery(qref) q
uery.history = [self] log.debug('%s, resolving: %s\n using:%s', self.id, qref, query) resolved = query.execute(self.schema) if resolved is None: log.debug(self.schema) raise TypeNotFound(qref) if resolved.builtin(): if nobuiltin: result...
midnightradio/gensim
gensim/corpora/indexedcorpus.py
Python
gpl-3.0
6,432
0.002177
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Base Indexed Corpus class.""" import logging import numpy from gensim import interfaces, utils logger = logging.getLogger(__name...
oesn't support indexing!" % serializer.__name__ ) # store offsets persistently, using pickle # we shouldn't have to worry about self.index being a numpy.ndarray as the serializer will return # the offsets that are actually stored on disk - we're not storing self.index in any case, t...
s", serializer.__name__, index_fname) utils.pickle(offsets, index_fname) def __len__(self): """Get the index length. Notes ----- If the corpus is not indexed, also count corpus length and cache this value. Returns ------- int Length of i...
spamalot/quichem
quichem/compilers/display/__init__.py
Python
lgpl-3.0
2,168
0.000461
# This file is part of quichem. # # quichem 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 # (at your option) any later version. # # quichem is distributed in the ho...
'coefficient': fragments.Coefficient(), 'charge': fragments.Charge(), 'state': fragments.State(), 'counter': fragme
nts.Counter(), 'open group': fragments.OpenCloseGroup(), 'close group': fragments.OpenCloseGroup()} self.token_fragments = {tokened_strings[string]: fragment for string, fragment in self.fragments.items()} def compile(self, ast): """Compile a ...
lingui/js-lingui
docs/_ext/linguidocs.py
Python
mit
2,809
0.000712
""" Lingui docs extensions Inspired by Django Docs https://github.com/django/django/blob/main/docs/_ext/djangodocs.py """ from docutils import nodes from sphinx import addnodes from sphinx.domains.std import Cmdoption from sphinx.locale import _ from sphinx.util.docfields import TypedField class jsxmacro(nodes.Inli...
onent', rolename='component', indextemplate="pair: %s; component", r
ef_nodeclass=react_component, objname='Component', doc_field_types=[ TypedField('props', label=_('Props'), names=('prop',), typerolename='component', typenames=('proptype', 'type')), ] ) app.add_node(react_c...
uwgraphics/Ubiqu-Ity
Ity/celery_tasks.py
Python
bsd-2-clause
12,033
0.001828
# coding=utf-8 from __future__ import absolute_import import os import sys sys.path.append(os.path.join( os.path.dirname(os.path.basename(__file__)), ".." )) sys.path.append(os.path.dirname(__file__)) from collections import OrderedDict import codecs import json import hashlib # Ity Imports import Ity from ...
to the Ity.Utilities.Corpus init() method: `pat
h`, `output_path`, etc. :return: """ corpus = Corpus(**corpus_kwargs) # Take the tokenizer, taggers, formatters, and batch_formatters arguments # and initialize whatever modules we need. tokenizer = init_tokenizer(tokenizer) taggers = [ init_tagger(tagger) for tagger in tagge...
hyperized/ansible
lib/ansible/modules/cloud/azure/azure_rm_galleryimageversion.py
Python
gpl-3.0
16,660
0.002221
#!/usr/bin/python # # Copyright (c) 2019 Zim Kalinowski, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
inition in which the Image Version is to
be created. required: true type: str name: description: - >- The name of the gallery Image Version to be created. Needs to follow semantic version name pattern: The allowed characters are digit and period. Digits must be within the range of a 32-bit integer. Format: <...
exploreshaifali/portal
systers_portal/community/forms.py
Python
gpl-2.0
3,969
0
from django import forms from django.contrib.auth.models import Group from common.forms import ModelFormWithHelper from common.helpers import SubmitCancelFormHelper from community.constants import COMMUNITY_ADMIN from community.models import Community, CommunityPage from community.utils import get_groups from users.mo...
ave(self): """Update the groups of which the user is member of""" group_pks = [int(pk) for pk in self.cleaned_data['groups']] for member_group in self.member_groups: if member_group.pk not in group_pks: self.user.leave_group(member_group) for pk in
group_pks: group = Group.objects.get(pk=pk) if not self.user.is_group_member(group.name): self.user.join_group(group)
ama-jharrison/agdc
agdc/tests/test_new_ingest.py
Python
apache-2.0
1,629
0.003683
#!/usr/bin/env python #=============================================================================== # Copyright 2015 Geoscience Australia # # 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 #...
ataset.the_suite()) suite_list.append(test_landsat_bandstack.the_suite()) suite_list.append(test_dataset_record.the_suite()) # suite_list.append(test_tile_record.the_suite(fast=True)) # suite_list.append(test_tile_contests.the_suite(fast=True)) return unittest.TestSuite(suite_list) # # Run unit test...
'__main__': unittest.TextTestRunner(verbosity=2).run(the_suite())
walty8/trac
trac/attachment.py
Python
bsd-3-clause
47,208
0.00053
# -*- coding: utf-8 -*- # # Copyright (C) 2003-2009 Edgewall Software # Copyright (C) 2003-2005 Jonas Borgström <jonas@edgewall.com> # Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of th...
last_slash = path.rfind('/') if last_slash == -1: parent_id, filename = path, '' else: parent_id, filename = path[:last_slash], path[last_slash + 1:] parent = parent_realm(id=parent_id) if not resource_exists(self.env, parent): ...
_("Parent resource %(parent)s doesn't exist", parent=get_resource_name(self.env, parent))) # Link the attachment page to parent resource parent_name = get_resource_name(self.env, parent) parent_url = get_resource_url(self.env, parent, req.href) add_link(req, 'up'...
AaronM04/coding-practice
pe_49/main.py
Python
gpl-3.0
1,693
0.004135
#!/usr/bin/python ## globals primes_set = set() primes_list = [] def is_prime(n): limit = int(round(sqrt(n))) i = 2 while True: if i > limit: return True if n % i == 0: return False def find_prime_permutations(n): "find the prime permutations including n" ...
f k == i or k == j: continue for l in xrange(4): if l == i or l == j or l == k: continue s2 = s[i] + s[j] + s[k] + s[l] n2 = int(s2) if n2 in primes_s
et: perm_set.add(n2) return perm_set def find_arith_seq(_set): l = sorted(list(_set)) if len(l) < 3: return None for i in xrange(1, len(l)-1): # not either end for j in xrange(0, i): n = l[i]*2 - l[j] if n in _set and n != l[i] and n !...
eldie1984/Scripts
pg/scripts mios/python/ly/errores_cc_ant.py
Python
gpl-2.0
9,892
0.024876
#!/usr/bin/env python #-*- coding:utf-8 -*- # # # Autor: Diego Gasch # # Empresa: CMD s.a # # Fecha de generación: 2013-07-03 # # Fecha de ultima modificación: 2013-07-03 # # Ultima modificación: ([quien] + [que]) dgasch creacion del script # # # Objetivo: Enviar un reporte con los errores de envio desde BAC a Liberty...
conexion a la base de LY") except Exception: logging.error("Nos se pudo realizar la conexion a la base de LY") exit(2) cursor_cc.execute("""select de.id from deals d, deal_externals de where d.is_end_user=1 and end_date<'2013-11-01' and de.created > '2013-08-01' and de.deal_id=d.id ...
etchall(): lista.append(str(registro[0])) str_lista = (',').join(lista) #print str_lista #logging.debug("la lista de ID's es: \n %s" % str_lista) #print "la lista de ID's es: \n %s" % str_lista cursor.execute("""select efl.C_Invoice_ID,efl.id_lote,epl.C_AllocationHdr_ID,epl.id_pago from cce_cargo cc left j...
gems-uff/labsys
migrations/versions/2018-09-19_09:49:05__251447ab2060.py
Python
mit
680
0.001471
"""empty message Revision ID: 251447ab2060 Revises: 53ac0b4e8891 Create Date: 2018-09-19 09:49:05.552597 """ from alembic import op import sqlalchemy as sa # revision id
entifiers, used by Alembic. revision = '251447ab2060' down_revision = '53ac0b4e8891' branch_labels = None depends_on = None def upg
rade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('transactions', sa.Column('lot_number', sa.String(length=64), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('transactio...
DeniSix/SublimeNodeStacktrace
node_debugger/commands/attach_debugger.py
Python
mit
3,423
0.025124
import sublime, sublime_plugin from .. import config from .. import globals from .. import logger from ..debug_client import DebugClient from ..clicks import Clicks log = logger.get('cmd_attach_debugger') def lookup_ref(id, refs): for ref in refs: if id == ref['handle']: return ref return None def open_file(...
_callback(data): log('exception', data) body = data['body'] window = sublime.active_window() if config.get('show_stack
trace'): globals.exception = body['exception']['text'] window.set_layout(config.get('debug_layout')) # Create new buffer for stacktrace globals.st = st = window.new_file() st.set_scratch(True) st.set_name(config.get('stacktrace_name')) st.settings().set('word_wrap', False) st.settings().set('syntax', 'P...
mbr/tinyrpc
tests/test_protocols.py
Python
mit
1,721
0.002905
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tinyrpc.protocols.jsonrpc import JSONRPCProtocol from tinyrpc import RPCErrorResponse @pytest.fixture(params=['jsonrpc']) def protocol(request): if 'jsonrpc': return JSONRPCProtocol() raise RuntimeError('Bad protocol name in test case...
ssert isinstance(err_rep.serialize(), bytes) def test_one_way(protocol): req = protocol.create_request('foo', None, {'a': 'b'}, True) assert req.respond(None) == None def test_raises_on_args_and_kwargs(protocol): with pytest.raises(Exception): protocol.create_request('foo', ['arg1', 'arg2'], {'...
_args(protocol): protocol.create_request('foo') def test_creates_error_response(protocol): req = protocol.create_request('foo', ['bar']) err_rep = req.error_respond(Exception('foo')) assert hasattr(err_rep, 'error') def test_parses_error_response(protocol): req = protocol.create_request('fo...