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
j-herrera/icarus
icarus_site/ISStrace/urls.py
Python
gpl-2.0
279
0.014337
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.map, name='map'), url(r'^mapSim', views.mapSim, name='mapSim'), url(r
'^api/getPos', views.getPos, name='getPos'), url(r'^api/getProjAndPos', views.getProjAndPos, name='getP
rojAndPos'), ]
scholer/nascent
nascent/graph_sim_nx/debug.py
Python
agpl-3.0
1,923
0.00832
# -*- coding: utf-8 -*- ## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com ## ## This file is part of Nascent. ## ## Nasc
ent 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, or (at your option) any later version. ## ## This program is distributed in the hope that it will be...
TY 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/>. #pylint: disable=C0103,C0111,W0613 from __future__ im...
chickonice/AutonomousFlight
simulation/simulation_ws/build/rotors_simulator/rotors_joy_interface/catkin_generated/pkg.develspace.context.pc.py
Python
gpl-3.0
669
0.004484
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/spacecat/AutonomousFlight/simulation/simulation_ws/src/rotors_simulator/rotors_joy_interface/include".split(';') if "/home/spacecat/AutonomousFlight/simulation/simulation_ws/src/rotors_simulator/...
T_NAME = "rotors_joy_interface" PROJECT_SPACE_DIR = "/home/spac
ecat/AutonomousFlight/simulation/simulation_ws/devel" PROJECT_VERSION = "1.0.0"
stephenlienharrell/roster-dns-management
roster-config-manager/setup.py
Python
bsd-3-clause
3,685
0.005156
#!/usr/bin/env python # Copyright (c) 2009, Purdue University # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # l...
GE. """Setup script for roster config manager.""" __copyright__ = 'Copyright (C) 2009, Purdue University' __license__ = 'BSD' __version__ = '#TRUNK#' try: from setuptools import setup except ImportError: from distutils.core import setup current_version = __version__ if( __version__.startswith('#') ): current...
Roster', long_description='Roster is DNS management software for use with Bind 9. ' 'Roster is written in Python and uses a MySQL database ' 'with an XML-RPC front-end. It contains a set of ' 'command line user tools that connect to the XML-RPC ...
thonkify/thonkify
src/lib/telegram/contrib/botan.py
Python
mit
1,522
0.001971
import logging from future.moves.urllib.parse import quote from future.moves.urllib.error import HTTPError, URLError from future.moves.urllib.request import urlopen, Request logging.getLogger(__name__).addHandler(logging.NullHandler()) class Botan(object): """This class helps to send incoming events to your bot...
id={uid}&name={name}&src=python-telegram-bot' def __init__(self, token): self.token = token self.logger = logging.getLogger(__name__) def track(self, message, event_name='event'): try: uid = message.chat_id except AttributeError: self.logger.warn('No cha...
, uid=str(uid), name=quote(event_name)) request = Request( url, data=data.encode(), headers={'Content-Type': 'application/json'}) urlopen(request) return True except HTTPError as error: self.logger.warn('Botan track error ' + str(error.code) + ':' ...
liuzhenyang14/Meeting
codex/baseerror.py
Python
gpl-3.0
629
0.00159
# -*- coding: utf-8 -*- # __author__ = "Epsirom" class BaseError(Exception): def __init__(self, code, msg): super(BaseError, self).__init__(msg) self.code = code self.msg = msg def __repr__(self): return '[ERRCODE=%d] %s' % (self.code, self.msg) class InputError(BaseErro...
or): def __init__(self, msg): super(LogicError, self).__init__(2, msg) class ValidateError(BaseError): def __init__(self, msg): sup
er(ValidateError, self).__init__(3, msg)
pesaply/sarafu
smpp.py
Python
mit
447
0.067114
%bash/bin/python import sys
import os import socket host = localhost port = 2275 } s == socket.socket { s.connect('$port' , '$host' ); def curlhttp ('http k
eepalive == 300 tps '): curlhttp ('http keepalive == 300 tps '): elif curlhttp ('https keepalive == <300 ('https keepalive == <300 print "Not Valid Request " ) ) #require Connection From Socket #require verison control
moagstar/python-uncompyle6
test/simple_source/expression/03_map.py
Python
mit
361
0
# Bug in 2.7 base64.py _b32alphabet = {
0: 'A', 9: 'J', 18: 'S', 27: '3', 1: 'B', 10: 'K', 19: 'T', 28: '4', 2: 'C', 11: 'L', 20: 'U', 29: '5', 3: 'D', 12: 'M', 21: 'V', 30: '6', 4: 'E', 13: 'N', 22: 'W', 31: '7', 5: 'F', 1
4: 'O', 23: 'X', 6: 'G', 15: 'P', 24: 'Y', 7: 'H', 16: 'Q', 25: 'Z', 8: 'I', 17: 'R', 26: '2', }
tsabata/PyDNB
pydnb/dnb.py
Python
mit
6,733
0.001782
import time import numpy as np import pandas as pd class DNB: """ Class representing Dynamic Naive Bayes. """ def __init__(self, debug=False): self.states_prior = None self.states_list = None self.features = None self.A = None self.B = None self.debug ...
port scipy.stats as st if features is None: self.features = dict.fromkeys(list(df.columns.values), st.norm) else: self.features = features for f, dist in self.
features.items(): params = dist.fit(df[f]) arg = params[:-2] loc = params[-2] scale = params[-1] if self.debug: print("Distribution: %s, args: %s, loc: %s, scale: %s" % (str(dist), str(arg), str(loc), str(scale))) self.B[(state, f)]...
lebabouin/CouchPotatoServer-develop
couchpotato/core/notifications/synoindex/main.py
Python
gpl-3.0
1,104
0.009964
from couchpotato.core.event import addEvent f
rom couchpotato.core.logger import CPLog from couchpotato.core.notifications.base import Notification import os import subprocess log = CPLog(__name__) class Synoindex(Notification): index_path = '/usr/syno/bin/synoindex' def __init__(self): super(Synoindex, self).__init__() a
ddEvent('renamer.after', self.addToLibrary) def addToLibrary(self, message = None, group = None): if self.isDisabled(): return if not group: group = {} command = [self.index_path, '-A', group.get('destination_dir')] log.info('Executing synoindex command: %s ', command) try:...
jangsutsr/tower-cli
tests/test_resources_job_template.py
Python
apache-2.0
8,499
0
# Copyright 2015, Ansible, Inc. # Alan Rominger <arominger@ansible.com> # # 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 ...
'job_type': 'run'}, method='PATC
H') self.res.modify(name='bar', extra_vars=["a: 5"]) self.assertEqual(t.requests[0].method, 'GET') self.assertEqual(t.requests[1].method, 'PATCH') self.assertEqual(len(t.requests), 2) def test_associate_label(self): """Establish that the associate method make...
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/modules/bl_i18n_utils/bl_extract_messages.py
Python
gpl-3.0
39,687
0.004009
# ***** BEGIN GPL LICENSE BLOCK ***** # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed ...
eived a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ***** END GPL LICENSE BLOCK ***** # <pep8 compliant> # Populate a
template file (POT format currently) from Blender RNA/py/C data. # XXX: This script is meant to be used from inside Blender! # You should not directly use this script, rather use update_msg.py! import collections import copy import datetime import os import re import sys # XXX Relative import does not work here...
ctsit/research-subject-mapper
rsm/utils/redcap_transactions.py
Python
bsd-3-clause
3,580
0.004469
import logging import httplib from urllib import urlencode import os import sys from lxml import etree # This addresses the issues with relative paths file_dir = os.path.dirname(os.path.realpath(__file__)) goal_dir = os.path.join(file_dir, "../../") proj_root = os.path.abspath(goal_dir)+'/' sys.path.insert(0, proj_root...
tplib.HTTPSConnection(properties['host']) else: redcap_connection = httplib.HTTPConnection(properties['host']) redcap_connection.request('POST', properties['path'], urlencode(params), {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'}) ...
eturned = response_buffer.read() logger.info('***********RESPONSE RECEIVED FROM REDCAP***********') redcap_connection.close() return returned
TaliesinSkye/evennia
wintersoasis-master/web/urls.py
Python
bsd-3-clause
3,320
0.005422
# # File that determines what each URL points to. This uses _Python_ regular # expressions, not Perl's. # # See: # http://diveintopython.org/regular_expressions/street_addresses.html#re.matching.2.3 # from django.conf import settings from django.conf.urls.defaults import * from django.contrib import admin from django....
$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), (r'^wiki/([^/]+/)*wiki/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT + '/wiki/'}) ) # PM Extension if (forum_set
tings.PM_SUPPORT): urlpatterns += patterns('', (r'^mail/', include('mail_urls')), ) if (settings.DEBUG): urlpatterns += patterns('', (r'^%s(?P<path>.*)$' % settings.MEDIA_URL.lstrip('/'), 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), )
our-city-app/oca-backend
src/solutions/common/job/module_statistics.py
Python
apache-2.0
6,018
0.001329
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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...
1 else: combined[module] += 1 return combined def combiner(key, new_values, previously_combined_values): # t
ype: (str, list[list[str]], list[dict[str, int]]) -> GeneratorType if DEBUG: logging.debug('combiner %s new_values: %s', key, new_values) logging.debug('combiner %s previously_combined_values: %s', key, previously_combined_values) combined = _combine(new_values, previously_combined_values) i...
irskep/clubsandwich
clubsandwich/blt/nice_terminal.py
Python
mit
3,101
0.000322
""" .. py:attribute:: terminal Exactly like ``bearlibterminal.terminal``, but for any function that takes arguments ``x, y``, ``dx, dy``, or ``x, y, width, height``, you can instead pass a single argument of type :py:class:`Point` (for the first two) or :py:class:`Rect` (for the last). This makes ...
[0], Point): return _terminal.print(args[0].x, args[0].y, *args[1:]) else: return _terminal.print(*args) def printf(self, *args): if isinstance(args[0], Point): return _terminal.printf(args[0].x, args[0].y, *args[1:]) else: return _terminal.pr...
gs): if isinstance(args[0], Point): return _terminal.put(args[0].x, args[0].y, *args[1:]) else: return _terminal.put(*args) def pick(self, *args): if isinstance(args[0], Point): return _terminal.pick(args[0].x, args[0].y, *args[1:]) else: ...
kennedyshead/home-assistant
tests/components/threshold/test_binary_sensor.py
Python
apache-2.0
11,914
0.001007
"""The test for the threshold sensor platform.""" from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, TEMP_CELSIUS from homeassistant.setup import async_setup_component async def test_sensor_upper(hass): """Test if source is above threshold.""" config = { "binary_sensor": { ...
{ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS} ) await hass.async_block_till_done() state = hass.states.get("binary_sensor.threshold") assert state.attributes.get("entity_id") == "sensor.test_monitored" assert state.attributes.get("sensor_value") == 16 assert state.attributes.get("position") == "in_...
) assert state.attributes.get("hysteresis") == float( config["binary_sensor"]["hysteresis"] ) assert state.attributes.get("type") == "range" assert state.state == "on" hass.states.async_set("sensor.test_monitored", 8) await hass.async_block_till_done() state = hass.states.get("bin...
fgolemo/SocWeb-Reddit-Crawler
usersToFile.py
Python
mit
195
0.005128
import cPickle as pickle import
os users = list(pickle.load(file('users.pickle'))) pickle.dump
(users, open("users.list.pickle.tmp", "wb")) os.rename("users.list.pickle.tmp", "users.list.pickle")
mrknow/filmkodi
script.mrknow.urlresolver/lib/urlresolver9/plugins/ol_gmu.py
Python
apache-2.0
2,291
0.003492
# -*- coding: utf-8 -*- """ openload.io urlresolver plugin Copyright (C) 2015 tknorris 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 v...
ic License fo
r more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import re import urllib2 from HTMLParser import HTMLParser from urlresolver9 import common from urlresolver9.resolver import ResolverError net = common.Net() de...
tdfischer/organizer
events/models.py
Python
agpl-3.0
1,124
0.003559
# -*-
coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone from crm.models import Person from geocodable.models import LocationAlias import uuid class Event(models.Model): name = models.CharField(max_length=200) timestamp = models.DateTimeField() ...
ls.ManyToManyField(Person, related_name='events', blank=True) uid = models.CharField(max_length=200, blank=True) location = models.ForeignKey(LocationAlias, default=None, blank=True, null=True) instance_id = models.CharField(max_length=200, blank=True) @property def geo(self): r...
bundgus/python-playground
matplotlib-playground/examples/animation/double_pendulum_animated.py
Python
mit
2,354
0.001274
# Double pendulum formula translated from the C code at # http://www.physics.usyd.edu.au/~wheat/dpend_html/solve_dpend.c from numpy import sin, cos import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate import matplotlib.animation as animation G = 9.8 # acceleration due to gravity, in...
_text def animate(i): thisx = [0, x1[i], x2[i]] thisy = [0, y1[i], y2[i]] line.set_data(thisx, thisy) time_text.set_text(time_template % (i
*dt)) return line, time_text ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)), interval=25, blit=True, init_func=init) #ani.save('double_pendulum.mp4', fps=15) plt.show()
manojngb/Crazyfly_simple_lift
src/cfclient/ui/widgets/ai.py
Python
gpl-2.0
8,202
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
0.08), pos, "{}".format(i / 10)) elif i % 50 == 0: length = 0.2 * w else: length = 0.1 * w qp.drawLine((w / 2) - (length / 2), pos, (w / 2) + (length / 2), pos) ...
qp.setPen(pen) qp.drawLine(0, h / 2, w, h / 2) # Draw Hover vs Target qp.setWorldMatrixEnabled(False) pen = QtGui.QPen(QtGui.QColor(255, 255, 255), 2, QtCore.Qt.SolidLine) qp.setBrush(QtGui.QColor(255, 255, 255)) qp.setPen(pen) fh = ...
ychaim/FPGA-Litecoin-Miner
experimental/LX150-EIGHT-B/ltcminer-test-dynclock.py
Python
gpl-3.0
8,949
0.027154
#!/usr/bin/env python # by teknohog # Python wrapper for Xilinx Serial Miner # Host/user configuration is NOT USED in ltctestmode.py ... # host = "localhost" # Stratum Proxy alternative # user = "username.1" # Your worker goes here # password = "password" # Worker password, NOT your account password # http_port = "8...
lf.line = self.infile.readline() if (len(self.line) != 257): print "EOF on test data" # Or its an error, but let's not be worrysome # quit() # Except it doesn't ... self.go = False # Terminating threads is
a bit tricksy break self.nonce_tested = self.nonce_tested + 1 self.block = self.line.rstrip() # Hard-code a diff=32 target for test work # Replace MSB 16 bits of target with clock (NB its reversed) self.target = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff07" + self.dyncloc...
antoinecarme/pyaf
tests/artificial/transf_RelativeDifference/trend_PolyTrend/cycle_30/ar_/test_artificial_32_RelativeDifference_PolyTrend_30__20.py
Python
bsd-3-clause
273
0.084249
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype =
"PolyTrend", cycle_length = 30, transform = "RelativeDifference", sigma = 0.
0, exog_count = 20, ar_order = 0);
kylazhang/virt-test
libguestfs/tests/guestmount.py
Python
gpl-2.0
2,277
0
import logging import os from autotest.client.shared import error, utils from virttest import data_dir, utils_test def umount_fs(mountpoint): if os.path.ismount(mountpoint): result = utils.run("umount -l %s" % mountpoint, ignore_status=True) if result.exit_status: logging.debug("Umount...
t = utils_test.libguestfs.VirtTools(vm, params) if special_mount: # Get root filesystem before test params['libvirt_domain'] = params.
get("main_vm") params['gf_inspector'] = True gf = utils_test.libguestfs.GuestfishTools(params) roots, rootfs = gf.get_root() gf.close_session() if roots is False: raise error.TestError("Can not get root filesystem " "in guestfish befo...
johnbachman/indra
indra/pipeline/pipeline.py
Python
bsd-2-clause
16,636
0.00006
import json import logging import inspect from .decorators import pipeline_functions, register_pipeline from indra.statements import get_statement_by_name, Statement logger = logging.getLogger(__name__) class AssemblyPipeline(): """An assembly pipeline that runs the specified steps on a given set of statem...
1) Provide a JSON file containing the steps, then use the classmethod `from_json_file`, and run it with the `run` method on a list of statements. This option allows storing pipeline versions in a separate file and reproducing the same results. All functions referenced in the JSON file have to be regist...
path(__file__)) >>> filename = os.path.abspath( ... os.path.join(path_this, '..', 'tests', 'pipeline_test.json')) >>> ap = AssemblyPipeline.from_json_file(filename) >>> assembled_stmts = ap.run(stmts) 2) Initialize a pipeline with a list of steps and run it with the `run` method on a list of st...
missionpinball/mpf
mpf/modes/carousel/code/carousel.py
Python
mit
6,517
0.003376
"""Mode which allows the player to select another mode to run.""" from mpf.core.utility_functions import Util from mpf.core.mode import Mode class Carousel(Mode): """Mode which allows the player to select another mode to run.""" __slots__ = ["_all_items", "_items", "_select_item_events", "_next_item_events...
e.events.post("{}_items_empty".
format(self.name)) '''event (carousel_name)_items_empty desc: A carousel's items are all conditional and all evaluated false. If this event is posted, the carousel mode will not be started. ''' self.stop() return super().mo...
Dev-Cloud-Platform/Dev-Cloud
dev_cloud/cc1/src/cm/utils/threads/image.py
Python
apache-2.0
8,639
0.002084
# -*- coding: utf-8 -*- # @COPYRIGHT_begin # # Copyright [2010-2014] Institute of Nuclear Physics PAN, Krakow, Poland # # License
d under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
ng permissions and # limitations under the License. # # @COPYRIGHT_end """@package src.cm.utils.threads.image """ import subprocess import threading import urllib2 from common.states import image_states from common.hardware import disk_format_commands, disk_filesystems_reversed import os from cm.utils import log i...
whiteear/newrelic-plugin-agent
newrelic_plugin_agent/publisher/__init__.py
Python
bsd-3-clause
918
0.005447
# # Copyright 2015 chinaskycloud.com.cn # # Author: Chunyang Liu
<liucy@chinaskycloud.com> # # 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, s...
anguage governing permissions and limitations # under the License. """ Publish plugins are responsible for publish fetched metrics into different monitoring system. """ plugins = { 'file':'newrelic_plugin_agent.publisher.file.FilePublisher', 'ceilometer':'newrelic_plugin_agent.publisher.ceilometer.Ceilomete...
danielElopez/PI-Connector-for-UFL-Samples
COMPLETE_SOLUTIONS/North American General Bike Feed/putJSONdata_SF_Bikes_service.py
Python
apache-2.0
3,727
0.003756
""" putJSONdata.py Copyright 2016 OSIsoft, 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 a...
sue with requesting the data:") print(e) sys.exit(0) data = getData(args.restexternal) # remove verify=False if the certificate used is a trusted one response = s.put(args.restufl, data=data, verify=False) # If instead of using the put reques
t, you need to use the post request # use the function as listed below # response = s.post(args.resturl + '/post', data=data, verify=False) if response.status_code != 200: print("Sending data to the UFL connect failed due to error {0} {1}".format(response.status_code, response.reason)) else: print('The data wa...
tanglu-org/tdak
daklib/fstransactions.py
Python
gpl-2.0
6,500
0.001385
# Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This pr...
bool @param link: try hardlinking, falling back to copying @type symlink: bool @param symlink: create a symlink instead of copying @type mode: int @param mode: permissions to change C{destination} to """ if isinstance
(mode, str) or isinstance(mode, unicode): mode = int(mode, 8) self.actions.append(_FilesystemCopyAction(source, destination, link=link, symlink=symlink, mode=mode)) def move(self, source, destination, mode=None): """move C{source} to C{destination} @type source: str @...
twerp/django-admin-flexselect-py3
flex_project/urls.py
Python
cc0-1.0
816
0
"""flex_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.sit
e.urls)), url(r'^flexselect/', include('flexselect.urls')), ]
information-machine/information-machine-api-python
InformationMachineAPILib/Models/GetNutrientsWrapper.py
Python
mit
2,942
0.003059
# -*- coding: utf-8 -*- """ InformationMachineAPILib.Models.GetNutrientsWrapper """ from InformationMachineAPILib.APIHelper import APIHelper from InformationMachineAPILib.Models.NutrientInfo import NutrientInfo from InformationMachineAPILib.Models.MetaBase import MetaBase class GetNutrientsWrapper(object): ...
for key in kwargs: # Only add arguments that are actually part of this object if key in replace_names: setattr(self, replace
_names[key], kwargs[key]) # Other objects also need to be initialised properly if "result" in kwargs: # Parameter is an array, so we need to iterate through it self.result = list() for item in kwargs["result"]: self.result.appe...
Juniper/ceilometer
ceilometer/event/storage/impl_elasticsearch.py
Python
apache-2.0
11,518
0
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
self.get_trait_types(record['_type'])) for key in record['_source']['traits'].keys(): value = record['_source']['traits'][key] for t_map in trait_mappings[record['_type']]: if t_map['name'] == key: d...
trait_list.append(models.Trait( name=key, dtype=dtype, value=models.Trait.convert_value(dtype, value))) gen_ts = timeutils.normalize_time(timeutils.parse_isotime( record['_source']['timestamp'])) yield m...
chippey/gaffer
python/GafferImageTest/ObjectToImageTest.py
Python
bsd-3-clause
3,067
0.025106
########################################################################## # # Copyright (c) 2013-2015, 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: # # * Redi...
GafferImageTest.ImageTestCase ) : fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" ) negFileName = os.path.expandvars( "$GAFFER_ROOT/python/Gaff
erImageTest/images/checkerWithNegativeDataWindow.200x150.exr" ) def test( self ) : i = IECore.Reader.create( self.fileName ).read() n = GafferImage.ObjectToImage() n["object"].setValue( i ) self.assertEqual( n["out"].image(), i ) def testImageWithANegativeDataWindow( self ) : i = IECore.Reader.create(...
RobLoach/lutris
lutris/runners/__init__.py
Python
gpl-3.0
1,920
0
"""Generic runner functions.""" # from lutris.util.log import logger __all__ = ( # Native "linux", "steam", "browser", "web", # Microsoft based "wine", "winesteam", "dosbox", # Multi-system "mame", "mess", "mednafen", "scummvm", "residualvm", "libretro", "ags", # Commdore "fsuae", "vice...
ef __init__(self, message): self.message = message class RunnerInstallationError(Exception): def __init__(self, message): self.message = message class NonInstallableRunnerError(Exce
ption): def __init__(self, message): self.message = message def get_runner_module(runner_name): if runner_name not in __all__: raise InvalidRunner("Invalid runner name '%s'" % runner_name) return __import__('lutris.runners.%s' % runner_name, globals(), locals(), [runn...
yewsiang/botmother
gunicorn.py
Python
agpl-3.0
417
0.002398
import os
def numCPUs(): if not hasattr(os, "sysconf"): raise RuntimeError("No sysconf detected.") return os.sysconf("SC_NPROCESSORS_ONLN") bind = "0.0.0.0:8000" # workers = numCPUs() * 2 + 1 workers = 1 backlog = 2048 worker_class = "sync" # worker_class = "gevent" debug = True # daemon = True # errorlog = 'gun...
'
alex/changes
migrations/versions/2b8459f1e2d6_initial_schema.py
Python
apache-2.0
9,758
0.016807
"""Initial schema Revision ID: 2b
8459f1e2d6 Revi
ses: None Create Date: 2013-10-22 14:31:32.654367 """ # revision identifiers, used by Alembic. revision = '2b8459f1e2d6' down_revision = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): ### commands auto generated by Alembic - please adjust! ### o...
JanFan/py-aho-corasick
py_aho_corasick/__init__.py
Python
mit
114
0
# -*- coding: utf-8 -*- __author__ = """JanFan""" __email__ = 'guangyizhang.jan@gmail.com' __version__ = '0.1.
0'
smashwilson/deconst-preparer-sphinx
deconstrst/builder.py
Python
apache-2.0
1,067
0
# -*- coding: utf-8 -*- from sphinx.builders.html import JSONHTMLBuilder from sphinx.util import jsonimpl class DeconstJSONImpl: """ Enhance the default JSON encoder by adding additional keys. """ def dump(self, obj, fp, *args, **kwargs): self._enhance(obj) return jsonimpl.dump(obj, ...
turn jsonimpl.loads(*args, **kwargs) def _enhance(self, obj): """ Add additional properties to "obj" to get them into the JSON. """ obj["hello"] = "Sup" class DeconstJSONBuilder(JSONHTMLBuilder): """ Custom Sphinx builder that generates Deconst-compatible JSON documents. ...
l() name = 'deconst' out_suffix = '.json' def init(self): JSONHTMLBuilder.init(self)
tdargent/TCXfilestodata
readTCXFiles.py
Python
mit
784
0.026786
# -*- coding: utf-8 -*- import os,tcxparser cd = os.path.dirname(os.path.abspath(__file__)) #use to browse tcx files at the correct location file_list=os.listdir(os.getcwd()) f=open("result.txt","a") f.write("date (ISO UTC Format)"+'\t'+"Distance [m]"+'\t'+"
Duration [s]"+'\n') for a in
file_list: if a == "result.txt": print() #Quick and dirty... elif a== "readTCXFiles.py": print() #Quick and dirty... else: tcx=tcxparser.TCXParser(cd+'/'+a) #see https://github.com/vkurup/python-tcxparser/ for details if tcx.activity_type == 'biking' : #To sel...
BenjaminSchubert/py_github_update_checker
setup.py
Python
mit
995
0
#!/usr/bin/python3 # -*- Coding : UTF-8 -*- from os import path import github_update_checker from setuptools import setup, find_packages file_path = path.abspath(path
.dirname(__file__)) with open(path.join(file_path, "README.md"), encoding="UTF-8") as f: long_description = f.read() setup( name="github_update_checker", version=github_update_checker.__version__, description="A simple update checker for github in python", long_description=long_description, ur...
ert@gmail.com", license="MIT", classifiers=[ 'Development Status :: 5 - Stable', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :...
Yubico/yubiadmin
yubiadmin/util/app.py
Python
bsd-2-clause
7,953
0.000251
# Copyright (c) 2013 Yubico AB # 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 # notice, this list of conditi...
y: if success_msg: alerts = [{'type': 'success', 'title': success_msg}] for form in filter(lambda x: hasattr(x, 'save'), forms): form.save() except Exception as e: alerts = [{'type': 'error', 'tit...
'Invalid data!'}] return render(template, target=request.path, fieldsets=forms, alerts=alerts, **kwargs) ITEM_RANGE = re.compile('(\d+)-(\d+)') class CollectionApp(App): base_url = '' caption = 'Items' item_name = 'Items' columns = [] template = 'table' scripts...
michaelbrooks/django-twitter-stream
twitter_stream/migrations/0002_auto__add_index_tweet_analyzed_by__add_index_tweet_created_at.py
Python
mit
6,130
0.007341
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding index on 'Tweet', fields ['analyzed_by'] db.create_index(u'twitt...
'None', 'max_length': '75', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'twitter_stream.filterterm': { 'Meta': {'object_name': 'FilterTerm'},...
ooleanField', [], {'default': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'term': ('django.db.models.fields.CharField', [], {'max_length': '250'}) }, u'twitter_stream.streamprocess': { 'Meta': {'object_name': 'StreamProcess'}, ...
dunkhong/grr
grr/client/grr_response_client/client_actions/file_finder_utils/subactions.py
Python
apache-2.0
4,871
0.006159
#!/usr/bin/env python """Implementation of client-side file-finder subactions.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import abc from future.utils import with_metaclass from grr_response_client import client_utils from grr_response_client imp...
A parent flow action that spawned the subaction. opts: A `FileFinderStatActionOptions` instance. """ def __init__(self, flow, opts): super(StatAction, self).__init__(flow) self.opts = opts def Execute(self, filepath, result): stat_cache = self.
flow.stat_cache stat = stat_cache.Get(filepath, follow_symlink=self.opts.resolve_links) result.stat_entry = client_utils.StatEntryFromStatPathSpec( stat, ext_attrs=self.opts.collect_ext_attrs) class HashAction(Action): """Implementation of the hash subaction. This subaction returns results of va...
NetApp/cinder
cinder/volume/drivers/vmware/datastore.py
Python
apache-2.0
12,036
0
# Copyright (c) 2014 VMware, 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...
e_result.objects: for obj_content in retrieve_result.objects: props = self._get_object_properties(obj_content) if ('host' in props and hasattr(props['host'], 'DatastoreHostMount')): props['host'] = props['host']....
self._session.invoke_api(vim_util, 'continue_retrieval', self._session.vim, retrieve_result) return datastores def _get_host_properties(self,...
AlxMar/conduction-cylinder
genpics.py
Python
gpl-3.0
2,141
0.01915
### Generating picture frames to a "pic" folder #from pylab import * import numpy as np from time import sleep import matplotlib matplotlib.use("Agg") from matplotlib import rc matplotlib.rcParams['text.usetex'] = True matplotlib.rcParams['text.latex.unicode'] = True import matplotlib.pyplot as plt #matplotlib.use("A...
plt.getp(color_bar.ax.axes, 'xticklabels') plt.setp(cbytick_obj, color = 'white') #cax = ax.pcolormesh(theta,r, T[i,:,0,:]) for i in range(len(time)): #Color bar txt = ax.text(0.9*np.pi,3., r'$t = ' + str(time[i]) + r'$', color='white', fontsize=16) #Plottingi cax.set_array(T[i,:-1,:-1].ravel()) ...
) #fig.clear()
FirstDraftGIS/firstdraft
projfd/appfd/models/base.py
Python
apache-2.0
940
0.006383
#-*- coding: utf-8 -*- from django.contrib.gis.db.models import DateTimeField, Model class Base(Model): created = DateTimeField(auto_now_add=True, null=True) modified = DateTimeField(auto_now=True, null=True) class Meta: abstract = True def __str__(self
): try: for propname in ["name", "key", "token", "text"]: if hasattr(self, propname): text = getattr(self, propname).encode("utf-8")
if len(text) > 20: return text[:20] + "..." else: return text else: return str(self.id) except: return str(self.id) def update(self, d): save = False for k,v in d.i...
GoogleCloudPlatform/datacatalog-connectors
google-datacatalog-connectors-commons/src/google/datacatalog_connectors/commons/monitoring/__init__.py
Python
apache-2.0
744
0
#!/usr/bin/python # # 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 ag...
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 .metrics_processor import MetricsProcessor from .monitoring_facade import MonitoringFacade __all__ = ('Monitori
ngFacade', 'MetricsProcessor')
RaJiska/Warband-PW-Punishments-Manager
scripts/process_map_icons.py
Python
gpl-3.0
796
0.020101
import process_operations as po
import module_map_icons def process_entry(processor, txt_file, entry, index): entry_len = len(entry) output_list = ["%s %d %s %f %d " % (entry[0], entry[1], entry[2], entry[3], processor.process_id(entry[4], "snd"))] triggers = [] if entry_len >= 8: output_list.append("%f %f %f " % entry[5:8]) if entry...
put_list.extend(processor.process_triggers(triggers, entry[0])) output_list.append("\r\n\r\n") txt_file.write("".join(output_list)) export = po.make_export(data=module_map_icons.map_icons, data_name="map_icons", tag="icon", header_format="map_icons_file version 1\r\n%d\r\n", process_entry=process_entry)
bqbn/addons-server
src/olympia/lib/safe_xml.py
Python
bsd-3-clause
774
0.002584
""" Monkey
patch and defuse all stdlib xml packages and lxml. """ import sys patched_modules = ( 'lxml', 'ElementTree', 'minidom', 'pulldom', 'sax', 'expatbuilder', 'expatreader', 'xmlrpc', ) if any(module in sys.modules for module in patched_modules): existing_modules = [(module, module in...
dules) ) from defusedxml import defuse_stdlib # noqa defuse_stdlib() import lxml # noqa import lxml.etree # noqa from xml.sax.handler import ( # noqa feature_external_ges, feature_external_pes, ) from olympia.lib import safe_lxml_etree # noqa lxml.etree = safe_lxml_etree
qedsoftware/commcare-hq
corehq/pillows/groups_to_user.py
Python
bsd-3-clause
4,115
0.002916
from collections import namedtuple from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed from corehq.apps.change_feed.document_types import GROUP from corehq.apps.groups.models import Group from corehq.elastic import stream_es_query, get_es_new, ES_META from corehq.pillows.mappings.user_mapping import USER_...
'all_docs/by_doc_type', view_kwargs={ 'startkey': ['Group'], 'endkey': ['Group', {}],
'include_docs': True, } ), )
opennode/nodeconductor-openstack
setup.py
Python
mit
1,602
0.001873
#!/usr/bin/env python from setuptools import setup, find_packages tests_requires = [ 'ddt>=1.0.0' ] dev_requires = [ 'Sphinx==1.2.2', ] install_requires = [ 'pbr!=2.1.0', 'Babel!=2.4.0,>=2.3.4', 'cmd2<0.9.0', # TODO: Drop restriction after Waldur is migrated to Python 3. 'iptools>=0.6.1', ...
{ 'dev': dev_requ
ires, 'tests': tests_requires, }, entry_points={ 'waldur_extensions': ( 'openstack = waldur_openstack.openstack.extension:OpenStackExtension', 'openstack_tenant = waldur_openstack.openstack_tenant.extension:OpenStackTenantExtension', ), }, include_package_...
JPWKU/unix-agent
src/dcm/agent/tests/unit/test_cloudmetadata.py
Python
apache-2.0
9,676
0
# # Copyright (C) 2014 Dell, 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 wri...
e(self): self.assertRaises(exceptions.AgentNotImplementedException, self.cm_obj.get_cloud_type) def test_env_injected
_id_no_env(self): tmp_dir = tempfile.mkdtemp() try: self.conf.get_secure_dir.return_value = tmp_dir injected_id = self.cm_obj.get_injected_id() self.assertIsNone(injected_id) finally: shutil.rmtree(tmp_dir) def test_env_injected_id_env(self): ...
kvesteri/postgresql-audit
postgresql_audit/flask.py
Python
bsd-2-clause
2,063
0
from __future__ import absolute_import from contextlib import contextmanager from copy import copy from flask import g, request from flask.globals import _app_ctx_stack, _request_ctx_stack from .base import VersioningManager as BaseVersioningManager class VersioningManager(BaseVersioningManager): _actor_cls = ...
or_id'] = self.default_actor_id return values @property def default_actor_id(self): from flask_login import current_user # Return None if we are outside of request context. if not context_available():
return try: return current_user.id except AttributeError: return @property def default_client_addr(self): # Return None if we are outside of request context. if not context_available(): return return request.remote_addr or None ...
joergsimon/gesture-analysis
visualise/Stem.py
Python
apache-2.0
664
0.004518
from pylab import * def stem_user(user, channel_list, start_index, stop_index): data = user.windowData for channel in channel_list: stem_pandas_column(data, channel, start_index, stop_index) def stem_pandas_column(datafra
me, columname, start_index, stop_index): column = dataframe[columname] stem_channel(column.values, start_index, stop_index) def stem_channel(channel, start_index, stop_index): values = channel[start_index:stop_index] markerline, stemlines, baseline = stem(range(start_index,stop_index), values, '-.')
setp(markerline, 'markerfacecolor', 'b') setp(baseline, 'color','r', 'linewidth', 2) show()
lowRISC/opentitan
util/reggen/gen_rtl.py
Python
apache-2.0
5,763
0
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 """Generate SystemVerilog designs from IpBlock object""" import logging as log import os from typing import Dict, Optional, Tuple from mako import exceptions # type: igno...
e) -> Register: '''Get a Register representing an entry in the RegBase''' if isinstance(reg, Register): return reg else: assert isinstance(reg, MultiRegister) return reg.reg def get_iface_tx_type(block: IpBlock, iface_name: Optional[str], ...
: x2x = 'hw2reg' if hw2reg else 'reg2hw' pfx = get_type_name_pfx(block, iface_name) return '_'.join([pfx, x2x, 't']) def get_reg_tx_type(block: IpBlock, reg: RegBase, hw2reg: bool) -> str: '''Get the name of the hw2reg or reg2hw type for reg''' if isinstance(reg, Register): r0 = reg ...
DeanSherwin/django-dynamic-scraper
dynamic_scraper/management/commands/check_last_checker_deletes.py
Python
bsd-3-clause
3,890
0.007969
#Stage 2 Update (Python 3) from __future__ import print_function from __future__ import unicode_literals from builtins import str import datetime from optparse import make_option from django.conf import settings from django.core.mail import mail_admins from django.core.management import CommandError from django.core.ma...
h_next_alert = options['with_next_alert'] if with_next_alert: scrapers = Scraper.objects.filter(next_last_checker_delete_alert__lte=datetime.datetime.now()) print("{num} scraper(s) with future next alert timestamp found in DB...\n".format(num=len(scrapers))) els...
} scraper(s) found in DB...\n".format(num=len(scrapers))) for s in scrapers: if not (only_active and s.status != 'A'): td = s.get_last_checker_delete_alert_period_timedelta() if td: period = s.last_checker_delete_alert_period ...
chemlab/chemlab
chemlab/core/serialization.py
Python
gpl-3.0
2,379
0.003363
from __future__ import division, print_function import json from collections import Iterable, OrderedDict, namedtuple import numpy as np from six import string_types def isnamedtuple(obj): """Heuristic check if an object is a namedtuple.""" return isinstance(obj, tuple) \ and hasattr(obj, "_field...
"fields": list(data._fields), "values": [serialize(getattr(data, f)) for f in data._fields]}} if isinstance(data, dict): if all(isinstance(k, str) for k in data): return {k: serialize(v) for k, v in data.items()} return {"py/dict": [[serialize(k), serialize(v)] for ...
return {"py/set": [serialize(val) for val in data]} if isinstance(data, np.ndarray): return {"py/numpy.ndarray": { "values": data.tolist(), "dtype": str(data.dtype)}} raise TypeError("Type %s not data-serializable" % type(data)) def restore(dct): if "py/dict" in dct: ...
michelp/xodb
xodb/xaql.py
Python
mit
1,060
0.001887
import pyparsing """ The query language that won't die. Syntax: Typical search engine query language, terms with boolean operators and parenthesized grouping: (term AND (term OR term OR ...) AND NOT term ...) In it's simplest case, xaql searches for a list of terms: term term term ... ...
tions: Functions provide features that take query input from the user and do some transformation on the query itself. Functions begin with a star, then a name, then a pair of parenthesis that contain the query input. The syntax of the input is up to the function: $xp(...) -- Pass the input strin
g directly into the Xapian query parser. $rel(...) $now Prefix Modifiers: This are pre-prefixes that transform the following term. published-before:now """
cychenyin/sfproxy
py/timeutils.py
Python
apache-2.0
1,010
0.02521
# coding: utf-8 import time, datetime # 接收的参数可以为:1. 时间戳字符串 2. datetime, 3. None def unixtime_fromtimestamp(dt = None): if dt and isinstance(dt, datetime.datetime) : return int(time.mktime(dt.timetuple())) elif dt and isinstance(dt, basestring) : return int(time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M...
time.localtime(value if value else unixtime_fromtimestamp())) def timestamp_fromunixtime2(value=None, format=None): return time.strftime(format if format else '%Y%m
%d_%H%M%S' , time.localtime(value if value else unixtime_fromtimestamp())) if __name__ == "__main__": # print unixtime_fromtimestamp() print unixtime_fromtimestamp(datetime.datetime.today())
zdomjus60/astrometry
vsop87c/neptune.py
Python
cc0-1.0
232,946
0.003778
import math class Neptune: """ NEPTUNE - VSOP87 Series Version C HELIOCENTRIC DYNAMICAL ECLIPTIC AND EQUINOX OF THE DATE Rectangular (X,Y,Z) Coordinates in AU (Astronomical Units) Series Validity Span: 4000 BC < Date < 8000 AD Theoretical accuracy over span: +-1 arc sec ...
* self.t) X0 += 0.00000398091 * math.cos(5.50783691510 + 6.3484646555 * self.t)
X0 += 0.00000384065 * math.cos(4.72632236146 + 44.96913526031 * self.t) X0 += 0.00000395583 * math.cos(5.05527677390 + 108.70503356371 * self.t) X0 += 0.00000327446 * math.cos(
tomkentpayne/knitify
source/knitify.py
Python
gpl-2.0
676
0.008889
''' Generate a pdf knittinf pattern + chart from a bitmap image ''' __author__ = 'Thomas Payne' __email__ = 'tomkentpayne@hotmail.com' __copyrig
ht__ = 'Copyright © 2015 Th
omas Payne' __licence__ = 'GPL v2' from argparse import ArgumentParser from pattern import Pattern def parse_sys_args(): ''' Parse arguments for bitmap path ''' parser = ArgumentParser(description='Generate knitting pattern from a bitmap image') parser.add_argument('bitmap' ,action='store') return par...
adafruit/Adafruit_Legolas
Adafruit_Legolas/commands/__init__.py
Python
mit
1,864
0.002682
# Commands submodule definition. # # Import all python files in the directory to simplify adding commands. # Just drop a new command .py file in the directory and it will be picked up # automatically. # # Author: Tony DiCola # # The MIT License (MIT) # # Copyright (c) 2015 Adafruit Industries # # Permission is hereby ...
E OR OTHER DEALINGS IN THE # SOFTWARE. import os # Import all python files in the commands directory by setting them to the __all__ # global which tells python the modules to load. Grabs a list of all files in # the directory and filters down to just the names (without .py extensions) of # python files that don't st...
wer().endswith('.py'), os.listdir(__path__[0])))
shyamalschandra/scikit-learn
sklearn/linear_model/_bayes.py
Python
bsd-3-clause
26,416
0.000492
""" Various bayesian regression """ # Authors: V. Michel, F. Pedregosa, A. Gramfort # License: BSD 3 clause from math import log import numpy as np from scipy import linalg from ._base import LinearModel, _rescale_data from ..base import RegressorMixin from ._base import _deprecate_normalize from ..utils.extmath imp...
and thus has no associated variance. If set to False, no intercept will be used in calculations (i.e. data is expected to be centered). normalize : bool, default=False This parameter is ignored when ``fit_intercept`` is set to False. If True, the regressors X will be normalized b...
ocessing.StandardScaler` before calling ``fit`` on an estimator with ``normalize=False``. .. deprecated:: 1.0 ``normalize`` was deprecated in version 1.0 and will be removed in 1.2. copy_X : bool, default=True If True, X will be copied; else, it may be overwritten. ...
stonebig/bokeh
bokeh/colors/named.py
Python
bsd-3-clause
13,025
0.015432
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
edColor("lightgreen", 144, 238, 144) lightgrey = NamedColor("lightgrey", 211, 211, 211) lightpink
= NamedColor("lightpink", 255, 182, 193) lightsalmon = NamedColor("lightsalmon", 255, 160, 122) lightseagreen = NamedColor("lightseagreen", 32, 178, 170) lightskyblue = NamedColor("lightskyblue", 135, 206, 250) lightslategray = NamedCol...
nidhididi/CloudBot
plugins/attacks.py
Python
gpl-3.0
3,577
0.00643
import codecs import json import os import random import asyncio import re from cloudbot import hook from cloudbot.util import textgen @hook.on_start() def load_attacks(bot): """ :type bot: cloudbot.bot.CloudBot """ global larts, insults, flirts, kills, slaps, moms with codecs.open(os.path.join(...
:type nick: str """ phrase = get_attack_string(text, conn, nick, notice, flirts, message) if phrase is not None: message(phrase) @asyncio.
coroutine @hook.command() def kill(text, conn, nick, notice, action, message): """<user> - kills <user> :type text: str :type conn: cloudbot.client.Client :type nick: str """ phrase = get_attack_string(text, conn, nick, notice, kills, message) if phrase is not None: action(phra...
rvanlaar/tactic-client
test/pipeline_test.py
Python
epl-1.0
3,879
0.006961
#!/usr/bin/python ########################################################### # # Copyright (c) 2008, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way wi...
': 'Acme', 'city': 'Toronto', 'context': 'whatever' } # use client api from tact
ic_client_lib import TacticServerStub server = TacticServerStub() interpreter = PipelineInterpreter(my.pipeline_xml) interpreter.set_server(server) interpreter.set_package(package) interpreter.execute() # introspect the interpreter to see if everything ran well ...
OVERLOADROBOTICA/OVERLOADROBOTICA.github.io
mail/formspree-master/formspree/users/helpers.py
Python
mit
231
0.008658
from werkzeug.secur
ity import generate_password_hash, check_password_hash def hash_pwd(password): return generate_password_hash(passw
ord) def check_password(hashed, password): return check_password_hash(hashed, password)
maphy-psd/python-webuntis
tests/utils/test_remote.py
Python
bsd-3-clause
1,228
0
import webuntis import mock from webuntis.utils.third_party import json from .. import WebUntisTestCase, BytesIO class BasicUsage(WebUntisTestCase): def test_parse_result(self): x = webuntis.utils.remote._parse_result a = {'id': 2} b = {'id': 3} self.assertRaisesRegex(webuntis.err...
b = {'id': 2, 'result': 'YESSIR'} assert x(a, b) == 'YESSIR' def test_parse_error_code(self): x = webuntis.utils.remote._parse_error_code a = b = {} self.assertRaisesRegex(webuntis.errors.RemoteError, 'no information', x, a, b) b = {'...
ld', x, a, b) for code, exc in webuntis.utils.remote._errorcodes.items(): self.assertRaises(exc, x, a, { 'error': {'code': code, 'message': 'hello'} })
DanialLiu/SkiaWin32Port
third_party/externals/gyp/pylib/gyp/generator/ninja.py
Python
bsd-3-clause
74,180
0.006794
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import hashlib import multiprocessing import os.path import re import signal import subprocess import sys import gyp import gyp.common import gyp.msvs_...
acters with = in preprocesor definitions for # some reason. Octal-enco
de to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) class Target: """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates...
cnewcome/sos
sos/plugins/zfs.py
Python
gpl-2.0
1,124
0
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but...
s-linux',) def setup(self): self.add_cmd_output([ "zfs get all", "zfs list -t all -o space", "zpool list", "zpool status -x" ]) # vim: set et ts=4 sw=
4 :
dimagi/commcare-android
images/dpi_manager.py
Python
apache-2.0
4,399
0.000227
import os from PIL import Image import numpy from utils import ensure_dir DRAWABLE = 'drawable' class ImageTypeException(Exception): pass class Density(object): LDPI = 'ldpi' MDPI = 'mdpi' HDPI = 'hdpi' XHDPI = 'xhdpi' XXHDPI = 'xxhdpi' XXXHDPI = 'xxxhdpi' RATIOS = { LDPI: ...
and-the-halo-effect premult = numpy.fromstring(src_img.tobytes(), dtype=numpy.uint8) alphaLayer = premult[3::4] / 255.0 premult[::4] *= alphaLayer premult[1::4] *= alphaLayer
premult[2::4] *= alphaLayer src_img = Image.frombytes("RGBA", src_img.size, premult.tobytes()) # save original image to drawables default_dir = os.path.join(self.target_folder, DRAWABLE) ensure_dir(default_dir) default_path = os.path.join(default_dir, self.spec.filename) ...
strawlab/pyopy
pyopy/hctsa/hctsa_data.py
Python
bsd-3-clause
540
0
# coding=u
tf-8 """HCTSA test time series.""" import os.path as op import numpy as np from pyopy.hctsa.hctsa_config import HCTSA_TESTTS_DIR def hctsa_sine(): return np.loadtxt(op.join(HCTSA_TESTTS_DIR, 'SY_sine.dat')) def hctsa_noise(): return np.loadtxt(op.join(HCTSA_TESTTS_DIR, 'SY_noise.dat')) def hctsa_noisysinu...
tsa_noisysinusoid), )
vjpai/grpc
tools/run_tests/sanity/check_port_platform.py
Python
apache-2.0
2,915
0.000686
#!/usr/bin/env python3 # Copyright 2017 gRPC 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.apach
e.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limita...
(os.path.join(os.path.dirname(sys.argv[0]), '../../..')) def check_port_platform_inclusion(directory_root): bad_files = [] for root, dirs, files in os.walk(directory_root): for filename in files: path = os.path.join(root, filename) if os.path.splitext(path)[1] not in ['.c', '.c...
sublee/lets
lets/alarm.py
Python
bsd-3-clause
3,197
0.000313
# -*- coding: utf-8 -*- """ lets.alarm ~~~~~~~~~~ An event which is awoken up based on time. :copyright: (c) 2013-2018 by Heungsub Lee :license: BSD, see LICENSE for more details. """ import operator import time as time_ from gevent import get_hub, Timeout from gevent.event import Event __all__ = [...
return self.event.ready() def wait(self, timeout=None): """Waits until the awaking time. It returns the time.""" if self.event.wait(timeout): return self.time def get(self, block=True, timeout=None): """Waits
until and gets the awaking time and the value.""" if not block and not self.ready(): raise Timeout if self.event.wait(timeout): return self.time, self.value raise Timeout(timeout) def clear(self): """Discards the schedule for awaking.""" self.event.c...
pblottiere/QGIS
tests/src/python/test_qgsdefaultvalue.py
Python
gpl-2.0
1,300
0
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsDefaultValue. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ ...
rtEqual(value.a
pplyOnUpdate(), True) if __name__ == '__main__': unittest.main()
icyflame/batman
scripts/noreferences.py
Python
mit
25,133
0.000331
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script adds a missing references section to pages. It goes over multiple pages, searches for pages where <references /> is missing although a <ref> tag is present, and in that case adds a new references section. These command line parameters can be used to specify w...
e': [ u'ראו גם', u'לקריאה נוספת', u'קישורים חיצוניים', u'הערות שוליים', ], 'hsb': [ u'Nóžki', ], 'hu': [ u'Külső hivatkozások', u'Lásd még', ], 'it': [ u'Bibliografia', u'Voci correlate', u'Altri progetti', u...
references u'외부 링크', u'외부링크', u'바깥 고리', u'바깥고리', u'바깥 링크', u'바깥링크' u'외부 고리', u'외부고리' ], 'lt': [ # no explicit policy on where to put the references u'Nuorodos' ], 'nl': [ # no explicit policy on where to pu...
kshedstrom/pyroms
examples/cobalt-preproc/Clim_bio/make_clim_file_bio_addons.py
Python
bsd-3-clause
4,460
0.01009
import subprocess import os import sys import commands import numpy as np import pyroms import pyroms_toolbox from remap_bio_woa import remap_bio_woa from remap_bio_glodap import remap_bio_glodap data_dir_woa = '/archive/u1/uaf/kate/COBALT/' data_dir_glodap = '/archive/u1/uaf/kate/COBALT/' dst_dir='./' src_grd = py...
'frame':mm} remap_bio_woa(mydict, src_grd, dst_grd, dst_dir=dst_dir) out_file = dst
_dir + dst_grd.name + '_clim_bio_' + list_tracer_update_woa[ktr] + '.nc' command = ('ncks', '-a', '-A', out_file, clim_file) subprocess.check_call(command) os.remove(out_file) #--------- GLODAP ------------------------------- id_tracer_update_glodap = [0,3] list_tracer_update_glodap = [] tracer...
jiivan/python-oauth2
oauth2/__init__.py
Python
mit
25,600
0.003984
""" The MIT License Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel 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 ...
else: self.verifier = generate_verifier() def get_callback_url(self): if self.callback and self.verifier: # Append the oauth_verifier. parts = urlparse.urlparse(self.callback) scheme, netloc, path, params, query, fragment = parts[:6] if query...
else: query = 'oauth_verifier=%s' % self.verifier return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) return self.callback def to_string(self): """Returns this token as a plain string, suitable for storage. Th...
dokipen/trac
tracopt/perm/authz_policy.py
Python
bsd-3-clause
8,731
0.002978
# -*- coding: utf-8 -*- # # Copyright (C) 2007-2009 Edgewall Software # Copyright (C) 2007 Alec Thomas <alec@swapoff.org> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.ed...
ent: parent = flatten(parent) else: parent = [] return parent + ['%s:%s@%s' % (resource.realm or '*', resource.id or '*', resource.version or '*')] return '/'.join(flatte...
esource_key, username): # TODO: Handle permission negation in sections. eg. "if in this # ticket, remove TICKET_MODIFY" valid_users = ['*', 'anonymous'] if username and username != 'anonymous': valid_users = ['*', 'authenticated', username] for resource_section in [a ...
v-legoff/croissant
croissant/output/__init__.py
Python
bsd-3-clause
1,636
0
# Copyright (c) 2013 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and th...
RVICES; 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 # POSSIBILITY OF SUCH DAMAGE. """Package containing the different outputs. Each output type ...
kwailamchan/programming-languages
python/django/elf/elf/src/event/forms.py
Python
mit
332
0.006024
from django import forms from event.models import Event class EventForm(forms.ModelForm): class Meta: model = Event fields = [ 'date', 'starttime', 'endtime', 'event', 'location', 'organization',
'speakers', 'rating', 'feedback'
]
lkarsten/pyobd
network_codes.py
Python
gpl-2.0
18,096
0.066589
ucodes = { "U0001" : "High Speed CAN Communication Bus" , "U0002" : "High Speed CAN Communication Bus (Performance)" , "U0003" : "High Speed CAN Communication Bus (Open)" , "U0004" : "High Speed CAN Communication Bus (Low)" , "U0005" : "High Speed CAN Communication Bus (High)" , "U0006" : "High Speed ...
unication Bus (High)" , "U0024" : "Low Speed CAN Communication Bus (Open)" , "U0025" : "Low Speed CAN Communication Bus (Low)" , "U0026" : "Low Speed CAN Communication Bu
s (High)" , "U0027" : "Low Speed CAN Communication Bus (shorted to Bus)" , "U0028" : "Vehicle Communication Bus A" , "U0029" : "Vehicle Communication Bus A (Performance)" , "U0030" : "Vehicle Communication Bus A (Open)" , "U0031" : "Vehicle Communication Bus A (Low)" , "U0032" : "Vehicle Communication Bus A...
tlevine/vlermv
vlermv/__init__.py
Python
agpl-3.0
144
0
from ._f
s import Vlermv from ._s3 import S3Vlermv from . import serializers, transformers # For backwards compatibility cache = Vlermv
.memoize
FrankNagel/qlc
src/webapp/quanthistling/quanthistling/lib/base.py
Python
gpl-3.0
1,177
0.004248
"""The base Controller API Provides the BaseController class for subclassing. """ from pylons.controllers import WSGIController from pylons.templating import render_mako as render from quanthistling.model.meta import Session #from quanthistling.lib.helpers import History from pylons import request, response, s
ession, tmpl_context as c, url class BaseController(WSGIController): def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ...
ssion.remove() # def __after__(self, action): # if 'history' in session: # c.history = session['history'] # print "History in session" # else: # c.history = History(20) # # # if hasattr(c, 'heading'): # c.history.add(c.heading, url...
babykick/gain
tests/test_parser.py
Python
gpl-3.0
757
0.002642
from gain import Css, Item, Parser, Xpath def test_parse(): html = '<title class="username">tom</title><div class="karma">15</div>' class User(Item): username = Xpath('//title') karma = Css('.karma') parser = Parser(html, User) us
er = parser.parse_item(html) assert user.results == { 'username': 'tom', 'karma': '15' } def test_parse_urls(): html = ('<a href="item?id=14447885">64comments</a>' '<a href="item?id=14447886">64comments</a>') class User(Item): username = Xpath('//title') ka...
qsize() == 2
NIASC/VirusMeta
seq_corret_module/seg_trim.py
Python
gpl-3.0
963
0.030114
import os import sys from Bio import SeqIO with open(sys.argv[1], "rU") as handle, open(sys.argv[2], "r") as segments, open(sys.argv[3],"w") as out_handle: """ This function takes fasta file as first argument. As second argument it takes tab delimited file containing queryid and start and end po...
QI_pos_dict: if record.id == QI: out_handle.write(">%s\n%s\n" % (record.id,record.seq
[ int(QI_pos_dict[QI][0]) : int(QI_pos_dict[QI][1])] ))
imbolc/aiohttp-login
aiohttp_login/decorators.py
Python
isc
1,959
0
from functools import wraps from aiohttp.abc import AbstractView from aiohttp.web import HTTPForbidden, json_response, StreamResponse try: import ujson as json except ImportError: import json from .cfg import cfg from .utils import url_for, redirect, get_cur_user def _get_request(args): # Supports class...
andler) async def decorator(*args): request = _get_request(args) if not request[c
fg.REQUEST_USER_KEY]: return json_response({'error': 'Access denied'}, status=403) response = await handler(*args) if not isinstance(response, StreamResponse): response = json_response(response, dumps=json.dumps) return response return decorator def admin_required(h...
GALabs/StaticAid
static_aid/DataExtractor_Adlib.py
Python
mit
27,394
0.00522
from datetime import datetime from json import load, dump import logging from logging import INFO from os import listdir, makedirs, remove from os.path import join, exists import requests import shelve from static_aid import config from static_aid.DataExtractor import DataExtractor, bytesLabel def makeDir(dirPath): ...
self.cacheFilename('trees')) for category in self.objectCaches: cache = self.objectCaches[category] for adlibKey in cache: data = cache[adlibKey] # link re
cords together by type if category == 'objects': self.addRefToLinkedAgents(data, category) self.createTreeNode(tree, data, 'archival_object', category) elif category == 'collections': # NOTE: in ArchivesSpace, collection.tree.r...
jerry57/Robotframework-iRODS-Library
src/iRODSLibrary/__init__.py
Python
bsd-3-clause
422
0.004739
from iRODSLibrary import iRODSLibrary __vers
ion__ = "0.0.4" class iRODSLibrary(iRODSLibrary): """ iRODSLibrary is a client keyword library that uses the python-irodsclient module from iRODS https://github.com/irods/pytho
n-irodsclient Examples: | Connect To Grid | iPlant | data.iplantcollaborative.org | ${1247} | jdoe | jdoePassword | tempZone """ ROBOT_LIBRARY_SCOPE = 'GLOBAL'
uber/ludwig
ludwig/collect.py
Python
apache-2.0
15,469
0.000388
#! /usr/bin/env python # coding=utf-8 # Copyright (c) 2019 Uber Technologies, 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 # # Unles...
""" model = LudwigModel.load(model_path) collected_tensors = model.collect_weights() names = [name for name, w in collected_tensors] keras_model = model.model.get_connected_model(training=False) keras_model.summary() print('\nLayers:\n') for layer in keras_model.layers: print(layer...
communicate with the collection of tensors and there are several options that can specified when calling this function: --data_csv: Filepath for the input csv --data_hdf5: Filepath for the input hdf5 file, if there is a csv file, this is not read --d: Refers to the dataset type of the ...
onoga/wm
src/gnue/common/external/plex/Errors.py
Python
gpl-2.0
1,109
0.027953
#======================================================================= # # Python Lexical Analyser # # Exception classes # #======================================================================= import exceptions class PlexError(exceptions.Exception): message = "" class PlexTypeError(PlexError, TypeError): ...
PlexValueError(PlexError, ValueError): pass class InvalidRegex(PlexError): pass class InvalidToken(PlexError): def __init__(self, token_number, message): PlexError.__init__(self, "Token number %d: %s" % (token_number, message)) class InvalidScanner(PlexError): pass class AmbiguousAction(PlexError): message...
xError): scanner = None position = None state_name = None def __init__(self, scanner, state_name): self.scanner = scanner self.position = scanner.position() self.state_name = state_name def __str__(self): return ("'%s', line %d, char %d: Token not recognised in state %s" % (self.position + (repr(self....
h-hirokawa/swampdragon
swampdragon/tests/test_base_model_router_subscribe.py
Python
bsd-3-clause
911
0.002195
from ..route_handler import BaseModelRouter, SUCCESS from ..serializers.model_serializer import ModelSerializer from .dragon_test_case import DragonTestCase from swampdragon.tests.models import TwoFieldModel class Serializer(ModelSerializer): class Meta: update_fields = ('text', 'number') model = ...
ss Router(BaseModelRouter): model = TwoFieldModel serializer_class = Serializer class TestBaseModelRouter(DragonTestCase): def setUp(self): self.router = Router(self.connection) def test_sub
scribe(self): data = {'channel': 'client-channel'} self.router.subscribe(**data) self.assertEqual(self.connection.last_message['context']['state'], SUCCESS) self.assertIn('channel_data', self.connection.last_message) self.assertEqual(self.connection.last_message['channel_data']['...
swegener/sigrok-meter
multiplotwidget.py
Python
gpl-3.0
6,148
0.00244
## ## This file is part of the sigrok-meter project. ## ## Copyright (C) 2015 Jens Steinhauser <jens.steinhauser@gmail.com> ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2...
takes up two rows. ret
urn 2 * self._plots.index(plot) @QtCore.Slot() def _onHideActionTriggered(self, checked=False): # The plot that we want to hide. plot = self._hideActions[id(self.sender())] self.hidePlot(plot) def hidePlot(self, plot): '''Hides 'plot'.''' # Only hiding wouldn't giv...
lnxpgn/scrapy_multiple_spiders
commands/crawl.py
Python
mit
809
0.002472
from scrapy.commands.crawl import Command from scrapy.exceptions import UsageError class CustomCrawlCommand(Command): def run(self, args, opts): if len(args) < 1: raise UsageError() elif len(args) > 1: raise UsageError("running 'scrapy crawl' with more
than one spider is no longer supported") spname =
args[0] # added new code spider_settings_path = self.settings.getdict('SPIDER_SETTINGS', {}).get(spname, None) if spider_settings_path is not None: self.settings.setmodule(spider_settings_path, priority='cmdline') # end crawler = self.crawler_process.create_crawler...
wwgc/trafficstats
trafficstats.py
Python
gpl-2.0
912
0.032151
#!/usr/bin/env python #-*- coding: utf-8 -*- import paramiko def traffic(ip,username,passwd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) stdin, stdout, stderr = ssh.exec_command('cat /proc/n...
print '%s\tError'%(ip) if __name__=='__main__': ip_list=['192.168.1.55','192.168.1.100','192.168.1.101','192.168.1.200','192.168.1.201'] username = "root" #用户名 passwd = "" #密码 print '\nIP\t\tRX(G)\tTX(G)' for ip
in ip_list: traffic(ip,username,passwd) print '\n'
yasutaka/nlp_100
johnny/第1章/08.py
Python
mit
425
0.009412
# -*- coding:utf-8 -*- def cipher(string):
encoding = "" for character in string: #range 97 -> 123 = a-z if 97 <= ord(character) <= 123: #encode 219 - character number encoding +=chr(219-ord(character))
else: encoding += character return encoding input_value = "Hello World" print cipher(input_value) print cipher(cipher(input_value))
tommorris/mf2py
mf2py/__init__.py
Python
mit
369
0
""
" Microformats2 is a general way to mark up any HTML document with classes and propeties. This library parses structured data from a microformatted HTML document and returns a well-formed JSON dictionary. """ from .version import __version__ from .parser import Parser, parse from .mf_helpers import get_url __all__ =...
rl', '__version__']
meitham/python-client
neovim/msgpack_rpc/event_loop/asyncio.py
Python
apache-2.0
4,579
0
"""Event loop implementation that uses the `asyncio` standard module. The `asyncio` module was added to python standard library on 3.4, and it provides a pure python implementation of an event loop library. It is used as a fallback in case pyuv is not available(on python implementations other than CPython). Earlier p...
ss def _send(self, data): self._transport.write(data) def _run(self): while self._
queued_data: self._on_data(self._queued_data.popleft()) self._loop.run_forever() def _stop(self): self._loop.stop() def _close(self): if self._raw_transport is not None: self._raw_transport.close() self._loop.close() def _threadsafe_call(self, fn): ...