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 |
|---|---|---|---|---|---|---|---|---|
mbohlool/client-python | kubernetes/test/test_rbac_authorization_v1alpha1_api.py | Python | apache-2.0 | 5,278 | 0.006631 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | def test_replace_cluster_role(self):
"""
Test case for replace_cluster_role
"""
pass
def test_replace_cluster_role_binding(self):
"""
Test case for replace_cluster_role_bindi | ng
"""
pass
def test_replace_namespaced_role(self):
"""
Test case for replace_namespaced_role
"""
pass
def test_replace_namespaced_role_binding(self):
"""
Test case for replace_namespaced_role_binding
"""
... |
boegel/easybuild-easyblocks | easybuild/easyblocks/m/mymedialite.py | Python | gpl-2.0 | 2,788 | 0.002869 | ##
# Copyright 2009-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for MyMediaLite, implemented as an easyblock
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Gh... | ersity)
@author: Jens Timmerman (Ghent University)
"""
from distutils.version import LooseVersion
from easybuild.easyblocks.generic.configuremake import ConfigureMake
from easybuild.tools.run import run_cmd
class EB_MyMediaLite(ConfigureMake):
"""Support for building/installing MyMediaLite."""
def configur... |
luotao1/Paddle | python/paddle/fluid/tests/unittests/xpu/test_gaussian_random_op_xpu.py | Python | apache-2.0 | 1,364 | 0.006598 | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | ns and
# limitations under the License.
from __future__ import print_function
import sys
sys.path.append("..")
import unittest
import numpy as np
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
from paddle.fluid.op import Operator
from paddle.fluid.executor import Executor
from op_test | import OpTest
from test_gaussian_random_op import TestGaussianRandomOp
paddle.enable_static()
class TestXPUGaussianRandomOp(TestGaussianRandomOp):
def test_check_output(self):
if paddle.is_compiled_with_xpu():
place = paddle.XPUPlace(0)
outs = self.calc_output(place)
o... |
adrianp/cartz | server/utils.py | Python | mit | 210 | 0 | import random
import | string
def random_string(n):
result = ''
for _ in range(10):
result += random.SystemRandom().choice(
string.ascii_uppercase + str | ing.digits)
return result
|
bennylope/django-simple-auth | simple_auth/urls.py | Python | bsd-2-clause | 156 | 0 | from django.conf.urls import url
from .views import simple_password
urlpatterns = [
url(r'^$', view=simple_password, name="simple_auth_password"), |
]
| |
val314159/framist | fssvr/fs.py | Python | apache-2.0 | 1,267 | 0.037096 | import os,json
from cgi import escape
def unescape(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
# this has to be last:
s = s.replace("&", "&")
return s
class FilesystemMixin:
def h_fs_get(_,path,eltName=''):
from stat impo | rt S_ISDIR
data = (escape(open(path).read())
if not S_ISDIR(os.stat(path).st_mode)
else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode))
for p in os.listdir(path)])
_.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]}))
pass
d... | )
pass
def h_fs_system(_,path,eltName='',cwd=None):
import subprocess as sp
import shlex
data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate()
_.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]}));
pass
def h_fs... |
gokudomatic/cobiv | cobiv/modules/hud_components/progresshud/progresshud.py | Python | mit | 473 | 0.002114 | import os
from kivy.lang import Builder
from kivy.properties import NumericProperty, StringProperty
from kivy.uix.anchorlayout import AnchorLayout
from cobiv.modules.core.hud import Hud
Builder.load_file(os.path.abspath(os.path.join(os.path.dirname(__file__), 'progresshud.kv')))
class ProgressHud(Hud, AnchorL | ayout):
value = NumericProper | ty(0)
caption = StringProperty("")
def __init__(self, **kwargs):
super(ProgressHud, self).__init__(**kwargs)
|
schedulix/schedulix | src/examples/SimpleAccess3.py | Python | agpl-3.0 | 704 | 0.053977 | import sdms
server = { 'HOST' : 'localhost',
'PORT' : '2506',
'USER' : 'SYSTEM',
'PASSWORD' : 'VerySecret' }
conn = sdms.SDMSConnectionOpenV2(server, server['USER'], server['PASSWORD'], "Simple Access Example")
try:
if 'ERROR' in conn:
print(str(conn))
exit(1)
except:
pass
stmt = "LIST SESSIONS;"
re... | ))
else:
for r | ow in result['DATA']['TABLE']:
print("{0:3} {1:8} {2:32} {3:9} {4:15} {5:>15} {6}".format(\
str(row['THIS']), \
str(row['UID']), \
str(row['USER']), \
str(row['TYPE']), \
str(row['START']), \
str(row['IP']), \
str(row['INFORMATION'])))
conn.close()
|
gslab-econ/gslab_python | gslab_scons/tests/test_build_stata.py | Python | mit | 6,869 | 0.016305 | #! /usr/bin/env python
import unittest
import sys
import os
import shutil
import mock
import subprocess
import re
# Import gslab_scons testing helper modules
import _test_helpers as helpers
import _side_effects as fx
# Ensure that Python can find and load the GSLab libraries
os.chdir(os.path.dirname(os.path.realpath(_... | atch('%s.subprocess.check_output' % path)
def test_bad_extension(self, mock_check):
mock_check.side_effect | = fx.make_stata_side_effect('stata-mp')
env = {'stata_executable': 'stata-mp'}
helpers.bad_extension(self, gs.build_stata,
good = 'test.do', env = env)
def tearDown(self):
if os.path.exists('./build/'):
shutil.rmtree('./build/')
if os.path.... |
MDU-PHL/meningotype | update_meningotype.py | Python | gpl-3.0 | 1,346 | 0 | '''
Given a new mlst version or DB, update the container
'''
import pathlib
import click
import ji | nja2
import toml
import pendulum
import subprocess
import shlex
def l | oad_template(name):
'''
Return the singularity recipe template as unicode text
'''
template = pathlib.Path(name).read_text()
return template
@click.command()
@click.option("--version", default=None)
@click.option("--mlst_version", default="latest")
@click.option("--author", default=None)
@click.op... |
Architizer/mendel | mendel/migrations/0009_auto_20160623_1141.py | Python | agpl-3.0 | 1,091 | 0.001833 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-06-23 15:41
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mendel', '0008_auto_20160613_1911'),
]
operations =... | model_name='context',
old_name='keyword',
new_name='keyword_given',
),
migrations.RenameField(
model_name='review',
old_name='keyword',
new_name='keyword_given',
),
migrations.Add | Field(
model_name='review',
name='keyword_proposed',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='keyword_proposed', to='mendel.Keyword'),
preserve_default=False,
),
migrations.AlterUniqueTogether(
... |
dmnfarrell/peat | PEATSA/Core/__init__.py | Python | mit | 123 | 0.00813 | '''Contains the Co | re classes of the PEATSA com | mand line tool'''
import ProteinDesignTool, Data, Exceptions, PEATSAParallel
|
opencord/voltha | voltha/adapters/interface.py | Python | apache-2.0 | 20,438 | 0.00044 | #
# Copyright 2017 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ed to indicate if plugin shall assume or lose master role. The
master role can be used to perform functions that must be performed
from a single point in the cluster. In single-node deployments of
Voltha, the plugins are always in master r | ole.
:param master: (bool) True to indicate the mastership needs to be
assumed; False to indicate that mastership needs to be abandoned.
:return: (Deferred) which is fired by the adapter when mastership is
assumed/dropped, respectively.
"""
def adopt_device(device):
... |
tuxar-uk/Spectral-Harmonographs | harmonograph.py | Python | mit | 3,592 | 0.032294 | #!/usr/bin/python
''' Spectral Harmonographs Copyright 2014 Alan Richmond (Tuxar.uk)
Trace of 4 decaying sine waves, 2 per axis (x & y)(i.e. 2-pendula), with rainbow colour.
I did this in Java some decades ago (Encyclogram; I no longer have the source), this
version is in Python, with PyGame.
It r... | fy2 = r.randint(1,mx) + r.gauss(0,sd), r.randint(1,mx) + r.gauss(0,sd)
px1, px2 = r.uniform(0,2*pi), r.uniform(0,2*pi)
py1, py2 = r.uniform(0,2*pi), r.uniform(0,2*pi)
print ax1,ax2,ay1,ay2
print fx1,fx2,fy1,fy2
print px1,px2,py1,py2
dec=1.0
t=0.0 | # angle for sin
first=True
while dec>0.015:
# calculate next x,y point along line
x = xscale * dec * (ax1*sin(t * fx1 + px1) + ax2*sin(t * fx2 + px2)) + width/2
y = yscale * dec * (ay1*cos(t * fy1 + py1) + ay2*cos(t * fy2 + py2)) + height/2
dec*=dd ... |
tobykurien/rpi_lcars | app/ui/widgets/sprite.py | Python | mit | 3,393 | 0.006779 | import pygame
from ui.utils.interpolator import Interpolator
class LcarsWidget(pygame.sprite.DirtySprite):
"""Base class for all widgets"""
def __init__(self, color, pos, size, handler=None):
pygame.sprite.DirtySprite.__init__(self)
if self.image == None:
self.image = pygame.Surfac... | if self.line != None:
self.line.next()
if self.rect.center == self.line.pos:
self.dirty = 0
self.rect.center = self.line.p | os
else:
self.dirty = 0
screen.blit(self.image, self.rect)
def handleEvent(self, event, clock):
handled = False
if not self.visible:
self.focussed = False
return handled
if event.type == pygame.MOUSEBUTTONDOWN:
self.p... |
bauerj/electrum-server | src/processor.py | Python | mit | 9,045 | 0.002211 | #!/usr/bin/env python
# Copyright(C) 2011-2016 T | homas Voegtlin
#
# 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,... | to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT ... |
colloquium/spacewalk | client/tools/osad/test/simple-dispatcher.py | Python | gpl-2.0 | 1,087 | 0.00644 | #
# Copyright (c) 2008 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties | of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that... | ib
class SimpleDispatcherClient(test_lib.SimpleClient):
pass
class SimpleDispatcherRunner(test_lib.SimpleRunner):
client_factory = SimpleDispatcherClient
_resource = 'DISPATCHER'
def fix_connection(self, client):
client.retrieve_roster()
client.send_presence()
def main():
d ... |
wkschwartz/django | tests/admin_checks/tests.py | Python | bsd-3-clause | 32,171 | 0.000591 | from django import forms
from django.contrib import admin
from django.contrib.admin import AdminSite
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.contenttypes.admin import GenericStackedInline
from django.contrib.messages.m... | TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
| 'context_processors': [],
},
}],
)
def test_context_processor_dependencies(self):
expected = [
checks.Error(
"'django.contrib.auth.context_processors.auth' must be "
"enabled in DjangoTemplates (TEMPLATES) if using the default "
... |
JacobMiki/Emotionnaise-python | test.py | Python | mit | 1,452 | 0.00551 | import numpy as np
import cv2
from sys import argv
class Test:
def __init__(self, name, image):
self.image = image
self.name = name
self.list = []
def add(self, function):
self.list.append(function)
def run(self):
cv2.imshow(self.name, self.image)
... | ge):
cv2.medianBlur(image, 9, image)
return image
def unsharp(image):
image2 = cv2.GaussianBlur(image, (21,21), 21)
iamge = cv2.addWeighted(image, 1.5, image2, -0.5, 0, image)
return image
def harris(image):
x33 = image.shape[ | 1] / 3
x66 = image.shape[1] / 3 * 2
dst1 = cv2.goodFeaturesToTrack(image[:,:x33], 10, 0.1, 5)
mean1 = np.uint8(cv2.mean(dst1))
cv2.circle(image, (mean1[0], mean1[1]), 2, 255)
dst2 = cv2.goodFeaturesToTrack(image[:,x66:], 10, 0.1, 5)
dst2 += [x66, 0]
mean2 = np.uint8(cv2.mean(dst2))
... |
ffsdmad/af-web | cgi-bin/plugins/plugin_manager.py | Python | gpl-3.0 | 2,225 | 0.008539 | #!/usr/bin/env python
# -*- coding: utf8 -*-
#
# autocomplit.py
#
# Copyright 2011 Basmanov Illya <ffsdmad@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 Foundati... | k
#xml += "<%s>%s</%s>"% (k, plg[k], k)
return xml
class plugin_manager():
def __init__(self):
xml = user[3]+"""<plugins>plugin_manager</plugins>"""
txml = ""
for root, dirs, files in os.walk(PLGPATH):
for | f in files:
if f[-3:]==".py" and f!="__init__.py":
plg_path = root + "/" + f
plg_name = plg_path.replace("/", ".")[len(PLGPATH)+1:-3]
txml += "<row><plg_name>%s</plg_name><plg_path>%s</plg_path><title>%s</title></row>"% (plg_name, plg_path, m... |
d3adc0d3/DeadBot | events.py | Python | mit | 509 | 0.033399 | class Event:
MESSAGE = 'MESSAGE'
JOIN = 'JOIN'
LEAVE = 'LEAVE'
def __init__(self, _type, user, text):
self._type = _type
self.user = user
self.text = text
def __repr__(self):
return '[{}] {}: {}'.format(self._type, self.user, self.text)
def __str__(self):
return self.__repr__()
def message(user, te... | return Event(Event.MESSAGE, user, text)
def join(user) | :
return Event(Event.JOIN, user, 'joined the room')
def leave(user):
return Event(Event.LEAVE, user, 'leaved the room')
|
eduNEXT/edunext-platform | openedx/core/djangoapps/zendesk_proxy/urls.py | Python | agpl-3.0 | 412 | 0.004854 | """
Map urls to the relevant view handlers
"""
from django.conf.urls import url
from openedx.core.djangoapps.zendesk_proxy.v0.views import Z | endeskPassthroughView as v0_view
from openedx.core.djangoapps | .zendesk_proxy.v1.views import ZendeskPassthroughView as v1_view
urlpatterns = [
url(r'^v0$', v0_view.as_view(), name='zendesk_proxy_v0'),
url(r'^v1$', v1_view.as_view(), name='zendesk_proxy_v1'),
]
|
globalwordnet/OMW | omw/__init__.py | Python | mit | 35,734 | 0.007472 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import csv
from collections import (
defaultdict as dd,
OrderedDict as od
)
from math import log
import datetime
from flask import (
Flask,
render_template,
g,
request,
redirect,
u | rl_for,
send_from_directory,
flash,
jsonify,
make_response,
Markup,
Response
)
from flask_login import (
login_required,
login_user,
logout_user,
current_user
)
from packaging.version import Version
import gwadoc
import networkx as nx
## profiler
#from werkze | ug.contrib.profiler import ProfilerMiddleware
from omw.utils.utils import fetch_sorted_meta_by_version
app = Flask(__name__)
# Common configuration settings go here
app.config['REMEMBER_COOKIE_DURATION'] = datetime.timedelta(minutes=30)
# Installation-specific settings go in omw_config.py
app.config.from_object('confi... |
kparal/anaconda | pyanaconda/ui/gui/spokes/advstorage/iscsi.py | Python | gpl-2.0 | 20,233 | 0.003311 | # iSCSI configuration dialog
#
# Copyright (C) 2013 Red Hat, Inc.
#
# 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 General Public License v.2, or (at your option) any later version.
# This program is distribute... |
self._discoveryError = None
self._loginError = False
self._discoveredNodes = []
self._update_devicetree = False
self._authTypeCombo = self.builder.get_object("authTypeCombo")
self._authNotebook = self.builder.get_object("authNotebook")
self._iscsiNotebook = | self.builder.get_object("iscsiNotebook")
self._loginButton = self.builder.get_object("loginButton")
self._retryLoginButton = self.builder.get_object("retryLoginButton")
self._loginAuthTypeCombo = self.builder.get_object("loginAuthTypeCombo")
self._loginAuthNotebook = self.builder.get_o... |
GreyRook/madmin | doc/conf.py | Python | apache-2.0 | 8,136 | 0.006268 | # -*- coding: utf-8 -*-
#
# MAdmin documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 25 13:48:36 2013.
#
# 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.
#
# Al... | the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<projec... | tml_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs... |
SingularityHA/WebUI | infrastructure/migrations/0013_module_list_widget.py | Python | gpl-3.0 | 411 | 0.002433 | # encoding: utf8
from django.db import models, migrations
class | Migration(migrations.Migration):
dependencies = [
('infrastructure', '0012_auto_20140209_0400'),
]
operations = [
migrations.AddField(
model_name='module_list',
na | me='widget',
field=models.TextField(null=True, blank=True),
preserve_default=True,
),
]
|
repology/repology | repology/parsers/parsers/cran.py | Python | gpl-3.0 | 1,459 | 0.001371 | # Copyright (C) 2017-2019 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lic | ense as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# repology is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
... | License for more details.
#
# You should have received a copy of the GNU General Public License
# along with repology. If not, see <http://www.gnu.org/licenses/>.
import re
from typing import Iterable
from repology.packagemaker import NameType, PackageFactory, PackageMaker
from repology.parsers import Parser
class... |
cbitstech/Purple-Robot-Django | migrations/0037_auto__add_field_purplerobotdevice_first_reading_timestamp.py | Python | gpl-3.0 | 10,672 | 0.007309 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'PurpleRobotDevice.first_reading_timestamp'
db.add_column(... | : u | "orm['purple_robot_app.PurpleRobotConfiguration']"}),
'description': ('django.db.models.fields.TextField', [], {'max_length': '1048576', 'null': 'True', 'blank': 'True'}),
'device_group': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'devices'", 'null': 'T... |
darioml/fyp-public | data/make_pngs.py | Python | gpl-2.0 | 394 | 0.025381 | from os import listdir
from os.path import isfile, join
import paer
mypath = 'aedat/'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and f.endswith('.aedat')]
for fil | e in onlyfiles:
ae = paer.aefile(mypath + str(file))
aed= paer.aedata(ae).downsample((16,16))
paer.create_pngs(aed, '16x16_' + str(file) + '_',path='more_images/temp',step=3000, d | im=(16,16))
|
synsun/robotframework | utest/running/test_handlers.py | Python | apache-2.0 | 13,048 | 0.00138 | import unittest
import sys
import inspect
from robot.running.handlers import _PythonHandler, _JavaHandler, DynamicHandler
from robot import utils
from robot.utils.asserts import *
from robot.running.testlibraries import TestLibrary
from robot.running.dynamicmethods import (
GetKeywordArguments, GetKeywordDocumenta... | Error
from classes import NameLibrary, DocLibrary, ArgInfoLibrary
from ArgumentsPython import ArgumentsPython
if utils.JYTHON:
import ArgumentsJava
def _get_handler_methods(lib):
attrs = [getattr(lib, a) for a | in dir(lib) if not a.startswith('_')]
return [a for a in attrs if inspect.ismethod(a)]
def _get_java_handler_methods(lib):
# This hack assumes that all java handlers used start with 'a_' -- easier
# than excluding 'equals' etc. otherwise
return [a for a in _get_handler_methods(lib) if a.__name__.starts... |
brosner/django-notification | notification/message.py | Python | mit | 3,596 | 0.001947 | from django.db.models import get_model
from django.utils.translation import ugettext
# a notice like "foo and bar are now friends" is stored in the database
# as "{auth.User.5} and {auth.User.7} are now friends".
#
# encode_object takes an object and turns it into "{app.Model.pk}" or
# "{app.Model.pk.msgid}" if named ... | ate, objects):
if objects is None:
return message_template
if isinstance(objects, list) or isinstance(objects, tuple):
return message_template % tuple(encode_object(obj) for obj in objects)
if type(objects) is dict:
return message_template % dict((name, encode_object(obj, name)) for ... | ded
return get_model(app, name).objects.get(pk=pk), msgid
app, name, pk = decoded
return get_model(app, name).objects.get(pk=pk), None
class FormatException(Exception):
pass
def decode_message(message, decoder):
out = []
objects = []
mapping = {}
in_field = False
prev = 0
... |
stuntgoat/conf-syrup | conf_syrup/network_type.py | Python | mit | 307 | 0 | from commands import getoutput
def NetworkFromPrefix(val):
"""
Return the network with the network prefix given.
"""
ifaces = getoutput( | 'hostname -I') # *nix only.
sifaces = ifaces.strip().split()
for iface in sifaces:
if iface.startswith(val): |
return iface
|
yattom/crossword | crossword2.py | Python | mit | 7,931 | 0.003404 | # coding: utf-8
import re
from crossword import *
class Crossword2(Crossword):
def __init__(self):
self.grid = OpenGrid()
self.connected = {}
self.used_words = []
def copy(self):
copied = Crossword2()
copied.grid = self.grid.copy()
copied.connected = self.co... | proposed_words.append((OpenGrid.pos_inc(p, -(m.start() + idx), d), d, word))
idx += m.start() + 1
return proposed_words
def evaluate_crossword(c):
# return -len(c.used_words)
return (c.grid.width + | c.grid.height) * 1.0 / len(c.used_words) ** 2
# return (c.grid.width * c.grid.height) * 1.0 / sum([len(w) for w in c.used_words])
def pickup_crosswords(words, dump_option=None, monitor=False):
best = 9999
for c in build_crossword2(words, monitor=monitor):
if evaluate_crossword(c) < best:
... |
stebenve86/poem_reader | utilities/add_poem.py | Python | apache-2.0 | 1,540 | 0.016234 | #!/usr/bin/env python3
"""
Copyright 2015 Stefano Benvenuti <ste.benve86@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required ... | filename, e)
sys.exit(1)
finally:
| if f is not None:
f.close()
|
apiaas/gae-base-app-with-drf | src/landing/urls.py | Python | gpl-3.0 | 145 | 0.006897 | from djang | o.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.main_page, name='m | ain_page'),
)
|
JonSteinn/Kattis-Solutions | src/Soft Passwords/Python 3/main.py | Python | gpl-3.0 | 297 | 0.013468 | print('Yes' if (la | mbda a,b : (lambda number: a == b or (a | [1:] == b and a[0] in number and len(a)-1 == len(b)) or (a[:-1] == b and a[-1] in number and len(a)-1 == len(b)) or ''.join(x.upper() if x.islower() else x.lower() for x in b) == a)({str(i) for i in range(10)}))(input(), input()) else 'No') |
mganeva/mantid | Testing/SystemTests/tests/analysis/DirectInelasticDiagnostic2.py | Python | gpl-3.0 | 3,610 | 0.001662 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | rkspace=sample,
ReductionProperties=red_man_name)
MaskDetectors(sample, MaskedWorkspace=diag_mask)
# Save the masked spectra numbers to a simple ASCII file for comparison
self.saved_diag_file = os.path.join(config['defaultsave.directory'],
... | ex in range(sample.getNumberHistograms()):
if spectrumInfo.isMasked(index):
spec_no = sample.getSpectrum(index).getSpectrumNo()
handle.write(str(spec_no) + '\n')
def cleanup(self):
if os.path.exists(self.saved_diag_file):
if self.succeeded... |
tectronics/pyafipws.web2py-app | languages/zh-tw.py | Python | agpl-3.0 | 8,854 | 0.02909 | # coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s rows deleted': '已刪除 %s 筆',
'%s rows updated': ... | OR, and ~(...) for NOT to build more complex queries.': '使用下列方式來組合更複雜的條件式, (...)&(...) 代表同時存在的條件, (...)|(...) 代表擇一的條件, ~(...)則代表反向條件.',
'User %(id)s Logged-in': '使用者 %(id)s 已登入',
'User %(id)s Registered': '使用者 %(id)s 已註冊',
'User ID': '使用者編號',
'Verify Password': '驗證密碼',
'View': '視圖',
'Views': '視圖',
'WSBFE' | : 'WSBFE',
'WSFEX': 'WSFEX',
'WSFEv0': 'WSFEv0',
'WSFEv1': 'WSFEv1',
'WSMTXCA': 'WSMTXCA',
'Welcome %s': '歡迎 %s',
'Welcome to web2py': '歡迎使用 web2py',
'YES': '是',
'about': '關於',
'appadmin is disabled because insecure channel': '因為來自非安全通道,管理介面關閉',
'cache': '快取記憶體',
'change password': '變更密碼',
'click here for online exampl... |
unpingco/mp4utils | mp4_cut.py | Python | mit | 5,940 | 0.051852 | from datetime import datetime, timedelta
from subprocess import PIPE, call, Popen
import tempfile, os, argparse, sys, re
def get_file_duration(infilename):
'''
:param infilename: | input mp4 filename
:type infilename: str
:returns: (h,m,s) tuple
'''
cmd=['ffmpeg','-i',infilename]
p=Popen(cmd,stdout=PIPE,stderr=PIPE)
o | utput=p.stderr.read().decode('utf8')
match=re.search('Duration: (.*?)\.',output)
assert match
h,m,s= parse_ts(match.group(1))
return datetime(2017,1,1,h,m,s)
def parse_ts(instring):
'''
parse time notation
'''
x=instring.split(':')
if len(x)==2:
x.insert(0,'0')
h,m,s = map(int,x)
... |
krummas/cassandra | pylib/cqlshlib/test/run_cqlsh.py | Python | apache-2.0 | 12,156 | 0.002303 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | )
for replace_target in replace:
if (replace_target != ''):
| val = val.replace(replace_target, '')
cqlshlog.debug("read %r from subproc" % (val,))
if val == '':
raise EOFError("'until' pattern %r not found" % (until.pattern,))
got += val
m = until.search(got)
if ... |
tvhong/one | src/game.py | Python | gpl-3.0 | 8,378 | 0.012175 | import pygame, random, time, copy
from Piece import Piece
from pygame.locals import *
from gameconstants import *
# block direction constants
CMD_ROTATE_R, CMD_ROTATE_L, CMD_MOVE_R, CMD_MOVE_L = range(4)
OCCUPIED_S = '1'
OCCUPIED_F = '0'
BLANK = ' '
PENDING_MAX = 50 # max number of elements in pendings
PENDING_MIN = ... | gTime(level):
return 540 - level * 40; # TODO: need a better function
# 500, 460, 420, 380, 340 ...
def _getNextLvlScore(level):
return level*1000; # TODO: need a better function
def _removeEatenLines():
'''only check the static pieces'''
global board, staticPieces
eatenLines = []
for y i... | = False
if eaten:
eatenLines.append(y)
# clear the row in board
for x in range(BOARDCOLS): board[y][x] = BLANK
# clear the row in staticPieces
for p in staticPieces[:]:
ptop, pbot = p.split(y)
if pbot != p:... |
zr40/scc | debugger/cli.py | Python | mit | 6,986 | 0.031492 | import cmd
import json
try:
import readline
except ImportError:
pass
from lib.asmdecoder import AsmDecoder
from lib.uploadprogram import uploadProgram
def run(hardware):
cli = CommandLineInterface(hardware)
cli.printStatus()
cli.cmdloop()
class CommandLineInterface(cmd.Cmd):
def __init__(self, hardware, *args... | sue commands.'
return
self.running = True
self.hardware.run()
def do_stop(self, line):
if not self.running:
print "Can't stop. Program is not running."
return
self.hardware.stop()
self.running | = False
self.printStatus()
def do_reset(self, line):
if self.running:
print 'Program is running. Stop execution to issue commands.'
return
self.hardware.reset()
self.printStatus()
def do_exit(self, line):
'Quits the debugger.'
return True
def emptyline(self):
pass
def do_EOF(self, line):
... |
UtrechtUniversity/yoda-ansible | library/irods_moduser.py | Python | gpl-3.0 | 1,822 | 0.001098 | #!/usr/bin/python
# Copyright (c) 2017-2018 Utrecht University
# GNU General Public License v3.0
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'supported_by': 'community',
'status': ['preview']
}
from ansible.module_utils.basic import *
IRODSCLIENT_AVAILABLE = False
try:
from irods.session import ... | resource = session.users.modify(name, option, value)
except User | DoesNotExist:
module.fail_json(msg="User does not exist.")
else:
changed = True
module.exit_json(
changed=changed,
irods_environment=ienv)
if __name__ == '__main__':
main()
|
maxcutler/wp-xmlrpc-rest-wrapper | wp-rest.py | Python | mit | 13,839 | 0.002457 | from datetime import timedelta
from flask import Flask, json, helpers, request
from flask.views import MethodView
from wordpress_xmlrpc import Client
from wordpress_xmlrpc import methods as wp_methods
from wordpress_xmlrpc.methods import taxonomies as wp_taxonomies
app = Flask(__name__)
wp = Client('http://localhos... | return json.jsonify(response)
class UserApi(MethodView):
name = 'user'
media_type = 'application/vnd.wordpress.user.v1'
@staticmethod
def from_xmlrpc(obj):
return {
'_meta': {
'media_type': UserApi.media_type,
'supports': [' | GET'],
'links': {
'self': route_to_abs(helpers.url_for(UserApi.name, id=obj.id))
}
},
'id': obj.id,
'username': obj.username,
'nickname': obj.nickname,
'description': obj.bio,
'email': obj.email,
... |
titienmiami/mmc.repository | plugin.video.tvalacarta/servers/rtpa.py | Python | gpl-2.0 | 1,033 | 0.026163 | # -*- coding: utf-8 -*-
#-------------------------- | ----------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rtpa
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#--------------------------------------------------- | ---------
import urlparse,urllib2,urllib,re
import os
from core import scrapertools
from core import logger
from core import config
def get_video_url( page_url , premium = False , user="" , password="", video_password="", page_data="" ):
logger.info("tvalacarta.servers.rtpa get_video_url(page_url='%s')" % page_u... |
automl/auto-sklearn | test/test_pipeline/components/classification/test_base.py | Python | bsd-3-clause | 13,012 | 0.000999 | from typing import Optional, Dict
import unittest
from autosklearn.pipeline.util import _test_classifier, \
_test_classifier_predict_proba, _test_classifier_iterative_fit
from autosklearn.pipeline.constants import SPARSE
import sklearn.metrics
import numpy as np
from test.test_pipeline.ignored_warnings import i... | earn.metrics.log_loss(targets, predictions),
places=self.res.get("default_iris_proba_places", 7)
)
def test_default_iris_sparse(self):
if self.__class__ == BaseClassif | icationComponentTest:
return
if SPARSE not in self.module.get_properties()["input"]:
return
for i in range(2):
predictions, targets, _ = \
_test_classifier(dataset="iris",
classifier=self.module,
... |
GluuFederation/community-edition-setup | static/casa/scripts/casa-external_twilio_sms.py | Python | mit | 6,740 | 0.004748 | # This is a modified version of original twilio_sms Gluu's script to work with Casa
from java.util import Arrays
from javax.faces.application import FacesMessage
from org.gluu.jsf2.message import FacesMessages
from org.gluu.oxauth.security import Identity
from org.gluu.oxauth.service import UserService, Authenticati... | ring(user_name) and String | Helper.isNotEmptyString(user_password):
authenticationService.authenticate(user_name, user_password)
user = authenticationService.getAuthenticatedUser()
if user == None:
return False
#Attempt to send message now if user has only one mobil... |
pinntech/flask-logex | runner.py | Python | mit | 198 | 0 | """Runner for testing ap | p and blueprint logging individually"""
import subprocess
from tests.samples import app
if __name__ == '__main__':
app. | run()
subprocess.call(['rm', '-rf', 'logs'])
|
kayaman/jararaca | test/test_sns_projects.py | Python | mit | 1,358 | 0.0081 | from default_test_case import DefaultTestCase
from sns_project import SnsProject
class TestSnsProjects(DefaultTestCase):
def test_project_with_defaults(self):
project = SnsProject.find(self.loaded_config.sns_projects, 'project_with_defaults')
self.assertEqual(project | .raw_message, False)
self.assertEqual(project.env, 'default_sns_env')
self.assertEqual(project.region, 'default_sns_region')
def test_project_with_custom_env(self):
project = SnsProject.find(self.loaded_config.sns_projects, 'project_with_custom_env')
self.assertEqual(project.raw_message, False)
s... | oject.region, 'default_sns_region')
def test_project_with_custom_raw_message(self):
project = SnsProject.find(self.loaded_config.sns_projects, 'project_with_custom_raw_message')
self.assertEqual(project.raw_message, True)
self.assertEqual(project.env, 'default_sns_env')
self.assertEqual(project.regio... |
ctuning/ck | ck/repo/module/soft/module.py | Python | bsd-3-clause | 97,841 | 0.035261 | #
# Collective Knowledge (checking and installing software)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be update... | ['return']>0: return r
d=r['dict']
p=r['path']
duoa=r['data_uoa']
duid=r['data_uid']
if o=='con':
x=duoa
if duid!=duoa: x+=' ('+duid+')'
ck.out('Software d | escription entry found: '+x)
# Check if customize script is redirected into another entry:
#
another_entry_with_customize_script=d.get('use_customize_script_from_another_entry', None)
if another_entry_with_customize_script:
r=ck.access({'action':'find',
'module_uoa': anoth... |
prasanna08/oppia-ml | core/classifiers/TextClassifier/text_classifier_test.py | Python | apache-2.0 | 2,185 | 0 | # coding: utf-8
#
# Copyright 2017 The Oppia 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 requi... | .json')
with open(file_path, 'r') as f:
training_data = json.loads(f.read())
return training_data
class TextClassifierTests(test_utils.GenericTestBase):
"""Tests for text classifier."""
def setUp(self):
super(TextClassifierTests, self).setUp()
self.clf = TextClassifier.TextCla... | """Test that entire classifier is working end-to-end."""
self.clf.train(self.training_data)
classifier_data = self.clf.to_dict()
self.clf.validate(classifier_data)
def test_text_classifier_performance(self):
"""Test the performance of the text classifier.
This method measu... |
VShangxiao/tornado | tornado/auth.py | Python | apache-2.0 | 46,438 | 0.000538 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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... | request to the OP
args = dict((k, v[-1]) for k, v in self.request.arguments.ite | ms())
args["openid.mode"] = u("check_authentication")
url = self._OPENID_ENDPOINT
if http_client is None:
http_client = self.get_auth_http_client()
http_client.fetch(url, functools.partial(
self._on_authentication_verified, callback),
method="POST", bo... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractMobileSuitZetaGundamNovelsTranslation.py | Python | bsd-3-clause | 405 | 0.024691 | def extract | MobileSuitZetaGundamNovelsTranslation(item):
"""
Parser for 'Mobile Suit Zeta Gundam Novels Translation'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'WATTT' in item['tags']:
return buildReleaseMessageWi... | hp, frag=frag, postfix=postfix)
return False
|
kzys/buildbot | buildbot/process/properties.py | Python | gpl-2.0 | 5,112 | 0.005869 | import re
import weakref
from buildbot import util
class Properties(util.ComparableMixin):
"""
I represent a set of properties that can be interpolated into various
strings in buildsteps.
@ivar properties: dictionary mapping property values to tuples
(value, source), where source is a string ... | se it; otherwise, use repl
mo = self.colon_minus_re.match(key)
if mo:
prop, repl = mo.group(1,2)
if properties.has_key(prop):
rv = properties[prop]
else:
rv = repl
| else:
# %(prop:+repl)s
# if prop exists, use repl; otherwise, an empty string
mo = self.colon_plus_re.match(key)
if mo:
prop, repl = mo.group(1,2)
if properties.has_key(prop):
rv = repl
else:
... |
varses/awsch | lantz/drivers/rgblasersystems/__init__.py | Python | bsd-3-clause | 414 | 0 | # -*- coding: utf-8 -*-
"""
lan | tz.drivers.rgblasersystems
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:company: RGB Lasersysteme GmbH.
:description: Lasers and Lasers Systems.
:website: http://www.rgb-laser.com/
----
:copyright: 2015 by Lantz Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
fr... | asEvo']
|
birsoyo/conan | conans/test/build_helpers/cmake_test.py | Python | mit | 41,766 | 0.002275 | import os
import shutil
import stat
import sys
import unittest
import platform
from collections import namedtuple
from conans import tools
from conans.model.conan_file import ConanFile
from conans.model.ref import ConanFileReference
from conans.model.build_info import CppInfo, DepsCppInfo
from conans.model.settings i... | msg)
save(os.path.join(folder, "file3.txt"), msg)
save(os.path.join(folder, "file3.cmake"), msg)
save(os.path.j | oin(folder, "sub", "file3.cmake"), msg)
cmake = CMake(conan_file, generator="Unix Makefiles")
cmake.patch_config_paths()
for folder in (conan_file.build_folder, conan_file.package_folder):
self.assertEqual("Nothing", load(os.path.join(folder, "file1.cmake")))
self.assert... |
tangentlabs/django-fancypages | fancypages/dashboard/views.py | Python | bsd-3-clause | 1,888 | 0 | from django.views import generic
from django.db.models import get_model
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from . import forms
from ..utils import get_page_model, get_node_model
PageNode = get_node_model()
FancyPage = get_page_model()
ContentBlock = ... | t_data(**kwargs)
ctx['title'] = _("Create new page")
return ctx
def get_success_url(self):
return reverse('fp-d | ashboard:page-list')
class PageUpdateView(generic.UpdateView):
model = FancyPage
form_class = forms.PageNodeForm
context_object_name = 'fancypage'
template_name = "fancypages/dashboard/page_update.html"
def get_context_data(self, **kwargs):
ctx = super(PageUpdateView, self).get_context_da... |
nuagenetworks/vspk-python | vspk/v5_0/nuctranslationmap.py | Python | bsd-3-clause | 9,274 | 0.009165 | # -*- 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... |
@customer_alias_ip.setter
def customer_alias_ip(self, value):
""" Set customer_alias_ip value.
Notes:
Customer public IP in the provider domain.
This attribute is named `customerAliasIP` in VSD API.
"""
self... | Customer private IP in the customer domain.
This attribute is n |
pinterest/teletraan | deploy-board/deploy_board/webapp/helpers/placements_helper.py | Python | apache-2.0 | 1,467 | 0.003408 | # Copyright 2016 Pinterest, 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 writi... | S OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
from deploy_board.webapp.helpers.rodimus_client import RodimusClient
rodimus_client = RodimusClient()
def create_placemen | t(request, placement_info):
return rodimus_client.post("/placements", request.teletraan_user_id.token, data=placement_info)
def get_all(request, index, size):
params = [('pageIndex', index), ('pageSize', size)]
return rodimus_client.get("/placements", request.teletraan_user_id.token, params=params)
def ... |
arantebillywilson/python-snippets | py2/lpthw/ex13.py | Python | mit | 440 | 0.002273 | #!/usr/bin/env python
#
# ex13.py
#
| # Author: Billy Wilson Arante
# Created: 2016/04/26 PHT
#
from sys import argv
def main():
"""Exercise 13: Parameters, Unpacking, Va | riables"""
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
if __name__ == "__main__":
main()
|
MashSoftware/place-ui | mash_place_ui/__init__.py | Python | mit | 578 | 0.00519 | # flake8: noqa
from flask import Flask
from flask_ | assets import Environment, Bundle
from flask_compress import Compress
from flask_cache import Cache
from flask_wtf.csrf import CsrfProtect
app = Flask(__name__)
#App config
app.config.from_pyfile('config.py')
# Flask Assets
assets = Environment(app)
css = Bundle('css/custom.css', filters='cssmin', output='css/custom... | (app,config={'CACHE_TYPE': 'simple'})
# CSRF Protection
CsrfProtect(app)
import mash_place_ui.views
|
Alex-Jaeger/CodeBin | src/editor.py | Python | apache-2.0 | 6,836 | 0.010532 | import cgi
print "Content-Type: text/html\n"
form = cgi.FieldStorage()
print """
<!DOCTYPE html>
<html lang="en">
<head>
<title>CodeBin</title>
<link rel="stylesheet" type="text/css" href="./css/editor.css"/>
<link rel="stylesheet" rel="stylesheet" type="text/css" media="screen" href="http://openfontl... | }
keys = [];
};
}, true);
};
function startRickRoll() {
alert("Turn up your volume, You just got RickRolled!");
var rickroll = new Sound("bin/mp3/rickroll.mp3",100,true);
rickroll.start();
}
function loadtext()
{
"""
try:
... |
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var text=xmlhttp.responseText;
var textArray=text.split("\\r\\n");
text="";
for (var x=0;x<textArray.length;x++)
{
text+=textArray[x];
text+="\\n";
}
editor.getSession().setValue(text);
}
else ... |
kevinarpe/kevinarpe-rambutan3 | tests/check_args/annotation/test_NUMBER.py | Python | gpl-3.0 | 362 | 0 | from rambutan3.check_args.annotation.NUMBER import NUMBER
def test():
assert not NUMBER.matches("abc")
assert not NUMBER.matches(True)
assert N | UMBER.matches(-1.234)
assert NUMBER.matches( | -1)
assert NUMBER.matches(0)
assert NUMBER.matches(0.234)
assert NUMBER.matches(1)
assert NUMBER.matches(1.234)
assert NUMBER.matches(2)
|
rohe/pysaml2-3 | tools/parse_xsd2.py | Python | bsd-2-clause | 68,704 | 0.005618 | #!/usr/bin/env python
import re
import time
import getopt
import imp
import sys
import types
import errno
__version__ = 0.5
from xml.etree import cElementTree as ElementTree
INDENT = 4*" "
DEBUG = False
XMLSCHEMA = "http://www.w3.org/2001/XMLSchema"
XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
CLASS_PRO... | ].class_name
except KeyError:
| cname = cdict[class_pyify(typ)].class_name
else:
cname = typ
return mod, cname
def leading_uppercase(string):
try:
return string[0].upper()+string[1:]
except IndexError:
return string
except TypeError:
return ""
def leading_lowercase(string):
... |
SaschaMester/delicium | tools/telemetry/telemetry/web_perf/metrics/smoothness_unittest.py | Python | bsd-3-clause | 13,607 | 0.003087 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.internal.results import page_test_results
from telemetry.page import page as page_module
from telemetry.web_perf.metrics impo... | sture_scroll_update_latency=[[], []])
value = self.metric._ComputeFirstGestureScrollUpdateLatency(
self.page, stats)
self.assertEquals((), value)
d | ef testComputeGestureScrollUpdateLatencyWithNotEnoughFrames(self):
stats = _MockRenderingStats(
frame_timestamps=self.not_enough_frames_timestamps,
gesture_scroll_update_latency=[[10, 20], [30, 40, 50]])
gesture_value = self.metric._ComputeFirstGestureScrollUpdateLatency(
self.page, stat... |
imec-myhdl/pycontrol-gui | BlockEditor/libraries/library_can/Epos_AD.py | Python | lgpl-2.1 | 283 | 0.024735 | # cell definition
# name = 'Epos_AD'
# libname = 'can'
inp = 0
outp = 1
parameters = dict() #parametriseerbare cell
properties = {'Device ID': ' 0x01', 'Channel [0/1]': ' 0', 'name': 'epos_areadBlk'} #voor netlisten
#view variables:
ic | onSource = 'AD'
views | = {'icon':iconSource}
|
nanocell/lsync | python/boto/cloudformation/connection.py | Python | gpl-3.0 | 15,766 | 0.001395 | # Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
#
# 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, modi... | te_certs)
def _required_auth_capability(self):
return ['hmac-v4']
def encode_bool(self, v):
v = bool(v)
return {True: "true", False: "false"}[v]
def _build_create_or_update_params(self, stack_name, template_body,
template_url, parameters,
... | """
Helper that creates JSON parameters needed by a Stack Create or
Stack Update call.
:type stack_name: string
:param stack_name: The name of the Stack, must be unique amoung running
Stacks
:type template_body: string
:param template_body: ... |
uttamk/katas | roman_numerals/python/roman_numerals/__init__.py | Python | mit | 98 | 0.010204 | sin | gle_numeral_to_decimal_map = {"I": | 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
|
geodashio/geodash-server | geodashserver/apps.py | Python | bsd-3-clause | 143 | 0 | from djan | go.apps import AppConfig
c | lass GeoDashServerDjangoConfig(AppConfig):
name = 'geodashserver'
verbose_name = "GeoDash Server"
|
jeremiahyan/odoo | odoo/models.py | Python | gpl-3.0 | 303,080 | 0.002221 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
"""
Object Relational Mapping module:
* Hierarchical structure
* Constraints consistency and validation
* Object metadata depends on its status
* Optimised processing by complex query (multiple a... | name)
if len(name) > 63:
raise ValidationError("Table name %r is too long" % name)
# match private methods, to prevent their remote invocation
regex_private = re | .compile(r'^(_.*|init)$')
def check_method_name(name):
""" Raise an ``AccessError`` if ``name`` is a private method name. """
if regex_private.match(name):
raise AccessError(_('Private methods (such as %s) cannot be called remotely.') % (name,))
def fix_import_export_id_paths(fieldname):
"""
F... |
bikong2/django | tests/auth_tests/test_views.py | Python | bsd-3-clause | 45,028 | 0.001621 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import itertools
import os
import re
from importlib import import_module
from django.apps import apps
from django.conf import settings
from django.contrib.admin.models import LogEntry
from django.contrib.auth import REDIRECT_FIELD_NAME, S... | manageable', last_name='Password',
email='unmanageable_password@example.com', is_staff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
cls.u6 = User.objects.create(
password='foo$bar', last_login=datetime.datetime(2006, 12, 17, 7, 3, 31)... | aff=False, is_active=True,
date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
)
def login(self, username='testclient', password='password'):
response = self.client.post('/login/', {
'username': username,
'password': password,
})
self.assertIn(S... |
xiaoyexu/xCRM | crm/admin.py | Python | gpl-3.0 | 12,452 | 0.002008 | # -*- coding: UTF-8 -*-
from django.contrib import admin
from .models import *
class UserAdmin(admin.ModelAdmin):
list_display = ('nickName', 'realName')
admin.site.register(User, UserAdmin)
class UserLoginStatusAdmin(admin.ModelAdmin):
list_display = ('key', 'description')
admin.site.register(UserLogin... | ', 'description')
ad | min.site.register(PFType, PFTypeAdmin)
class PriorityTypeAdmin(admin.ModelAdmin):
list_display = ('orderType', 'key', 'description', 'sortOrder')
admin.site.register(PriorityType, PriorityTypeAdmin)
class StatusTypeAdmin(admin.ModelAdmin):
list_display = ('orderType', 'key', 'description', 'sortOrder')
... |
plotly/plotly.py | packages/python/plotly/plotly/validators/layout/_computed.py | Python | mit | 395 | 0 | import _plotly_utils.basev | alidators
class ComputedValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="computed", parent_name="layout", **kwargs):
super(ComputedValidator, self).__init__(
plotly_name=plotly_name,
| parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
rajrohith/blobstore | samples/file/__init__.py | Python | apache-2.0 | 902 | 0.003333 | #-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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 Licen | se 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 for the specific language governin... | t FileSasSamples
from .share_usage import ShareSamples
from .directory_usage import DirectorySamples
from .file_usage import FileSamples |
wallnerryan/quantum_migrate | quantum/plugins/cisco/nexus/cisco_nexus_plugin_v2.py | Python | apache-2.0 | 9,634 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache... | riate interfaces
for this VLAN
"""
LOG.debug(_("NexusPlugin:create_network() called") | )
# Grab the switch IP and port for this host
switch_ip = ''
port_id = ''
for switch in self._nexus_switches.keys():
for hostname in self._nexus_switches[switch].keys():
if str(hostname) == str(host):
switch_ip = switch
... |
harunyasar/rabbitmq_playground | default_exchange_receiver.py | Python | gpl-3.0 | 779 | 0.002567 | from sender import *
import threading
QUEUE_NAME = 'event_queue'
class CompetingReceiver(object):
def __init__(self):
self.connection = Connection().initialize()
def receive(self):
self.connection.channel.queue_declare(QUEUE_NAME, False, False, False, None)
self.connection.channel.ba... | on1 = CompetingReceiver()
connection2 = CompetingReceiver()
t1 = threading.Thread(target=connection1.receive())
t2 = threading.Thread(target=connection2.receive())
t1.start()
| t2.start()
t1.join()
t2.join()
connection1.connection.destroy()
connection2.connection.destroy()
|
teoreteetik/api-snippets | lookups/lookup-get-basic-example-1/lookup-get-basic-example-1.6.x.py | Python | mit | 406 | 0 | # Download the Python helper library from twilio.com/docs/python/install
from t | wilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACCOUNT_SID"
auth_token = "your_auth_token"
client = Client(a | ccount_sid, auth_token)
number = client.lookups.phone_numbers("+15108675309").fetch(type="carrier")
print(number.carrier['type'])
print(number.carrier['name'])
|
xskh2007/zjump | dbtool/test.py | Python | gpl-2.0 | 722 | 0.009772 | # -*- coding: UTF-8 -*-
# 来源:疯狂的蚂蚁的博客www.c | razyant.net总结整理
import MySQLdb as mdb
import sys
#获取数据库的链接对象
#con = mdb.connect('192.168.2.117', 'root', 'zzjr#2015', 'disconf')
con = mdb.connect('localhost', 'root', '', 'jumpserver')
with con:
#获取普通的查询cursor
cur = con.cursor()
cur.execute("select * from juser_user")
rows = cur.fetchall()
#获取... | (desc[0][0], desc[1][0])
# print rows[2][11].decode('ascii').encode('utf-8')
print rows[2][11]
|
rspavel/spack | var/spack/repos/builtin/packages/gdk-pixbuf/package.py | Python | lgpl-2.1 | 3,882 | 0.002061 | # Copy | right 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class GdkPixbuf(Package):
"""The Gdk Pixbuf is a toolkit for image loading and pixel buffer
man... | it off into a separate package in
preparation for the change to GTK+ 3."""
homepage = "https://developer.gnome.org/gdk-pixbuf/"
url = "https://ftp.acc.umu.se/pub/gnome/sources/gdk-pixbuf/2.40/gdk-pixbuf-2.40.0.tar.xz"
list_url = "https://ftp.acc.umu.se/pub/gnome/sources/gdk-pixbuf/"
list_de... |
xenigmax/seqan | util/bin/demo_checker.py | Python | bsd-3-clause | 4,665 | 0.005145 | #!/usr/bin/env python2
"""Demo checker script.
Given a demo .cpp file PATH.cpp we can make it a small test if there is a file
PATH.cpp.stdout and/or PATH.cpp.stderr. The test is implemented using this
script.
The script is called with the options --binary-path and one or both of
--stdout-path and --stderr-path. The... | ath:
with open(args.stdout_path, 'rb') as f:
out = f.read()
if args.stderr_path:
with open(args.stderr_path, 'rb') as f:
err = f.read()
return t(out.strip()).split('\n'), t(err.strip()).split('\n')
def runDemo(args):
cmd = [args.binary_path]
p = subprocess.Popen... | doutbuff, stderrbuff = p.communicate()
return t(stdoutbuff.strip()).split('\n'), t(stderrbuff.strip()).split('\n'), p.returncode
def main():
"""Program entry point."""
parser = argparse.ArgumentParser(description='Run SeqAn demos as apps.')
parser.add_argument('--binary-path', dest='binary_path', requ... |
ratnania/pyccel | pyccel/codegen/__init__.py | Python | mit | 125 | 0.024 | # -*- coding: UTF-8 -*-
from .c | odegen import *
from .cmake | import *
from .printing import *
from .utilities import *
|
agoose77/hivesystem | dragonfly/logic/toggle.py | Python | bsd-2-clause | 568 | 0.001761 | import bee
from bee.segments import *
class | toggle(bee.worker):
inp = antenna("push", "trigger")
on = variable("bool")
parameter(on, False)
state = output("pull", "bool")
connect(on, state)
true = output("push", "trigger")
trig_true = triggerfunc(true)
false = output("push", "trigger")
trig_false = trigge | rfunc(false)
@modifier
def m_trig(self):
if self.on:
self.on = False
self.trig_false()
else:
self.on = True
self.trig_true()
trigger(inp, m_trig) |
SnowWalkerJ/quantlib | quant/data/wind/tables/cbondbalancesheet.py | Python | gpl-3.0 | 14,897 | 0.019439 | from ....common.db.sql import VARCHAR, Numeric as NUMBER, DateTime as DATETIME, Column, BaseModel, CLOB, DATE
VARCHAR2 = VARCHAR
class CBondBalanceSheet(BaseModel):
"""
4.158 中国债券发行主体资产负债表
Attributes
----------
object_id: VARCHAR2(100)
对象ID
s_info_compcode: VARCHAR2(40)
公司I... | (20,4)
开发支出
goodwill: NUMBER(20,4)
商誉
long_term_deferred_exp: NUMBER(20,4)
长期待摊费用
deferred_tax_assets: NUMBER(20,4)
递延所得税资产
loans_and_adv_granted: NUMBER(20,4)
发放贷款及垫款
oth_non_cur_assets: NUMBER(20,4)
其他非流动资 | 产
tot_non_cur_assets: NUMBER(20,4)
非流动资产合计
cash_deposits_central_bank: NUMBER(20,4)
现金及存放中央银行款项
asset_dep_oth_banks_fin_inst: NUMBER(20,4)
存放同业和其它金融机构款项
precious_metals: NUMBER(20,4)
贵金属
derivative_fin_assets: NUMBER(20,4)
衍生金融资产
agency_b... |
pjurik2/pykarma | feeds/rss.py | Python | mit | 3,205 | 0.005304 | import os, sys
import random
import time
import feedparser
import itertools
import HTMLParser
from feed import Feed
if os.getcwd().rstrip(os.sep).endswith('feeds'):
os.chdir('..')
sys.path.insert(0, os.getcwd())
from gui_client import new_rpc
import web
import reddit
class RSSFeed(Feed):
def __init__(se... | eq.geturl()
except:
print 'URL retrieval error for ', url
retu | rn False
url = self.url_post_filter(url)
if (url in self.urls) or not url.startswith('http://'):
return False
self.urls.add(url)
feed_title = self.default_title_filter(post.get('title', ''))
page_title = self.default_title_filter(self.web.title... |
stormi/tsunami | src/secondaires/cuisine/commandes/recettes/__init__.py | Python | bsd-3-clause | 2,392 | 0.003349 | # -*-coding:Utf-8 -*
# Copyright (c) 2012 NOEL-BARON Léo
# 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
# li... | AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL... | DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant la commande... |
cyanfish/heltour | heltour/tournament/migrations/0146_league_description.py | Python | mit | 414 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-02-23 22:12
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('tournament', '0145 | _auto_20170211_1825'),
]
operations = [
migrations.AddField(
model_name='league',
name='description',
field=models.TextField(blank=True),
),
]
|
asiviero/brbeerindex | beerindex/spiders/beerspider.py | Python | lgpl-2.1 | 4,667 | 0.012642 | from scrapy.spiders import Spider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from scrapy.conf import settings
from beerindex.items import BeerindexItem
import logging
import lxml.html
from urlparse import urlparse
import re
class BeerSpider(Spider):
name = "beerspider"
beer_... | " : " | //div[@class='resumo']//span[@class='nome-tipo']//text()"
},
'www.emporioveredas.com.br' : {
"start_url" : 'http://www.emporioveredas.com.br/cervejas-importadas.html',
"next_link" : '.pager a.next::attr(href)',
"product_link" : '.products-grid a.product-image ::attr("... |
Makeystreet/makeystreet | woot/apps/catalog/migrations/0100_auto__add_field_space_kind__add_field_space_logo__add_field_space_lati.py | Python | apache-2.0 | 50,619 | 0.007645 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Space.kind'
db.add_column(u'catalog_space', 'kind',
... | o.db.models.fields.IntegerField')(default=0, null=True, blank=True),
| keep_default=False)
def backwards(self, orm):
# Deleting field 'Space.kind'
db.delete_column(u'catalog_space', 'kind')
# Deleting field 'Space.logo'
db.delete_column(u'catalog_space', 'logo')
# Deleting field 'Space.latitude'
db.delete_column(u'... |
tannoa2/RackHD | test/tests/switch/test_rackhd11_switch_pollers.py | Python | apache-2.0 | 12,932 | 0.004098 | '''
Copyright 2016, EMC, Inc.
Author(s):
FIT test script template
'''
import fit_path # NOQA: unused import
import sys
import subprocess
import pprint
import fit_common
import test_api_utils
# LOCAL
NODELIST = []
def get_switches():
# returns a list with valid node IDs that match ARGS_LIST.sku in 'Name' or ... | mestamp from current poll"
print "\t{0}".format(msg)
for node in NODELIST:
if fit_common.VERBOSITY | >= 2:
print "\nNode: ", node
nodetype = get_rackhd_nodetype(node)
# Run test against managed nodes only
if nodetype != "unknown" and nodetype != "Unmanaged":
poller_dict = test_api_utils.get_supported_pollers(node)
for poller in poller... |
teeple/pns_server | work/install/Python-2.7.4/Lib/test/test_setcomps.py | Python | gpl-2.0 | 3,847 | 0.00104 | doctests = """
########### Tests mostly copied from test_listcomps.py ############
Test simple loop with conditional
>>> sum({i*i for i in range(100) if i&1 == 1})
166650
Test simple case
>>> {2*y + x + 1 for x in (0,) for y in (1,)}
set([3])
Test simple nesting
>>> list(sorted({(i,j) for i in... | r i in range(5)}
... return {x() for x in ite | ms}
>>> test_func()
set([4])
>>> def test_func():
... items = {(lambda: i) for i in range(5)}
... i = 20
... return {x() for x in items}
>>> test_func()
set([4])
>>> def test_func():
... items = {(lambda: y) for i in range(5)}
... y = 2
... retur... |
maciekzdaleka/lab11 | write-aws-queue.py | Python | mit | 1,195 | 0.009205 |
# This script created a queue
#
# Author - Paul Doyle Nov 2015
#
#
import boto.sqs
import boto.sqs.queue
from boto.sqs.message import Message
from boto.sqs.connection import SQSConnection
from boto.exception import SQSError
import sy | s
import urllib2
# Get the keys from a specific url and then use them to connect to AWS Service
response = urllib2.urlopen('http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key')
html=response.read()
result = html.split(':')
#print (result[0])
#print (result[1])
access_key_id = result[0]
secret_access_key ... | ss_key_id=access_key_id, aws_secret_access_key=secret_access_key)
student_number = 'C13470112'
#conn.delete_queue(sys.argv[1])
queue_name = student_number+sys.argv[1]
# Get a list of the queues that exists and then print the list out
rs = conn.get_queue(queue_name)
# Get a list of the queues that exists and then print... |
wohllab/milkyway_proteomics | galaxy_milkyway_files/tools/wohl-proteomics/wohl_skyline/msstats_plots_wrapper.py | Python | mit | 7,436 | 0.023534 | import os, sys, re
import optparse
import shutil
import pandas
import numpy
import gc
import subprocess
#####################################
#This is a script to combine the output reports from
#Skyline, in preparation for MSstats! Let's get started.
#
#VERSION 0.70A
version="0.70A"
#DATE: 10/11/2016
date="10/11/201... | #So, first, let's check if we can output a heatmap (number of comp | arisons >2)
if len(comparison_df['Label'].unique().tolist())>=2:
#script_writer.write("groupComparisonPlots(data=comparisonResult$ComparisonResult,type=\"Heatmap\", logBase.pvalue=2, sig="+str(options.significance)+", FCcutoff="+str(options.FCthreshold)+",ylimUp="+str(ylimUp)+",ylimDown="+str(ylimDown)+",x... |
googledatalab/pydatalab | solutionbox/ml_workbench/tensorflow/setup.py | Python | apache-2.0 | 1,189 | 0.003364 | # Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
| #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITI | ONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
# This setup file is used when running cloud training or cloud dataflow jobs.
from setuptools import setup, find_packages
setup(
name='trainer',
version='1.0.0',
pa... |
hajgato/easybuild-easyblocks | setup.py | Python | gpl-2.0 | 3,586 | 0.012828 | ##
# Copyright 2012-2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | easy_install --user .
or
python setup.py --prefix=$HOME/easybuild
@author: Kenneth Hoste (Ghent University)
"""
import os
import r | e
import sys
from distutils import log
sys.path.append('easybuild')
from easyblocks import VERSION
API_VERSION = str(VERSION).split('.')[0]
suff = ''
rc_regexp = re.compile("^.*(rc[0-9]*)$")
res = rc_regexp.search(str(VERSION))
if res:
suff = res.group(1)
dev_regexp = re.compile("^.*[0-9]dev$")
if dev_regexp.mat... |
amlyj/pythonStudy | 2.7/rpc/RPyC/demo.py | Python | mit | 1,415 | 0.002126 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-8-13 下午1:31
# @Author : Tom.Lee
# @CopyRight : 2016-2017
# @File : demo.py
# @Product : PyCharm
# @Docs :
# @Source :
import rpyc
from rpyc.utils.server import ThreadedServer
class MyService(rpyc.Se... | def conn(cls):
connections = rpyc.connect('localhost', 15111)
connections.root.save_data(123)
print connections.r | oot.get_data()
if __name__ == '__main__':
import threading
import time
server = ThreadedServer(MyService, port=15111)
client = MyClient()
def start():
print '*************************************'
print '*************************************'
print '*****************RpyC... |
Show-Me-the-Code/python | Drake-Z/0010/0010.py | Python | mit | 1,049 | 0.01164 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'第 0010 题:使用 Python 生成类似于图中的字母验证码图片'
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 随机字母:
def rndChar():
return chr(rand | om.randint(65, 90))
# 随机颜色1:
def rndColor():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 随机颜色2:
def rndColor2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, ... | geDraw.Draw(image)
# 填充每个像素:
for x in range(width):
for y in range(height):
draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('0010\code.jpg', 'jpeg') |
harish2rb/pyGeoNet | test/test_pygeonet_processing.py | Python | gpl-3.0 | 4,709 | 0.031004 | # pyGeoNet_readGeotiff
#import sys
#import os
from osgeo import gdal
#from string import *
import numpy as np
from time import clock
import pygeonet_defaults as defaults
import pygeonet_prepare as Parameters
from math import modf, floor
#from scipy.stats.mstats import mquantiles
def read_dem_from_geotiff(demFileName... | s
Parameters.xDemSize=np.size(rawDemArray,0)
Parameters.yDemSize=np.size(ra | wDemArray,1)
# Calculate pixel length scale and assume square
Parameters.maxLowerLeftCoord = np.max([Parameters.xDemSize, Parameters.yDemSize])
print 'DTM size: ',Parameters.xDemSize, 'x' ,Parameters.yDemSize
#-----------------------------------------------------------------------------
# Compute s... |
abrenaut/waybackscraper | waybackscraper/exceptions.py | Python | mit | 82 | 0 | # -*- coding: utf-8 -*- |
c | lass ScrapeError(Exception):
"""scraping Failed"""
|
uclouvain/osis | assessments/templatetags/score_display.py | Python | agpl-3.0 | 1,668 | 0.0018 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | stration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2 | 015-2021 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... |
bigown/SOpt | Python/OOP/Static.py | Python | mit | 117 | 0.017094 | class Car:
def beep():
print('Beep')
car = C | ar()
Car.beep()
#ht | tps://pt.stackoverflow.com/q/482008/101
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.