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 |
|---|---|---|---|---|---|---|---|---|
akshitjain/dcos-cassandra-service | integration/tests/defaults.py | Python | apache-2.0 | 678 | 0 | import | os
import shakedown
DEFAULT_NODE_COUNT = 3
PACKAGE_NAME = 'mds-cassandra'
TASK_RUNNING_STATE | = 'TASK_RUNNING'
DCOS_URL = shakedown.run_dcos_command('config show core.dcos_url')[0].strip()
# expected SECURITY values: 'permissive', 'strict', 'disabled'
if os.environ.get('SECURITY', '') == 'strict':
print('Using strict mode test configuration')
PRINCIPAL = 'service-acct'
DEFAULT_OPTIONS_DICT = {
... |
manelore/django-haystack | tests/elasticsearch_tests/tests/__init__.py | Python | bsd-3-clause | 227 | 0.013216 | import warnings
warnings.simplefilter('ignore', Warning)
from elasticsearch_tests.tests.inputs import *
f | rom elasticsearch_tests.tests.elasticsearch_query import *
from elasticsearch_tests.tests.elasticsearch_backend imp | ort *
|
chrisspen/django-feeds | djangofeeds/migrations/0001_initial.py | Python | bsd-2-clause | 10,467 | 0.006879 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Category'
db.create_table(u'djangofeeds_category', (
(u'id', self.gf('django.db.... | rField')(default=0)),
))
db.send_create_signal(u'djangofeeds', ['Enclosure'])
# Adding model 'Post'
db.create_table(u'djangofeeds_post', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('feed', self.gf('django.db.models.fields.related.F... | y')(to=orm['djangofeeds.Feed'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=200)),
('link', self.gf('django.db.models.fields.URLField')(max_length=2048)),
('content', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('guid', se... |
louistin/thinkstation | a_byte_of_python/unit_9_module/mymodule_demo3.py | Python | mit | 114 | 0.009434 | #!/usr/bin/python3
from mymodule import *
sayhi()
# __versi | on__ 不会导入
# print('Version: ', __ve | rsion__)
|
tjanez/bup | cmd/daemon-cmd.py | Python | lgpl-2.1 | 2,128 | 0.003289 | #!/bin/sh
"""": # -*-python-*-
bup_python="$(dirname "$0")/bup-python" || exit $?
exec "$bup_python" "$0" ${1+"$@"}
"""
# end of bup preamble
import sys, getopt, socket, subprocess, fcntl
from bup import options, path
from bup.helpers import *
optspec = """
bup daemon [options...] -- [bup-server options...]
--
l,liste... | fd2 = os.dup(s.fileno())
s.close()
sp = subprocess.Popen([path.exe(), 'mux', '--',
path.exe(), 'server']
+ extra, stdin=fd1, stdout=fd2)
fina | lly:
os.close(fd1)
os.close(fd2)
finally:
for l in socks:
l.shutdown(socket.SHUT_RDWR)
l.close()
debug1("bup daemon: done")
|
eharney/cinder | cinder/volume/drivers/ibm/storwize_svc/storwize_svc_common.py | Python | apache-2.0 | 179,526 | 0.000045 | # Copyright 2015 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | err': err})
LOG.error(msg)
raise exception.VolumeBackendAPIException(data=msg)
def lsnode(self, node_id=None):
with_header = True
ssh_cmd = ['svcinfo', 'lsnode', '-delim', '!']
if node_id:
with_header = False
ssh_cmd.append(node_id)
re... | ssh_cmd = ['svcinfo', 'lslicense', '-delim', '!']
return self.run_ssh_info(ssh_cmd)[0]
|
ganeti/ganeti | test/py/ganeti.utils.log_unittest.py | Python | bsd-2-clause | 9,296 | 0.005271 | #!/usr/bin/python3
#
# Copyright (C) 2011 Google 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:
#
# 1. Redistributions of source code must retai | n the above copyright notice,
# this list of conditions and th | e following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" ... |
GoogleCloudPlatform/python-docs-samples | compute/encryption/generate_wrapped_rsa_key_test.py | Python | apache-2.0 | 1,721 | 0 | # Copyright 2016, Google, Inc.
# Licensed under the Apache License, Vers | ion 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 License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ... |
jaryn/virt-deploy | virtdeploy/test_driverbase.py | Python | gpl-2.0 | 2,986 | 0 | #
# Copyright 2015 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... | port__'
def try_import(spec):
def fake_import(na | me, globals={}, locals={}, fromlist=[], level=0):
try:
return spec(name, globals, locals, fromlist, level)
except ImportError:
return MagicMock()
return fake_import
class TestVirtDeployDriverBase(unittest.TestCase):
def _get_driver_methods(self):
return inspect.... |
takumak/tuna | src/sourceswidget.py | Python | mit | 4,761 | 0.010292 | import os
import logging
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import \
QWidget, QS | plitter, QTreeWidget, QTreeWidgetItem, QMenu, \
QTableWidgetItem
from sheetwidget import SheetWidget
from commonwidgets import *
class SourcesWidget(QSplitter):
updateRequested = pyqtSignal(name='updateRequested')
def __init__(self):
super().__init__(Qt.Horiz | ontal)
self.tree = QTreeWidget()
self.blank = QWidget()
self.addWidget(self.tree)
self.addWidget(self.blank)
self.tree.header().hide()
self.tree.itemSelectionChanged.connect(self.treeItemSelectionChanged)
self.tree.itemChanged.connect(lambda item, col: self.updateRequested.emit())
self... |
jpszerzp/sample_AI | projectParams.py | Python | apache-2.0 | 818 | 0.002445 | # projectParams.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkel... |
STUDENT_CODE_DEFAULT = 'multiAgents.py'
PROJECT_TEST_CLASSES = 'multiagentTestClasses.py'
PROJECT_NAME = 'Project 2: Multiagent search'
BONUS_PIC = Fals | e
|
manhhomienbienthuy/pythondotorg | sponsors/models/benefits.py | Python | apache-2.0 | 20,095 | 0.002787 | """
This module holds models related to benefits features and configurations
"""
from django import forms
from django.db import models
from django.db.models import UniqueConstraint
from django.urls import reverse
from polymorphic.models import PolymorphicModel
from sponsors.models.assets import ImgAsset, TextAsset, Fi... | )
help_text = models.CharField(
max_length=256,
help_text="Any helper comment on how the input should be populated",
default="",
blank=True
)
class Meta(BaseProvidedAsset.Meta):
abstract = True
class BaseProvidedFileAsset(BaseProvidedAsset):
ASSET_CLASS = FileAs... | help_text="What's the title used to display the file to the sponsor?"
)
help_text = models.CharField(
max_length=256,
help_text="Any helper comment on how the file should be used",
default="",
blank=True
)
shared_file = models.FileField(blank=True, null=True)
def sha... |
VitensTC/epynet | epynet/node.py | Python | apache-2.0 | 4,030 | 0.00397 | """ EPYNET Classes """
from . import epanet2
from .objectcollection import ObjectCollection
from .baseobject import BaseObject, lazy_property
from .pattern import Pattern
class Node(BaseObject):
""" Base EPANET Node class """
static_properties = {'elevation': epanet2.EN_ELEVATION}
properties = {'head': ep... | def inflow(self):
outflow = 0
for link in self.upstream_links:
outflow += abs(link.flow)
return outflow
@lazy_property
def outflow(self) | :
outflow = 0
for link in self.downstream_links:
outflow += abs(link.flow)
return outflow
""" calculates all the water flowing out of the node """
class Reservoir(Node):
""" EPANET Reservoir Class """
node_type = "Reservoir"
class Junction(Node):
""" EPANET Junc... |
alxgu/ansible | test/units/modules/storage/netapp/test_netapp_e_auditlog.py | Python | gpl-3.0 | 10,758 | 0.003346 | # (c) 2018, NetApp Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from ansible.modules.storage.netapp.netapp_e_auditlog import AuditLog
from units.modules.utils import AnsibleFailJson, ModuleTestCase, set_module_args
__metaclass__ = type
from units.compat import mock... | module_args.update(kwargs)
set_mod | ule_args(module_args)
def test_max_records_argument_pass(self):
"""Verify AuditLog arument's max_records and threshold upper and lower boundaries."""
initial = {"max_records": 1000,
"log_level": "writeOnly",
"full_policy": "overWrite",
"thres... |
bendykst/deluge | deluge/ui/gtkui/preferences.py | Python | gpl-3.0 | 58,154 | 0.002167 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007, 2008 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2011 Pedro Algarvio <pedro@algarvio.me>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with ... | ew.append_column(
gtk.TreeViewColumn(
_("Level"), gtk.CellRendererText(), text=ACCOUNTS_LEVEL
)
)
password_column = gtk.TreeViewColumn(
'password', gtk.CellRendererText(), text=ACCOUNTS_PASS | WORD
)
self.accounts_listview.append_column(password_column)
password_column.set_visible(False)
self.accounts_listview.set_model(self.accounts_liststore)
self.accounts_listview.get_selection().connect(
"changed", self._on_accounts_selection_changed
)
... |
awalin/rwis | views.py | Python | lgpl-3.0 | 4,395 | 0.020023 | from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.views.generic.base import View, TemplateView
from django.views import generic
from django.shortcuts import render_to_response
from django.template import RequestContext, load... | atetime import datetime
from django.views.decorators.csrf impo | rt ensure_csrf_cookie
import logging
from array import *
# logger = logging.getLogger('print')
class LoadCanvas(View):
template_name= "index.html"
def get(self, request, *args, **kwargs):
c = {}
c.update(csrf(request))
return render_to_response(self.template_name, c)
cla... |
airbnb/airflow | tests/dags/test_heartbeat_failed_fast.py | Python | apache-2.0 | 1,163 | 0.00086 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor lic | ense agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The A | SF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software d... |
gandreello/openthread | tests/scripts/thread-cert/Cert_7_1_04_BorderRouterAsRouter.py | Python | bsd-3-clause | 4,738 | 0.000633 | #!/usr/bin/env python
#
# Copyright (c) 2016, 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
# ... | EADER].set_mode('rsdn')
self.nodes[LEADER].add_whitelist(self.nodes[ROUTER].get_addr64())
| self.nodes[LEADER].enable_whitelist()
self.nodes[ROUTER].set_panid(0xface)
self.nodes[ROUTER].set_mode('rsdn')
self.nodes[ROUTER].add_whitelist(self.nodes[LEADER].get_addr64())
self.nodes[ROUTER].add_whitelist(self.nodes[ED2].get_addr64())
self.nodes[ROUTER].add_whitelist(self... |
Podcastor/podcastor-backend | src/app/api/urls.py | Python | gpl-2.0 | 1,923 | 0 | # -*- coding: utf-8 -*-
from rest_framework.routers import (Route,
DynamicDetailRoute,
SimpleRouter,
DynamicListRoute)
from app.api.account.views import AccountViewSet
from app.api.podcast.views import PodcastV... | on methods of the viewset.
DynamicDetailRoute(
| url=r'^{prefix}/{lookup}/{methodnamehyphen}{trailing_slash}$',
name='{basename}-{methodnamehyphen}',
initkwargs={}
),
]
router = CustomRouter()
router.register(r'accounts', AccountViewSet)
router.register(r'podcasts', PodcastViewSet)
router.register(r'episodes', EpisodeViewSet)
u... |
pknight007/electrum-vtc | plugins/keepkey/vtc.py | Python | mit | 353 | 0 | from ..trezor.qt_generic import QtPlugin
from keepkey import KeepKeyPlugin
c | lass Plugin(KeepKeyPlugin, QtPlugin):
icon_paired = ":icons/keepkey.png"
icon_unpaired = ":icons/keepkey_unpaired.png"
@classmethod
def pin_matrix_widget_cla | ss(self):
from keepkeylib.qt.pinmatrix import PinMatrixWidget
return PinMatrixWidget
|
djf604/viewer | util/link_out_scraper.py | Python | apache-2.0 | 1,060 | 0.003774 | __author__ = 'Jason Grundstad'
from django.conf import settings
fro | m pyvirtualdisplay import Display
from selenium import webdriver
from bs4 import BeautifulSoup
import json
MD_ANDERSON_URL = 'https://pct.mdanderson.org/#/home'
MD_ANDERSON_OUTFILE = settings.LINKS_OUT + 'mdanderson.json | '
def scrape_mdanderson():
"""
Scrape the rendered mdanderson page for gene names, create a .json
of links
:rtype : dict
"""
gene_list = dict()
d = Display(visible=0, size=(800,600)) # requires xvfb for headless mode
d.start()
driver = webdriver.Firefox()
driver.get(MD_ANDERSO... |
avinassh/learning-tornado | tornado-book/databases/definitions_readwrite.py | Python | mit | 1,628 | 0.023956 | import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import pymongo
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
# put your mongodb username and password
# "mongodb://username:password@staff.mongohq.com:someport... | coll.find_one({"word": word})
if word_doc:
word_doc['definition'] = definition
coll.save(word_doc)
else:
word_doc = {'word': word, 'definition': definition}
coll.inser | t(word_doc)
del word_doc["_id"]
self.write(word_doc)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
|
HazyResearch/snorkel | snorkel/learning/tensorflow/rnn/text_rnn.py | Python | apache-2.0 | 1,044 | 0.001916 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
import numpy as np
from .rnn_base import RNNBase
from .utils import SymbolTable
class TextRNN(RNNBase):
"""TextRNN for strings of text."""
... | toks = candidate.get_contexts()[0].text.split()
# Either extend word table or retrieve from it
f = self.word_dict.get if extend else self.word_dict.lookup
data.append(np.array(li | st(map(f, toks))))
ends.append(len(toks))
return data, ends
|
eco32i/ngs | ngs/wsgi.py | Python | mit | 1,410 | 0.000709 | """
WSGI config for ngs project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` sett... | ce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode wit | h each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "ngs.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ngs.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# ... |
aino/pymail365 | setup.py | Python | bsd-3-clause | 688 | 0.001453 | from setuptools import setup
setup(
name='pymail365',
version='0.1',
description='A python client for sending mail using Microsoft Office 365 rest service.',
long_description=open('README.r | st').read(),
author='Mikko Hellsing',
author_email='mikko@aino.se',
license='BSD',
url='https://github.com/aino/pymail365',
packages=['pymail365'],
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience ::... | BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
|
drwahl/i3pystatus | i3pystatus/window_title.py | Python | mit | 3,544 | 0.000847 | # -*- coding: utf-8 -*-
from i3pystatus import Module
from threading import Thread
import i3ipc
class WindowTitle(Module):
"""
Display the current window title with async update.
Uses asynchronous update via i3 IPC events.
Provides instant title update only when it required.
fork from window_tile... | onn.get_tree()
w = tree.find_focused()
p = w.parent
# don't show window title when the window already has means
# to display it
if (not self.always_show
and (w.border == "normal"
or w.type == "workspace"
or (p.layout in ("stacked", "... | w.name
class_name = w.window_class
if len(title) > self.max_width:
title = title[:self.max_width - 1] + "…"
return self.format.format(title=title, class_name=class_name)
def update_title(self, conn, e):
# catch only focused window title updates
t... |
TaskEvolution/Task-Coach-Evolution | taskcoach/taskcoachlib/thirdparty/src/reportlab/pdfgen/pdfimages.py | Python | gpl-3.0 | 8,517 | 0.009041 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/pdfimages.py
__version__=''' $Id$ '''
__doc__="""
Image functionality sliced out of canvas.py for generalization
"""
import os
import string
fr... | image.fp
fp.seek(0)
return self._jpg_imagedata(fp)
self.source = 'PIL'
zlib = import_zlib()
if not zlib: return
bpc = 8
# Use the colorSpace in the image
if image.mode == 'CMYK':
myimage = image
colorSpace = 'DeviceCMYK'
... | == 'L':
myimage = image
colorSpace = 'DeviceGray'
bpp = 1
else:
myimage = image.convert('RGB')
colorSpace = 'RGB'
bpp = 3
imgwidth, imgheight = myimage.size
# this describes what is in the image itself
# *NB* accor... |
google-research/falken | service/api/stop_session_handler.py | Python | apache-2.0 | 9,830 | 0.005086 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | rting_snapshot(
session_resource_id, starting_snapshots)
return ''
def _create_snapshot(session_resource_id, starting_snapshots,
model_resource_id, model_path, data_store):
"""Creates a new snapshot in data_store.
Args:
session_resource_id: resource_id.FalkenResourceID for ... |
new snapshot for.
model_resource_id: resource_id.FalkenResourceID for the model that was
selected by model_selector to create the snapshot for.
model_path: Path for the model to write the snapshot fo |
msegado/edx-platform | common/lib/xmodule/xmodule/partitions/partitions.py | Python | agpl-3.0 | 10,492 | 0.002669 | """Defines ``Group`` and ``UserPartition`` models for partitioning"""
from collections import namedtuple
from stevedore.extension import ExtensionManager
# We use ``id`` in this file as the IDs of our Groups and UserPartitions,
# which Pylint disapproves of.
# pylint: disable=redefined-builtin
# UserPartition IDs... | groups = [Group.from_json(g) for g in value["groups"]]
scheme = UserPartition.get_scheme(scheme_id)
if not scheme:
raise TypeError("UserPartition dict {0} has unrecognized scheme {1}".format(value, scheme_id))
if getattr(scheme, 'read_ | only', False):
raise ReadOnlyUserPartitionError("UserPartition dict {0} uses scheme {1} which is read only".format(value, scheme_id))
if hasattr(scheme, "create_user_partition"):
return scheme.create_user_partition(
value["id"],
value["name"],
... |
ycasg/PyNLO | src/pynlo/light/__init__.py | Python | gpl-3.0 | 245 | 0.004082 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 03 09:38:19 2014
"""
from .PulseBase import Pulse
from .beam import OneDBeam
from . import beam
from . imp | ort DerivedPulses
from . import PulseBase
from .high_V_waveguide import OneDBeam_hig | hV_WG |
LaurentClaessens/LaTeXparser | Occurrence.py | Python | gpl-3.0 | 7,331 | 0.015278 | # -*- coding: utf8 -*-
###########################################################################
# This is the package latexparser
#
# 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, ei... | the definition"
self.listoche = [None,None,None,None,None]
self.value,self.page,self.section_name,self.fourth,self.fifth=(None,None,None,None,None)
else :
self.name = self.arguments[0][0]
self.listoche = [a[0] for a in SearchArguments(s | elf.arguments[1][0],5)[0]]
self.value = self.listoche[0]
self.page = self.listoche[1]
self.section_name = self.listoche[2].replace(r"\relax","")
self.fourth = self.listoche[3] # I don't know the role of the fourth argument of \newlabel
self.fifth = self.l... |
pichuang/OpenNet | mininet-patch/examples/cluster/nctu_ec_wired_topo.py | Python | gpl-2.0 | 3,067 | 0.011412 | #!/usr/bin/python
'''
nctu_cs_wired_topo.gy
'''
from mininet.cluster.net import MininetCluster
from mininet.cluster.placer import DFSPlacer
from mininet.log import setLogLevel
from mininet.cluster.cli import ClusterCLI as CLI
from mininet.node import Controller, RemoteController
from mininet.topo import Topo
from iter... | self.access_sw_list = []
self.host_list = []
self.create_top_switch( "core", self.core_num, self.core_sw_list )
self.handle_top_down( "agg", self.agg_num, self.core_sw_list, self.agg_sw_list )
self.handl | e_top_down( "access", self.access_num, self.agg_sw_list, self.access_sw_list )
self.handle_host( "h", self.host_num, self.host_list )
self.handle_mesh( self.agg_sw_list )
def create_top_switch( self, prefix_name, sw_num, sw_list):
for i in xrange(1, sw_num+1):
sw_list.append(s... |
VictorAlessander/Smith | setup.py | Python | gpl-3.0 | 1,730 | 0.000578 | import io
from setuptools import (
setup,
find_packages,
) # pylint: disable=no-name-in-module,import-error
def dependencies(file):
with open(file) as f:
return f.read().splitlines()
with io.open("README.md", encoding="utf-8") as infile:
long_description = infile.read()
setup(
name="sm... | "Programming Language :: | Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3 :: Only",
],
python_requires=">=3.1",
description="A webscraper with a sofisticated toolkit to scrap the world",
long_description=long_description,
long_description_content_type="text/markd... |
googleapis/python-datalabeling | samples/generated_samples/datalabeling_v1beta1_generated_data_labeling_service_get_evaluation_sync.py | Python | apache-2.0 | 1,513 | 0.000661 | # -*- 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... | NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-datalabeling
# [START datalabeling_v1beta1_generated_Dat... | client
client = datalabeling_v1beta1.DataLabelingServiceClient()
# Initialize request argument(s)
request = datalabeling_v1beta1.GetEvaluationRequest(
name="name_value",
)
# Make the request
response = client.get_evaluation(request=request)
# Handle the response
print(respons... |
MongoEngine/mongoengine | mongoengine/fields.py | Python | mit | 90,689 | 0.001301 | import datetime
import decimal
import inspect
import itertools
import re
import socket
import time
import uuid
from io import BytesIO
from operator import itemgetter
import gridfs
import pymongo
from bson import SON, Binary, DBRef, ObjectId
from bson.int64 import Int64
from pymongo import ReturnDocument
try:
impo... | allow_utf8_user=False,
allow_ip_domain=False,
*args,
**kwargs,
):
"""
:param domain_whitelist: (optional) list of valid domain names applied during validation
:param allow_utf8_user: Allow user part of the email to contain utf8 | char
:param allow_ip_domain: Allow domain part of the email to be an IPv4 or IPv6 address
:param kwargs: Keyword arguments passed into the parent :class:`~mongoengine.StringField`
"""
self.domain_whitelist = domain_whitelist or []
self.allow_utf8_user = allow_utf8_user
s... |
michel-rodrigues/ecommerce2 | source/carts/migrations/0008_cart_tax_percentage.py | Python | gpl-3.0 | 489 | 0.002045 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-21 14:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('carts', '0007_auto_20161221_1337'),
]
operations = [
migrations.AddField(
... | odel_name='cart',
name='tax_percentage',
field=models.DecimalField(deci | mal_places=3, default=0.085, max_digits=20),
),
]
|
blopker/Color-Switch | colorswitch/http/downloaders/urllib.py | Python | mit | 1,149 | 0.002611 | from .downloader_base import DownloaderBase
from ... import logger
log = logger.get(__name__)
import traceback
import json
from urllib import request, error
try:
import ssl
SSL = True
except ImportError:
SSL = False
def is_available():
return SSL
class UrllibDownloader(DownloaderBase):
"""Down... | uses the native Python HTTP library.
Does not verify HTTPS certificates... """
def get(self, url):
try:
log.debug('Urllib downloader getting url %s', url)
result = request.urlopen(url)
except error.URLError as e:
log.error('Urllib downloader failed: %s' % e.r... | result = b''
if result.getcode() >= 400:
return b''
return result.read()
def get_json(self, url):
a = self.get(url)
if a:
try:
a = json.loads(a.decode('utf-8'))
except ValueError:
log.error('URL %s does no... |
sravan953/pulseq-gpi | pulseq2jemris/jemris_nodes/JMakeDelaySequence_GPI.py | Python | gpl-3.0 | 990 | 0.00404 | import gpi
class ExternalNode(gpi.NodeAPI):
"""This Node provides allows the user to make a DelaySequence for Jemris."""
def initUI(self):
# Widgets
self.delay_labels = ['Name', 'Observe', 'ADCs', 'Aux1', 'Aux2', 'Aux3', 'Delay', 'DelayType', 'HardwareMode',
'Phas... | T_' in self.getEvents():
delay_seq = {'DelaySequence': True}
for label in self.delay_labels:
if self.getVal(label) != '':
delay_seq[label] = self | .getVal(label)
self.setData('DelaySequence', [delay_seq])
return 0
|
cmaclell/pyAFM | pyafm/roll_up.py | Python | mit | 7,059 | 0 | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import csv
from dateutil.parser import parse
def write_problem(steps, problem_views, kc_ops, row_count, kc_model_names,
out):
# variable to store ... | if t['outcome'].lower() == 'hint':
hints += 1
for kc_mod in kc_model_names:
for kc in t[kc_mod].split("~~"):
kc_sets[kc_mod].add(kc)
# for each rolled up step, we need to increment the KC counts.
kc_to_write = []
for kc_mod in kc_... | name = kc_mod[4:-1]
kcs = list(kc_sets[kc_mod])
kc_to_write.append("~~".join(kcs))
if model_name not in kc_ops:
kc_ops[model_name] = {}
ops = []
for kc in kcs:
if kc not in kc_ops[model_name]:
kc_ops[model_... |
outoftime/learnpad | tools/npx.py | Python | mit | 171 | 0 | #!/usr/bin/env python
from util import nodeenv | _delegate
from setup import setup
if __name__ == "__main__":
setup(skip_dependencies=True)
nodeenv_delegate("npx | ")
|
tedye/leetcode | Python/leetcode.059.spiral-matrix-ii.py | Python | mit | 1,134 | 0.013228 | class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n <= 0:
return []
if n == 1:
return [[1]]
matrix = [[None] * n for _ in range(n)]
x = y = 0
direction = [(0,1),(1,0),(0... | u += 1
x -= 1
y += 1
dc += 1
elif y > d:
| r -= 1
y -= 1
x -= 1
dc +=1
elif x < l:
d -= 1
x += 1
y -= 1
dc += 1
elif y < u:
l += 1
y += 1
x += 1
dc += 1
... |
hbenniou/trunk | doc/sphinx/book/confReference.py | Python | gpl-2.0 | 26,536 | 0.030762 | # -*- coding: utf-8 -*-
#
# Yade documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 16 21:49:34 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | et.startswith('external:'):
exttarget=target.split(':',1)[1]
if not explicitText: text=exttarget
target=exttarget if '.' in exttarget else 'module-'+exttarget
uri=(('%%external#%s'%target) if writer=='latex' else 'external.html#%s'%target)
else:
uri=(('%%yade.wrapper#yade.wrapper.%s'%target) if | writer=='latex' else 'yade.wrapper.html#yade.wrapper.%s'%target)
#print writer,uri
return nodes.reference(rawtext,docutils.utils.unescape(text),refuri=uri,**options)
#return [refnode],[]
def ydefault_role(role,rawtext,text,lineno,inliner,options={},content=[]):
"Handle the :ydefault:`something` role. fixSignatur... |
zarnold/transitfeed | extensions/googletransit/pybcp47/__init__.py | Python | apache-2.0 | 637 | 0 | #!/usr/bin/python2.5
# Copyright (C) 2011 Google 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 writing, software
# distributed under the License is di... | mitations under the License.
from bcp47languageparser import *
|
ntthuy11/CodeFights | Arcade/04_Python/07_CaravanOfCollections/frequencyAnalysis.py | Python | mit | 1,131 | 0.000884 | """ You've recently read "The Gold-Bug" by Edgar Allan Poe, and was so impressed by the cryptogram in it that
decided to try and decipher an encrypted text yourself. You asked your friend to encode a piece of text using
a substitution cipher, and now have an encryptedText that you'd like to decipher.
The encryption ... | et) # CodeFights asks to change this line only | |
RealTimeWeb/datasets | preprocess/medal_of_honor/fix.py | Python | gpl-2.0 | 3,268 | 0.004896 | import json
with open('medalofhonor-old.json') as input:
data = json.load(input)
months = {
'January': 1,
'February': 2,
'March': 3,
'April': 4,
'May': 5,
'June': 6,
'July': 7,
'August': 8,
'September': 9,
'October': 10,
'November': 11,
'December': 12,
}
d... | h, day, loca | tion]
except:
return [-1, -1, -1, record['Born']]
else:
try:
return [-1, -1, int(record['Born']), ""]
except ValueError:
return [-1, -1, -1, record['Born']]
from pprint import pprint
[parse_locdate(record) for record in data]
new_data = [
... |
noselasd/testrunner | testrunner.py | Python | mit | 21,002 | 0.005142 | #!/usr/bin/env python
import sys
import re
import subprocess
import os
import optparse
import datetime
import inspect
import threading
from xml.sax.saxutils import XMLGenerator
from xml.sax.xmlreader import AttributesImpl
VERSION = '1.0.0'
ALL_TESTS = []
LOGFILE = None
CURRENT_SUITE = 'default'
DEFAULT_TEST_TIMEOUT = ... | return self.__class__ == other.__class__
def __repr__(self):
return str(self)
class TestResult(object):
class PASS(SimpleEnum):
pass
class FAIL(SimpleEnum):
pass
class TIMEDOUT(SimpleEnum):
pass
class NOTRUN(Si | mpleEnum):
pass
class TestFailure(object):
def __init__(self, test, msg):
self.test_name = test.name
self.result = test.result
self.msg = msg
def __str__(self):
return '%s %s:\n%s' % (self.result, self.test_name, self.msg)
def __repr__(self):
return str(se... |
acrisci/i3ipc-glib | test/test_get_config.py | Python | gpl-3.0 | 347 | 0 | from ipctest import IpcTest
from gi.repository import i3ipc
import pytest
@pyte | st.mark.skip(reason='TODO')
class TestGetConfig(IpcTest):
def test_get_config(self, i3):
config = i3.get_config()
assert isin | stance(config, i3ipc.ConfigReply)
with open('test/i3.config') as f:
assert config.config == f.read()
|
DESHRAJ/fjord | vendor/packages/nose/functional_tests/support/twist/test_twisted.py | Python | bsd-3-clause | 304 | 0.003289 | from twisted.trial import unittest
class | TestTwisted(unittest.TestCase):
def test(self):
pass
def test_fail(self):
self.fail("I failed")
def test_error(self):
raise TypeError("oops, wrong type")
def test_skip(self):
r | aise unittest.SkipTest('skip me')
|
CSchool/SchoolSite | CSchoolSite/main/migrations/0002_notification_queued.py | Python | apache-2.0 | 457 | 0 | # -*- coding: utf-8 -*-
# Gen | erated by Django 1.11 on 2017-05-04 12:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial') | ,
]
operations = [
migrations.AddField(
model_name='notification',
name='queued',
field=models.BooleanField(db_index=True, default=False),
),
]
|
chirilo/remo | vendor-local/lib/python/rest_framework/renderers.py | Python | bsd-3-clause | 24,971 | 0.000921 | """
Renderers are used to serialize a response into specific media types.
They give us a generic way of being able to handle various media types
on the response, such as JSON encoded data or HTML output.
REST framework also provides an HTML renderer the renders the browsable API.
"""
from __future__ import unicode_li... | The data supplied to the Response object should be | a dictionary that will
be used as context for the template.
The template name is determined by (in order of preference):
1. An explicit `.template_name` attribute set on the response.
2. An explicit `.template_name` attribute set on this class.
3. The return result of calling `view.get_template_n... |
meidli/yabgp | yabgp/handler/default_handler.py | Python | apache-2.0 | 7,759 | 0.000516 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# import json
# replace with simplejson
import simplejson as json
import os
import time
import logging
import traceback
import sys
from oslo_config import cfg
from yabgp.common import constants as bgp_cons
from yabgp.handler import BaseHandler
CONF = cfg.CONF
LOG = loggin... | % time.time()
LOG.info('Open a new message file %s', msg_file_name)
msg_file = open(os.path.join(msg_path + msg_file_name), 'a')
self.peer_files[peer.lower()] = (msg_path, msg_file)
return True
return False
def on_update_error(self, peer, time... | ,
msg={'msg': msg}
)
def update_received(self, peer, timestamp, msg):
# write message to disk
self.write_msg(
peer=peer.factory.peer_addr,
timestamp=timestamp,
msg_type=bgp_cons.MSG_UPDATE,
msg={"msg": msg}
)
self.c... |
msztolcman/ff | test/mocks/__init__.py | Python | mit | 190 | 0.005263 | #!/usr/bin/en | v python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
import os, os.path
import re
import sys
from pprint import | pprint, pformat
|
ronaldahmed/robot-navigation | neural-navigation-with-lstm/MARCO/nltk/parser/__init__.py | Python | mit | 52,728 | 0.002731 | # Natural Language Toolkit: Parsers
#
# Copyright (C) 2001 University of Pennsylvania
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# Steven Bird <sb@ldc.upenn.edu>
# Scott Currie <sccurrie@seas.upenn.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: __init__... | he man" with a typical grammar, C{ShiftReduceParser} will produce
the following stack, which covers "the dog saw"::
[(NP: (Det: <'the'>) (N: <'dog'>)), (V: <'saw'>)]
C{ShiftReduceParser} attempts to extend the stack to cover the
entire text, and to combine the stack elements into a single tree,
... | s extended to cover the text,
from left to right, by repeatedly applying two operations:
- X{shift} moves a token from the beginning of the text to the
end of the stack.
- X{reduce} uses a CFG production to com |
gagnonlg/explore-ml | sngp/tf_import/__init__.py | Python | gpl-3.0 | 136 | 0 | from .gaussian_process import RandomFeatureGaussianProcess, mean | _field_logits
from .spectral_normalization import SpectralNormaliza | tion
|
Alexanderkorn/Automatisation | oude scripts/les 5/fibonacci-reeks.py | Python | gpl-3.0 | 415 | 0.007264 | __author__ = 'alexander'
def fibonacci(n) | :
voorlaatste_cijfer = 1
laatste_cijfer = 1
print(voorlaatste_cijfer)
print(laatste_cijfer)
for i in range(n-2):# n – 2, omdat we de eerste twee cijfers al weten
nieuw_cijfer = laatste_cijfer + voorlaatste_cijfer
print(nieuw_cijfer)
voorlaatste_cijfer = laatste_cijfer
... | laatste_cijfer = nieuw_cijfer
fibonacci(6) |
antoinecarme/pyaf | tests/artificial/transf_RelativeDifference/trend_MovingAverage/cycle_7/ar_/test_artificial_32_RelativeDifference_MovingAverage_7__20.py | Python | bsd-3-clause | 276 | 0.083333 | 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 | = "MovingAverage", cycle_length = 7, transform = "RelativeDifference", sigma = 0.0, exog_count | = 20, ar_order = 0); |
zutshi/S3CAMX | src/example_list.py | Python | bsd-2-clause | 2,248 | 0.003114 | from __future__ import print_function
import configparser as cp
import fileOps | as f
import err
import logging
#EXAMPLE_LIST_FN = 'example_list'
example_list_str = | \
'''0_vanDerPol = ./examples/vanderpol_python/
1_vanDerPol = ./examples/vanderpol_m_file/
2_dc = ./examples/dc_controller_hand_coded/
3_dci = ./examples/dc_controller_hand_coded_input/
4_ex1a = ./examples/ex1a/
5_ex1b = ./examples/ex1b/
6_AbstractFuelControl = ./examples/abstractFuelControl/
7_AbstractFuelControl = ./... |
AntonioMtn/NZBMegaSearch | werkzeug/contrib/kickstart.py | Python | gpl-2.0 | 11,308 | 0.000354 | # -*- coding: utf-8 -*-
"""
werkzeug.contrib.kickstart
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides some simple shortcuts to make using Werkzeug simpler
for small scripts.
These improvements include predefined `Request` and `Response` objects as
well as a predefined `Application` object whi... | # check all view processors
for processor in self.processors:
action = processor.process_view(request, callback | , (), args)
if action is not None:
# it is overriding the default behaviour, this is
# short-circuiting the processing, so it returns here
return action(environ, start_response)
try:
response = callback(request, **a... |
avanzosc/avanzosc6.1 | avanzosc_stpick_expectdate/__init__.py | Python | agpl-3.0 | 1,019 | 0.003925 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2008-2014 AvanzOSC (Daniel). All Rights Reserved
# Date: 20/02/2014
#
# This program is free software: you can redistribute it and/o... | as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURP... | should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/.
#
##############################################################################
import wizard |
ProjectSWGCore/NGECore2 | scripts/loot/lootItems/re_junk/mark_v_vocab_module.py | Python | lgpl-3.0 | 418 | 0.064593 |
def itemTemplate():
return ['o | bject/tangible/loot/npc_loot/shared_softwa | re_module_orange_generic.iff']
def customItemName():
return 'Mark V Vocab Module'
def lootDescriptor():
return 'customattributes'
def customizationAttributes():
return ['/private/index_color_1']
def customizationValues():
return [0]
def stackable():
return 1
def junkDealerPrice():
return 28
def j... |
stdweird/aquilon | upgrade/1.8.18/add_sandbox_startpoint.py | Python | apache-2.0 | 4,924 | 0.002437 | #!/usr/bin/env python2.6
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2012,2013 Contributor
#
# 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... | onfig
from sqlalchemy.orm import defer
from sqlalchemy.sql import text
from sqlalchemy.exc import DatabaseError
from aquilon.aqdb.model import Base, Sandbox, Domain
from aquilon.aqdb.db_factory import DbFactory
from aquilon.worker.processes import r | un_git
db = DbFactory()
Base.metadata.bind = db.engine
session = db.Session()
config = Config()
def main():
print "Calculating sandbox base commits. This may take around 10 minutes."
logging.basicConfig(level=logging.WARNING)
kingdir = config.get("broker", "kingdir")
domains = session.query(Domain... |
structrans/Canon | test/seq/test_seqreader.py | Python | mit | 560 | 0 | import pytest
from canon.seq.seqreader import SeqReader
from .. import resource
def test_read_seq():
reader = SeqReader(resource('seq/Quartz_500Mpa_.SEQ'))
reader.get_Om()
Z, _, N = reader.get_Zmap('orsnr___')
def test_merge_Zmap():
reader = SeqReader()
reader.read_seq(r | esource( | 'seq/au30_a1_.SEQ'))
Z1, _, N1 = reader.get_Zmap('orsnr___')
reader.read_seq(resource('seq/au30_m1_.SEQ'))
Z2, _, N2 = reader.get_Zmap('orsnr___')
Z, N = SeqReader.merge_Zmap(Z1, Z2, N1, N2)
if __name__ == '__main__':
pytest.main()
|
rafaelmartins/blohg | blohg/vcs_backends/git/changectx.py | Python | gpl-2.0 | 4,270 | 0 | # -*- coding: utf-8 -*-
"""
blohg.vcs_backends.git.changectx
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Model with classes to represent Git change context.
:copyright: (c) 2010-2013 by Rafael Goncalves Martins
:license: GPL-2, see LICENSE for more details.
"""
import time
from flask.helpers import locked_c... | t inherits the common implementation
from the class :class:`ChangeCtxBase`.
"""
@locked_cached_property
def revision_id(self):
if self._repo.workdir is None:
raise RuntimeError('Bare repositories should be deployed with '
'REVISION_DEFAULT change conte... | try:
return self._repo.head.target
except Exception:
raise RuntimeError('HEAD reference not found! Please do your '
'first commit.')
@locked_cached_property
def files(self):
return [entry.path for entry in self._repo.index]
def nee... |
anshulsharmanyu/twitter_plot | Twitter Map Cloud Assignment/googleMapsTweet/apps.py | Python | gpl-3.0 | 145 | 0.006897 | from __future__ impor | t unicode_literals
from django.apps import AppConfig
class GooglemapstweetConfig(AppConf | ig):
name = 'googleMapsTweet'
|
jbedorf/tensorflow | tensorflow/compiler/tests/variable_ops_test.py | Python | apache-2.0 | 21,657 | 0.008635 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | t GradientDescentOptimizer
class VariableOpsTest(xla_test.XLATestCase):
"""Test cases for resource variable operators."""
def testWriteEmptyShape(self):
# Verifies that we can pass an uninitialized variable with an empty shape,
| # assign it a value, and successfully return it.
for dtype in self.numeric_types:
with self.test_session() as sess, self.test_scope():
zeros = np.zeros([3, 0], dtype=dtype)
v = resource_variable_ops.ResourceVariable(zeros)
p = array_ops.placeholder(dtype)
x = v.assign(p)
... |
Eclipse-2017/waveforms | playback/inmarsat_playback.py | Python | gpl-3.0 | 26,718 | 0.010517 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Inmarsat Playback
# Generated: Mon Aug 21 21:42:34 2017
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.plat... | cutoff_line_edit.text().toAscii()))))
self.top_grid_layout.addWidget(self._cutoff_tool_bar, 13,0,1,2)
self._cols_range = Range(1, 500, 1, 54, 200)
self._cols | _win = RangeWidget(self._cols_range, self.set_cols, "cols", "counter_slider", float)
self.top_grid_layout.addWidget(self._cols_win, 12,4,1,4)
self.rational_resampler_xxx_0_0 = filter.rational_resampler_ccc(
interpolation=interp,
decimation=decim,
taps=None... |
gregmuellegger/django-autofixture | autofixture_tests/tests/test_autodiscover.py | Python | bsd-3-clause | 325 | 0 | from django.contrib.auth.models import User
from django.test i | mport TestCase
import autofixture
autofixture.autodiscover()
class AutodiscoverTestCase(TestCase):
def test_builtin_fixtures(self):
from autofixture.autofixtures import UserFixture
self.as | sertEqual(autofixture.REGISTRY[User], UserFixture)
|
googlefonts/cu2qu | tests/pens_test.py | Python | apache-2.0 | 13,027 | 0.000077 | from __future__ import print_function, division, absolute_import
import unittest
from cu2qu.pens import Cu2QuPen, Cu2QuPointPen
from . import CUBIC_GLYPHS, QUAD_GLYPHS
from .utils import DummyGlyph, DummyPointGlyph
from .utils import DummyPen, DummyPointPen
from fontTools.misc.loggingTools import CapturingLogHandler
f... | source = CUBIC_GLYPHS[name]
normal_glyph = self.convert_glyph(sour | ce)
reversed_glyph = self.convert_glyph(source, reverse_direction=True)
# the number of commands is the same, just their order is iverted
self.assertTrue(
len(normal_glyph.outline), len(reversed_glyph.outline))
self.assertNotEqual(normal_glyph, reversed_g... |
jrowan/zulip | zerver/tornado/event_queue.py | Python | apache-2.0 | 37,008 | 0.002972 | # See http://zulip.readthedocs.io/en/latest/events-system.html for
# high-level documentation on how this system works.
from __future__ import absolute_import
from typing import cast, AbstractSet, Any, Callable, Dict, List, \
Mapping, MutableMapping, Optional, Iterable, Sequence, Set, Text, Union
from django.utils... | t_client_name = None # type: Optional[Text]
self.event_queue = event_queue
self.queue_timeout = lifespan_secs
self.event_types = event_types
self.last_connection_time = time.time()
self.apply_markdown = apply_markdown
self.all_public_streams = all_public_streams
| self.client_type_name = client_type_name
self._timeout_handle = None # type: Any # TODO: should be return type of ioloop.add_timeout
self.narrow = narrow
self.narrow_filter = build_narrow_filter(narrow)
# Clamp queue_timeout to between minimum and maximum timeouts
self.queu... |
DCPUTeam/DCPUToolchain | docs/sphinxext/toolchain.py | Python | mit | 335 | 0.020896 | # Directi | ves using the toolchain
# documentation.
import docutils
def setup(app):
app.add_object_type("asmdirective", "asmdir");
app.add_object_type("asminstruction", "asminst");
app.add_obje | ct_type("ppexpressionop", "ppexprop");
app.add_object_type("ppdirective", "ppdir");
app.add_object_type("literal", "lit"); |
great-expectations/great_expectations | tests/integration/docusaurus/connecting_to_your_data/database/redshift_yaml_example.py | Python | apache-2.0 | 3,566 | 0.001963 | import os
from ruamel import yaml
import great_expectations as ge
from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest
redshift_username = os.environ.get("REDSHIFT_USERNAME")
redshift_password = os.environ.get("REDSHIFT_PASSWORD")
redshift_host = os.environ.get("REDSHIFT_HOST")
redshift_port =... | st_yaml_config(datasource_yaml)
context.add_datasource(**yaml.load(datasource_yaml))
# First test for RuntimeBatchRequest using a query
batch_request = RuntimeBatchRequest(
datasource_name="my_redshift_datasource",
data_connector_name="default_runtime_data_connector_name",
data_asset_name="default_name", ... | r_name": "default_identifier"},
)
context.create_expectation_suite(
expectation_suite_name="test_suite", overwrite_existing=True
)
validator = context.get_validator(
batch_request=batch_request, expectation_suite_name="test_suite"
)
print(validator.head())
# NOTE: The following code is only for testing and ca... |
mionch/django-getpaid | getpaid/backends/eservice/urls.py | Python | mit | 488 | 0.010246 | from django.conf.ur | ls import patterns, url
from django.views.decorators.csrf import csrf_exempt
from getpaid.backends.eservice.views import PendingView, SuccessView, FailureView
urlpatterns = patterns('',
url(r'^pending/$', csrf_exempt(PendingView.as_view()), name='getpaid-eservice-pending'),
url(r'^success/$', csrf_exempt(Succ... | etpaid-eservice-failure'),
)
|
rembo10/headphones | lib/feedparser/util.py | Python | gpl-3.0 | 6,490 | 0.000308 | # Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistrib... | s fallback will be removed in a future version "
"of feedparser. | ",
DeprecationWarning,
)
return dict.__getitem__(self, 'published')
return dict.__getitem__(self, 'updated')
elif key == 'updated_parsed':
if (
not dict.__contains__(self, 'updated_parsed')
and di... |
sebastic/QGIS | python/plugins/GdalTools/__init__.py | Python | gpl-2.0 | 1,251 | 0.000799 | """
/***************************************************************************
Name : GdalTools
Description : Integrate gdal tools into qgis
Date : 17/Sep/09
copyright : (C) 2009 by Lorenzo Masini and Giuseppe Sucameli (Faunalia)
email : lorenxo86@gma... | shed by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
... | gin, making it known to QGIS.
"""
def classFactory(iface):
# load GdalTools class from file GdalTools
from GdalTools import GdalTools
return GdalTools(iface)
|
noelevans/sandpit | decay_fns/decay_weightings.py | Python | mit | 574 | 0.020906 | import numpy as np
import pandas as pd
def decay_me | an(ol, half_life=5):
years = np.array([2012, 2013, 2014, 2016, 2017])
ratings = np.array([9, 11, 14, 11, 4])
today = 2016 + 1
print(ratings.mean())
elapsed_time = years - today
half_life = 2
weights = np.e ** -(elapsed_time * half_life)
print weights
print weights / sum(... | rint(ratings.mean())
if __name__ == '__main__':
main()
|
puruckertom/poptox | poptox/generic/generic_batchinput.py | Python | unlicense | 1,372 | 0.019679 | import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import numpy as np
import cgi
import cgitb
cgitb.enable()
c | lass genericBatchInputPage(webapp.RequestHandler):
def get(self):
templatepath = os.path.dirname(__file__) + '/../templates/'
html = template.render(templatepath + '01pop_uberheader.html', {'title'})
html = html + template.render(templatepath + '02pop_uberintroblock_wmodellinks.html', {'mode... | template.render (templatepath + '03pop_ubertext_links_left.html', {})
html = html + template.render(templatepath + '04uberbatchinput.html', {
'model':'generic',
'model_attributes':'generic Batch Input'})
html = html + template.render(templatepath ... |
jorgecarleitao/public-contracts | contracts/category_urls.py | Python | bsd-3-clause | 977 | 0.007165 | from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from . import category_views
from . import feed
urlpatterns = patterns('',
url(r'(\d+)$', category_views.main_view, name='category'),
url(r'(\d+)/%s$' % _('contracts'), cate... | /%s/rss$' % _('contracts'), feed.CategoryContractsFeed(), name='category_contracts_rss'),
url(r'(\d+)/%s$' % _('contractors'), category_views.contractors, name='category_contractors'),
url(r'(\d+)/%s$' % _('contracted'), category_views.contracted, name='category_contracted'... | url(r'(\d+)/%s$' % _('tenders'), category_views.tenders, name='category_tenders'),
url(r'(\d+)/%s/rss$' % _('tenders'), feed.CategoryTendersFeed(), name='category_tenders_rss'),
)
|
yuanagain/seniorthesis | venv/lib/python2.7/site-packages/scipy/io/tests/test_idl.py | Python | mit | 19,614 | 0.005302 | from __future__ import division, print_function, absolute_import
from os import path
import warnings
DATA_PATH = path.join(path.dirname(__file__), 'data')
import numpy as np
from numpy.testing import (assert_equal, assert_array_equal, run_module_suite,
assert_)
from scipy.io.idl import readsav
def object_arra... | s = readsav(path.join(DATA_PATH, 'scalar_int64.sav'), verbose=False)
assert_identical(s.i64s, np.int64(-9223372036854774567))
def test_uint64(self):
s = readsav(pat | h.join(DATA_PATH, 'scalar_uint64.sav'), verbose=False)
assert_identical(s.i64u, np.uint64(18446744073709529285))
class TestCompressed(TestScalars):
# Test that compressed .sav files can be read in
def test_compressed(self):
s = readsav(path.join(DATA_PATH, 'various_compressed.sav'), verbose=F... |
ericholscher/django | django/test/client.py | Python | bsd-3-clause | 22,448 | 0.000757 | from __future__ import unicode_literals
import sys
import os
import re
import mimetypes
from copy import copy
from importlib import import_module
from io import BytesIO
from django.conf import settings
from django.contrib.auth import authenticate, login, logout, get_user_model
from django.core.handlers.base import Ba... | nnot read more than the available bytes from the HTTP incoming data."
content = self.__content.read(num_bytes)
self.__len -= num_bytes
return content
def write(self, content):
| if self.read_started:
raise ValueError("Unable to write a payload after he's been read")
content = force_bytes(content)
self.__content.write(content)
self.__len += len(content)
def closing_iterator_wrapper(iterable, close):
try:
for item in iterable:
... |
ii0/bits | python/einj.py | Python | bsd-3-clause | 23,447 | 0.004478 | # Copyright (c) 2015, Intel Corporation
# 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 condit... | atal or error_type.pci_express_uncorrectable_fatal:
error_type, flags, segment, bus, device, function = val | ue
pcie_error = acpi.set_error_type_with_addr.from_address(entry.register_region.address)
print('WRITE_REGISTER SET_ERROR_TYPE_WITH_ADDRESS address - {0:#x}'.format(entry.register_region.address))
pcie_error.error_type = error_type
pcie_error.flags = flags
pci... |
mikalstill/nova | nova/api/openstack/placement/exception.py | Python | apache-2.0 | 6,885 | 0.000436 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | msg_fmt = _("Policy does not allow %(action)s to be performed.")
class ResourceClassCannotDeleteStandard | (_BaseException):
msg_fmt = _("Cannot delete standard resource class %(resource_class)s.")
class ResourceClassCannotUpdateStandard(_BaseException):
msg_fmt = _("Cannot update standard resource class %(resource_class)s.")
class ResourceClassExists(_BaseException):
msg_fmt = _("Resource class %(resource_c... |
macknowak/vrepsim | vrepsim/base.py | Python | gpl-3.0 | 699 | 0 | # -*- coding: utf-8 -*-
"""Assorted base data structures.
Assorted base data structures provide a generic com | municator with V-REP
simulator.
"""
from vrep | sim.simulator import get_default_simulator
class Communicator(object):
"""Generic communicator with V-REP simulator."""
def __init__(self, vrep_sim):
if vrep_sim is not None:
self._vrep_sim = vrep_sim
else:
self._vrep_sim = get_default_simulator(raise_on_none=True)
... |
Asana/boto | boto/rds2/layer1.py | Python | mit | 159,859 | 0.00015 | # Copyright (c) 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 ... | ceeded": exceptions.DBParameterGroupQuotaExceeded,
"DBSubnetGroupAlreadyExists": exceptions.DBSubnetGroupAlreadyExists,
"DBSubnetGroupQuotaExceeded": exceptions.DBSubnetGroupQuotaExceeded,
"InstanceQuotaExceeded": exceptions.InstanceQuotaExceeded,
"InvalidRestore": exceptions.InvalidRest... | horizationQuotaExceeded,
"DBSecurityGroupAlreadyExists": exceptions.DBSecurityGroupAlreadyExists,
"InsufficientDBInstanceCapacity": exceptions.InsufficientDBInstanceCapacity,
"ReservedDBInstanceQuotaExceeded": exceptions.ReservedDBInstanceQuotaExceeded,
"DBSecurityGroupNotFound": excepti... |
Shaps/ansible | test/units/plugins/cache/test_cache.py | Python | gpl-3.0 | 5,922 | 0.001013 | # (c) 2012-2015, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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) an... | self.cache['cache_key']['key2'] == 'updatedvalue'
class TestFactCache(unittest.TestCase):
def setUp(self):
with mock.patch('ansible.constants.CACHE_PLUGIN', 'memory'):
self.cache = FactCache()
def test_copy(self):
self.cache['avocado'] = 'fruit'
self.cache['daisy'] = 'fl... | ='flower'))
def test_plugin_load_failure(self):
# See https://github.com/ansible/ansible/issues/18751
# Note no fact_connection config set, so this will fail
with mock.patch('ansible.constants.CACHE_PLUGIN', 'json'):
self.assertRaisesRegexp(AnsibleError,
... |
pdm126/rss-crawler | dev.py | Python | mit | 4,063 | 0.03618 | #!/usr/bin/env python2.7
import feedparser
import sys
import string
# holds the feeds
feeds = []
Feed_list = []
kill = 'g'
tags = 'g'
# multiple feed list ... | ll == 'y':
menu()
def quick_list():
# option c line by line
for feed in feeds:
for post in feed.entries:
pri | nt post.title
print post.link
print '+++++'
kill == raw_input('next? ')
if kill == 'y':
menu()
# deals with keywords
def keyword_titl... |
kyokyos/bioinform | HBV_APRI_FIB4.py | Python | unlicense | 1,993 | 0.038821 | # -*- coding: utf-8 -*-
"""
Spyder Editor
APRI和FIB4推测肝纤维化或肝硬化情况
This is a temporary script file.
"""
import math
#APRI缩写:AST to Platelet Ratio Index
#AST单位iu/l
#PRI单位10**9/L
#如果APRI>2,可能有肝硬化
def APRI(AST,upper_AST,PRI):
apri=((AST*1.0/upper_AST)*100)/PRI
return apri
#FIB-4缩写Fibrosis-4
#age单位:年
#AST和ALT单... | ng():
print("因算法不断改进,计算结果仅供参考。请随访感染科或肝病科专业医生")
def Print_unit():
print("生化指标来自肝功检测和血常规检测")
print("AST单位:iu/l")
print("ALT单位:U/L")
p | rint("PRI单位:10**9/L")
print("年龄单位:年")
print("U/L和iu/L一般可以通用,前者是中国单位,后者是国际单位")
#提示
Print_warming()
#输出生化值单位
print("-"*30)
Print_unit()
print("-"*30)
print("")
print("")
#输入参数
print("请输入以下参数(例如10,23.5等等):")
AST=float(input("天门冬氨酸转移酶值(AST):"))
upper_AST=float(input("天门冬氨酸转移酶(AST)上限值:"))
ALT=float(input(... |
dshyshov/MAVProxy | MAVProxy/modules/mavproxy_calibration.py | Python | gpl-3.0 | 3,874 | 0.003872 | #!/usr/bin/env python
'''calibration command handling'''
import time, os
from pymavlink import mavutil
from MAVProxy.modules.lib import mp_module
class CalibrationModule(mp_module.MPModule):
def __init__(self, mpstate):
super(CalibrationModule, self).__init__(mpstate, "calibration")
self.add_comm... | ompass/motor interference calibration')
self.add_command('calpress', self.cmd_calpressure,'calibrate pressure sensors')
self.add_command('accelcal', self.cmd_accelcal, 'do 3D accelerometer calibration')
self.add_command('gyrocal', self.cmd_gyrocal, 'do gyro calibration')
self.accelcal_co... | cal_wait_enter = False
self.compassmot_running = False
self.empty_input_count = 0
def cmd_ground(self, args):
'''do a ground start mode'''
self.master.calibrate_imu()
def cmd_level(self, args):
'''run a accel level'''
self.master.calibrate_level()
def cmd_a... |
cliftonmcintosh/openstates | openstates/hi/events.py | Python | gpl-3.0 | 3,151 | 0.001269 | from openstates.utils import LXMLMixin
import datetime as dt
from pupa.scrape import Scraper, Event
from .utils import get_short_codes
from requests import HTTPError
import pytz
URL = "http://www.capitol.hawaii.gov/upcominghearings.aspx"
class HIEventScraper(Scraper, LXMLMixin):
def get_related_bills(self, hre... | t_content().strip()
where = tds[3].text_content().strip()
notice = tds[4].xpath(".//a")[0]
notice_href = notice.attrib['href']
notice_name = notice.text
when = d | t.datetime.strptime(when, "%m/%d/%Y %I:%M %p")
when = pytz.utc.localize(when)
event = Event(name=descr, start_time=when, classification='committee-meeting',
description=descr, location_name=where, timezone=tz.zone)
if "/" in committee:
commi... |
sarvex/tensorflow | tensorflow/python/keras/tests/add_loss_correctness_test.py | Python | apache-2.0 | 16,393 | 0.007137 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | self.bias(inputs[0])
self.add_loss(MAE()(inputs[1], outputs, inputs[2]))
self.add_loss(math_ops.reduce_m | ean(inputs[2] * mae(inputs[1], outputs)))
return outputs
model = MyModel()
model.predict([self.x, self.y, self.w])
model.compile(
optimizer_v2.gradient_descent.SGD(0.05),
run_eagerly=testing_utils.should_run_eagerly())
history = model.fit([self.x, self.y, self.w], batch_size=3,... |
ChinaNetCloud/nc-backup-py | nc-backup-py/tests/backup_main_commands_test.py | Python | apache-2.0 | 293 | 0.010239 | import unittest
impor | t config_test
from backupcmd.commands import backupCommands
class BackupCommandsTestCase(unittest.TestCase):
"""Test commands passed to main script"""
def test_hyphen_r_option(self):
print 'Pending BackupComm | andsTestCase'
self.assertEqual(1,1)
|
anthraxx/pwndbg | pwndbg/commands/mprotect.py | Python | mit | 2,402 | 0.000833 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import gdb
import pwndbg.chain
import pwndbg.commands
import pwndbg.enhance
import pwndbg.file
import pwndbg.which
import pwndbg.wrappers.checksec
import pwndbg.wrappers.readelf
from pwndbg.color import message
parser = argparse.ArgumentParser(descriptio... | print('mprotect returned {}'.format(pwndbg.regs.rax))
# restore registers and memory
pwndbg.memory.write(saved_rip, saved_instruction_2bytes)
gdb.execute('set $rax={}'.format(saved_rax))
gdb.execute('set $rbx={}'.format(saved_rbx))
gdb.execute('set $rcx={}'.format(saved_rcx))
gdb.execute('set ... | (saved_rdx))
gdb.execute('set $rip={}'.format(saved_rip))
pwndbg.regs.rax = saved_rax
pwndbg.regs.rbx = saved_rbx
pwndbg.regs.rcx = saved_rcx
pwndbg.regs.rdx = saved_rdx
pwndbg.regs.rip = saved_rip
|
xuru/pyvisdk | pyvisdk/do/virtual_hardware_option.py | Python | mit | 1,413 | 0.012031 |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def VirtualHardwareOption(vim, *args, **kwargs):
'''The VirtualHardwareOption data object... | else:
raise InvalidArgumentError("Invalid argum | ent: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
|
VisTrails/VisTrails | vistrails/packages/pipelineEdit/__init__.py | Python | bsd-3-clause | 2,254 | 0.011979 | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah. |
## All rights reserved.
## Contact: contact@ | vistrails.org
##
## This file is part of VisTrails.
##
## "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 t... |
statsmodels/statsmodels | statsmodels/multivariate/tests/test_factor.py | Python | bsd-3-clause | 11,521 | 0.000868 | # -*- coding: utf-8 -*-
import warnings
from statsmodels.compat.pandas import PD_LT_1_4
import os
import numpy as np
import pandas as pd
from statsmodels.multivariate.factor import Factor
from numpy.testing import (assert_equal, assert_array_almost_equal, assert_,
assert_raises, assert_arr... | rs=2, fm="pa", rotate="none", SMC=FALSE, min.err=1e-10)
# b <- cbind(a$loadings[,1], -a$loadings[,2])
# b
# a <- fa(Y, nfactors=2, fm="pa", rotate="Promax", SMC=TRUE, min.err=1e-10)
# b <- cbind(a$loadings[,1], a$loadings[,2])
# b
# a <- fa(Y, n | factors=2, fm="pa", rotate="Varimax", SMC=TRUE, min.err=1e-10)
# b <- cbind(a$loadings[,1], a$loadings[,2])
# b
# a <- fa(Y, nfactors=2, fm="pa", rotate="quartimax", SMC=TRUE, min.err=1e-10)
# b <- cbind(a$loadings[,1], -a$loadings[,2])
# b
# a <- fa(Y, nfactors=2, fm="pa", rotate="oblimin", SMC... |
twamarc/schemaorg | lib/rdflib_jsonld/serializer.py | Python | apache-2.0 | 12,215 | 0.001555 | # -*- coding: utf-8 -*-
"""
This serialiser will output an RDF Graph as a JSON-LD formatted document. See:
http://json-ld.org/
Example usage::
>>> from rdflib.plugin import register, Serializer
>>> register('json-ld', Serializer, 'rdflib_jsonld.serializer', 'JsonLDSerializer')
>>> from rdflib import... | else:
default_graph + | = g
else:
graphs = [graph]
context = self.context
objs = []
for g in graphs:
obj = {}
graphname = None
if isinstance(g.identifier, URIRef):
graphname = context.shrink_iri(g.identifier)
obj[context.id_key] ... |
mortbauer/openfoam-extend-Breeder-other-scripting-PyFoam | PyFoam/Basics/STLFile.py | Python | gpl-2.0 | 6,542 | 0.024152 | # ICE Revision: $Id$
"""Read a STL file and do simple manipulations"""
from os import path
from PyFoam.Error import error
from PyFoam.ThirdParty.six import next as iterNext
class STLFile(object):
"""Store a complete STL-file and do simple manipulations with it"""
noName="<no name given>"
def __init__(... | name",parts[1],"Expected",currentName)
| currentName=None
elif parts[0]=="solid":
currentName=parts[1]
if currentName in patchNames:
keep=False
nextState=False
if keep:
processed.append(l)
elif len(parts... |
olduvaihand/ProjectEuler | src/python/problem074.py | Python | mit | 1,088 | 0.001842 | # -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem074.py
#
# Digit factorial chains
# ======================
# Published on Friday, 16th July 2004, 06:00 pm
#
# The number 145 is well known for the property that the sum of the factorial
# of its | digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less
# well known is 169, in that it produces the longest chain of numbers that link
# back to 169; it t | urns out that there are only three such loops that exist:
# 169 363601 1454 169 871 45361 871 872 45362 872 It is not difficult to
# prove that EVERY starting number will eventually get stuck in a loop. For
# example, 69 363600 1454 169 363601 ( 1454) 78 45360 871 45361 ( 871)
# 540 145 ( 145) Starting w... |
yandex/mastermind | src/cocaine-app/indexes.py | Python | gpl-2.0 | 3,478 | 0.001438 | from Queue import Queue
import elliptics
class SecondaryIndex(object):
def __init__(self, idx, key_tpl, meta_session):
self.idx = idx
self.key_tpl = key_tpl
self.meta_session = meta_session
def __iter__(self):
for idx in self.meta_session.find_all_indexes([self.idx]):
... | f, tag):
idxes = [idx.id for idx in
self.meta_session.clone().find_all_indexes([self.main_idx, self.idx_tpl % tag])]
self.logger.info('Received {0} records from tagged index {1}'.format(
| len(idxes), self.idx_tpl % tag))
processed = 0
for data in self._iter_keys(idxes):
processed += 1
yield data
self.logger.info('Processed {0} records from tagged index {1}'.format(
processed, self.idx_tpl % tag))
def __setitem__(self, key, val):
... |
xbmc/atv2 | xbmc/lib/libPython/Python/Lib/test/test_warnings.py | Python | gpl-2.0 | 3,221 | 0.003105 | import warnings
import os
import unittest
from test import test_support
# The warnings module isn't easily tested, because it relies on module
# globals to store configuration information. | setUp() and tearDown()
# preserve the current settings to avoid bashing them while running tests.
# To capture the warning messages, a replacement for showwarning() is
# used to save warning information in a global variable.
class WarningMessage:
"Holds results of latest | showwarning() call"
pass
def showwarning(message, category, filename, lineno, file=None):
msg.message = str(message)
msg.category = category.__name__
msg.filename = os.path.basename(filename)
msg.lineno = lineno
class TestModule(unittest.TestCase):
def setUp(self):
global msg
... |
rwl/openpowersystem | cpsm/load_model/season.py | Python | agpl-3.0 | 1,789 | 0.00559 | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# 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; version 2 dated June... | ne.ext import db
# >>> imports
class Season(Element):
""" A specified time period of the year, e.g., Spring, Summer, Fall, Winter
"""
# <<< season.attributes
# @generated
# Date season ends
end_date = db.DateTimeProperty()
# Date season starts
start_date = db.DateTimeProperty()
... | pass # season_day_type_schedules
# >>> season.references
# <<< season.operations
# @generated
# >>> season.operations
# EOF -------------------------------------------------------------------------
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.