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 |
|---|---|---|---|---|---|---|---|---|
latteBot/piRAT | piRAT/core.py | Python | apache-2.0 | 1,729 | 0.039329 | import os
import sys
import json
import pdb
class client:
def __init__(self):
self.defaultEncoding = ""
self.system = ""
self.deviceName = ""
self.pythonVersion = ""
self.username = ""
self.cwd = ""
self.filesInCurrentDirectory = ""
self.currentUserID = ""
self.OS = ""
self.serverPort = 0
self.s... | elf.cwd = os.getcwd()
self.filesInCurrentDirectory = os.listdir(os.getcwd())
self.currentUserID = os.getuid()
def determineSystem(self):
# System Dict based upon sys.platform responses in Python
systemDict = {'linux2':'Linux (2.x and 3.x)', 'win32':'Windows',
'cygwin':'Windows/Cyg | win', 'darwin':'Mac OS X', 'os2':'OS/2',
'os2emx':'OS/2 EMX', 'riscos':'RiscOS', 'atheos':'AtheOS',
'freebsd7':'FreeBSD 7', 'freebsd8':'FreeBSD 8', 'freebsd9':'FreeBSD 9',
'freebsd10':'FreeBSD10', 'freebsd11':'FreeBSD 11'}
# Assign the correct sys.platform response to the self.OS value
for key in systemDict:
... |
django-json-api/rest_framework_ember | example/migrations/0008_labresults.py | Python | bsd-2-clause | 1,087 | 0 | # Generated by Django 3.0.3 on 2020-02-06 10:24
import django.db | .models.deletion
from django.db import migrations, mode | ls
class Migration(migrations.Migration):
dependencies = [
("example", "0007_artproject_description"),
]
operations = [
migrations.CreateModel(
name="LabResults",
fields=[
(
"id",
models.AutoField(
... |
ICTU/quality-time | components/collector/src/source_collectors/anchore_jenkins_plugin/source_up_to_dateness.py | Python | apache-2.0 | 312 | 0.00641 | """Anchore Jenkins plugin source up- | to-dateness collector."""
from base_collectors import JenkinsPluginSourceUpToDatenessCollector
class AnchoreJenkinsPluginSourceUpToDateness(JenkinsPluginSourceUpToDatenessCollector):
"""Co | llector for the up to dateness of the Anchore Jenkins plugin security report."""
|
Preston4tw/elearning | coursera/algo-pt1/week4/graph_primitives.py | Python | mit | 3,909 | 0.005116 | import itertools
def topological_order(graph):
global current_label
current_label = len(graph)
global label_offset
label_offset = -1
global ordered_graph
ordered_graph = {}
explored_nodes = []
for node in graph:
if node not in explored_nodes:
explored_nodes.extend(df... | = 1
global ordered_graph
ordered_graph = {}
for node in reversed(list(reversed_graph.keys())):
if node not in reversed | _graph_explored_nodes:
reversed_graph_explored_nodes.extend(
dfs(reversed_graph,
node,
explored_nodes=reversed_graph_explored_nodes
)
)
return ordered_graph
def get_strongly_connected_components(graph):
# Kosaraju t... |
DigitalCampus/django-oppia | gamification/models.py | Python | gpl-3.0 | 2,912 | 0 | # oppia/gamification/models.py
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from oppia.models import Course, Activity, Media
class DefaultGamificationEvent(models.Model):
GLOBAL = 'global'
CO... | elf):
return self.default_event.helper_text
class CourseGamificationEvent(GamificationEvent):
course = models.ForeignKey(Course,
on_delete=models.CASCADE,
related_name='gamification_events')
| class Meta:
verbose_name = _(u'Course Gamification Event')
verbose_name_plural = _(u'Course Gamification Events')
class ActivityGamificationEvent(GamificationEvent):
activity = models.ForeignKey(Activity,
on_delete=models.CASCADE,
r... |
snorecore/MincePi | mince/colours.py | Python | mit | 856 | 0.004673 | ''' Colour code '''
import webcolors
from operator import itemgetter
# Replacing Matplotlib code with webcolors
CNAMES = webcolors.css3_names_to_hex
# Special gradients
gradients = {}
# Colours from images
def top_colours(image, n):
''' Return top-n colours in the image with counts. '''
size = image.size[0] ... | s]
def common_colours(image, min_prop=0.01):
''' Return all colours in image above a certain proportion threshold'''
size = image.size[0] * image.size[1]
counts = image.getcolors(size)
min_num = size * min_prop
counts = sorted(counts, key=itemgetter(0), reverse=True)
counts = [(y, float(x)... | ]
return counts
|
ainterr/scoring_engine | engine/templatetags/dyn_form.py | Python | mit | 144 | 0.006944 | from django import template
from .. import forms
register = template.Library()
@register.filt | er
def dyn_form(forms, pk):
return | forms[pk]
|
miklos1/watton | measure.py | Python | mit | 1,052 | 0 | import math
import numpy as np
from firedrake import *
from | pyop2 import MPI
from pyop2.profiling import Timer
parameters["pyop2_options"]["profiling"] = True
def measure(name, thunk):
if MPI.comm.rank == 0:
print "name:", name
mesh = thunk()
mesh.init()
timer = Timer("Mesh: cell_closure (quadrilateral)")
runtime = timer._timings[- | 1]
sendbuf = np.array([runtime, runtime * runtime], dtype=float)
recvbuf = MPI.comm.reduce(sendbuf)
if MPI.comm.rank == 0:
M1, M2 = recvbuf
m = M1 / MPI.comm.size
s = math.sqrt((M2 - M1*M1 / MPI.comm.size) / (MPI.comm.size - 1))
print "cell_closure seconds %s: %g +- %g" % (na... |
vulcansteel/autorest | AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/auto_rest_parameter_grouping_test_service/operations/parameter_grouping_operations.py | Python | mit | 11,840 | 0.00228 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | t response alongside the
deserialized response
:rtype: None or (None, requests.response) or concurrent.futures.Future
"""
custom_header = None
if parameter_grouping_post_optional_parameters is not None:
custom_header = parameter_grouping_post_optional_parameters.custo... | ters is not None:
query = parameter_grouping_post_optional_parameters.query
# Construct URL
url = '/parameterGrouping/postOptional'
# Construct parameters
query_parameters = {}
if query is not None:
query_parameters['query'] = self._serialize.query("quer... |
CalebM1987/serverAdminTools | serverAdminTools/restapi/rest_utils.py | Python | gpl-3.0 | 41,101 | 0.003358 | """Helper functions and base classes for restapi module"""
from __future__ import print_function
import requests
import fnmatch
import datetime
import collections
import mimetypes
import urllib
import tempfile
import time
import codecs
import json
import copy
import os
import sys
import munch
from itertools import izip... | nal:
params -- query parameters, user is responsible for passing in the
proper parameters
"""
frmat = params.get(F, JSON)
if F in params:
del params[F]
p = '&'.join('{}={}'.format(k,v) for k,v in params.iteritems())
# probably a better way t | o do this...
return requests.post('{}?{}?f={}&{}'.format(proxy, url, frmat, p).rstrip('&'), verify=False, headers={'User-Agent': USER_AGENT})
def guess_proxy_url(domain):
"""grade school level hack to see if there is a standard esri proxy available for a domain
Required:
domain -- url to domain to... |
bioinfocao/pysapc | pysapc/sparseMatrixPrepare.py | Python | bsd-3-clause | 8,514 | 0.024078 | """
Prepare Sparse Matrix for Sparse Affinity Propagation Clustering (SAP)
"""
# Authors: Huojun Cao <bioinfocao at gmail.com>
# License: BSD 3 clause
import numpy as np
import pandas as pd
import sparseAP_cy # cython for calculation
####################################################################################... | copyData=df[(df.col==ind) & (df.row!=ind)].sort_values(['data']).copy()
copyData_min=copyData[0:1]
copy_row_list+=list(copyD | ata_min.col)
copy_col_list+=list(copyData_min.row)
copy_data_list+=list(copyData_min.data)
rowBased_row_array=np.concatenate((rowBased_row_array,copy_row_list))
rowBased_col_array=np.concatenate((rowBased_col_array,copy_col_list))
rowBased_data_array=np.concatenate((rowBased_data_array,copy_... |
bmr-cymru/boom | tests/config_tests.py | Python | gpl-2.0 | 4,151 | 0.001686 | # Copyright (C) 2017 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.com>
#
# config_tests.py - Boom report API tests.
#
# This file is part of the boom project.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU Genera... | configura | tion file.
"""
with self.assertRaises(ValueError) as cm:
load_boom_config()
# vim: set et ts=4 sw=4 :
|
skevy/django | django/contrib/formtools/preview.py | Python | bsd-3-clause | 5,860 | 0.003072 | """
Formtools Preview application.
"""
try:
import cPickle as pickle
except ImportError:
import pickle
from django.conf import settings
from django.http import Http404
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.crypto import constant_ti... | for the form. Needed when
rendering two form previews in the same template.
"""
return AUTO_ID
def get_initial(self, request):
| """
Takes a request argument and returns a dictionary to pass to the form's
``initial`` kwarg when the form is being created from an HTTP get.
"""
return {}
def get_context(self, request, form):
"Context for template rendering."
return {'form': form, 'stage_field':... |
aequitas/home-assistant | homeassistant/components/google_assistant/const.py | Python | apache-2.0 | 3,816 | 0 | """Constants for Google Assistant."""
from homeassistant.components import (
binary_sensor,
camera,
climate,
cover,
fan,
group,
input_boolean,
light,
lock,
media_player,
scene,
script,
switch,
vacuum,
)
DOMAIN = 'google_assistant'
GOOGLE_ASSISTANT_API_ENDPOINT = ... | mate', 'cover', 'fan', 'group', 'input_boolean', 'light',
'media_player', 'scene', 'script', 'switch', 'vacuum', 'lock',
'binary_sensor', 'sensor'
]
PREFIX_TYPES = 'action.devices.types.'
TYPE_CAMERA = PREFIX_TYPES + 'CAMERA'
TYPE_LIGHT = PREFIX_TY | PES + 'LIGHT'
TYPE_SWITCH = PREFIX_TYPES + 'SWITCH'
TYPE_VACUUM = PREFIX_TYPES + 'VACUUM'
TYPE_SCENE = PREFIX_TYPES + 'SCENE'
TYPE_FAN = PREFIX_TYPES + 'FAN'
TYPE_THERMOSTAT = PREFIX_TYPES + 'THERMOSTAT'
TYPE_LOCK = PREFIX_TYPES + 'LOCK'
TYPE_BLINDS = PREFIX_TYPES + 'BLINDS'
TYPE_GARAGE = PREFIX_TYPES + 'GARAGE'
TYPE_O... |
innotechsoftware/Quantum-GIS | python/plugins/fTools/tools/doSpatialIndex.py | Python | gpl-2.0 | 7,344 | 0.03908 | # -*- coding: utf-8 -*-
"""
***************************************************************************
doSpatialIndex.py - build spatial index for vector layers or files
--------------------------------------
Date : 11-Nov-2011
Copyright : (C) 2011 by Alexander Bruy
Ema... | iles.setEnabled( False )
self.btnClearList.setEnabled( | False )
self.fillLayersList()
def fillLayersList( self ):
self.lstLayers.clear()
layers = ftools_utils.getLayerNames( [ QGis.Line, QGis.Point, QGis.Polygon ] )
for lay in layers:
source = ftools_utils.getVectorLayerByName( lay ).source()
item = QListWidgetItem( lay, self.lstLayers )
... |
whoww/peel-flink-kmeans | VarianceBenchmarkResults/AccuracyMeasure.py | Python | apache-2.0 | 815 | 0.001227 | #!/usr/bin/env python
import csv, sys
mapping = {}
totalTruth, totalTesting, hit, miss, errors = (0, 0, 0, 0, 0)
with open(sys.argv[1], 'rb') as groundtruth:
reader = csv.reader(groundtruth)
| for row in reader:
| totalTruth += 1
mapping[(row[1], row[2])] = row[0]
with open(sys.argv[2], 'rb') as testing:
reader = csv.reader(testing)
for row in reader:
totalTesting += 1
try:
if (mapping[(row[1], row[2])] == row[0]):
hit += 1
else:
miss ... |
DmZ/ajenti | plugins/notepad/__init__.py | Python | lgpl-3.0 | 192 | 0.005208 | MODULES = ['main', | 'config']
DEPS = []
NAME = | 'Notepad'
PLATFORMS = ['any']
DESCRIPTION = 'Configuration files editor'
VERSION = '0.1'
AUTHOR = 'Ajenti team'
HOMEPAGE = 'http://ajenti.org'
|
pinax/pinax-eventlog | pinax/eventlog/compat.py | Python | mit | 379 | 0 | """
For Django < 3.1, rely on django-jsonfield-backport for | JSONField
functionality
https://github.com/laymonage/django-jsonfield-backport#installation | ERROR: type should be string, got "\nhttps://github.com/laymonage/django-jsonfield-backport#why-create-another-one\n\"\"\"\n\ntry:\n from django.db.models import JSONField # noqa\nexcept ImportError:\n from django_jsonfield_backport.models import JSONField # noqa\n" |
0359xiaodong/viewfinder | backend/op/update_follower_op.py | Python | apache-2.0 | 4,084 | 0.008815 | # Copyright 2013 Viewfinder Inc. All Rights Reserved.
"""Viewfinder UpdateFollowerOperation.
This operation update's follower metadata for a user.
"""
__authors__ = ['mike@emailscrubbed.com (Mike Purtell)',
'andy@emailscrubbed.com (Andy Kimball)']
import json
import logging
from tornado import gen
f... | ser_id, self._viewpoint_id))
self._viewpoint = yield gen.Task(Viewpoint.Query, self._client, self._viewpoint_id, None)
if 'labels' in self._foll_dict:
self._follower.SetLabels(self._foll_dict['labels'])
@gen.coroutine
def _Update(self):
"""Updates the database:
1. Updates the follower me... | lf._foll_dict['labels']), \
(self._foll_dict, self._follower.labels)
if 'viewed_seq' in self._foll_dict:
# Don't allow viewed_seq to exceed update_seq.
if self._foll_dict['viewed_seq'] > self._viewpoint.update_seq:
self._foll_dict['viewed_seq'] = self._viewpoint.update_seq
# R... |
mithrandi/treq | src/treq/test/test_testing.py | Python | mit | 17,263 | 0 | """
In-memory treq returns stubbed responses.
"""
from functools import partial
from inspect import getmembers, isfunction
from mock import ANY
from six import text_type, binary_type
from twisted.web.client import ResponseFailed
from twisted.web.error import SchemeNotSupported
from twisted.web.resource import Resour... | mport _PY3
import treq
from treq.test.util import TestCase
from treq.testing import (
HasHeaders,
RequestSequence,
StringStubbingResource,
StubTreq
)
class _StaticTestResource(Resource):
"""Resource that always returns 418 "I'm a teapot"""
isLeaf = True
def render(self, request):
... | teapot", b"teapot!")
return b"I'm a teapot"
class _NonResponsiveTestResource(Resource):
"""Resource that returns NOT_DONE_YET and never finishes the request"""
isLeaf = True
def render(self, request):
return NOT_DONE_YET
class _EventuallyResponsiveTestResource(Resource):
"""
Res... |
sam-m888/addons-source | libwebconnect/libwebconnect.gpr.py | Python | gpl-2.0 | 516 | 0.027132 | #------ | ------------------------------------------------------------------
#
# Register the Addon
#
#------------------------------------------------------------------------
register(GENERAL,
id="libwebconnect",
name="libwebconnect",
description = _("Libr | ary for web site collections"),
status = STABLE, # not yet tested with python 3
version = '1.0.29',
gramps_target_version = "5.1",
fname="libwebconnect.py",
load_on_reg = True,
)
|
Unix4ever/spike | common/config.py | Python | mit | 1,403 | 0.003564 | import json
import glob
import logging
import os
config = {}
log = logging.getLogger(__name__)
def get(key, default_value=None):
path = key.split(".")
value = config.copy()
for i in path:
if i not in value:
value = None
break
value = value[i]
return value or d... | *folders):
global config
files = []
if not folders:
folders = ["conf.d/*.json"]
for folder in folders:
files.extend(glob.glob(folder))
filtered = []
[filtered.append(i) for i in files if no | t filtered.count(i)]
files = filtered
for f in files:
with open(f, "r") as config_file:
try:
data = json.load(config_file)
except ValueError, e:
log.exception("Failed to read config file %s", f)
continue
config = deep_... |
edisonlz/fruit | web_project/base/site-packages/django/contrib/staticfiles/handlers.py | Python | apache-2.0 | 2,440 | 0.00082 | from django.conf import settings
from django.core.handlers.base import get_path_info
from django.core.handlers.wsgi import WSGIHandler
from django.utils.six.moves.urllib.parse import urlparse
from django.utils.six.moves.urllib.request import url2pathname
from django.contrib.staticfiles import utils
from django.contrib... | relative path to the media file on disk for the given URL.
"""
relative_url = url[len(self.base_url[2]):]
return url2pathname(relative_url)
def serve(self, request):
" | ""
Actually serves the request path.
"""
return serve(request, self.file_path(request.path), insecure=True)
def get_response(self, request):
from django.http import Http404
if self._should_handle(request.path):
try:
return self.serve(request)
... |
felipenaselva/repo.felipe | plugin.video.exodus/resources/lib/sources/pftv_tv.py | Python | gpl-2.0 | 5,225 | 0.010718 | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 l... | 8')
sources.append({'source': host, 'quality': 'SD', 'provider': 'PFTV', 'url': url, 'direct': False, 'debridonly': False})
except:
pass
return sources
except:
return | sources
def resolve(self, url):
try:
r = proxy.request(url, 'nofollow')
url = client.parseDOM(r, 'a', ret='href', attrs = {'rel': 'nofollow'})
url = [i for i in url if not urlparse.urlparse(self.base_link).netloc in i]
url = client.replaceHTMLCodes(url[0])... |
stdweird/aquilon | upgrade/1.4.5/aquilon/aqdb/model/machine_specs.py | Python | apache-2.0 | 4,639 | 0.006036 | # -*- cpy-indent- | level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,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 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 express or implied.
# See the License ... |
simodalla/mezzanine_mailchimper | project_template/settings.py | Python | bsd-3-clause | 14,784 | 0.000271 | from __future__ import absolute_import, unicode_literals
######################
# MEZZANINE SETTINGS #
######################
# The following settings are already defined with default values in
# the ``defaults.py`` module within each of Mezzanine's apps, but are
# common enough to be put here, commented out, for con... | a field to *all* of Mezzanine's content types:
# (
# "mezzanine.pages.models.Page.another_field",
# "IntegerField", # 'django.db.models.' is implied if path is omitted.
# ("Another name",),
# {"blank": True, "default": 1},
# ),
# )
# Setting to turn on featured images for blog | posts. Defaults to False.
#
# BLOG_USE_FEATURED_IMAGE = True
# If True, the south application will be automatically added to the
# INSTALLED_APPS setting.
USE_SOUTH = True
########################
# MAIN DJANGO SETTINGS #
########################
# People who get code error notifications.
# In the format (('Full N... |
nrc/dxr | dxr/plugins/omniglot/htmlifier.py | Python | mit | 10,987 | 0.001547 | import marshal
import os
import subprocess
import urlparse
import dxr.plugins
"""Omniglot - Speaking all commonly-used version control systems.
At present, this plugin is still under development, so not all features are
fully implemented.
Omniglot first scans the project directory looking for the hallmarks of a VCS
... | return path not in self.untracked_files
def get_rev(self, path):
"""Return a human-readable revision identifier for the repository."""
raise NotImplemented
def generate_log(self, path):
"""Return a URL for a page that lists revisions for this file."""
raise NotImplemente... | raise NotImplemented
def generate_diff(self, path):
"""Return a URL for a page that shows the last change made to this file.
"""
raise NotImplemented
def generate_raw(self, path):
"""Return a URL for a page that returns a raw copy of this file."""
raise NotImple... |
flumotion-mirror/flumotion | flumotion/component/effects/videoscale/admin_gtk.py | Python | lgpl-2.1 | 4,782 | 0.000209 | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modified under the terms of
# the GNU Lesser General Pub... | = self.wtree.get_widget('videoscale-par_d')
self._is_square = self.wtree.get_widget('vi | deoscale-is_square')
self._add_borders = self.wtree.get_widget('videoscale-add_borders')
self._apply = self.wtree.get_widget('videoscale-apply')
# do the callbacks for the mode setting
self._height.connect('value-changed', self._cb_height)
self._width.connect('value-changed', se... |
UFRB/chdocente | cadastro/views.py | Python | agpl-3.0 | 13,491 | 0.005275 | # -*- coding: utf-8 -*-
import unicodecsv
from collections import Counter
from django.http import HttpResponse
from django.shortcuts import render
from .models import Disciplina, Docente, Pesquisa, Extensao, Administrativo
def query_estudantes(query):
result = [
['1-6', query.filter(estudantes__gte=... | num_docentes_extensao = len(docentes_extensao)
num_docentes_afastados = docentes_admin.filter(afastamento=True) \
.distinct('docente').count()
docentes_admin = docentes_admin \
.filter(cargo__in=['fg', 'cd', 'fuc'])
ensino = [
['Com atividades de ensino', num_docentes_ensino],
... | 'Sem atividades de pesquisa', num_docentes - num_docentes_pesquisa]
]
extensao = [
['Com atividades de extensão', num_docentes_extensao],
['Sem atividades de extensão', num_docentes - num_docentes_extensao]
]
ens_pes_ext = [
['Sim', len(docentes_ens_pes_ext)],
[... |
Dan-Donovan/cs3240-labdemo | helperMaster.py | Python | mit | 30 | 0.066667 | p | rint ("ssimiliar to develop") | |
P0cL4bs/3vilTwinAttacker | plugins/external/sergio_proxy/plugins/CacheKill.py | Python | gpl-3.0 | 952 | 0.015756 | from plugins.external.sergio_proxy.plugins.plugin import Plugin
class CacheKill(Plugin):
name = "CacheKill Plugin"
optname = "cachekill"
desc = "Kills page | caching by modifying headers."
implements = ["handleHeader","connectionMade"]
has_opts = True
bad_headers = ['if-none-match','if-modified-since']
| def add_options(self,options):
options.add_argument("--preserve-cookies",action="store_true",
help="Preserve cookies (will allow caching in some situations).")
def handleHeader(self,request,key,value):
'''Handles all response headers'''
request.client.headers['Expires'] =... |
SnowWalkerJ/quantlib | quant/data/wind/tables/cbondspecialconditions.py | Python | gpl-3.0 | 1,754 | 0.011139 | from ....common.db.sql import VARCHAR, Numeric as NUMBER, DateTime as DATETIME, Column, BaseModel, CLOB, DATE
VARCHAR2 = VARCHAR
class CBondSpecialC | onditions(BaseModel):
"""
4.127 中国债券特殊条款
Attributes
----------
object_id: VARCHAR2(100)
对象ID
s_info_windcode: VARCHAR2(40)
Wind代码
b_info_provisiontype: VARCHAR2(100)
条款类型
b_info_callbkorputbkprice: NUMBER(20,4)
赎回价/回售价 元
b_info_callbkorputb... | ded: VARCHAR2(40)
含权期限说明
b_info_execmaturityembedded: NUMBER(20,4)
行权期限
b_info_couponadj_max: NUMBER(20,4)
票面利率调整上限
b_info_couponadj_min: NUMBER(20,4)
票面利率调整下限
b_info_content: VARCHAR2(3000)
条款内容
opdate: DATETIME
opdate
opmode: VA... |
Yipit/troposphere | troposphere/dynamodb.py | Python | bsd-2-clause | 2,797 | 0.000358 | # Copyright (c) 2012-2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
import warnings
from . import AWSHelperFn, AWSObject, AWSProperty
warnings.warn("This module is outdated and will be replaced with "
"troposphere.dynamodb2. Please see the README for "
... | .data
class ProvisionedThroughput(AWSHelperFn):
def __init__(self, ReadCapacityUnits, WriteCapacityUnits):
self.data = {
'ReadCapacityUnits': ReadCapacityUnits,
'WriteCapacityUnits': WriteCapacityUnits,
}
def JSONrepr(self):
return self.dat | a
class Projection(AWSHelperFn):
def __init__(self, ProjectionType, NonKeyAttributes=None):
self.data = {
'ProjectionType': ProjectionType
}
if NonKeyAttributes is not None:
self.data['NonKeyAttributes'] = NonKeyAttributes
def JSONrepr(self):
return sel... |
srz-zumix/wandbox-api | wandbox/__ghc__.py | Python | mit | 4,680 | 0.000427 | import glob
import os
import re
import yaml
from argparse import ArgumentParser
from .runner import Runner
from .cli import CLI
class GhcRunner(Runner):
IMPORT_REGEX = re.compile(r'^\s*import\s+(.*?)$')
def reset(self):
self.required = []
self.incdirs = []
def make_code(self, file, fil... | th open('package.yaml', 'r') as yml:
config = yaml.safe_load(yml)
exec_config = config['executables']['haskell-stack-exe']
main = exec_config['main']
main_dir = exec_config['source-dirs']
run_options.append(os.path.join(main_dir, main))
options = e... | for dir in dirs:
cmd.libdirs.append(dir)
for x in glob.glob(os.path.join(dir, '*.hs')):
run_options.append(x)
cmd.execute_with_args(cli_options + run_options)
def ghc(compiler=None):
cli = GhcCLI(compiler)
cli.execute()
def haskell_stac... |
wuga214/Django-Wuga | env/lib/python2.7/site-packages/markdownx/fields.py | Python | apache-2.0 | 1,070 | 0.004673 | from django import forms
from .widgets import MarkdownxWidget
class MarkdownxFormField(forms.CharField):
"""
Used in FormFields as a Markdown enabled replacement for ``CharField``.
"""
def __init__(self, *args, **kwargs):
"""
Arguments are similar to Django's default ``CharField``.
... | issubclass(item.__class__, MarkdownxWidget)
for item in getattr(self.widget, 'widgets', list())
)
if not is_markdownx_widget:
self.widget = MarkdownxWidget()
elif not issubclass(self. | widget.__class__, MarkdownxWidget):
self.widget = MarkdownxWidget()
|
sidnarayanan/BAdNet | train/pf/adv/models/train_panda_3.py | Python | mit | 9,427 | 0.017079 | #!/usr/local/bin/python2.7
from sys import exit, stdout, argv
from os import environ, system
environ['KERAS_BACKEND'] = 'tensorflow'
import numpy as np
import utils
import signal
from keras.layers import Input, Dense, Dropout, concatenate, LSTM, BatchNormalization, Conv1D, concatenate
from keras.models import Model ... | eps_per_epoch=1000,
epochs=2)
save_classifier(name='pretrained_conv')
# np.set_printoptions(threshold='nan')
# print test_o
# print classifier.predict(test_i)
def save_and_exit(signal=None, frame=None, name='regularized_conv', model=c | lassifier):
save_classifier(name, model)
flog.close()
exit(1)
signal.signal(signal.SIGINT, save_and_exit)
print ' -Training the adversarial stack'
# now train the model for real
pivoter.fit_generator(train_gen,
steps_per_epoch=5000,
... |
google-business-communications/bm-bonjour-meal-django-starter-code | bonjourmeal-codelab/full-sample/bmcodelab/settings.py | Python | apache-2.0 | 5,084 | 0.000787 | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ng>
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'Place/your/CloudSQL/hos | tname/here',
'NAME': 'bonjour_meal',
'USER': 'bmdbuser',
'PASSWORD': 'bmdbpassword',
}
}
else:
# Running locally so connect to either a local MySQL instance or connect to
# Cloud SQL via the proxy. To start the proxy via command line:
#
# $ cloud_sql_p... |
alexoneill/15-love | game/core.py | Python | mit | 1,573 | 0.031786 | #!/usr/bin/python2
# core.py
# aoneill - 04/10/17
import sys
import random
import time
import pauschpharos as PF
import lumiversepython as L
SEQ_LIM = 200
def memoize(ignore = None):
if(ignore is None):
ignore = set()
def inner(func):
cache = dict()
def wrapper(*args):
m... | (upload = True, run = True, wipe = True, fire = True):
rig = L.Rig("/home/teacher/Lumiverse/PBridge.rig.json")
rig.init()
# Upload the blank template
if(upload):
blank()
# Run if requested
if(run):
rig.run()
# Wipe if requested
if(wipe):
for seq in xrange(SEQ_LI | M):
query(rig, '$sequence=%d' % seq).setRGBRaw(0, 0, 0)
# Heat up the cache
if(fire and not wipe):
fireplace(rig)
return rig
@memoize(ignore = set([0]))
def query(rig, text):
return rig.select(text)
def seq(rig, num):
return query(rig, '$sequence=%d' % num)
def rand_color():
... |
artemistomaras/django-ethereum-events | runtests.py | Python | mit | 570 | 0 | import os
import sys
import django
from django.conf import | settings
def runtests():
settings_file = 'django_ethereum_events.settings.test'
if not settings.configured:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_file)
django.setup()
from django.test.runner import DiscoverRunner
runner_class = DiscoverRunner
test_args = ['django_e... | ue, failfast=False).run_tests(test_args)
sys.exit(failures)
if __name__ == '__main__':
runtests()
|
muk-it/muk_dms | muk_dms_attachment/models/ir_attachment.py | Python | lgpl-3.0 | 10,186 | 0.005007 | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Attachment
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GN... | port os
import re
import base64
import hashlib
import itertools
import logging
import mimetypes
import textwrap
from collections import defaultdict
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import AccessError, ValidationError
from odoo.tools import config, human_size, ustr, htm... | r = logging.getLogger(__name__)
class DocumentIrAttachment(models.Model):
_inherit = 'ir.attachment'
#----------------------------------------------------------
# Database
#----------------------------------------------------------
store_document = fields.Many2one(
comodel_name='... |
ShashaQin/erpnext | erpnext/hr/doctype/employee/employee.py | Python | agpl-3.0 | 8,327 | 0.023778 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import getdate, validate_email_add, today
from frappe.model.naming import make_autoname
from frappe import throw, _
imp... | frappe.get_doc({
"doctype": "File",
"file_name": self.image,
"attached_to_doctype": "User",
"attached_to_name": self. | user_id
}).insert()
except frappe.DuplicateEntryError:
# already exists
pass
user.save()
def validate_date(self):
if self.date_of_birth and getdate(self.date_of_birth) > getdate(today()):
throw(_("Date of Birth cannot be greater than today."))
if self.date_of_birth and self.date_of_joini... |
duanhun/apk_for_linux | settings.py | Python | apache-2.0 | 47 | 0 | # -*- coding: UT | F-8 -*-
__author__ = 'Jeffrey'
| |
ChopChopKodi/pelisalacarta | python/main-classic/channels/descargacineclasico.py | Python | gpl-3.0 | 6,362 | 0.017781 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Canal para cuevana
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urlparse
from channelselector import get_thum... | sys
for line in sys.exc_info():
logger.error( "%s" % line )
return []
return agregadas(item)
def agregadas(item):
logger.info("[descargacineclasico.py] agregadas")
itemlist = []
'''
# Descarga la pagina
if "?search=" in item.url:
url_search = item.url.split... | ls.cache_page(item.url)
logger.info("data="+data)
'''
data = scrapertools.cache_page(item.url)
logger.info("data="+data)
# Extrae las entradas
fichas = re.sub(r"\n|\s{2}","",scrapertools.get_match(data,'<div class="review-box-container">(.*?)wp-pagenavi'))
#<a href="http://www.descargacin... |
912/M-new | virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/gis/geoip/libgeoip.py | Python | gpl-2.0 | 1,094 | 0.001828 | import os
from ctypes import CDLL
from ctypes.util import find_library
from django.conf import settings
# Creating the settings dictionary with any settings, if needed.
GEOIP_SETTINGS = dict((key, getattr(settings, key))
for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY... | lib_name = None
else:
# TODO: Is this really the library name for Windows?
lib_name = 'GeoIP'
# Getting the path to the GeoIP lib | rary.
if lib_name:
lib_path = find_library(lib_name)
if lib_path is None:
raise RuntimeError('Could not find the GeoIP library (tried "%s"). '
'Try setting GEOIP_LIBRARY_PATH in your settings.' % lib_name)
lgeoip = CDLL(lib_path)
# Getting the C `free` for the platform.
if os.name == 'nt... |
3v1n0/snapcraft | snapcraft/tests/test_meta.py | Python | gpl-3.0 | 27,949 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015-2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | f.write(setup_icon_content)
declared_icon_content = b'declared icon'
with open('my-icon.png', 'wb') as f:
f.write(declared_icon_content)
self.config_data['icon'] = 'my-icon.png'
y = self.generate_meta_yaml()
expected_icon = os.path.join(self.meta_dir, 'gui'... | 'icon.png was not setup correctly')
with open(expected_icon, 'rb') as f:
self.assertEqual(f.read(), declared_icon_content)
self.assertFalse('icon' in y,
'icon found in snap.yaml {}'.format(y))
def test_create_meta_with_declared_icon_and_setup_ran_twice_ok(... |
hzlf/openbroadcast | website/apps/musicbrainzngs/util.py | Python | gpl-3.0 | 1,428 | 0.010504 | # This file is part of the musicbrainzngs library
# Copyright (C) Alastair Porter, Adrian Sampson, and others
# This file is distributed under a BSD-2-Clause type license.
# See the COPYING file for more information.
import sys
import locale
import xml.etree.ElementTree as ET
from . import compat
def _unicode(string... | ing, stdin, preferred until something != None is found
| if encoding is None:
encoding = sys.stdin.encoding
if encoding is None:
encoding = locale.getpreferredencoding()
unicode_string = string.decode(encoding, "ignore")
else:
unicode_string = compat.unicode(string)
return unicode_string.replace('\x00', '').strip()
... |
cduff4464/2016_summer_XPD | out_of_date/reverse_engineer/display2.py | Python | bsd-2-clause | 155 | 0.006452 | """
This file is meant to try the idea of having the diffraction pattern | data appear in
one window, and then give | the user the option of simply having
"""
|
bokeh/bokeh | bokeh/sampledata/degrees.py | Python | bsd-3-clause | 2,054 | 0.008763 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | --------------------
#------------------------------------- | ----------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
data = package_csv(... |
jaap3/django-richtextfield | setup.py | Python | mit | 1,486 | 0.000673 | import os
import sys
from setuptools import setup
version = '1.6.2.dev0'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdis | t bdist_wheel upload')
print("You probably want to also tag the version now:")
print(" git tag -a %s -m 'version %s'" % (version, version))
print(" git push --tags")
sys.exit()
readme = open('README.rst').read()
history = open('HISTORY.rst').read()
setup(
name='django-richtextfield',
version... | history,
author='Jaap Roes',
author_email='jaap.roes@gmail.com',
url='https://github.com/jaap3/django-richtextfield',
packages=[
'djrichtextfield',
],
include_package_data=True,
install_requires=[],
python_requires='>=3.6',
license='MIT',
zip_safe=False,
keywords='dja... |
tdf/tdc | tdc/urls.py | Python | gpl-3.0 | 489 | 0.010225 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from counter.api import router
admin.autodiscove | r()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tdc.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^', include(admin.sit | e.urls)),
url(r'^', include("massadmin.urls")),
url(r'^api/v1/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
|
catsop/CATMAID | django/lib/custom_postgresql_psycopg2/__init__.py | Python | gpl-3.0 | 1,268 | 0.003155 | # This is a hack to disable GDAL support in GeoDjango. It seems there is no
# easier way due to the GDAL_LIBRARY_PATH setting not behaving as documented
# (i.e. setting it to a non-existent file will disable G | DAL). Disabling GDAL is
# unfortunately needed, because it breaks TIFF support for pgmagick, which is
# required by e.g. the cropping back-end. GeoDjan | go loads GDAL into memory
# which a) is a waste of memory if we don't use it and b) on at least Ubuntu
# GDAL seems to be compiled in a way that it takes over TIFF I/O. And this
# causes pgmagick to segfault. This patch is added here, because the database
# engine is the first thing that is loaded which loads GeoDjango... |
czardoz/hornet | hornet/tests/commands/test_ls.py | Python | gpl-3.0 | 45,918 | 0.001503 | # !/usr/bin/env python
#
# Hornet - SSH Honeypot
#
# Copyright (C) 2015 Aniket Panse <aniketpanse@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or... | port == 0: # wait until the server is ready
gevent.sleep(0)
port = honeypot.server.server_port
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# If we log in properly, this should raise no errors
client.connect('127.0.0.1', ... | ecv_ready():
gevent.sleep(0) # :-(
welcome = ''
while channel.recv_ready():
welcome += channel.recv(1)
lines = welcome.split('\r\n')
prompt = lines[-1]
self.assertTrue(prompt.endswith('$ '))
# Now send the ls command
ls_command = 'ls -l'... |
mh21/goobook | goobook/goobook.py | Python | gpl-3.0 | 15,990 | 0.002252 | # vim: fileencoding=UTF-8 filetype=python ff=unix expandtab sw=4 sts=4 tw=120
# maintainer: Christer Sjöholm -- goobook AT furuvik DOT net
# authors: Marcus Nitzschke -- marcus.nitzschke AT gmx DOT com
#
# Copyright (C) 2009 Carlos José Barroso
# Copyright (C) 2010 Christer Sjöholm
#
# This program is free software: ... | for mutt. It's developed in python and uses the fine
google data api (gdata).
'''
import codecs
import email.parser
import email.header
import gdata.service
import itertools
import logging
import os
import pickle
| import re
import sys
import time
import xml.etree.ElementTree as ET
import unicodedata
from storage import Storage, storageify, unstorageify
log = logging.getLogger(__name__)
CACHE_FORMAT_VERSION = '4.0'
G_MAX_SRESULTS = 9999 # Maximum number of entries to ask google for.
GDATA_VERSION = '3'
ATOM_NS = '{http://www.... |
SKA-ScienceDataProcessor/algorithm-reference-library | processing_components/simulation/configurations.py | Python | apache-2.0 | 11,417 | 0.006131 | """Configuration definitions
"""
import numpy
from astropy import units as u
from astropy.coordinates import EarthLocation
from processing_library.util.coordinate_support import xyz_at_latitude
from data_models.memory_data_models import Configuration
from data_models.parameters import arl_path, get_parameter
from pr... | nts)
diameters = numpy.repeat(35.0, nants)
antxyz, diameters, mounts, anames = limit_rmax(antxyz, diameters, anames, mounts, rmax)
fc = Configuration(location=location, names=anames, mount=mounts, xyz=antxyz,
diameter=diameters, name='LOFAR')
return fc
def create_named_con... | LAA, ASKAP
:param rmax: Maximum distance of station from the average (m)
:return:
For LOWBD2, setting rmax gives the following number of stations
100.0 13
300.0 94
1000.0 251
3000.0 314
10000.0 398
30000.0 476
100000.0 512
"""
if... |
jeremiah-c-leary/vhdl-style-guide | vsg/token/selected_waveform_assignment.py | Python | gpl-3.0 | 1,188 | 0 |
from vsg import parser
class with_keyword(parser.keyword):
'''
unique_id = selected_waveform_assignment : with_keyword
'''
def __init__(self, sString):
parser.keyword.__init__(self, sString)
class select_keyword(parser.keyword):
'''
unique_id = selected_waveform_assignment : select... | k
'''
def __init__(self, sString='?'):
parser.question_mark.__init__(self)
class target(parser.target):
'''
unique_id = selected_waveform_assignment : target
'''
def __init__(self, sString):
parser.target.__init__(self, sString)
class assignment(parser.assignment):
'''
... | ing):
parser.assignment.__init__(self, sString)
class semicolon(parser.semicolon):
'''
unique_id = selected_waveform_assignment : semicolon
'''
def __init__(self, sString=';'):
parser.semicolon.__init__(self)
|
rays/ipodderx-core | BitTorrent/zurllib.py | Python | mit | 4,720 | 0.005297 | #
# zurllib.py
#
# This is (hopefully) a drop-in for urllib which will request gzip/deflate
# compression and then decompress the output if a compressed response is
# received while maintaining the API.
#
# by Robert Stone 2/22/2003
# extended by Matt Chisholm
#
from BitTorrent.platform import user_agent
import urllib... | # we need to do something more sophisticated here to deal with
# multiple values? What about other weird crap like q-values?
# basically this only works for the most simplistic case and will
# break in some other cases, but for now we only care about making
# this work with the BT track... | print "Contents of Content-encoding: " + headers['Content-encoding'] + "\n"
self.gzip = 1
self.rawfp = fp
fp = GzipStream(fp)
else:
self.gzip = 0
return addinfourl.__init__(self, fp, headers, url)
def close(self):
self.fp.close()
... |
cburschka/modod | src/modod/lexer.py | Python | mit | 2,843 | 0.003166 | import string
# The lexer knows two classes of symbols:
# - any number of meta-symbols, which match a single meta-charac | ter each.
# this argument is a dic | tionary mapping meta-characters to symbol classes.
#
# - exactly one terminal symbol, which matches a run of any characters
# but ends as soon as a meta-character or a whitespace character
# (not escaped with "\") is encountered.
# whitespace characters delimit a sequence of multiple terminal symbols.
#
#... |
kai06046/labeler | main.py | Python | apache-2.0 | 1,067 | 0.02343 | import logging
import sys
import tkinter as tk
from src.app import Labeler
LOGGER = logging.getLogger(__name__)
# parser = argparse.ArgumentParser(description='Some arguement for path connector')
# parser.add_argument('-m', '--max', type=int, default=300, help='maximum frame for displaying path')
# parser.add_argume... | logger.addHandler(sh)
logger.setLevel(logging.DEBUG)
if __name__ == '__main__':
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)12s:L%(lineno)3s [%(levelname)8s] %(message)s',
datefmt='%Y-%m-%d | %H:%M:%S',
stream=sys.stdout
)
log_handler(LOGGER)
labeler = Labeler()
labeler.run()
|
koolkt/mendoza | tests/smtp_server/test_echo/test_echo.py | Python | gpl-3.0 | 2,153 | 0.002322 | import unittest
import socket
from time import sleep
import subprocess
TESTMSG = 'Hello World'
MSGLEN = len(TESTMSG)
PORT = 3000
class MySocket:
"""demonstration class only
- coded for clarity, not efficiency
"""
def close(self):
self.sock.close()
def __init__(self, sock=None):
... | t.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
| def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = t... |
ssudholt/phocnet | tools/train_phocnet.py | Python | bsd-3-clause | 4,914 | 0.014449 | import argparse
from phocnet.training.phocnet_trainer import PHOCNetTrainer
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# required training parameters
parser.add_argument('--doc_img_dir', action='store', type=str, required=True,
help='The location of the document ima... | ML is separated by | special delimiters, it can be specified here.')
parser.add_argument('--use_lower_case_only', '-ulco', action='store_true', default=False,
help='Flag indicating to convert all annotations from the XML to lower case before proceeding')
params = vars(parser.parse_args())
PHOCNetTrain... |
pbaesse/Sissens | lib/python2.7/site-packages/eventlet/support/dns/rdataset.py | Python | gpl-3.0 | 11,374 | 0.000176 | # Copyright (C) 2001-2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND ... | n, relativize=relativize,
**kw)))
#
# We strip off the final \n for the caller's convenience in printing
#
return s.getvalue()[:-1]
def to_wire(self, name, file, compress=None, origin=None,
override_rdclass=None, want_shuffle=True):
"... | use.
*file* is the file where the name is emitted (typically a
BytesIO file).
*compress*, a ``dict``, is the compression table to use. If
``None`` (the default), names will not be compressed.
*origin* is a ``dns.name.Name`` or ``None``. If the name is
relative and or... |
halonsecurity/halonctl | halonctl/modules/status.py | Python | bsd-3-clause | 576 | 0.027778 | from __future__ import print_function
import six
import datetime
from halonctl.modapi import Module
from halonctl.roles import HTTPStatus
class StatusModule(Module):
'''Checks node statuses'''
def run(self, nodes, args):
yield (u"Cluster", u"Name", u"Address", u"Uptime", u"Status")
for node, | (code, result) in six.iteritems(nodes.service.getUptime()):
if code != 200:
self.partial = True
uptime = datetime.timedelta(seco | nds=result) if code == 200 else None
yield (node.cluster, node, node.host, uptime, HTTPStatus(code))
module = StatusModule()
|
mtbc/openmicroscopy | components/tools/OmeroPy/src/omero/processor.py | Python | gpl-2.0 | 35,039 | 0.004053 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# OMERO Grid Processor
# Copyright 2008 Glencoe Software, Inc. All Rights Reserved.
# Use is subject to license terms supplied in LICENSE.txt
#
import os
import time
import signal
import logging
import traceback
import killableprocess as subprocess
from path import pat... | _path = self.dir / "out"
self.stderr_path = self.dir / "err"
def make_config(self):
"""
Creates the ICE_CONFIG file used by the client.
"""
config_file = open(str(self.config_path), "w")
try:
for key in | self.properties.iterkeys():
config_file.write("%s=%s\n" % (key, self.properties[key]))
finally:
config_file.close()
def tmp_client(self):
"""
Create a client for performing cleanup operations.
This client should be closed as soon as possible
by t... |
Crop-R/django-mediagenerator | mediagenerator/generators/bundles/base.py | Python | bsd-3-clause | 8,535 | 0.001875 | from .settings import DEFAULT_MEDIA_FILTERS
from django.utils.encoding import smart_str
from hashlib import sha1
from mediagenerator.settings import MEDIA_DEV_MODE
from mediagenerator.utils import load_backend, find_file, read_text_file
import os
import time
class Filter(object):
takes_input = True
def __init... |
return self._input_filters
self._input_filters = []
for input in self.input:
if isinstance(input, dict):
filter = self.get_filter(input)
else:
filter = sel | f.get_item(input)
self._input_filters.append(filter)
return self._input_filters
def get_filter(self, config):
backend_class = load_backend(config.get('filter'))
return backend_class(filetype=self.input_filetype, bundle=self.bundle,
**config)
def... |
dkillick/iris | setup.py | Python | lgpl-3.0 | 8,908 | 0.000449 | from __future__ import print_function
from contextlib import contextmanager
from distutils.util import convert_path
import os
from shutil import copyfile
import sys
import textwrap
from setuptools import setup, Command
from setuptools.command.develop import develop as develop_cmd
from setuptools.command.build_py impo... |
if file_name.endswith('pyc') or file_name.endswith('pyo'):
compiled_path = os.path.join(root_path, file_name)
source_path = compiled_path[:-1]
if not os.path.exists(source_path):
print('Cleaning | ', compiled_path)
os.remove(compiled_path)
def compile_pyke_rules(cmd, directory):
# Call out to the python executable to pre-compile the Pyke rules.
# Significant effort was put in to trying to get these to compile
# within this build process but there was no obvious way of findin... |
js850/PyGMIN | pygmin/wham/wham_potential.py | Python | gpl-3.0 | 4,820 | 0.011618 | import numpy as np
from pygmin.potentials.potential import BasePotential
class WhamPotential(BasePotential):
"""
#############################################################################
# the idea behind this minimization procedure is as follows:
##################################################... | ning: many bins will be completely unoccupied for all replicas. This means there will be
a lot of extra work done trying to minimize irrelevant variables. This is fine, just make sure
logP == 0 for all bins with zero visits, not logP = -inf
"""
self.nreps, self.nbins = logP.sh... |
#self.reduced_energy = reduced_energy
if ( np.isinf(self.logP).any() or np.isnan(self.logP).any() ):
print "logP is NaN or infinite"
exit(1)
if False: #see how much effort is wasted
nallzero = len( np.where(np.abs(self.logP.sum(1)) < 1e-10 )[0])
... |
KnowNo/reviewboard | reviewboard/hostingsvcs/utils/tests.py | Python | mit | 7,168 | 0 | from __future__ import unicode_literals
from django.utils.six.moves.urllib.parse import parse_qs, urlsplit
from reviewboard.hostingsvcs.utils.paginator import (APIPaginator,
InvalidPageError,
ProxyPaginator)
from... | self.proxy = ProxyPaginator(self.paginator)
def test_has_prev(self):
"""Testing ProxyPaginator.has_prev"""
self.assertFalse(self.proxy.has_prev)
self.paginator.prev_url = 'http://example.com/?start=1'
self.assertTrue(self.proxy.has_prev)
def test_has | _next(self):
"""Testing ProxyPaginator.has_next"""
self.assertFalse(self.proxy.has_next)
self.paginator.next_url = 'http://example.com/?start=2'
self.assertTrue(self.proxy.has_next)
def test_per_page(self):
"""Testing ProxyPaginator.per_page"""
self.paginator.per_pa... |
eriknelson/gam3 | game/test/test_script.py | Python | mit | 4,405 | 0.002724 | """
Tests for Game scripts.
"""
import sys
from twisted.trial.unittest import TestCase
from twisted.python.failure import Failure
from twisted.internet.defer import Deferred
from twisted.python import log
from twisted.internet import reactor
from game.ui import UI
from game.scripts.network_client import NetworkClien... | the L{Deferred} returned by the UI's C{start} method fires,
L{NetworkClient} stops the reactor.
"""
self.networkClient.run('host', 123)
self.assertEquals(self.reactor.stops, 0)
self.ui.starts[('host', 123)].callback(None)
self.assertEquals(self.reactor.stops, 1)
def... | _stopOnError(self):
"""
If the L{Deferred} returned by the UI's C{start} method fires with a
L{Failure}, the failure is logged and L{NetworkClient} stops the
reactor.
"""
self.networkClient.run('host', 123)
self.ui.starts[('host', 123)].errback(Failure(RuntimeErro... |
masahir0y/buildroot-yamada | support/testing/tests/package/test_python_can.py | Python | gpl-2.0 | 617 | 0 | from tests.package. | test_python import TestPythonPackageBase
class TestPythonPy2Can(TestPythonPackageBase):
__test__ = True
config = TestPythonPackageBase.config + \
"""
BR2_PACKAGE_PYTHON=y
BR2_PACKAGE_PYTHON_CAN=y
"""
sample_scripts = ["tests/package/sample_python_can.py"]
timeout = 40
... | stPythonPackageBase.config + \
"""
BR2_PACKAGE_PYTHON3=y
BR2_PACKAGE_PYTHON_CAN=y
"""
sample_scripts = ["tests/package/sample_python_can.py"]
timeout = 40
|
devilry/devilry-django | devilry/devilry_cradmin/tests/test_devilry_listbuilder/test_assignment.py | Python | bsd-3-clause | 1,305 | 0.005364 | # -*- coding: utf-8 -*-
import htmls
from django import test
from cradmin_legacy import datetimeutils
from model_bakery import baker
from devilry.devilry_cradmin import devilry_listbuilder
class TestItemValue(test.TestCase):
def test_title(self):
testassignment = baker.make('core.Assignment', long_name... | ry_listbuilder.assignment.ItemValue(value=testassignment).render())
self.assertEqual(
'Test Assignment',
selector.one('.cradmin-legacy-listbuilder-item | value-titledescription-title').alltext_normalized)
def test_description(self):
testassignment = baker.make('core.Assignment',
publishing_time=datetimeutils.default_timezone_datetime(2016, 12, 11),
first_deadline=datetimeutils.default_t... |
askomics/askomics | docs/conf.py | Python | agpl-3.0 | 778 | 0 | import os
import sys
from recommonmark.parser import CommonMarkParser
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'askomics'))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
master_doc = 'index'
# The suffix of source filenames.
source_suffix = ['.rst', '.md']
source_parsers = {
... | ath.abspath(os.path.dirname(__file__))
sys | .path.append(parent_folder)
module = os.path.join(parent_folder, 'askomics')
output_path = os.path.join(cur_dir, 'api')
main(['-e', '-f', '-o', output_path, module])
def setup(app):
app.connect('builder-inited', run_apidoc)
|
gabrielf10/webAmpunc | sistema/migrations/0016_auto_20161024_1447.py | Python | bsd-3-clause | 1,903 | 0.001051 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migrati | on):
dependencies = [
( | 'sistema', '0015_aporte'),
]
operations = [
migrations.RenameField(
model_name='aporte',
old_name='total',
new_name='interes',
),
migrations.RenameField(
model_name='servicio',
old_name='cextraordinaria',
new_name='... |
OpenUniversity/ovirt-engine | packaging/setup/plugins/ovirt-engine-common/base/core/misc.py | Python | apache-2.0 | 4,950 | 0 | #
# ovirt-engine-setup -- ovirt engine setup
# Copyright (C) 2013-2015 Red Hat, 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
#
# Unl... | ,
None
)
self.environment[
osetupcons.CoreEnv.ORIGINAL_GENERATED_BY_VERSION
] = self.environment[
osetupcons.CoreEnv.GENERATED_BY_VERSION
]
self.environment[
osetupcons.CoreEnv.GENERATED_BY_VERSION |
] = osetupcons.Const.PACKAGE_VERSION
self.environment.setdefault(
osetupcons.CoreEnv.DEVELOPER_MODE,
None
)
self.environment.setdefault(
osetupcons.CoreEnv.UPGRADE_SUPPORTED_VERSIONS,
'3.0,3.1,3.2,3.3,3.4,3.5,3.6,4.0'
)
s... |
adamtheturtle/flocker | flocker/apiclient/__init__.py | Python | apache-2.0 | 383 | 0 | # Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Client for the Flocker RES | T API.
This may eventually be a standalone package.
"""
from ._client import (
IFlockerAPIV1Client, FakeFlockerClient, Dataset, DatasetState,
DatasetAlreadyExists,
)
__all__ = ["IFlockerAPIV1Client", "FakeFlockerClient", "Dataset",
"Datase | tState", "DatasetAlreadyExists"]
|
bsmr-eve/Pyfa | eos/effects/structuremodifypowerrechargerate.py | Python | gpl-3.0 | 284 | 0.003521 | # structureModifyPowerRechargeRate
#
# Used by:
# Structure Modules from group: Structure Capacitor Power Relay (2 of 2)
type = "passive"
def handler(fit, module, context):
fit.ship.multiplyItemAttr("rechargeRate", module.getModifiedItemAttr("capa | citorRechargeRateMultiplier | "))
|
kobejean/tensorflow | tensorflow/python/ops/ctc_ops.py | Python | apache-2.0 | 11,926 | 0.00218 | # Copyright 2016 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... | `.
The logits.
sequence_length: 1-D `int32` vector, size `[batch_size]`.
The sequence lengths.
preprocess_collapse_repeated: Boolean. Default: False.
If True, repeated labels are collapsed prior to the CTC calculation.
ctc_merge_repeated: Boolean. Default: True.
ignore_longer_outputs... | than inputs will be ignored.
time_major: The shape format of the `inputs` Tensors.
If True, these `Tensors` must be shaped `[max_time, batch_size,
num_classes]`.
If False, these `Tensors` must be shaped `[batch_size, max_time,
num_classes]`.
Using `time_major = True` (default) is a bi... |
janusnic/hug | tests/test_output_format.py | Python | mit | 2,987 | 0.004687 | """tests/test_output_format.py.
Tests the output format handlers included with Hug
Copyright (C) 2015 Timothy Edmund Crosley
Permission is hereby granted, free of charge, to any person obtaining a copy | of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, ... |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN... |
asmacdo/shelf-reader | shelf_reader/ui.py | Python | gpl-2.0 | 1,924 | 0.00052 | # -*- coding: utf-8 -*-
from __future__ import print_function
from .compat import user_input
def correct(call_a, call_b):
"""
Informs the user that the order is correct.
:param call_a: first call number - not used at this time but could be
important in later versions.
:param call... | print()
def get_next_callnumber(barcode_dict):
"""
Prompts the user for a barcode and returns the appropriate call number. If
the user inputs a barcode that is not in the dictionary, the user is
prompted again.
:param barcode_ | dict: dictionary of barcodes and call numbers
:returns: call number that matches user input barcode
"""
barcode = user_input("Barcode >>> ")
while barcode.lower() != 'exit':
call_number = barcode_dict.get(barcode)
if call_number is not None:
return cal... |
salesking/salesking_python_sdk | salesking/tests/test_contacts_collection_mock.py | Python | apache-2.0 | 24,848 | 0.000926 | from salesking.tests.base import SalesKingBaseTestCase
class MockCollectionContactResponse(object):
def __init__(self):
self.status_code = 200
self.content = u'''
{"contacts":
[{"contact":{"id":"a55-akQyir5ld2abxfpGMl","parent_id":null,"type":"Client","is_employee":false,"number":"K-2015-1286","... | s.py-api@mailinator.com","url":null,"birthday":null,"tag_list":"","cre | ated_at":"2015-01-31T20:49:11+01:00","updated_at":"2015-01-31T20:49:11+01:00","language":null,"currency":"EUR","payment_method":null,"bank_name":null,"bank_number":null,"bank_account_number":null,"bank_iban":null,"bank_swift":null,"bank_owner":null,"phone_fax":null,"phone_office":null,"phone_home":null,"phone_mobile":n... |
bayesimpact/bob-emploi | frontend/release/compress_notes.py | Python | gpl-3.0 | 1,668 | 0.002398 | """Manipulate release notes from Github commits to make them more compact.
Gets its input from stdin, assumed in the following format:
1 line per commit, starting with "[Some subject]" and ending with "(#123456)"
Lines with the same subject will be grouped together, sorted by increasing PR number.
Commits not starti... | ED_SUBJECTS = [f'[{subject}]' for subject in ['Clean Code', 'Small Fix', 'Easy Dev']]
def _subject_key(line: str) -> str:
"""Get the subject for the line or an empty string."""
if subject_match := _SUBJECT_REGEX.search(line):
retu | rn subject_match.group()
return ''
def _pr_key(line: str) -> int:
"""Get the PR number for the line or 0."""
if pr_match := _PR_REGEX.search(line):
return int(pr_match.group(1))
return 0
def compress_notes(notes: Iterator[str]) -> str:
"""Group all commit messages by subject."""
se... |
ReactiveX/RxPY | reactivex/observable/marbles.py | Python | mit | 9,232 | 0.000542 | import re
import threading
from datetime import datetime, timedelta
from typing import Any, List, Mapping, Optional, Tuple, Union
from reactivex import Notification, Observable, abc, notification, typing
from reactivex.disposable import CompositeDisposable, Disposable
from reactivex.scheduler import NewThreadScheduler... | lookup=lookup,
| error=error,
raise_stopped=True,
)
lock = threading.RLock()
is_stopped = False
observers: List[abc.ObserverBase[Any]] = []
def subscribe(
observer: abc.ObserverBase[Any], scheduler: Optional[abc.SchedulerBase] = None
) -> abc.DisposableBase:
# should a hot observab... |
inveniosoftware/invenio-search | invenio_search/config.py | Python | mit | 3,755 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Configuration options for Invenio-Search.
The documentation for the configuration... | ven
search query and it is not absolute value. Therefore, setting `min_score` too
high can lead to 0 results because | it can be higher than any result's `_score`.
Please refer to `Elasticsearch min_score documentation
<https://www.elastic.co/guide/en/elasticsearch/reference/current/
search-request-min-score.html>`_ for more information.
"""
SEARCH_INDEX_PREFIX = ''
"""Any index, alias and templates will be prefixed with this string.... |
weinbe58/QuSpin | sphinx/doc_examples/evolve-example.py | Python | bsd-3-clause | 3,153 | 0.047257 | from __future__ import print_function, division
#
import sys,os
quspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,quspin_path)
#
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import boson_basis_1d # Hilbert space spin basis
from quspin.tools.evolution import ev... | _dot[:Ns] = H.static.dot(phi[Ns:]).real
phi_dot[Ns:] = -H.static.dot(phi[:Ns]).real
# static GPE interaction
phi_dot_2 = np.abs(phi[:Ns])**2 + np.abs(phi[Ns:])**2
phi_dot[:Ns] += U*phi_dot_2*phi[Ns:]
phi_dot[Ns:] -= U*phi_dot_2*phi[:Ns]
# dynamic single-particle term
for func, Hdyn in iteritems(H.dynamic):
fu... | dyn.dot(phi[Ns:]) ).real
return phi_dot
# define ODE solver parameters
GPE_params = (H,U)
# solving the real-valued GPE takes one line
phi_t = evolve(phi0,t.i,t.vals,GPE_real,stack_state=True,f_params=GPE_params) |
batxes/4Cin | SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/mtx1_models/SHH_WT_models8077.py | Python | gpl-3.0 | 17,576 | 0.025091 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | icle_19 geometry"]=s
s | = marker_sets["particle_19 geometry"]
mark=s.place_marker((6486.83, 7632.59, 2637.98), (0.7, 0.7, 0.7), 677.181)
if "particle_20 geometry" not in marker_sets:
s=new_marker_set('particle_20 geometry')
marker_sets["particle_20 geometry"]=s
s= marker_sets["particle_20 geometry"]
mark=s.place_marker((4929.54, 5993.99, ... |
jusjusjus/Motiftoolbox | Fitzhugh_n-cell/run.py | Python | gpl-2.0 | 368 | 0.005435 | #!/usr/bin/env python
import system as sys
import traces a | s tra
import info as nf
import pylab as pl
pos_info = '+0+600'
pos_tra = '+300+600'
pos_sys = '+0+0'
i = nf.info(position=pos_info)
s = sys.system(info=i, position=pos_sys)
t = tra.traces(s, info=i, position=pos_tra)
if pl.get_backend | () == 'TkAgg':
s.fig.tight_layout()
t.fig.tight_layout()
pl.show()
|
fogcitymarathoner/gae_p27_dj17 | p27_d17_prj/wsgi.py | Python | mit | 1,789 | 0.000559 | """
WSGI config for p27_d17 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`` ... | other
framework.
"""
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
#
# BASE_DIR is useless as it is one directory above the one with manage.py
PROJECT_DIR = os.path.join(os.path.dirname(__file__))
APPS_DIR = os.path.join(BASE_DIR, 'apps')
# put apps on first part of path so we can leave of... | ys.path.insert(0, APPS_DIR)
print sys.path
# 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 with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "p27_d17.s... |
qpython-android/QPython3-core | pybuild/main.py | Python | apache-2.0 | 2,041 | 0.00196 | import os
import re
from typing import Iterable
from .env import use_bintray, skip_build_py, skip_build_py2, skip_build_py_module, skip_build_py2_module, py_packages, py_packages2
from .package import enumerate_packages, import_package
built_packags: set = set()
need_rebuild: set = set()
def parse_packages(pkg_spec... | built_packags.add(pkgname)
return
for dep in pkg.dependencies:
build_package(dep)
if pkg.fresh():
for src in pkg.sources:
src.download()
for patch in getattr(pkg, 'patches', []):
patch.apply(pkg.source)
try:
pkg.prepare()
... |
pkg.create_tarball()
pkg.upload_tarball()
built_packags.add(pkgname)
def main():
# TODO: Make this configurable
need_rebuild.update(parse_packages(':COMMIT_MARKER'))
print(f'Packages to rebuild: {need_rebuild}')
if not skip_build_py:
build_package('python')
if not skip_buil... |
JoshuaSkelly/Toast | toast/animation.py | Python | mit | 2,328 | 0.010309 | from toast.scene_graph import Component
class Animation(Component):
def __init__(self, key=None, frames=None):
super(Animation, self).__init__()
self.__animation_list = {}
self.key = ''
self.__current_image = None
self.__index = 0
self.__time = 0
... |
if hasattr(self.game_object, 'image'):
self.game_object.image = self.image
if self.__time > duration:
self.__time = 0
self.__index +=1
if callback:
callback()
... | if not self.key:
self.key = key
self.__current_image = frames[0][0]
self.__animation_list[key] = frames
@property
def image(self):
""" Returns the current image of the playing animation"""
return self.__current_image
@property
d... |
asajeffrey/servo | tests/wpt/web-platform-tests/tools/third_party/aioquic/src/aioquic/quic/retry.py | Python | mpl-2.0 | 1,449 | 0.003451 | import ipaddress
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from .connection import NetworkAddress
def encode_address(addr: NetworkAddress) -> bytes:
return ipaddress.ip_address(add... | self._key = rsa.generate_private_key(
public_exponent=65537, key_size=1024, backend=default_backend()
)
def create_token(self, addr: NetworkAddress, destination_cid: bytes) -> bytes:
retry_message = encode_address(addr) + b"|" + destination_cid
return self._key.public_key... | =hashes.SHA256(), label=None
),
)
def validate_token(self, addr: NetworkAddress, token: bytes) -> bytes:
retry_message = self._key.decrypt(
token,
padding.OAEP(
mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None
)... |
illume/numpy3k | numpy/lib/tests/test__iotools.py | Python | bsd-3-clause | 6,114 | 0.004416 |
import StringIO
import numpy as np
from numpy.lib._iotools import LineSplitter, NameValidator, StringConverter,\
has_nested_fields
from numpy.testing import *
class TestLineSplitter(TestCase):
"Tests the LineSplitter class."
#
def test_no_delimiter(self):
"Test Line... | r('missed'), converter.default)
try:
converter('miss')
except ValueError:
pass
#
def test_upgrademapper(self):
"Tests updatemapper"
from datetime import date
import time
dateparser = lambda s : date(*time.strptime(s, "%Y-%m-%d")[:3])
... | r(dateparser, date(2000,1,1))
convert = StringConverter(dateparser, date(2000, 1, 1))
test = convert('2001-01-01')
assert_equal(test, date(2001, 01, 01))
test = convert('2009-01-01')
assert_equal(test, date(2009, 01, 01))
test = convert('')
assert_equal(test, date... |
lwahlmeier/python-litesockets | litesockets/socketexecuter.py | Python | unlicense | 21,816 | 0.018702 | import select, logging, threading, sys, ssl, errno, socket, platform, time
from threadly import Scheduler, Clock
from .stats import Stats
from .stats import noExcept
from .client import Client
from .server import Server
from .tcp import TCPClient, TCPServer
from .udp import UDPServer
try:
xrange(1)
except:
xra... | e:
self.__log.debug("errorCB Error: %s"%(sys.exc_info()[0]))
self.__log.debug(e)
for rdy in rlist:
try:
if rdy in self.__acceptServers:
self.__acceptCallback(rdy.fileno())
except Exception as e:
self.__log.debug("Accept Error: %s"%(sys.exc_info()[ | 0]))
self.__log.debug( |
zhangf911/common | test/model/content_test.py | Python | mit | 1,322 | 0 | import unittest
from mock import Mock
from biicode.common.model.content import Content
from biicode.common.model.content import ContentDeserializer
from biicode.common.model.content import content_diff
from biicode.common.exception import BiiSerializationException
from biicode.common.model.id import ID
class ContentT... | assertIsNone(ContentDeserializer(ID).deserialize(None))
def test_content_diff(self):
content_load1 = Mock()
content_load2 = Mock()
content_load1.is_binary = Mock(return_value=True)
self.assertEquals(content_diff(content_load1, content_load2),
"Unable to dif... | ue)
self.assertEquals(content_diff(content_load1, content_load2),
"Unable to diff binary contents of base")
def test_content_similarity(self):
content = Content(ID((0, 0, 0)), load=None)
self.assertEquals(content.similarity(content), 1)
|
ddebrunner/streamsx.topology | test/python/spl/tests/test_splpy_primitives.py | Python | apache-2.0 | 8,994 | 0.008117 | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2016
import os
import unittest
import sys
import itertools
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import schema
import streamsx.topology.context
import streamsx.spl.op as op
... | self.tester.contents(r[0], [{'v1':9237}, {'v1':-24}])
self.tester.contents(r[1], [{'v2':9237+921}, {'v2':-24+921}])
self.tester.contents(r[2], [{'v3':9237-407}, {'v3':-24-407}])
self.tester.test(self.test_ctxtype, self.test_config)
def test_dict_output_ports(self):
"""Operato... | with multiple output port submitting dict objects."""
topo = Topology()
streamsx.spl.toolkit.add_toolkit(topo, stu._tk_dir('testtkpy'))
s = topo.source([9237, -24])
s = s.map(lambda x : (x,x*2,x+4), schema='tuple<int64 d, int64 e, int64 f>')
bop = op.Invoke(topo, "com.ibm.stre... |
uniite/pyirc | models/session.py | Python | mit | 3,127 | 0.003518 | from json_serializable import JSONSerializable
from irc_connection import IRCConnection
from models import Conversation, Message
from observable import ObservableList, SimpleObservable
class Session(SimpleObservable, JSONSerializable):
_json_attrs = ["conversations", "users"]
def __init__(self):
self.... | sage, chatroom=None):
if chatroom:
conv_name = chatroom
else:
conv_name = username
| conv = self.get_conversation(connection, conv_name)
if not conv:
conv = self.create_conversation(connection, conv_name)
conv.recv_message(Message(None, username, message, conv))
def conversation_by_id(self, conv_id):
matches = [c for c in self.conversations if c.id == co... |
Habbie/pdns | docs/conf.py | Python | gpl-2.0 | 8,446 | 0.001658 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# PowerDNS Recursor documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 28 14:56:44 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in... | TML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_ | theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = 'guzzle_sphinx_theme'
extensions.append("guzzle_sphinx_theme")
html_theme_options = {
# Set the name of the project to appear in the sidebar
"project_nav_name": "PowerDNS Authoritative Server",
}
html_favicon = 'common/favicon.ico'
# Theme optio... |
hopkira/k9-chess-angular | python/roboclaw_simplepwm.py | Python | unlicense | 963 | 0.070613 | import time
from roboclaw import Roboclaw
#Windows comport name
rc = Roboclaw("COM11",115200)
#Linux comport name
#rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
address = 0x80
while(1):
rc.ForwardM1(address,32) #1/4 power forward
rc.BackwardM2(address,32) #1/4 power backward
time.sleep(2)
rc.B... |
time.sleep(2)
rc.ForwardBackwardM1(address,64) #Stopped
rc.ForwardBackwardM2(address,64) #Stopped
time. | sleep(2)
|
pedroernesto/morphounit | setup.py | Python | bsd-3-clause | 1,115 | 0.008072 | try:
from setuptools import setup
except Import | Error:
from distutils.core import setup
setup(
name='morphounit',
version='1.0.4',
author='Shailesh Appukuttan, Pedro Garcia-Rodriguez',
author_email='shailesh.appukuttan@cnrs.fr, pedro.garcia@cnrs.fr',
packages=['morphounit',
'morphounit.capabilities',
'morphounit.t... | ',
'morphounit.scores',
'morphounit.plots'],
url='https://github.com/appukuttan-shailesh/morphounit',
keywords = ['morphology', 'structure', 'circuit', 'testing', 'validation framework'],
license='BSD 3-Clause',
description='A SciUnit library for data-driven testing of neuron... |
rartino/ENVISIoN | envisionpy/processor_network/LinePlotNetworkHandler.py | Python | bsd-2-clause | 11,390 | 0.003337 | # ENVISIoN
#
# Copyright (c) 2019-2021 Jesper Ericsson, Gabriel Anderberg, Didrik Axén,
# Adam Engman, Kristoffer Gubberud Maras, Joakim Stenborg
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | vas = None
# If already in correct mode dont do anything
if (graphCanvas and enable) or (not graphCanvas and not enable):
return
if enable:
graphCanvas = self.add_processor('org.inviwo.CanvasGL', 'graphCanvas', 25*7, 525)
graphCanvas.inputSize.dimensions.val... | lf.remove_processor('graphCanvas')
def show(self):
try:
self.get_processor('graphCanvas').widget.show()
except:
pass
def hide(self):
try:
self.get_processor('graphCanvas').widget.hide()
except:
pass
def set_y_selection_type(s... |
TobiasLohner/mapgen | lib/xcsoar/mapgen/waypoints/welt2000_reader.py | Python | gpl-2.0 | 4,373 | 0.028813 | import re
from xcsoar.mapgen.waypoints.waypoint import Waypoint
from xcsoar.mapgen.waypoints.list import WaypointList
def __parse_line(line, bounds = None):
if line.startswith('$'): return None
lat = line[45:52]
lat_neg = lat.startswith('S')
lat = float(lat[1:3]) + float(lat[3:5]) / 60. + float... | {0,3}($|\s)', wp.name): wp.type = 'highway exit'
if re.search('(\s)(\w){0,3}XA(\d){0,3}($|\s)', wp.name): wp.type = 'highway cross'
if re.search('(\s)(\w){0,3}YA(\d){0,3}($|\s)', wp.name): wp.type = 'highway junction'
if re.search('(\s)STR($|\s) | ', wp.name): wp.type = 'road'
if re.search('(\s)SX($|\s)', wp.name): wp.type = 'road cross'
if re.search('(\s)SY($|\s)', wp.name): wp.type = 'road junction'
if re.search('(\s)EX($|\s)', wp.name): wp.type = 'railway cross'
if re.search('(\s)EY($|\s)', wp.name): wp.type = 'railway junction'
if re.sear... |
nuagenetworks/vspk-python | vspk/v6/nuunderlay.py | Python | bsd-3-clause | 11,766 | 0.009009 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# 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 copyrigh... |
This attribute is named `lastUpdatedBy` in VSD A | PI.
"""
self._last_updated_by = value
@property
def last_updated_date(self):
""" Get last_updated_date value.
Notes:
Time stamp when this object was last updated.
This attribute is named `lastUpdatedDat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.