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 |
|---|---|---|---|---|---|---|---|---|
jeremiah-c-leary/vhdl-style-guide | vsg/vhdlFile/classify/integer_type_definition.py | Python | gpl-3.0 | 211 | 0 |
from vsg.vhdlFile.clas | sify import range_constraint
def detect(iToken, lObjects):
'''
integer_type_definition ::=
range_constraint
'''
return range_constraint.detect(iToken, lOb | jects)
|
sean797/tracer | tracer/__init__.py | Python | gpl-2.0 | 273 | 0.018315 | from __futur | e__ import absolute_import
from tracer.query import Query
from tracer.resources.package import Package
from tracer.resources.applications import Application
from tracer.resources.proce | sses import Process
__all__ = [
Query,
Package,
Application,
Process,
] |
caot/intellij-community | python/testData/keywordCompletion/exceptNotIndented.py | Python | apache-2.0 | 26 | 0.115385 | try: |
a = 1
exce<caret | > |
goanpeca/mongokit | mongokit/operators.py | Python | bsd-3-clause | 3,264 | 0.000306 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2010, Nicolas Clairon
# 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 abov... | ity of California, Berkeley nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific | prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS AND CONTRIBUTORS BE L... |
qliu/globe_nocturne | globenocturne/globenocturneapp/models.py | Python | gpl-2.0 | 10,974 | 0.013851 | from django.contrib.gis.db import models
class SatYear(models.Model):
year = models.IntegerField(primary_key=True)
def __unicode__(self):
return str(self.year)
class Meta:
verbose_name = 'Year'
db_table = u'sat_year'
class Satellite(models.Model):
# id = model... | class Meta:
verbose_name = 'Satellite'
db_table = u'satellite'
class DMSPProduct(models.Model):
# id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'DMSP Prod... | els.CharField(max_length=100,null='True',blank='True')
year = models.ForeignKey('SatYear',verbose_name='Year')
satellite = models.ForeignKey('Satellite',verbose_name='Satellite')
product = models.ForeignKey('DMSPProduct',verbose_name='DMSP Product')
wms_layer = models.CharField(max_length=100,verbose_na... |
nave91/teak-nbtree | src/project.py | Python | gpl-2.0 | 1,490 | 0.043624 | from reader import *
from di | st import *
from sys import *
from table import *
def project(z,data):
d = anyi(data[z])
if d == len(data[z]):
d-=1
x = [0]*len(data[z])
y = [0]*len(data[z])
east = furthest(d,data,z)
west = furthest(data[z].index(east),data,z)
inde = data[z].index(east)
indw = data[z].index(wes... | t "+"
bigger = 1.05
some = 0.000001
c = dist(data[z][east],data[z][west],data,z,indep,nump)
for d in data[z]:
ind = data[z].index(d)
a = dist(data[z][ind],data[z][east],data,z,indep,nump)
b = dist(data[z][ind],data[z][west],data,z,indep,nump)
if a > c*bigger:
... |
navdeepghai/bcommerce | bcommerce/utils/products.py | Python | mit | 13,513 | 0.038111 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
'''
Developer Navdeep Ghai
Email navdeep@korecent.com
License Korecent Solution Pvt. Ltd.
'''
import frappe
from frappe import _, msgprint, throw
from bcommerce.utils.api import get_connection, is_exists
from erpnext.controllers.item_variant import cr... | ions in
OptionSet and then create the Item Attribute
'''
def create_variants(attribute, template, product, setting):
attr_name = attrib | ute[0].get("attribute") if len(attribute) >= 1 else None
if not attr_name:
return
options = frappe.db.get_values("Item Attribute Value", filters={"parent": attr_name},
fieldname=["attribute_value", "abbr"], as_dict=True)
for opt in options:
args = {}
item_code = "{0}-{1}".format(template.item_code, opt.ge... |
sebrandon1/tempest | tempest/api/volume/admin/test_qos.py | Python | apache-2.0 | 6,582 | 0 | # 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... | self.created_qos['id'], operation,
vol_type[0]['id'])
# disassociate all volume-types from qos-specs
self.admin_volume_qos_client.disassociate_all_qos(
self.created_qos['id'])
ope | ration = 'disassociate-all'
waiters.wait_for_qos_operations(self.admin_volume_qos_client,
self.created_qos['id'], operation)
class QosSpecsV1TestJSON(QosSpecsV2TestJSON):
_api_version = 1
|
vickz84259/XKCD | scripts/argument.py | Python | mit | 2,906 | 0 | #!/usr/bin/env python
# Standard library modules
import ConfigParser
import argparse
import os
import textwrap
def create_config(configuration):
""" Function used to create the configuration file
if it does not exist in the program's path.
It returns a ConfigParser object
"""
configuration.add_s... | --range 30 100 # represents th | e latest comic.')
args = parser.parse_args()
if args.path != config.get('Defaults', 'path'):
if not os.path.lexists(args.path):
os.mkdir(args.path)
config.set('Defaults', 'path', args.path)
else:
config.set('Defaults', 'path', args.path)
with open(... |
summermk/dragonfly | dragonfly/language/other/number_arabic.py | Python | lgpl-3.0 | 5,267 | 0.016999 | #
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version ... | ilder({
| "واحد": 1,
"اثنان": 2,
"ثلاثة": 3,
"اربعة": 4,
"خمسة": 5,
"ستة": 6,
... |
CyberLabs-BR/face_detect | pyimagesearch/nn/mxconv/__init__.py | Python | mit | 245 | 0.004082 | # import the necessary packages
from .mxalexnet import MxAlexNet
from .mxvggnet import M | xVGGN | et
from .mxgooglenet import MxGoogLeNet
from .mxresnet import MxResNet
from .mxsqueezenet import MxSqueezeNet
from .mxagegendernet import MxAgeGenderNet |
Ch00k/gun | setup.py | Python | mit | 728 | 0.034341 | #!/usr/bin/env python
from setuptools import setup
from gun import __version__
setup(
name = 'gun',
version = __version__,
description = 'Gentoo Updates Notifier',
author = 'Andriy Yurchuk',
author_email = 'ayurchuk@minuteware.net',
url = 'https://github.com/Ch00k/gun',
licen... | ]
},
packages = ['gun'],
data_files = [('/etc/gun/', ['data/gun.conf'])],
install_requires = | ['xmpppy >= 0.5.0-rc1']
) |
gedakc/manuskript | manuskript/converters/__init__.py | Python | gpl-3.0 | 1,027 | 0.000974 | #!/usr/bin/env python
# --!-- coding: utf8 --!--
"""
The converters package provide functions to quickly convert on the fly from
one format to another. It is responsible to check what external library are
present, and do the job as best as possible with what we have in hand.
"""
from manuskript.converters.abstractCon... | nvert from HT | ML to plain text.
"""
if pandocConverter.isValid():
return pandocConverter.convert(html, _from="html", to="plain")
# Last resort: probably resource inefficient
e = QTextEdit()
e.setHtml(html)
return e.toPlainText()
|
GcsSloop/PythonNote | PythonCode/Python进阶/模块/导入模块.py | Python | apache-2.0 | 2,071 | 0.005311 | #coding=utf-8
#author: sloop
'''
ÈÎÎñ
PythonµÄos.pathÄ£¿éÌṩÁË isdir() ºÍ isfile()º¯Êý£¬Çëµ¼Èë¸ÃÄ£¿é£¬²¢µ÷Óú¯ÊýÅжÏÖ¸¶¨µÄĿ¼ºÍÎļþÊÇ·ñ´æÔÚ¡£
×¢Òâ:
1. ÓÉÓÚÔËÐл·¾³ÊÇÆ½Ì¨·þÎñÆ÷£¬ËùÒÔ²âÊÔµÄÒ²ÊÇ·þÎñÆ÷ÖеÄÎļþ¼ÐºÍÎļþ£¬¸Ã·þÎñÆ÷ÉÏÓÐ/data/webroot/resource/pythonÎļþ¼ÐºÍ/data/webroot/resource/python/test.txtÎļþ£¬´ó¼Ò | ¿ÉÒÔ²âÊÔÏ¡£
2. µ±È»£¬´ó¼Ò¿ÉÒÔÔÚ±¾»úÉϲâÊÔÊÇ·ñ´æÔÚÏàÓ¦µÄÎļþ¼ÐºÍÎļþ¡£
import os
print os.path.isdir(r'C:\Windows')
print os.path.isfile(r'C:\Windows\notepad.exe')
'''
import os
print os.path.isdir(r'C:\Windows')
print os.path.isfile(r'C:\Windows\notepad.exe')
'''
×¢Òâµ½os.pathÄ£¿é¿ÉÒÔÒÔÈô¸ÉÖÖ·½Ê½µ¼È룺
import os
i... | ´úÂë:
import os
print os.path.isdir(r'/data/webroot/resource/python')
print os.path.isfile(r'/data/webroot/resource/python/test.txt')
'''
'''
µ¼ÈëÄ£¿é
ҪʹÓÃÒ»¸öÄ£¿é£¬ÎÒÃDZØÐëÊ×Ïȵ¼Èë¸ÃÄ£¿é¡£PythonʹÓÃimportÓï¾äµ¼ÈëÒ»¸öÄ£¿é¡£ÀýÈ磬µ¼Èëϵͳ×Ô´øµÄÄ£¿é math£º
import math
Äã¿ÉÒÔÈÏΪmath¾ÍÊÇÒ»¸öÖ¸ÏòÒѵ¼ÈëÄ£¿éµÄ±äÁ¿£¬Í¨¹ý... |
sklnet/opendroid-enigma2 | lib/python/Plugins/SystemPlugins/DeviceManager/HddSetup.py | Python | gpl-2.0 | 8,530 | 0.030481 | # for localized messages
from . import _
from enigma import *
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.Sources.List import List
from Tools.Directories import resolveFilename, SCOPE_CURRENT_PLUGIN
from Tools.LoadPixmap import LoadPixmap
from Components.Button import B... | e = LoadPixmap(cached = True, path = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/DeviceManager/icons/diskusb.png"));
else:
picture = LoadPi | xmap(cached = True, path = resolveFilename(SCOPE_CURRENT_PLUGIN, "SystemPlugins/DeviceManager/icons/disk.png"));
return (picture, model, size)
class HddSetup(Screen):
skin = """
<screen name="HddSetup" position="center,center" size="560,430" title="Hard Drive Setup">
<ePixmap pixmap="skin_default/buttons/red.png... |
Baldanos/hydrafw | src/build-scripts/dfu-convert.py | Python | apache-2.0 | 5,855 | 0.029889 | #!/usr/bin/python2
# Written by Antonio Galea - 2010/11/18
# Distributed under Gnu LGPL 3.0
# see http://www.gnu.org/licenses/lgpl-3.0.txt
import sys,struct,zlib,os
from optparse import OptionParser
from intelhex import IntelHex
DEFAULT_DEVICE="0x0483:0xdf11"
DEFAULT_REVISION="0.0"
def named(tuple,names):
return ... | ddress, 'data': data })
revision = DEFAULT_REVISION
if options.revision:
try:
rev2byte(options.revision)
revision = options.revision
except ValueError:
print("Invalid revision value.")
sys.exit(1)
outfile = args[0]
device = DEFAULT_D... | evice.split(':',1)]
except:
print("Invalid device '%s'." % device)
sys.exit(1)
build(outfile,[target],device, revision)
elif len(args)==1:
infile = args[0]
if not os.path.isfile(infile):
print("Unreadable file '%s'." % infile)
sys.exit(1)
parse(infile, dump_images=options.d... |
trondhindenes/ansible | test/runner/lib/cloud/vcenter.py | Python | gpl-3.0 | 5,079 | 0.002363 | """VMware vCenter plugin for integration tests."""
from __future__ import absolute_import, print_function
import os
from lib.cloud import (
CloudProvider,
CloudEnvironment,
)
from lib.util import (
find_executable,
display,
)
from lib.docker_util import (
docker_run,
docker_rm,
docker_in... | es after tests complete."""
if self.container_name:
docker_rm(self.args, self.container_name)
super(Vce | nterProvider, self).cleanup()
def _setup_dynamic(self):
"""Create a vcenter simulator using docker."""
container_id = get_docker_container_id()
if container_id:
display.info('Running in docker container: %s' % container_id, verbosity=1)
self.container_name = self.DOCKE... |
fernandog/Medusa | medusa/providers/torrent/html/speedcd.py | Python | gpl-3.0 | 7,255 | 0.002205 | # coding=utf-8
"""Provider code for Speed.cd."""
from __future__ import unicode_literals
import logging
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.providers.torren... | ():
log.debug('Unable to get login URL')
return False
response = self.session.post(self.urls['login_post'], data=login_params)
if not response or not response.text:
log.debug('Unable to connect to provider using login URL: {url}',
{'url': self.u... | password. please try again' in response.text.lower():
log.warning('Invalid username or password. Check your settings')
return False
return True
log.warning('Unable to connect to provider')
return
def login_url(self):
"""Get the login url (post) as speed.cd ... |
mmirecki/ovirt-provider-mock | vifdriver/vif_driver.py | Python | gpl-2.0 | 1,986 | 0 | from abc import abstractmethod
class VIFDriver(object):
@abstractmethod
def after_device_destroy(self, environ, domxml):
return domxml
@abstractmethod
def after_device_create(self, environ, domxml):
return domxml
@abstractmethod
def after_network_setup(self, environ, json_co... | ation_source(self, environ, domxml):
return domxml
@abstractmethod
def before_migration_destination(self, environ, domxml) | :
return domxml
@abstractmethod
def before_network_setup(self, environ, json_content):
return json_content
@abstractmethod
def before_vm_start(self, environ, domxml):
return domxml
|
saukrIppl/seahub | thirdpart/djangorestframework-3.3.2-py2.7.egg/rest_framework/relations.py | Python | apache-2.0 | 18,087 | 0.000829 | # coding: utf-8
from __future__ import unicode_literals
from collections import OrderedDict
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.core.urlresolvers import (
NoReverseMatch, Resolver404, get_script_prefix, resolve
)
from django.db.models import Manager
from django.... | off_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text)
assert self.queryset is not None or kwargs.get('read_only', None), (
'Relational f | ield must provide a `queryset` argument, '
'or set read_only=`True`.'
)
assert not (self.queryset is not None and kwargs.get('read_only', None)), (
'Relational fields should not provide a `queryset` argument, '
'when setting read_only=`True`.'
)
kwargs... |
qistoph/thug | src/DOM/W3C/HTML/HTMLImageElement.py | Python | gpl-2.0 | 984 | 0.014228 | #!/usr/bin/env python
from .HTMLElement import HTMLElement
from .attr_property import attr_property
from .compatibility import thug_long
class HTMLImageElement(HTMLElement):
def __init__(self, doc, tag):
HTMLElement.__init__(self, do | c, tag)
align = attr_property("align")
alt = attr_property(" | alt")
border = attr_property("border")
height = attr_property("height", thug_long)
hspace = attr_property("hspace", thug_long)
isMap = attr_property("ismap", bool)
longDesc = attr_property("longdesc")
# Removed in DOM Level 2
#lowSrc = att... |
cosynus/python | acedefconfig.py | Python | mit | 1,800 | 0.001111 | '''
AceProxy default configuration script
DO NOT EDI | T THIS FILE!
Copy this file to aceconfig.py and change only needed options.
'''
import logging
import platform
from aceclient.acemessages import AceConst
class AceDefConfig(object):
acespawn = False
acecmd = "acestreamengine --client-console"
acekey = 'n51LvQoTlJzNGaFxseRK-uvnvX-sD4Vm5Axwmc4UcoD-jruxmKsu... | aceage = AceConst.AGE_18_24
acesex = AceConst.SEX_MALE
acestartuptimeout = 10
aceconntimeout = 5
aceresulttimeout = 10
debug = logging.DEBUG
#
httphost = '0.0.0.0'
httpport = 8000
aceproxyuser = ''
firewall = False
firewallblacklistmode = False
firewallnetranges = (
... |
fmfn/UnbalancedDataset | examples/over-sampling/plot_shrinkage_effect.py | Python | mit | 3,955 | 0.002528 | """
======================================================
Effect of the shrinkage factor in random over-sampling
======================================================
This example shows the effect of the shrinkage factor used to generate the
smoothed bootstrap using the
:class:`~imblearn.over_sampling.RandomOverSamp... | nerating the smoothed bootstrap.
sampler = RandomOverSampler(shrinkage=3, random_state=0)
X_res, y_res = sampler.fit_resample(X, y)
Counter(y_res)
# %%
fig, ax = plt.subplots(figsize=(7, 7))
scatter = plt.scatter(X_res[:, 0], X_res[:, 1], c=y_res, alpha=0.4)
class_legend = ax.legend(*scatter.legend_elements(), loc="lo... |
ax.set_xlabel("Feature #1")
_ = ax.set_ylabel("Feature #2")
plt.tight_layout()
# %%
# Increasing the value of `shrinkage` will disperse the new samples. Forcing
# the shrinkage to 0 will be equivalent to generating a normal bootstrap.
sampler = RandomOverSampler(shrinkage=0, random_state=0)
X_res, y_res = sampler.fit... |
pythonchelle/opencomparison | apps/searchv1/urls.py | Python | mit | 1,067 | 0.049672 | from django.conf.urls.defaults import *
from searchv1.views import (
search, find_grids_autocomplete, find_packages_autocomplete, search_by_function_autocomplete,
search_by_category_autocomplete)
urlpatterns = patterns("",
url(
regex = '^$',
view = search,
name = ... |
),
url(
regex = '^grids/autocomplete/$',
view = search_by_function_autocomplete,
name = 'search_grids_autocomplete',
kwargs = dict(
search_function=find_grids_autocomplete,
)
),
url(
regex = '^pa... | complete',
kwargs = dict(
search_function=find_packages_autocomplete,
)
),
url(
regex = '^packages/by-category/autocomplete/$',
view = search_by_category_autocomplete,
name = 'search_by_category_autocomplete',
),
)
|
gkc1000/pyscf | examples/local_orb/pmloc.py | Python | apache-2.0 | 8,521 | 0.064312 | # Copyright 2014-2018 The PySCF Developers. 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 appl... | 532, 0.0])],
['O',map(lambda x:x*fac,[-2.050 | 381, -2.530377, 0.0])],
['O',map(lambda x:x*fac,[2.050381, -2.530377, 0.0])],
['O',map(lambda x:x*fac,[-2.050381, 2.530377, 0.0])],
['O',map(lambda x:x*fac,[2.050381, 2.530377, 0.0])]]
mol.basis = 'aug-cc-pvdz'
mol.charge = 0
mol.spin = 0
mol.build()
mf = scf.RHF(mol)
mf.init_g... |
frnsys/broca | broca/knowledge/doc2vec.py | Python | mit | 1,614 | 0.001239 | from gensim.models.doc2vec import Doc2Vec, LabeledSentence
from nltk.tokenize import sent_tokenize, word_tokenize
from sup.progress import Progress
def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs):
"""
Train a doc2vec model on a list of files.
"""
kwar... | 2vec model.
"""
i = 0
p = Progress()
for path in paths:
with open | (path, 'r') as f:
for line in f:
i += 1
p.print_progress(i/n)
# We do minimal pre-processing here so the model can learn
# punctuation
line = line.lower()
if sentences:
for sent in sent_toke... |
Pholey/vcfx | vcfx/field/explanatory/nodes.py | Python | mit | 1,485 | 0.012795 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
from vcfx.field.nodes import Field
class | Categories(Field):
KEY = "CATEGORIES"
def __init__(self, *a, **kw):
super(Cat | egories, self).__init__(*a, **kw)
def clean_values(self, v):
self.value = v.strip("\r\n").split(",")
class Note(Field):
KEY = "NOTE"
def __init__(self, *a, **kw):
super(Note, self).__init__(*a, **kw)
class Prodid(Field):
KEY = "PRODID"
def __init__(self, *a, **kw):
super(P... |
fouk666/xoxo | XOXO/app/__init__.py | Python | mit | 258 | 0.004673 | from flask import Flask
from flask_socketio | import SocketIO
# создаем экземпляр класса Flask
app = Flask(__name__)
# создаем | экземпляр класса SocketIO
socketio = SocketIO(app)
from app.views import home
|
sonntagsgesicht/regtest | .aux/venv/lib/python3.9/site-packages/auxilium/tools/setup_tools.py | Python | apache-2.0 | 3,576 | 0 | # -*- coding: utf-8 -*-
# auxilium
# --------
# Python project for an automated test and deploy toolkit.
#
# Author: sonntagsgesicht
# Version: 0.1.8, copyright Saturday, 02 October 2021
# Website: https://github.com/sonntagsgesicht/auxilium
# License: Apache License 2.0 (see LICENSE file)
from datetime import ... | ogan: ') if slogan is None else slogan
slogan += EXT
author = input('Enter author name : ') if author is None else author
email = input('Enter project email : ') if email is None else email
url = input('Enter project url : ') if url is None else url
url = url | or 'https://github.com/<author>/<name>'
project_path = join(path, name)
pkg_path = join(path, name, name)
# setup project infrastructure
if exists(project_path):
msg = 'Project dir %s exists. ' \
'Cannot create new project.' % project_path
raise FileExistsError(msg)
... |
numaru/injector | injector_cli.py | Python | gpl-3.0 | 318 | 0.003145 | import | sys
from injector import Injector
def main():
path_exe = str(sys.argv[1])
path_dll = str(sys.argv[2])
injector = Injector()
pid = injector.create_process(path_exe)
injector.load_from_pid(pid)
injector.inject_dll(path_dll)
injector.unload()
if __name | __ == "__main__":
main()
|
jcnelson/syndicate | python/syndicate/observer/storage/common.py | Python | apache-2.0 | 2,548 | 0.02394 | #!/usr/bin/python
"""
Copyright 2014 The Trustees of Princeton University
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 ... | yptoKey.importKey( observer_pkey_pem ).publickey().exportKey()
except Exception, e:
logger.exception(e)
logger.error("Failed to derive public key from private key")
return None
# encrypt the data
rc, sealed_slice_secret = c_syndicate.encrypt_data( observer_pkey_pem, observer_pubk... | ce_secret_b64 = base64.b64encode( sealed_slice_secret )
return sealed_slice_secret_b64
#-------------------------------
def decrypt_slice_secret( observer_pkey_pem, sealed_slice_secret_b64 ):
"""
Unserialize and decrypt a slice secret
"""
# get the public key
try:
obse... |
Eric-Gaudiello/tensorflow_dev | tensorflow_home/tensorflow_venv/lib/python3.4/site-packages/tensorflow/python/platform/default/_status_bar.py | Python | gpl-3.0 | 914 | 0.001094 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | RANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""A no-op implementation of status bar functions."""
from __future__ im... | ort print_function
def SetupStatusBarInsideGoogle(unused_link_text, unused_port):
pass
|
roncohen/apm-server | _beats/dev-tools/cmd/dashboards/export_5x_dashboards.py | Python | apache-2.0 | 3,663 | 0.001365 | from elasticsearch import Elasticsearch
import argparse
import os
import json
import re
def ExportDashboards(es, regex, kibana_index, output_directory):
res = es.search(
index=kibana_index,
doc_type="dashboard",
size=1000)
try:
reg_exp = re.compile(regex, re.IGNORECASE)
ex... | n", doc, output_directory)
# save dependencies
if "savedSearchId" in doc["_source"]:
search = doc["_source"]['savedSearchId']
ExportSearch(
es,
search,
kibana_index,
output_directory)
def ExportSearch(es, search, kibana_index, output_directory):... | doc_type="search",
id=search)
# save search
SaveJson("search", doc, output_directory)
def SaveJson(doc_type, doc, output_directory):
dir = os.path.join(output_directory, doc_type)
if not os.path.exists(dir):
os.makedirs(dir)
# replace unsupported characters
filepath = os.... |
nficano/jotonce.com | jotonce/api/passphrases.py | Python | mit | 285 | 0 | # -*- coding: utf-8 -*-
from flask import Bluepr | int
from jotonce.api import route
from jotonce.passphrases.models import Passphrase
bp = Blueprint('passphrase', __name__, url_p | refix='/passphrase')
@route(bp, '/')
def get():
p = Passphrase.get_random()
return {"results": p}
|
adobe-mds/dcos-cassandra-service | cassandra-test-client/launcher.py | Python | apache-2.0 | 8,836 | 0.007583 | #!/usr/bin/python
'''Launches cassandra-stress instances in Marathon.'''
import json
import logging
import pprint
import random
import string
import sys
import urllib
# non-stdlib libs:
try:
import click
import requests
from requests.exceptions import HTTPError
except ImportError:
print("Failed to lo... | "Please run: $ pip install -r requirements.txt")
sys.exit(1)
def __urljoin(*elements):
return "/".join(elem.strip("/") for elem in elements)
def __post(url, headers={}, json=Non | e):
pprint.pprint(json)
response = requests.post(url, json=json, headers=headers)
return __handle_response("POST", url, response)
def __handle_response(httpcmd, url, response):
# http code 200-299 => success!
if response.status_code < 200 or response.status_code >= 300:
errmsg = "Error code... |
smtheard/ShowTracker | controllers/show_follow.py | Python | gpl-3.0 | 1,287 | 0.002331 | import bottle
from config import app, Session
from models.show_follow import ShowFollow
@app.get("/rest/show-follow/<show_id>")
def get_show_follow(session, show_id):
user_id = session.get("user_id")
if user_id:
sa_session = Session()
show_follow = sa_session.query(ShowFollow) \
... | user_id = session.get("user_id")
if user_id:
sa_session = Session()
if following:
sa_session.query(ShowFollow) \
.filter(ShowFollow.show_id == show_id, ShowFollow.user_id == user_id) \
.delete()
sa_session.commit()
retu... | wing=False, success=True)
show_follow = ShowFollow(show_id=show_id, user_id=user_id)
sa_session.add(show_follow)
sa_session.commit()
return dict(following=True, success=True)
return dict(redirect="/register")
|
rueckstiess/mtools | mtools/util/pattern.py | Python | apache-2.0 | 7,303 | 0.011368 | #!/usr/bin/env python3
import json
import re
import sys
def _decode_pattern_list(data):
rv = []
contains_dict = False
for item in data:
if isinstance(item, list):
item = _decode_pattern_list(item)
elif isinstance(item, dict):
item = _decode_pattern_dict(item)
... | part of the value and
# also cases where list values are url's "nnn://aaa.bbb" will correctly be simplified to '1'
s, _ = re.subn(r'("\S+"\s*:\s*\[\s*(?=\"))(.+)((?<=\")\s*\]\s*[,}])', '\\1 1 \\3', s)
if debug : print (s, file=sys.stderr)
# now convert to dictionary, converting unicod | e to ascii
doc = {}
try:
doc = json.loads(s, object_hook=_decode_pattern_dict)
except Exception as err:
if debug:
## print some context info and return without any extracted query data..
msg = f'''json2pattern():json.loads Exception:\n Error: {err} : {sys.exc_info()[... |
fproldan/pyday2016 | pyday2016/wsgi.py | Python | gpl-3.0 | 396 | 0 | """
WSGI config for pyday2016 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https: | //docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pyday2016.settings")
application = get_wsgi_applica | tion()
|
rainerraul/pi-python | rfr101a.py | Python | mit | 191 | 0.036649 | #!/usr/bin/python3
import serial
import time
serialRFID = serial.Serial("/dev/ttyAMA0", 9600)
while Tr | ue:
print (serialRFID.read(12)[1:11])
serialRFID.flushInput()
time.sleep(0.2)
| |
erikr/howtostoreiosdata | howtostoreiosdata/urls.py | Python | mit | 355 | 0.008451 | from django.conf import set | tings
from django.conf.urls import patterns, include, url
urlpatterns = patterns( | '',
url(r'^', include('howtostoreiosdata.wizard.urls', namespace="wizard")),
)
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
|
solashirai/edx-platform | scripts/safe_template_linter.py | Python | agpl-3.0 | 30,181 | 0.001325 | #!/usr/bin/env python
"""
A linting tool to check if templates are safe
"""
from enum import Enum
import os
import re
import sys
_skip_dirs = (
'/node_modules',
'/vendor',
'/spec',
'/.pycharm_helpers',
'/test_root',
'/reports/diff_quality',
'/common/static/xmodule/modules',
)
_skip_mako_dir... |
Returns:
A list of indices into the string at which each line break can be
found.
"""
line_breaks = [0]
index = 0
while True:
index = string.find('\n', index)
if index < 0:
break
index += 1
| line_breaks.append(index)
return line_breaks
def _get_line_number(self, line_breaks, index):
"""
Given the list of line break indices, and an index, determines the line of
the index.
Arguments:
line_breaks: A list of indices into a string at which each line break
was found.
... |
paris-saclay-cds/ramp-workflow | rampwf/score_types/tests/test_soft_accuracy.py | Python | bsd-3-clause | 3,379 | 0 | import numpy as np
from rampwf.score_types.soft_accuracy import SoftAccuracy
score_matrix_1 = np.array([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
])
score_matrix_2 = np.array([
[1, 0.5, 0],
[0.3, 1, 0.3],
[0, 0.5, 1],
])
y_true_proba_1 = np.array([1, 0, 0])
y_true_proba_2 = np.array([0, 1, 0])
y_tr... | ay([y_proba_3])) == 1
assert score_2(np.array([y_true_proba_2]), np.array([y_proba_4])) == 1
assert score_2(np.array([y_true_proba_3]), np.array([y_proba_1])) == 0.65
assert score_2(np.array([y_true_proba_3]), np.array([y_proba_2])) == 0.75
assert score_2(np.array([y_true_proba_1]), np.array([y_proba_5]... | roba_2]), np.array([y_proba_5])) == 0.0
assert score_2(np.array([y_true_proba_3]), np.array([y_proba_5])) == 0.0
assert score_2(np.array([y_true_proba_1]), np.array([y_proba_6])) == 1 / 3
assert score_2(np.array([y_true_proba_2]), np.array([y_proba_6])) == 0.3
assert score_2(np.array([y_true_proba_3]), ... |
mja054/swift_plugin | swift/obj/server.py | Python | apache-2.0 | 39,651 | 0.001841 | # Copyright (c) 2010-2011 OpenStack, LLC.
# Copyright (c) 2008-2011 Gluster, 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 ... | cache(self.fp.fileno(), dropped_cache,
read - dropped_cache)
dropped_cache = read
yield chunk
else:
self.read_to_eof = True
self.drop_cache(self.fp.fileno(), dropped_cache,
... | over the data file for range (start, stop)"""
if start:
self.fp.seek(start)
if stop is not None:
length = stop - start
else:
length = None
for chunk in self:
if length is not None:
length -= len(chunk)
if len... |
rendon/omegaup | stuff/libkarel.py | Python | bsd-3-clause | 5,548 | 0.026073 | # -*- coding: utf-8 -*-
"""Librería para parsear entradas y salidas de Karel en XML."""
import xml.etree.ElementTree as ET
import sys
def load():
"""Regresa (input, output, nombre de caso) para la ejecución actual"""
with open('data.in', 'r') as data_in:
return KarelInput(data_in.read()), KarelOutput(sys.stdin.re... | sición y final de Karel. None si no se encuentra en la salida.
* direccion: La orientación inicial de Karel. Puede ser uno de ['NORTE', 'ESTE', 'SUR', 'OESTE'], o None si no se encuentra
* _zumbadores: Un diccionario donde cada llave (x, y) tiene como valor el número de zumbadores en esa casilla al final de la ejec... | __init__(self, string):
self.root = ET.fromstring(string)
self._zumbadores = {}
for linea in self.root.findall('mundos/mundo/linea'):
y = int(linea.attrib['fila'])
x = 0
for token in linea.text.strip().split():
if token[0] == '(':
x = int(token[1:-1])
else:
self._zumbadores[(x, y)] = t... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractForthemoneyTranslations.py | Python | bsd-3-clause | 249 | 0.028112 | def extractForthemo | neyTranslations(item):
"""
Forthemoney Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return N | one
return False
|
Konubinix/qutebrowser | tests/unit/javascript/position_caret/test_position_caret.py | Python | gpl-3.0 | 3,322 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | n.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU | General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for position_caret.js."""
import pytest
from PyQt5.QtCore import Qt
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKi... |
igor-shevchenko/rutermextract | example.py | Python | mit | 274 | 0.004386 | # coding=utf-8
| from rutermextract import TermExtractor
term_extractor = TermExtractor()
text = | u'Съешь ещё этих мягких французских булок да выпей же чаю.'
for term in term_extractor(text):
print term.normalized, term.count |
zac11/AutomateThingsWithPython | Lists/presence_of_element.py | Python | mit | 241 | 0.024896 | listofcricket=['kohli','mathews','morgan','sou | thee','tamim','smith']
print('Enter a name to search')
name = input()
if name not in listofcricket:
print(name+' is not in the list of cricketers')
else:
print(nam | e+' is in this list')
|
SalesforceFoundation/mrbelvedereci | metaci/testresults/migrations/0013_install_summary_job.py | Python | bsd-3-clause | 1,046 | 0 | # Generated by Django 2.1.7 on 2019-04-26 17:55
from django.db import migrations, models
from scheduler.models import RepeatableJob
from django.utils import timezone
from django_rq import job
@job("short")
def install_generate_summaries_job(apps, schema_editor):
job, created = RepeatableJob.objects.get_or_create... | peatableJob.objects.filter(name="generate_summaries_job") | .delete()
class Migration(migrations.Migration):
atomic = False
dependencies = [("testresults", "0012_create_summaries")]
operations = [
migrations.RunPython(
install_generate_summaries_job,
reverse_code=uninstall_generate_summaries_job,
)
]
|
qiita-spots/qp-qiime2 | qp_qiime2/util.py | Python | bsd-3-clause | 1,804 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | predicate.append(fme['name'])
else:
predicate.append(f['name'])
predicate = sorted(list(set(predicate)))
else:
predicate = element.qiime_type.predicate
name = to | _ast['name']
return name, predicate
|
andre-geldenhuis/bloggregator | blogaggregator/tests/test_models.py | Python | gpl-2.0 | 1,687 | 0.001186 | # -*- coding: utf-8 -*-
"""Model unit tests."""
import datetime as dt
import pytest
from blogaggregator.user.models import User, Role
from .factories import UserFactory
@pytest.mark.usefixtures('db')
class TestUser:
def test_get_by_id(self):
user = User('foo', 'foo@bar.com')
user.save()
... | bool(user.username)
assert bool(user.email)
assert bool(user.created_at)
assert user.is_admin is False
assert user.active is True
assert u | ser.check_password('myprecious')
def test_check_password(self):
user = User.create(username="foo", email="foo@bar.com",
password="foobarbaz123")
assert user.check_password('foobarbaz123') is True
assert user.check_password("barfoobaz") is False
def test_full_name(se... |
nricklin/leafpy | tests/unit/test_login.py | Python | mit | 2,246 | 0.008459 | import unittest
from leafpy import Leaf
from leafpy.auth import login
import vcr
USERNAME = 'dummyuser'
PASSWORD = 'dummypass'
class LoginTests(unittest.TestCase):
@vcr.use_cassette('tests/unit/cassettes/test_login.yaml',
filter_post_data_parameters=['UserId','Password'])
def test_login(self):
... | d_used(self):
leaf = Leaf(VIN='vin345',custom_sessionid='csid123')
with self.assertRaises(Exception) as w:
leaf.BatteryStatusRecordsRequest()
def test_login_with_only_username_raises_exception(self):
| with self.assertRaises(Exception):
leaf = Leaf('username')
def test_login_with_only_VIN_raises_exception(self):
with self.assertRaises(Exception):
leaf = Leaf(VIN='vin123')
def test_login_with_only_custom_sessionid_raises_exception(self):
with self.assertRaises(Ex... |
mightypenguin/qotd | slackbot.py | Python | mit | 4,015 | 0.003736 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from collections import namedtuple
import json
import logging
import time
from collections import namedtuple
from slackclient import SlackClient
class SlackBot(object):
def __init__(self, settingsFilePath='settings.j... | n help')
self.botcheck = '' # <@' + s['bot']['id'] + '>: '
self.commands = {}
#"""{ u'channel': u'G1FS1CJ84',
# u'team': u'T05311JTT',
# u'text': u'<@U1FRJ3WMU>: lol',
# u'ts': u'1465583194.000034',
# u'type': u'message',
# u'user': u'U0LJ6Q4S0'}""" ### Typical structure of a command ... | as_user='true',
channel=msg['channel'],
text=self.commands["help"].help)
logging.debug(output)
def generateHelp(self):
helptext = 'Commands are:\n'
for c in self.commands:
helptext += "\t" + self.... |
enigmampc/catalyst | catalyst/finance/performance/position_tracker.py | Python | apache-2.0 | 13,092 | 0.000076 | #
# Copyright 2016 Quantopian, 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 wr... | ice
if last_sale_date is not None:
position.last_sale_date = last_sale_date
if cost_basis is not None:
position.cost_basis = cost_basis
def execute_transaction(self, txn):
# Update Position
# ----------------
asset = txn.asset
if asset not in... | = Position(asset)
self.positions[asset] = position
else:
position = self.positions[asset]
position.update(txn)
if position.amount == 0:
del self.positions[asset]
try:
# if this position exists in our user-facing dictionary,
... |
pytorch/vision | torchvision/ops/boxes.py | Python | bsd-3-clause | 12,872 | 0.002331 | from typing import Tuple
import torch
import torchvision
from torch import Tensor
from torchvision.extension import _assert_has_ops
from ..utils import _log_api_usage_once
from ._box_convert import _box_cxcywh_to_xyxy, _box_xyxy_to_cxcywh, _box_xywh_to_xyxy, _box_xyxy_to_xywh
def nms(boxes: Tensor, scores: Tensor, ... | f given boxes. Supported formats are ['xyxy', 'xywh', 'cxcywh']
Returns:
Tensor[N, 4]: Boxes into converted format.
"""
if not torch.jit.is_scripting() and not torch.jit.i | s_tracing():
_log_api_usage_once(box_convert)
allowed_fmts = ("xyxy", "xywh", "cxcywh")
if in_fmt not in allowed_fmts or out_fmt not in allowed_fmts:
raise ValueError("Unsupported Bounding Box Conversions for given in_fmt and out_fmt")
if in_fmt == out_fmt:
return boxes.clone()
... |
SFII/cufcq-new | models/campus.py | Python | mit | 1,334 | 0.004498 | from models.basemodel import BaseModel
class Campus(BaseModel):
CAMPUS_CODES = ['BD', 'DN', 'CS']
LONG_NAMES = {
'BD': 'University of Colorado, Boulder',
'DN': 'University of Colorado, Denver',
'CS': 'University of Colorado, Colorado Springs'
}
def requiredFields(self):
... | , 'colleges', 'id']
def fields(self):
return {
'campus': (self.is_in_list(self.CAMPUS_CODES), ),
'fcq | s': (self.is_list, self.schema_list_check(self.is_string, )),
'grades': (self.is_list, self.schema_list_check(self.is_string, ),),
'courses': (self.is_list, self.schema_list_check(self.is_string, )),
'instructors': (self.is_list, self.schema_list_check(self.is_string, )),
... |
D4wN/brickv | src/build_data/windows/OpenGL/GL/NV/texture_env_combine4.py | Python | gpl-2.0 | 1,343 | 0.026806 | '''OpenGL extension NV.texture_env_combine4
This module customises the behaviour of the
OpenGL.raw.GL.NV.texture_env_combine4 to provide a more
Python-friendly API
Overview (from the spec)
New texture environment function COMBINE4_NV allows programmable
texture combiner operations, including
ADD ... | Arg0 * Arg1 + Arg2 * Arg3
ADD_SIGNED_EXT Arg0 * Arg1 + Arg2 * Arg3 - 0.5
where Arg0, Arg1, Arg2 and Arg3 are derived from
ZERO the value 0
PRIMARY_COLOR_EXT primary color of incoming fragment
TEXTURE texture color of corresponding textur... | texture unit 0, this maps to PRIMARY_COLOR_EXT
TEXTURE<n>_ARB texture color of the <n>th texture unit
In addition, the result may be scaled by 1.0, 2.0 or 4.0.
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/NV/texture_env_combine4.txt
'''
from Open... |
noironetworks/aci-integration-module | aim/tests/unit/test_infra_manager.py | Python | apache-2.0 | 3,823 | 0 | # Copyright (c) 2016 Cisco Systems
# 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 require... | d))
# Verify overwrite
port2 = 3
self.infra_mgr.add_hostlink(
host2, ifname2, ifmac2, swid2, module2, port2, path2,
pod_id2, from_config2)
| hlinks = self.infra_mgr.get_hostlinks_for_host(
'f6-compute-2.noiro.lab')
self.assertEqual('3', hlinks[0].port)
self.infra_mgr.delete_hostlink(host, ifname)
# Idempotent
self.infra_mgr.delete_hostlink(host, ifname)
self.infra_mgr.delete_hostlink(host2, ifname2)
... |
mbernson/iscp-search-engine | retrouve/__init__.py | Python | gpl-3.0 | 53 | 0.018868 | fr | om dote | nv import load_dotenv
load_dotenv('./.env') |
lmingcsce/p4factory | targets/sai_p4/tests/ptf-tests/sai_thrift/sai_base_test.py | Python | apache-2.0 | 1,788 | 0.002796 | """
Base classes for test cases
Tests will usually inherit from one of these classes to have the controller
and/or dataplane automatically set up.
"""
import os
import lo | gging
import unittest
import ptf
from ptf.base_tests import BaseTest
from ptf import config
import ptf.datapl | ane as dataplane
################################################################
#
# Thrift interface base tests
#
################################################################
import p4_sai_rpc.sai_p4_sai as p4_sai_rpc
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.proto... |
corpusmusic/bb-cluster | obsolete_scripts/rn_header.py | Python | gpl-3.0 | 204 | 0.004902 | rn = ['I', 'bII', 'II', 'bIII', 'III', 'IV', 'bV', 'V | ', 'bVI', 'VI', 'bVII', 'VII']
header = []
for n in rn:
for next_n in rn:
header.ap | pend(n + '-' + next_n)
print(header)
print(len(header))
|
abinashk-inf/AstroBox | src/astroprint/about/__init__.py | Python | agpl-3.0 | 441 | 0.004535 | from flask import Flask
from flask import render | _template
app = Flask(__name__)
def info():
user = {
'nickname': 'Praful',
'key': 'A154XWA256'
}
posts = {
'company': 'Ethereal Machines',
'link': 'http://www.etherealmachines.com/',
'firmware' : 'Marlin Firmware',
'version': 'v1.01'
}
return rende... | posts=posts)
|
eliostvs/django-kb-example | example/settings/settings/base.py | Python | bsd-3-clause | 7,689 | 0.00065 | from __future__ import unicode_literals
from os.path import abspath, basename, dirname, join, normpath
from sys import path
import markdown
"""Common settings and globals."""
# PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
# Absolut... | 'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
)
THIRD_PARTY_APPS = (
'taggit',
'haystack',
'crispy_forms',
'djangosecure',
'kb',
)
# ... |
# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# END APP CONFIGURATION
# LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# perfo... |
APSL/puput-demo | config/settings/common.py | Python | mit | 7,805 | 0.001025 | # -*- coding: utf-8 -*-
"""
Django settings for puput_demo project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_... | '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(threa | d)d %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler'... |
fogelomer/cloudify-filebeat-plugin | setup.py | Python | apache-2.0 | 1,438 | 0 | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... | es',
author_email='cosmo-admin@gigaspaces.com',
description='plugin for running logging interface (based on Filebeats)',
# This mu | st correspond to the actual packages in the plugin.
packages=['filebeat_plugin'],
package_data={'filebeat_plugin': ['resources/filebeat.yml']},
license='LICENSE',
zip_safe=False,
install_requires=[
# Necessary dependency for developing plugins, do not remove!
'cloudify-plugins-common... |
oblitum/YouCompleteMe | python/ycm/vimsupport.py | Python | gpl-3.0 | 40,365 | 0.0301 | # Copyright (C) 2011-2012 Google Inc.
# 2016 YouCompleteMe contributors
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe 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 versi... | e buffer number for that.
return os.path.join( GetCurrentDirectory(), str( buffer_object.number ) )
def GetCurrentBufferNumber():
return vim.current.buffer.number
def GetBufferChangedTick( bufnr ):
return GetIntValue( 'getbufvar({0}, "changedtick")'.format( bufnr ) )
def UnplaceSignInBuffer( buffer_ | number, sign_id ):
if buffer_number < 0:
return
vim.command(
'try | exec "sign unplace {0} buffer={1}" | catch /E158/ | endtry'.format(
sign_id, buffer_number ) )
def PlaceSign( sign_id, line_num, buffer_num, is_error = True ):
# libclang can give us diagnostics that point "outside" the file; Vi... |
cXhristian/django-wiki | tests/core/test_template_tags.py | Python | gpl-3.0 | 10,375 | 0.000193 | """
Almost all test cases covers both tag calling and template using.
"""
from __future__ import print_function, unicode_literals
from django.conf import settings as django_settings
from django.contrib.contenttypes.models import ContentType
from django.http import HttpRequest
from django.utils.six import assertCountE... | el(article)
ArticleForObject.objects.create(
article=article,
content_type=content_type,
object_id=1
)
from wiki.templatetags import wiki_tags
wiki_tags._cache = {article: 'spam'}
output = article_for_object({}, article)
self.assertE... | )
output = self.render({'obj': article})
self.assertIn(article, wiki_tags._cache)
self.assertEqual(wiki_tags._cache[article], article)
expected = 'Article without content (1)'
self.assertIn(expected, output)
# TODO manage plugins in template
class WikiRenderTest(TemplateTes... |
Ebag333/Pyfa | eos/effects/missilethermaldmgbonusheavy.py | Python | gpl-3.0 | 369 | 0.00542 | # missileThermalDmgBonusHeavy
#
# Used by:
# Implants named like: Zainou 'Snapshot' Heavy Missiles HM (6 of 6)
type = "passive"
def handler(fit, container, context):
fit.modules.filteredChargeBoost(lambda mod: mod.charge.requiresSkill("Heavy Mis | siles"),
"thermalDamage", container.ge | tModifiedItemAttr("damageMultiplierBonus"))
|
cedriclaunay/gaffer | python/GafferImageTest/ImageReaderTest.py | Python | bsd-3-clause | 10,516 | 0.048117 | ##########################################################################
#
# Copyright (c) 2012, John Haddon. All rights reserved.
# Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | geReader()
n["fileName"].setValue( self.negativeDisplayWindowFileName )
f = n["out"]["format"].getValue()
d = n["out"]["dataWindow"].getValue()
self.assertEqual( f.getDisplayWindow(), IECore.Box2i( IECore.V2i( -5, -5 ), IECore.V2i( 20, 20 ) ) )
self.assertEqual | ( d, IECore.Box2i( IECore.V2i( 2, -14 ), IECore.V2i( 35, 19 ) ) )
expectedImage = IECore.Reader.create( self.negativeDisplayWindowFileName ).read()
expectedImage.blindData().clear()
self.assertEqual( expectedImage, n["out"].image() )
def testNegativeDataWindow( self ) :
n = GafferImage.ImageReader()
n["fi... |
Sonicbids/django | tests/migrations/test_executor.py | Python | bsd-3-clause | 19,946 | 0.001604 | from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.graph import MigrationGraph
from django.test import modify_settings, override_settings, TestCase
from django.apps.registry import apps as global_apps
from .test_base import MigrationTestBase
@modify... | oader.graph.nodes["migrations", "0001_initial"], False),
(executor.loader.graph.nodes["migrations", "0002_second"], False),
],
)
# Were the tables there before?
self.assertTableNotExists("migrations_author")
self.assertTableNotExists("migrations_book")
... | tables there now?
self.assertTableExists("migrations_author")
self.assertTableExists("migrations_book")
# Rebuild the graph to reflect the new DB state
executor.loader.build_graph()
# Alright, let's undo what we did
plan = executor.migration_plan([("migrations", None)])
... |
zooniverse/aggregation | docs/source/images/rectangle_overlap.py | Python | apache-2.0 | 713 | 0.093969 | import cv2
import numpy as np
template = np.zeros((500,500,3),np.uint8)
template[:,:,0] = 255
template[:,:,1] = 255
template[:,:,2] = 255
x = [50,250,250,50,50]
y = [50,50,250,250,50]
cnt = np.asarray(zip(x,y))
cv2.drawContours(template,[cnt],0,0,1)
x = [100,200,200,100,100]
y = [300,300,150,150,300]
cnt = np.asar... | ,y))
cv2.drawContours(template,[cnt],0,0,1)
x = [150,400,400,150,150]
y = [200,200,400,400,200]
cnt = np.asarray(zip(x,y))
cv2.drawContours(template,[cnt],0,0,1)
| x = [150,200,200,150,150]
y = [250,250,200,200,250]
cnt = np.asarray(zip(x,y))
cv2.drawContours(template,[cnt],0,(255,0,0),-1)
cv2.imwrite("/home/ggdhines/github/aggregation/docs/images/rectangle_overlap.jpg",template) |
cloudbau/nova | nova/tests/api/openstack/compute/test_limits.py | Python | apache-2.0 | 35,992 | 0.00025 | # Copyright 2011 OpenStack Foundation
# 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 requ... | oating_ips': 10,
'security_groups': 10,
'security_group_rules': 20,
}
response = request.get_response(self.controller)
expected = {
"limits": {
"rate": [
{
| "regex": ".*",
"uri": "*",
"limit": [
{
"verb": "GET",
"next-available": "1970-01-01T00:00:00Z",
"unit": "MINUTE",
... |
redhat-openstack/trove | trove/db/sqlalchemy/migrate_repo/versions/006_dns_records.py | Python | apache-2.0 | 1,320 | 0 | # Copyright 2011 OpenStack Foundation
# 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 requ... | WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the Licens | e.
from sqlalchemy.schema import Column
from sqlalchemy.schema import MetaData
from trove.db.sqlalchemy.migrate_repo.schema import create_tables
from trove.db.sqlalchemy.migrate_repo.schema import drop_tables
from trove.db.sqlalchemy.migrate_repo.schema import String
from trove.db.sqlalchemy.migrate_repo.schema impor... |
bobrathbone/piradio | rotary_class.py | Python | gpl-3.0 | 6,950 | 0.004317 | #!/usr/bin/env python
# Raspberry Pi Rotary Encoder Class
# $Id: rotary_class.py,v 1.7 2017/01/07 11:38:47 bob Exp $
#
# Copyright 2011 Ben Buxton. Licenced under the GNU GPL Version 3.
# Contact: bb@cactii.net
# Adapted by : Bob Rathbone and Lubos Ruckl (Czech republic)
# Site : http://www.bobrathbone.com
#
# This c... | te happens (for example we go from '0-1' straight
# to '1-0 | '), the state machine resets to the start until 0-0 and the
# next valid codes occur.
#
# The biggest advantage of using a state machine over other algorithms
# is that this has inherent debounce built in. Other algorithms emit spurious
# output with switch bounce, but this one will simply flip between
# sub-states unt... |
nexlab/domotikad | domotika/mediasources/modules/OpenPLI/__init__.py | Python | gpl-3.0 | 1,420 | 0.002113 | ############################################################### | ############
# Copyright (c) 2011-2014 Unixmedia S.r.l. <info@unixme | dia.it>
# Copyright (c) 2011-2014 Franco (nextime) Lanza <franco@unixmedia.it>
#
# Domotika System Controller Daemon "domotikad" [http://trac.unixmedia.it]
#
# This file is part of domotikad.
#
# domotikad is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as... |
jirikuncar/invenio-formatter | invenio_formatter/registry.py | Python | gpl-2.0 | 3,187 | 0.000314 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your optio... | for t in reversed(format_templates):
_register(t)
return out
format_templates_look | up = LazyDict(create_format_templates_lookup)
def create_output_formats_lookup():
"""Create output formats."""
out = {}
for f in output_formats_files:
of = os.path.basename(f).lower()
data = {'names': {}}
if of.endswith('.yml'):
of = of[:-4]
with open(f, 'r... |
Donkyhotay/MoonPy | zope/app/publication/publicationtraverse.py | Python | gpl-3.0 | 3,091 | 0.001941 | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... | ope.traversing.interfaces import TraversalError
from zope.publisher.interfaces import IPublishTraverse
class DuplicateNamespaces(Exception):
"""More than one namespace was specified in a request"""
class UnknownNamespace(Exception):
"""A | parameter specified an unknown namespace"""
class PublicationTraverse(object):
def traverseName(self, request, ob, name):
nm = name # the name to look up the object with
if name and name[:1] in '@+':
# Process URI segment parameters.
ns, nm = nsParse(name)
if ... |
kodi-czsk/plugin.video.hejbejse.tv | resources/lib/hejbejse.py | Python | gpl-2.0 | 2,611 | 0.03447 | # -*- coding: UTF-8 -*-
#/*
# * Copyright (C) 2011 Ivo Brhel
# *
# *
# * This Program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2, or (at your option)
# * any later version.
#... | result.append(item)
return result
def resolve(self,item,captcha_cb=None,select_cb=None):
item = item.copy()
url = self._url(item['url'])
page = util.parse_html(url)
result = []
data=str(page.select('div.entry3 > center')[0])
resolved = resolver.findstreams(data,['<iframe(.+?)src=[\"\'](?P<url>.+?)[\'\"... | item = self.video_item()
item['title'] = i['name']
item['url'] = i['url']
item['quality'] = i['quality']
item['surl'] = i['surl']
result.append(item)
except:
print '===Unknown resolver==='
if len(result)==1:
return result[0]
elif len(result) > 1 and select_cb:
return select_c... |
cg31/tensorflow | tensorflow/python/kernel_tests/shape_ops_test.py | Python | apache-2.0 | 19,895 | 0.010003 | # Copyright 2015 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... | tf_ans = tf.shape(x)
tf_ans_64 = tf.shape(x | , out_type=tf.int64)
result = tf_ans.eval()
result_64 = tf_ans_64.eval()
self.assertAllEqual(np_ans, result)
self.assertAllEqual(np_ans, result_64)
self.assertShapeEqual(np_ans, tf_ans)
def _compareShapeSparse(self, x_np, use_gpu=False):
np_ans = np.array(np.shape(x_np))
x_tf, unused_... |
honnibal/spaCy | spacy/lang/ur/__init__.py | Python | mit | 461 | 0.002169 | from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_SUFFIXES
from ...language impo | rt Language, BaseDefaults
class UrduDefaults(BaseDefaults):
suffixes = TOKENIZER_SUFFIXES
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
writing_system = {"direction": "rtl", "has_case": False, "has_letters": True}
class Urdu(Language):
lang = "ur"
Defaults = UrduDefaults
__a | ll__ = ["Urdu"]
|
alejob/mdanalysis | package/MDAnalysis/migration/test_dummy_old_MDA_code.py | Python | gpl-2.0 | 6,334 | 0.018945 | import MDAnalysis
from MDAnalysis.tests.datafiles import GRO, XTC
universe = MDAnalysis.Universe(GRO, XTC)
#old selection
all_selection = universe.selectAtoms('all')
#additional old selectAtoms selection (this comment shouldn't be modified despite containing the method name)
all_selection.selectAtoms('bynum 1:10')
#... | als()
#from MDAnalysis.lib.distances import calc_torsions
from MDAnalysis.lib.distances import calc_torsions
#MDAnalysis.lib.distances.calc_torsions()
MDAnalysis.lib.distances.calc_torsions()
result = MDAnalysis.lib.distances.calc_torsions()
#dist.calc_torsions()
dist | .calc_torsions()
#atomgroup method pluralizations
#set_mass(new) --> set_masses(new)
ag.set_mass(new)
#set_charge(new) --> set_charges(new)
ag.set_charge(new)
#set_name(new) --> set_names(new)
ag.set_name(new)
#set_type(new) --> set_types(new)
ag.set_type(new)
#set_radius(new) --> set_radii(new)
ag.set_radius(new)... |
gongleiarei/qemu | scripts/qapi-introspect.py | Python | gpl-2.0 | 7,230 | 0.000138 | #
# QAPI introspection generator
#
# Copyright (C) 2015-2016 Red Hat, Inc.
#
# Authors:
# Markus Armbruster <armbru@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2.
# See the COPYING file in the top-level directory.
from qapi import *
# Caveman's json.dumps() replacement (we're stuck... | elf._jsons = []
for typ in self._used_types:
typ.visit(self)
# generate C
# TODO can generate awfully long lines
jsons.extend(self._jsons)
name = prefix + 'qmp_schema_json'
self.decl = mcgen('''
extern const char %(c_name)s[];
''',
c_... | or line in lines])
self.defn = mcgen('''
const char %(c_name)s[] = %(c_string)s;
''',
c_name=c_name(name),
c_string=c_string)
self._schema = None
self._jsons = None
self._used_types = None
self._name_map = None
def visit_ne... |
openstack/diskimage-builder | diskimage_builder/elements/package-installs/tests/test_package_squash.py | Python | apache-2.0 | 7,323 | 0 | # Copyright 2018 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
#
# Unless required by applicable law or agre... | ls_squash.collect_data(
self.final_dict, objs, 'test_element')
expected = {
'install.d': {
'install': [('test_package', 'test_element'),
('test_arm64_package', 'test_element')]
}
}
self.assertThat(result, IsMatchin... | DIB_UBUNTU_KERNEL = linux-image-generic',
},
{
'arch': 'arm64',
'when': (
'DIB_RELEASE != xenial',
'DIB_UBUNTU_KERNEL = linux-image-generic',
)
},
],
'linux-generic-hwe-16.04': {
... |
ITDevLtd/MCVirt | source/mcvirt-daemon/usr/lib/python2.7/dist-packages/mcvirt/parser_modules/virtual_machine/delete_parser.py | Python | gpl-2.0 | 2,888 | 0.003809 | """Provides VM delete parser."""
# Copyright (c) 2018 - I.T. Dev Ltd
#
# This file is part of MCVirt.
#
# MCVirt is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your ... | 'the same name until this directory '
'is removed'))
self.delete_parser.add_argument('vm_name', metavar='VM Name', type=str, help='Name of VM')
def handle_delete(self, p_, args):
"""Handle delete."""
vm_factory = p_.rpc.get_connection('vir... | virtual_machine_by_name(args.vm_name)
p_.rpc.annotate_object(vm_object)
vm_object.delete(keep_disks=args.keep_disks,
keep_config=args.keep_config)
|
lucidbard/requests-oauthlib | requests_oauthlib/oauth2_session.py | Python | isc | 14,834 | 0.00209 | from __future__ import unicode_literals
import logging
from oauthlib.common import generate_token, urldecode
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
from oauthlib.oauth2 import TokenExpiredError, is_secure_transport
import requests
log = logging.getLogger(__name__)
log.setLevel(loggi... | nUpdated warning will be raised when a token
has been refreshed. This warning will carry the token
in its token argument.
:param kwargs: Arguments to pass to the Session constructor.
"""
super(OAuth2Session, self).__init__(**kwargs)
self.cl... | not self.client_id:
self.client_id = client.client_id
self.scope = scope
self.redirect_uri = redirect_uri
self.token = token or {}
self.state = state or generate_token
self._state = state
self.auto_refresh_url = auto_refresh_url
self.auto_refresh_kwarg... |
BrunoCaimar/ArcREST | samples/change_folder.py | Python | apache-2.0 | 883 | 0.006795 |
"""
This sample shows how to loop through the folders
and print their titles
Python 2/3
ArcREST version 3.5.x
"""
from __future__ import print_function
from arcrest.security import AGOLTokenSecurityHandler
import arcrest
if __name__ == "__main__":
username = ""#Username
password = ""#password
... | password=password)
admin = arcrest.manageorg.Administration(securityHandler=agolSH)
content = admin.content
user = content.users.user()
for folder in user.folders:
title = folder['tit | le']
print("Analyzing {}".format(title))
user.currentFolder = title
print("Current folder is {}".format(user.currentFolder))
print("Current folder has {} items".format(len(user.items))) |
YouNeedToSleep/sleepy | src/sleepy/models/user.py | Python | bsd-3-clause | 184 | 0 | # -*- coding: utf-8 -*-
"""
slee | py.models.user
~~~~~~~~~~~~~~~~~~
User model.
"""
from django.contrib.auth.models import Abstract | User
class User(AbstractUser):
pass
|
crooks/nymserv | nymserv/daemon.py | Python | gpl-3.0 | 3,773 | 0.00053 | #!/usr/bin/env python
#
# vim: tabstop=4 expandtab shiftwidth=4 noautoindent
import sys
import os
import time
import atexit
from signal import SIGTERM
class Daemon:
"""A generic daemon class.
Usage: subclass the Daemon class and override the run() method"""
def __init__(self, pidfile, stdin='/dev/null',
... | (self.pidfile, 'w+')
pf.write("%s\n" % os.getpid())
pf.close()
def delpid(se | lf):
os.remove(self.pidfile)
def start(self):
"""Start the daemon"""
# Check for a pidfile to see if the daemon already runs
try:
pf = open(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
... |
tencrance/cool-config | python3/grpc/greeter_server.py | Python | mit | 690 | 0.01462 | from concurrent import futures
import time
import grpc
import demo_pb2
import demo_pb2_grpc
_ONE_DAY_IN_SECOND = 60 * 60 * 24
class Greeter(demo_pb2_grpc.GreeterServicer):
def SayHello(sel | f,request,context):
return demo_pb2.HelloReply(message='Hello, %s' % request.name)
def serve | ():
#grpc服务器
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
demo_pb2_grpc.add_GreeterServicer_to_server(Greeter(),server)
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECOND)
except KeyboardInterrupt:
... |
opensignal/airflow | airflow/operators/__init__.py | Python | apache-2.0 | 2,447 | 0.000409 | # Imports operators dynamically while keeping the package API clean,
# abstracting the underlying modules
from airflow.utils import import_module_attrs as _import_module_attrs
# These need to be integrated first as other operators depend on them
_import_module_attrs(globals(), {
'check_operator': [
'CheckO... | ,
'sensors': [
'BaseSensorOperator',
'ExternalTaskSensor',
' | HdfsSensor',
'HivePartitionSensor',
'HttpSensor',
'MetastorePartitionSensor',
'S3KeySensor',
'S3PrefixSensor',
'SqlSensor',
'TimeDeltaSensor',
'TimeSensor',
'WebHdfsSensor',
],
'subdag_operator': ['SubDagOperator'],
'hive_stats_operator... |
deepmind/open_spiel | open_spiel/python/games/data.py | Python | apache-2.0 | 1,333 | 0.002251 | # Copyright 2019 DeepMind Technologies Limited
#
# 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, sof | tware
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Numerical information about some games or some specific settings... |
IODisrupt/OmegaBot | cogs/runescapecompare.py | Python | gpl-3.0 | 2,978 | 0.01041 | import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffl... | arexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher | than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
|
neurohackweek/avalanche | doc/conf.py | Python | apache-2.0 | 9,704 | 0.004637 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# shablona documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 14 10:29:06 2015.
#
# 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
# a... | enerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of ... | this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If tru... |
kyungkoo/gae-ota-plist-maker | appengine_config.py | Python | mit | 160 | 0 | import sys
import os.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))
sys.path.insert(0, os.path.join(os.path.dirname( | __file_ | _), 'py'))
|
DavidNorman/tensorflow | tensorflow/python/ops/linalg/sparse/sparse.py | Python | apache-2.0 | 1,085 | 0 | # Copyrigh | t 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | her express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Public API for tf.linalg.sparse namespace."""
from __future__ import absolute_import
from __future__ import ... |
jigneshvasoya/ruffus | ruffus/print_dependencies.py | Python | mit | 26,918 | 0.013485 | #!/usr/bin/env python
################################################################################
#
# print_dependencies.py
#
#
# Copyright (c) 10/9/2009 Leo Goodstadt
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the... | tion for dot format
turns dictionary into a=b, c=d | ...
"""
# remove ugly __main__. qualifier
name = name.replace("__main__.", "")
# if a label is specified, that overrides the node name
if "label" not in attributes:
attributes["label"] = name.replace(" before ", "\\nbefore ").replace(", ", ",\n")
# remove any quotes
if attribut... |
hycis/TensorGraph | test/data_iterator_test.py | Python | apache-2.0 | 1,793 | 0.001673 | import tensorgraph as tg
import numpy as np
import time
def test_SimpleBlocks():
X = np.random.rand(100, 200)
with open('X.npy', 'wb') as f:
np.save(f, X)
db = tg.SimpleBlocks(['X.npy']*10, batchsize=32, allow_preload=True)
t1 = time.time()
count = 1
for blk in db:
print(count... | 1
for blk in db:
print(count)
count += 1
for batch in blk:
print(time.sleep(0.1))
pass
print('without preload time:', time.time() - t1)
db = tg.SimpleBlocks([('X.npy', 'X.npy'), ('X.npy', 'X.npy')], batchsize=32, allow_preload=False)
for blk in db:
... | print('len batch:', len(batch))
print('batch1 size:', batch[0].shape)
print('batch2 size:', batch[1].shape)
def test_DataBlocks():
X = np.random.rand(100, 200)
with open('X.npy', 'wb') as f:
np.save(f, X)
db = tg.DataBlocks(['X.npy']*10, batchsize=32, allow_preload=False)
... |
liquidinstruments/pymoku | pymoku/_iirfilterbox.py | Python | mit | 32,876 | 0 |
import logging
import struct
from copy import deepcopy
from pymoku._oscilloscope import _CoreOscilloscope
from pymoku._instrument import to_reg_signed
from pymoku._instrument import from_reg_signed
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument i... | ----+------+------+-------+
| s4 | | b0.4 | b1.4 | b2.4 | a1.4 | a2.4 |
+----------+------+------+------+------+-------+
Each 'a' coefficient must be a float in the range [-4.0, +4.0). 's'
coefficients are multiplied into each 'b' coefficient before being sent to
the device. These products (sN x b0.N, sN x b1.N, sN x b2.N) must also fal... |
tuxology/bcc | examples/tracing/mallocstacks.py | Python | apache-2.0 | 1,942 | 0.000515 | #!/usr/bin/python
#
# mallocstacks Trace malloc() calls in a process and print the full
# stack trace for all callsites.
# For Linux, uses BCC, eBPF. Embedded C.
#
# This script is a basic example of the new Linux 4.6+ BPF_STACK_TRACE
# table API.
#
# Copyright 2016 GitHub, Inc.
# Licensed ... | val = calls.lookup_or_try_init(&key, &zero);
if (val) {
(*val) += size;
}
return 0;
};
""")
b.attach_uprobe(name="c", sym="malloc", fn_name="alloc_ | enter", pid=pid)
print("Attaching to malloc in pid %d, Ctrl+C to quit." % pid)
# sleep until Ctrl-C
try:
sleep(99999999)
except KeyboardInterrupt:
pass
calls = b.get_table("calls")
stack_traces = b.get_table("stack_traces")
for k, v in reversed(sorted(calls.items(), key=lambda c: c[1].value)):
print("%d ... |
teenvio/SOAP-API | examples/example_soap.py | Python | lgpl-3.0 | 1,984 | 0.015121 | #!/usr/bin/env python
#
# @copyright Ipdea Land, S.L.
#
# LGPL v3 - GNU LESSER GENERAL PUBLIC LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER General Public License as published by
# the Free Software Foundation, either version 3 of the License.
#... | =server.getUserData()
user_dict = user[0]
for fila in user_dict:
value=fila['value']
if type(value) is int:
value=str(value)
print fila['key']+": "+value
print
print "group 885 data:"
print "--------------"
server.loggin(usuario='user',plan='plan',password='pass') # cha | nge this!!
group_data=server.getGroupData(id_grupo=885)
print "Name: "+group_data['Nombre']
print "Desc: "+group_data['Descripcion']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.