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 |
|---|---|---|---|---|---|---|---|---|
moduspwnens/boa-chat | boa-nimbus/lambda-pip-modules/cfnresponse/cfnresponse/__init__.py | Python | mit | 1,738 | 0.008055 | # Copyright 2016 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
# This file is licensed to you under the AWS Customer Agreement (the "License").
# You may not use this file except in compli | ance with the License.
# A copy of the License is located at http://aws.amazon.com/agreement/ .
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.
# See the License for the specific language governing permissions and limitations under the License.
from ... | ED"
def send(event, context, responseStatus, responseData, physicalResourceId=None):
responseUrl = event['ResponseURL']
print responseUrl
responseBody = {}
responseBody['Status'] = responseStatus
responseBody['Reason'] = 'See the details in CloudWatch Log Stream: ' + context.log_stream_name
r... |
MiloProject/nabaztag | src/bdd.py | Python | gpl-3.0 | 2,594 | 0.022463 | """
La base de données des réponses
La clef du dictionnaire est une expression régulière
La valeur est une liste des actions dispos (dit_blabla, chante_fichier etc...)
"""
data = {
".*(coucou|bonjour|salut).*": ["joue:salut", "joue:bonjour", "joue:coucou"],
".*(comment tu t'appelles|comment t'appelles tu|quel est to... | e:i_kissed_a_g | irl", "joue:si_je_men_sors", "joue:trem_bala"],
".*bonne nuit.*": ["execute:sudo killall -s 9 main.py && sudo poweroff"],
}
default = ["joue:pas_compris", "joue:pas_compris_repete", "joue:arrive_pas_comprendre"]
|
kjchavez/distributed-deep-q | viz/vizpolicy.py | Python | mit | 2,693 | 0.002228 | import argparse
import cPickle
import random
import os
from barista import baristanet
from barista import netutils
from replay import ReplayDataset
from expgain import *
from gamesim.SnakeGame import SnakeGame, gray_scale
import cv2
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("archi... | exp_gain.actions[idx]
exp_gain.play_action(action)
# Render frame
frame = gray_scale(exp_gain.sequence[-1].reshape((1,)+exp_gain.sequence[-1] | .shape))[-1]
big_frame = cv2.resize(frame, (0,0), fx=10, fy=10, interpolation=cv2.INTER_NEAREST)
cv2.imwrite(os.path.join(args.output_dir, "frame-%d.png" % frame_index), big_frame)
frame_index += 1
# cv2.imshow("Game", frame)
# cv2.waitKey(33)
# Check if Snake has died... |
viger/docker | proxy/proxy/code/default/gae_proxy/server/lib/httplib2/__init__.py | Python | mit | 69,728 | 0.005622 | from __future__ import generators
| """
httplib2
A caching http interface that supports ETags and gzip
to conserve bandwidth.
Requires Python 2.3 or later
Changelog:
2007-08-18, Rick: M | odified so it's able to use a socks proxy if needed.
"""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = ["Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",... |
tidalf/plugin.audio.qobuz | resources/lib/qobuz/api/easy.py | Python | gpl-3.0 | 4,196 | 0 | '''
qobuz.api.easy
~~~~~~~~~~~~~~
Add 'get' to qobuz.api.raw, All requests made trough this method are
cached (see qobuz.cache.qobuz)
:part_of: kodi-qobuz
:copyright: (c) 2012-2018 by Joachim Basmaison, Cyril Leclerc
:license: GPLv3, see LICENSE for more details.
'''
from qobuz import conf... | (Exception):
pass
def is_notification_enabled(_self):
return config.app.registry.get('notify_api_error', to='bool')
class EasyApi(RawApi):
def __init__(self):
self.cache_base_path = None
super(EasyApi, self).__init__()
notify = property(is_notification_enabled)
@cache.cached
... | :
"""Wrapper that cache query to our raw api. We are enforcing format
because cache entry key are made based on *a and **ka parameters.
('artist/get' and '/artist/get' will generate different key)
Path are mapped to raw api and raise InvalidQuery on error
::example
from ... |
twisted/txaws | txaws/route53/tests/test_model.py | Python | mit | 2,729 | 0.001466 | # Licenced under the txaws licence available at /LICENSE in the txaws source.
"""
Tests for L{txaws.route53.model}.
"""
from ipaddress import IPv4Address
from twisted.trial.unittest import TestCase
from txaws.route53.model import (
Name, SOA, NS, CNAME, A,
)
from txaws.util import XML
class BasicResourceRecor... | hrough XML.
"""
self._test_roundtrip(
NS,
NS(nameserver=Name(u"ns1.example.invalid.")),
XML(self._ns_xml),
)
_cname_xml = (
"<ResourceR | ecord>"
"<Value>"
"sub.example.invalid."
"</Value>"
"</ResourceRecord>"
)
def test_cname(self):
"""
L{CNAME} can round-trip a I{CNAME} record through XML.
"""
self._test_roundtrip(
CNAME,
CNAME(canonical_name=Name(u"sub.exam... |
karllessard/tensorflow | tensorflow/python/keras/applications/efficientnet.py | Python | apache-2.0 | 24,166 | 0.003559 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: Optional number of classes to classify images
| into, only to be specified if `include_top` is True, and
if no `weights` argument is specified. Defaults to 1000 (number of
ImageNet classes).
classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
... |
doraemonext/wechat-platform | wechat_platform/system/plugin/framework.py | Python | bsd-2-clause | 26,824 | 0.001737 | # -*- coding: utf-8 -*-
import logging
import os
import sys
import requests
from imp import find_module, load_module, acquire_lock, release_lock
from tempfile import mkstemp
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.exceptions import ObjectDoesNotExist
from wechat_... | ' 时, 返回值为 None
"""
if pattern == 'auto':
pattern = self.best_pattern(response_type='image')
try:
image = LibraryImage.manager.get(
official_account=self.official_account,
plugin_iden=self.plugin.iden,
image_id=library_id,
... | if pattern == 'basic': # 当基本被动响应发送模式时
raise Exception('have not yet implemented')
elif pattern == 'service': # 当多客服发送模式时
raise Exception('have not yet implemented')
elif pattern == 'simulation': # 当模拟登陆发送模式时
try:
simulation = self._get_simula... |
initzx/ignore-pls | cogs/private/smod_cmds.py | Python | mit | 2,353 | 0.00085 | import discord
from discord.ext import commands
from utils import p_check
class SModCommands:
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
@p_check()
async def spurge(self, ctx):
params = ctx.message.content.split()
member = None
amoun... | nds.command(pass_context=True)
@p_check()
async def skick(self, ctx, *, member: discord.Member = None):
try:
await self.bot.kick(member)
except discord.Forbidden:
await self.bot.say('bot ain\'t got perms yo', delete_after=1)
except discord.HTTPException:
... | er=1)
else:
await self.bot.say('kicked this fgt', delete_after=1)
def setup(bot):
bot.add_cog(SModCommands(bot))
|
obi-two/Rebelion | data/scripts/templates/object/tangible/wearables/armor/ithorian_defender/shared_ith_armor_s01_bicep_r.py | Python | mit | 494 | 0.044534 | #### | NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/armor/ithorian_defender/shared_ith_armor_ | s01_bicep_r.iff"
result.attribute_template_id = 0
result.stfName("wearables_name","ith_armor_s01_bicep_r")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
subfusc/DasBot | src/IRCbot.py | Python | gpl-3.0 | 20,314 | 0.006695 | # -*- coding: utf-8 -*-
# Basic interface class for communicating with an IRC server.
# Copyright (C) 2012 Sindre Wetjen
# 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... | rlf>
<prefix> ::=
<servername> | <nick> [ '!' <user> ] [ '@' <host> ]
<command> ::=
<letter> { <letter> } | <number> <number> <number>
<SPACE> ::=
' ' { ' ' }
<params> ::=
<SPACE> [ ':' <trailing> | <middle> <params> ]
<middle> ::=
<Any *non-empty* sequence of octets not including SPACE or NUL or CR... | y, possibly *empty*, sequence of octets not including NUL or CR or LF>
<crlf> ::=
CR LF
"""
CRLF_RE = r'$' # This is not CRLF but its stripped before the RE is used, so it will be correct in our case
PARAMS_RE = r'((\s+(?P<middle>[^:](\S|(\s(?!:)))+))?(\s+:(?P<params>[^\r\n]*))?)'
COMMAND_RE = r'(?P<command>\S+)'
... |
ohgodscience/Python | Exercises/ExOh.py | Python | gpl-2.0 | 230 | 0.069565 | def ExOh(str):
temp = list(str)
xcount = | 0
ocount = 0
for c in temp:
if c == "x":
xcount += 1
if c == "o":
ocount += 1
if xcount == ocount:
print "true"
elif xcount != ocount:
print "false | "
ExOh(raw_input()) |
tethysplatform/TethysCluster | tethyscluster/volume.py | Python | lgpl-3.0 | 15,688 | 0.000127 | # Copyright 2009-2014 Justin Riley
#
# This file is part of TethysCluster.
#
# TethysCluster 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, or (at your option) any
# la... | f._volume
def _validate_host_instance(self, instance, zone):
if instance.state not in ['pending', 'running']:
raise exception.InstanceNotRunning(instance.id)
if instance.placement != zone:
raise exception.ValidationError(
"specified host instance %s is not in... | (instance.id, zone))
return True
def _validate_image_and_type(self, image, itype):
img = self.ec2.get_image_or_none(image)
if not img:
raise exception.ValidationError(
'image %s does not exist' % image)
if itype not in static.INSTANCE_TYPES:
... |
eduardomesquita/crud-flask | codigo-fonte/app/utils/string_utils.py | Python | mit | 343 | 0.002915 | '''
Classe ut | ilitaria para realizacao dos testes
'''
class StringUtils(object):
def to_upper(self, string):
return string.upper()
def to_lower(self, string):
return string.lower()
def is_up | per(self, string):
return string.isupper()
def join(self, list_object):
return ','.join(list_object)
|
Spoken-tutorial/spoken-website | certificate/migrations/0004_auto_20160818_1609.py | Python | gpl-3.0 | 2,044 | 0 | # -*- coding: utf-8 -*-
# Third Party Stuff
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('certificate', '0003_auto_20160816_1148'),
]
operations = [
migrations.DeleteModel(
name='Dwsim_participant',
),
mig... | ations.DeleteModel(
name='Scipy_speaker',
),
migrations.DeleteModel(
name='Scipy_speaker_2015',
),
migrations.DeleteModel(
name='Tbc_freeeda',
),
migrations.AlterField(
model_name='drupal_camp',
name='email',
... | migrations.AlterField(
model_name='drupal_ws',
name='email',
field=models.EmailField(max_length=254),
),
migrations.DeleteModel(
name='Profile',
),
]
|
James226/BrowserConfigurationUtility | cache/Page.py | Python | mit | 135 | 0.007407 | import cStringIO
class Page | (object):
| def __init__(self):
self.Nests = {'': {}}
self.buffer = cStringIO.StringIO()
|
hsonntag/yatb | pyatb/examples/__init__.py | Python | gpl-2.0 | 77 | 0.012987 | """
Example Directory
.. automodule:: pyatb.examples.get_current | _price
""" | |
palashahuja/myhdl | myhdl/_modbv.py | Python | lgpl-2.1 | 2,156 | 0.003711 | # This fil | e is part of the myhdl library, a Python package for using
# Python as a Hardware Description Language.
#
# Copyright (C) 2003-2011 Jan Decaluwe
#
# The myhdl library 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 Sof... | rsion 2.1 of the
# License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more detail... |
pombredanne/django-fluent-contents | fluent_contents/appsettings.py | Python | apache-2.0 | 658 | 0.006079 | """
Overview of all settings which can be customized.
"""
from django.conf import settings
from parler import appsettings as parler_appsettings
FLUENT_CONTENTS_CACHE_OUTPUT = getattr(settings, 'FLUENT_CONTENTS_CACHE_OUTPUT', True)
FLUENT_CONTENTS_PLACEHOLDER_CONFIG = getattr(settings, 'FLUENT_CONTENTS_PLACEHOLDER_CO... | : the default language setting is used during the migrations
FLUENT_DEFAULT_LANGUAGE_CODE = getattr(settings, 'FLUENT_DEFAULT_LANGUAGE_CODE', parler_appsettings.PARLER_DEFAULT_LANGUAGE_CODE)
FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE = getattr(settings, 'FLUENT_CONTENTS_DEFAULT_LANGUAGE_CODE | ', FLUENT_DEFAULT_LANGUAGE_CODE)
|
rsalmaso/django-cms | cms/utils/mail.py | Python | bsd-3-clause | 1,470 | 0.002041 | from django.contrib.sites.models import Si | te
from django.core.mail im | port EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.translation import gettext_lazy as _
from cms.utils.urlutils import admin_reverse, urljoin
def send_mail(subject, txt_template, to, context=None, html_template=None, fail_silently=True):
"""
Multipart message he... |
lmazuel/azure-sdk-for-python | azure-mgmt-servicebus/azure/mgmt/servicebus/models/action.py | Python | mit | 1,703 | 0.001762 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | sql_expression: str
:param compatibility_level: This property is reserved for future use. An
| integer value showing the compatibility level, currently hard-coded to 20.
:type compatibility_level: int
:param requires_preprocessing: Value that indicates whether the rule
action requires preprocessing. Default value: True .
:type requires_preprocessing: bool
"""
_attribute_map = {
... |
matthiasvegh/LazyIterator | .ycm_extra_conf.py | Python | gpl-2.0 | 3,363 | 0.023491 | import os
import ycm_core
from clang_helpers import PrepareClangFlags
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
# Most projects will NOT n... | goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x', 'c++',
'-isystem', '/usr/local/incl | ude/c++/4.8.2/',
'-isystem', '/usr/local/include/',
'-I', 'src/',
'-I', 'include/'
]
if compilation_database_folder:
database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
database = None
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def MakeRelative... |
nilsFK/py-privatekonomi | py_privatekonomi/core/db.py | Python | mit | 2,285 | 0.003501 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import sqlalchemy
from sqlalchemy import __version__
from sqlalchemy import create_engine
import sqlalchemy.engine.url as url
from py_privatekonomi.utilities... | and not is_Struct(db_config):
raise Exception("db_config must be either dict or common.Struct: %s" % (repr(db_config)))
if is_Struct(d | b_config):
db_config = as_dict(db_config)
query = None
if 'charset' in db_config:
if db_config['charset'] == 'utf-8': # SQLAlchemy won't accept 'utf-8'...
db_config['charset'] = 'utf8'
query = {
'charset' : db_config['charset']
... |
arbrandes/hastexo-xblock | hastexo/gcloud.py | Python | agpl-3.0 | 1,560 | 0 | from google.oauth2 import service_account
from googleapiclient.discovery import build
class | GcloudService(object):
"""
A meta-class for wrapping Gcloud services.
"""
gc_info = (
"type",
"project_id",
"private_key_id",
"private_key",
"client_email",
"client_id",
"auth_uri",
"token_uri",
"auth_provider_x509_cert_ur | l",
"client_x509_cert_url"
)
service_name = None
api_version = None
default_api_version = None
info = {}
def __init__(self, **info):
self.api_version = info.get('gc_%s_api_version' % self.service_name)
if not self.api_version:
self.api_version = self.default... |
adviti/melange | app/soc/views/helper/url_patterns.py | Python | apache-2.0 | 3,026 | 0.007931 | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange 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 applic... | (['sponsor', 'program'])
KEY = namedKeyBasedPattern(['sponsor', 'program'])
SPONSOR = namedLinkIdPattern(['sponsor'])
PROGRAM = namedLinkIdPattern(['sponsor', 'program'])
CREATE_PROFILE = _role + namedLinkIdPattern(['sponsor', 'program'])
PROFILE = namedLinkIdPattern(['sponsor', 'program', 'user'])
DOCUMENT... | ntor_role + ORG
USER = namedLinkIdPattern(['link_id'])
|
monopole/test-infra | hack/analyze-memory-profiles.py | Python | apache-2.0 | 5,404 | 0.002221 | #!/usr/bin/env python3
# Copyright 2021 The Kubernetes 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 appl... | * 1024 * 1024
return float(value[:-2]) * multiple
dates_by_name = {}
flat_usage_over_time = {}
cumulative_usage_over_time = {}
max_usage = 0
for subdir, dirs, files in os.walk(profile_dir):
for file in files:
output = subprocess.run(
["go", "tool", "pprof", "-top", "-inuse_space", os.pa... | # Type: inuse_space
# Time: Mar 19, 2021 at 10:30am (PDT)
# Showing nodes accounting for 66.05MB, 100% of 66.05MB total
# flat flat% sum% cum cum%
# 64MB 96.90% 96.90% 64MB 96.90% google.golang.org/api/internal/gensupport...
#
# We want... |
sdague/home-assistant | homeassistant/components/mqtt/light/__init__.py | Python | apache-2.0 | 2,689 | 0.001116 | """Support for MQTT lights."""
import logging
import voluptuous as vol
from homeassistant.components import light
from homeassistant.components.mqtt import ATTR_DISCOVERY_HASH
from homeassistant.components.mqtt.discovery import (
MQTT_DISCOVERY_NEW,
clear_discovery_hash,
)
from homeassistant.helpers.dispatche... | payload):
"""Disc | over and add a MQTT light."""
discovery_data = discovery_payload.discovery_data
try:
config = PLATFORM_SCHEMA(discovery_payload)
await _async_setup_entity(
hass, config, async_add_entities, config_entry, discovery_data
)
except Exception:
... |
adtac/exterminate | exterminate/AltRange.py | Python | mit | 183 | 0 | from exterminate.Utilities import built | ins
_range = range
def alt_range(start, stop, step=1):
return _range(start-2, stop+2, max(1, in | t(step/2)))
builtins.range = alt_range
|
hryamzik/ansible | test/units/modules/network/junos/test_junos_command.py | Python | gpl-3.0 | 6,207 | 0.001933 | # (c) 2017 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is dis... | ait_for, match='all'))
self.execute_module(failed=True)
def test_junos_command_simple_json(self):
set_module_args(dict(commands=['show version'], display='json'))
result = self.execute_module(format='json')
self.assertEqual(len(result['stdout']), 1)
self.assertTrue("software... | (rpcs=['get-software-information'], display='text'))
result = self.execute_module(format='text')
self.assertEqual(len(result['stdout']), 1)
self.assertTrue(result['stdout'][0].startswith('Hostname:'))
def test_junos_command_simple_rpc_json(self):
set_module_args(dict(rpcs=['get-soft... |
project-rig/network_tester | examples/link_integrity_test.py | Python | gpl-2.0 | 2,976 | 0 | """This network tester script attempts to check the link integrity of every
link in a SpiNNaker system. It is intended to be run repeatedly for long
durations and provides a steady (though not hugely intense) flow of traffic
over all links. The script verifies that all packets sent arrived at their
destinations ensurin... | sults = e.run()
# Report any mismatches in sent/received packet counts
for result in results.flow_totals():
flow = result["flow"]
sent = result["sent"]
received = result["received"]
if sent != received:
print("Error: Sent {} and received {} across link {}".format(
sent, received, fl... | ed_multicast"])
if num_dropped != 0:
print("Error: {} packets dropped by a router.".format(num_dropped))
|
Eddy0402/Environment | vim/ycmd/third_party/bottle/test/test_securecookies.py | Python | gpl-3.0 | 2,109 | 0.007645 | #coding: utf-8
import unittest
import bottle
from bottle import tob, touni
class TestSecureCookies(unittest.TestCase):
def setUp(self):
self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
self.key = tob('secret')
def testDeEncode(self):
cookie = bottle.cookie_enco... | , secret=self.secret)
pairs = self.get_pairs()
self.set_pairs([(k+'xxx', v) | for (k, v) in pairs])
result = bottle.request.get_cookie('key', secret=self.secret)
self.assertEqual(None, result)
if __name__ == '__main__': #pragma: no cover
unittest.main()
|
heibanke/python_do_something | Code/Chapter4/func_callback1.py | Python | apache-2.0 | 383 | 0.028721 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#copyRight by heibanke
def test(callback):
print 'test | func begin'
callback()
def test1(callback):
print 'test1 func begin'
for func in callback:
func()
def cb1():
print 'callback 1'
de | f cb2():
print 'callback 2'
if __name__ == '__main__':
#test(cb1)
#test(cb2)
test1([cb1,cb2]) |
Tesora-Release/tesora-trove-dashboard | trove_dashboard/content/databases/logs/urls.py | Python | apache-2.0 | 1,148 | 0 | # Copyright 2016 Tesora 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 requ | ired by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# unde | r the License.
from django.conf.urls import patterns
from django.conf.urls import url
from trove_dashboard.content.databases.logs import views
VIEWS_MOD = ('trove_dashboard.content.databases.logs.views')
LOGS = r'^(?P<filename>[^/]+)/%s$'
urlpatterns = patterns(
VIEWS_MOD,
url(LOGS % 'console', 'console',... |
emreg00/biana | biana/BianaObjects/Ontology.py | Python | gpl-3.0 | 10,887 | 0.012951 | """
BIANA: Biologic Interactions and Network Analysis
Copyright (C) 2009 Javier Garcia-Garcia, Emre Guney, Baldo Oliva
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 vers... | cendants.has_key(ontologyElementID):
return self.precalculated_descendants[ontologyElementID]
result = set()
#result = []
for current_descendant_id in self.hierarchy[ontologyElementID]:
if current_descendant_id == ontologyElementID:
sys.stderr.write("Ont... | t_id,self.linked_attribute_values[current_descendant_id]))
return result
else:
if current_descendant_id not in result:
result.add(current_descendant_id)
result.update(self.get_descendants(current_descendant_id))
# re... |
qwefi/nova | nova/tests/api/openstack/compute/contrib/test_neutron_security_groups.py | Python | apache-2.0 | 34,999 | 0.000143 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Nicira, 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/lic... | manager._addSecurityGroup( | req, '1', body)
def test_associate_port_security_enabled_true(self):
sg = self._create_sg_templa |
zongtongyi/leetcode | 019_Remove_Nth_Node_From_End_of_List.py | Python | mit | 1,088 | 0.009191 | #!/usr/bin/env python
def printlist(head):
print head.val
while head.next:
head = head.next
print head.val
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFro... | ListNode(5)
# printlis | t(head)
n = 1
head = Solution().removeNthFromEnd(head, n)
printlist(head)
|
DayGitH/Python-Challenges | DailyProgrammer/DP20160217B.py | Python | mit | 2,571 | 0.005834 | """
[2016-02-17] Challenge #254 [Intermediate] Finding Legal Reversi Moves
https://www.reddit.com/r/dailyprogrammer/comments/468pvf/20160217_challenge_254_intermediate_finding_legal/
# Description
The game of Reversi (or Othello) is a color flipping strategy game played between two players. It's played on an 8x8
unch... | ently empty square. The other requirement is that it be placed so t | hat one or more of their opponent's chips lie
between the empty square and another chip of the player's color. That is, the player placing a black chip must place it
on an empty square with one or more white chips in a row - vertical, horizontal, or diagonal - between it and another
black chip.
The object of the game i... |
ddico/odoo | odoo/addons/test_convert/tests/__init__.py | Python | agpl-3.0 | 74 | 0 | # -*- coding: utf- | 8 -*-
f | rom . import test_convert
from . import test_env
|
manti-by/Churchill | churchill/apps/currencies/services.py | Python | bsd-3-clause | 2,372 | 0.000422 | import logging
import requests
import xml.etree.ElementTree as ET
from django.utils.translation import gettext_lazy as _
from churchill.apps.currencies.models import CurrencyValue, Currency, CurrencyValueType
logger = logging.getLogger()
def get_default_currency_id() -> int:
currency, _ = Currency.objects.get_... | e").text),
)
CurrencyValue.objects.create(
currency=currency,
type=Cur | rencyValueType.SELL,
value=float(node.find("sale").text),
)
def update_currencies():
byn_currency = Currency.objects.first(iso3="BYN")
eur_currency = Currency.objects.first(iso3="EUR")
rub_currency = Currency.objects.first(iso3="RUB")
if not any((byn_currency, eur_currency, rub_currency)):... |
Sonicbids/django | tests/from_db_value/models.py | Python | bsd-3-clause | 750 | 0 | import decimal
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Cash(decimal. | Decimal):
currency = 'USD'
def __str__(self):
s = super(Cash, self).__str__(self)
return '%s %s' % (s, self.currency)
class CashField(models.DecimalField):
def __init__(self, **kwargs):
kwargs['max_digits'] = 20
kwargs['decimal_places'] = 2
super(CashField, self)._... | sh(value)
cash.vendor = connection.vendor
return cash
@python_2_unicode_compatible
class CashModel(models.Model):
cash = CashField()
def __str__(self):
return str(self.cash)
|
benoit-canet/ravellobmc | test.py | Python | apache-2.0 | 3,544 | 0.000282 | #!/usr/bin/env python
#
# Copyright 2015 Ravello Systems 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 applica... | 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 L | icense for the specific language governing permissions and
# limitations under the License.
__author__ = 'benoit.canet@nodalink.com'
from ravellobmc import RavelloBmc
from ravellobmc import IPMI_PORT
from ravello_sdk import message_queue
import subprocess
import threading
import time
import unittest
my_bmc = None
my... |
arkalon76/bob | bobserver.py | Python | gpl-3.0 | 1,846 | 0.002167 | import socketserver, os
from configparser import ConfigParser
"""
Byte
[1] = Action 255 items
"""
class BOBServer(socketserver.BaseRequestHandler):
"""
The request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement c... | d back the same data, but upper-cased
self.request.sendall(self.data)
def crete_init_configfile():
config = ConfigParser()
config['Server'] = {'port': 7766,
'host': "localhost"}
with open(BOB | Server.config_filename, 'w') as configfile:
config.write(configfile)
config.read_file(open(BOBServer.config_filename))
return config
"""
Load's the server config file. If it cannot find one, it will create a basic one
"""
def load_config_file():
config = ConfigParser... |
wulczer/ansible | lib/ansible/runner/action_plugins/assemble.py | Python | gpl-3.0 | 6,198 | 0.002743 | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Stephen Fromm <sfromm@gmail.com>
# Brian Coca <briancoca+dev@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... | er = runner
def _assemble_from_fragments(self, src_path, delimiter=None, compiled_regexp=None):
''' assemble a file from a directory of fragments '''
tmpfd, temp_path = tempfile.mkstemp()
tmp = os.fdopen(tmpfd,'w')
delimit_me = False
add_new | line = False
for f in sorted(os.listdir(src_path)):
if compiled_regexp and not compiled_regexp.search(f):
continue
fragment = "%s/%s" % (src_path, f)
if not os.path.isfile(fragment):
continue
fragment_content = file(fragment).read(... |
latusrepo/latus | run_pytest_until_error.py | Python | gpl-3.0 | 1,334 | 0.00075 |
import os
import sys
import signal
import logging
import pytest
import latus.logger
import test_latus.tstutil
os.environ["PYTHONPATH"] = '.'
g_keep_running = True
def control_key_handler(signal, frame):
global g_keep_running
print('%s : ctrl-c detected - exiting' % __file__)
g_keep_running = False
... | g_keep_running = False
else:
count['pass'] += 1
print('test iteration : %s : return=%s' % (str(count), str(r)))
def main():
run_pyte | st_until_error()
if __name__ == '__main__':
main()
|
automl/auto-sklearn | test/test_pipeline/test_create_searchspace_util_classification.py | Python | bsd-3-clause | 6,398 | 0.000938 | from collections import OrderedDict
import unittest
import numpy
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter
from autosklearn.pipeline.components.classification.liblinear_svc import LibLinear_SVC
from autosklearn.pipeline.components... | SVD'] = TruncatedSVD
m = autosklearn.pipeline.create_searchspace_util.get_match_array(
pipeline=((0, Preprocessors), (1, LDA)),
dataset_properties={'sparse': True})
self.assertEqual(m[0], [0]) # pca
self.assertEqual(m[1], [1]) # svd
m = autosklearn.pipeline.cre... | dataset_properties={'sparse': False})
self.assertEqual(m[0], [1]) # pca
self.assertEqual(m[1], [0]) # svd
preprocessors['none'] = NoPreprocessing
m = autosklearn.pipeline.create_searchspace_util.get_match_array(
pipeline=((0, Preprocessors), (1, LDA)),
dataset... |
dasmith/FrameNet-python | 1.5/frameIndexSub.py | Python | mit | 5,466 | 0.003293 | #!/usr/bin/env python
#
# Generated Fri Apr 15 16:00:42 2011 by generateDS.py version 2.4c.
#
import sys
import ??? as supermod
etree_ = None
Verbose_import_ = False
( XMLParser_import_none, XMLParser_import_lxml,
XMLParser_import_elementtree
) = range(3)
XMLParser_import_library = None
try:
# lxml
... | s = supermod.frameIndex
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('<?xml version="1.0" ?>\n')
rootOb | j.export(sys.stdout, 0, name_=rootTag,
namespacedef_='')
return rootObj
def parseLiteral(inFilename):
doc = parsexml_(inFilename)
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
if rootClass is None:
rootTag = 'frameIndex'
rootClass = supermod.frameInde... |
bharcode/MachineLearning | commons_ml/Similarity_measures/using_similarity.py | Python | gpl-2.0 | 338 | 0.079882 | #!/usr/bin/env python
from similaritymeasures import Similarity
def main():
""" main function to create Similarity class instance and get use of it """
measures = Similarity()
print measures.euclidean_distance([0,3,4,5],[7,6,3,-1])
print measures.jaccard_similarity([0,1,2,5,6],[0,2,3,5,7,9])
if __name__ == "... | in__":
main() | |
vt09/bazel | tools/android/build_incremental_dexmanifest.py | Python | apache-2.0 | 3,855 | 0.006485 | # 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 ag... | mplied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Construct a dex manifest from a set of input .dex.zip files.
Usage: %s <output manifest> <input | zip file>*
%s @<params file>
Input files must be either .zip files containing one or more .dex files or
.dex files.
A manifest file is written that contains one line for each input dex in the
following form:
<input zip> <path in input zip> <path in output zip> <MD5 checksum>
or
<input dex> - <path in outpu... |
virt-manager/virt-manager | tests/uitests/test_mediachange.py | Python | gpl-2.0 | 3,727 | 0.000805 | # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import os
import tests
from . import lib
#############################################
# UI tests for details storage media change #
#############################################
def testMediaChange(app):
v... | ls.check(lambda: appl.sensitive)
appl.click()
app.click_alert_button("already in use by", "Yes")
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda: "backing" in entry.text)
entry.set_text("")
appl.click()
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda... | d_details_window(vmname, click_details=True)
hw = win.find("hw-list")
entry = win.find("media-entry")
appl = win.find("config-apply")
hw.find("IDE CDROM 1", "table cell").click()
lib.utils.check(lambda: not entry.text)
# Catch path does not exist error
entry.set_text("/dev/sr7")
appl.cl... |
milkyjing/TCAX | src/TCAX/tcax/templates/saiyaku_pro_ver/tcaxPy_template_saiyaku_pro_ver.py | Python | gpl-3.0 | 2,816 | 0.009246 | # Version: initial version
from tcaxPy import *
def tcaxPy_Init():
# some common pre-defined global values
global fontSize # as name implies
global resX # horizontal resolution
global resY # vertical resolution
global marginX # horizontal margin
global marginY # ve... | Height)
advance = GetVal(val_TextAdvance)
advDiff = GetVal(val_TextAdvanceDiff)
def tcaxPy_Fin():
return
def tcaxPy_User():
ASS = CreateAssFile(GetVal(val_OutFile) + '.ass', GetVal(val_AssHeader))
for i in range(lineNum):
initPosX = (resX - textLength[i | ]) / 2 + marginX # if marginX = 0, then it's just on the middle
initPosY = marginY
for j in range(textNum[i]):
ASS_BUF = [] # you can put the BUF anywhere according to your usage
if text[i][j] == '' or text[i][j] == ' ' or text[i][j] == ' ':
continue
... |
nitely/ochDownloader | addons/ip_renewer/ip_renewer_gui.py | Python | lgpl-3.0 | 2,017 | 0.006445 | import weakref
import logging
logger = logging.getLogger(__name__)
import core.cons as cons
from core.api import api
from core.config import conf
from qt import signals
#Config parser
OPTION_IP_RENEW_ACTIVE = "ip_renew_active"
OPTION_RENEW_S | CRIPT_ACTIVE = "renew_script_active"
class IPRenewerGUI:
""""""
def __init__(self, parent, ip_renewer):
""""""
self.ip_renewer = ip_renewer
| self.weak_parent = weakref.ref(parent)
self.id_item_list = []
self.is_working = True
if self.can_change_ip():
self.id_item_list = [download_item.id for download_item in api.get_active_downloads().values() + api.get_queue_downloads().values()]
signals.on_stop_a... |
tonysimpson/nanomsg-python | docs/conf.py | Python | mit | 8,357 | 0.006222 | # -*- coding: utf-8 -*-
#
# nanomsg-python documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 23 17:17:17 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
# autogenerated file... | xtra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_las... | = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# temp... |
gwiedeman/eadmachine | source/EADtoSpreadsheet/func/archdescsimple.py | Python | unlicense | 1,380 | 0.024638 | # module for the simple elements of the collection-level <archdesc> element
import x | ml.etree.cElementTree as ET
import globals
from mixed_content import mixed_content
def archdescsimple(arch_root, arch_element, parent, child_tagname, version):
if arch_root.find(arch_element) is None:
pass
else:
parent.clear()
for simple_archelement in arch_root:
if simple_archelement.tag == arch_element:
... | ')
child_element.append(UnitID_element)
Text_element = ET.Element('Text')
child_element.append(Text_element)
Text_element.text = mixed_content(para)
for dumb_descgrp in arch_root:
if dumb_descgrp.tag == "descgrp":
if dumb_descgrp.find(arch_element) is None:
pass
else:
parent.cle... |
caesar2164/edx-platform | common/test/acceptance/tests/lms/test_learner_profile.py | Python | agpl-3.0 | 34,815 | 0.002872 | # -*- coding: utf-8 -*-
"""
End-to-end tests for Student's Profile Page.
"""
from contextlib import contextmanager
from datetime import datetime
from nose.plugins.attrib import attr
from common.test.acceptance.pages.common.logout import LogoutPage
from common.test.acceptance.pages.lms.account_settings import AccountS... | Given that I am a new user.
When I go to my profile page.
| Then I see that the profile visibility is set to public.
"""
username, __ = self.log_in_as_unique_user()
profile_page = self.visit_profile_page(username)
self.verify_profile_page_is_public(profile_page)
def assert_default_image_has_public_access(self, profile_page):
"""
... |
cevaris/pants | src/python/pants/backend/jvm/targets/unpacked_jars.py | Python | apache-2.0 | 2,099 | 0.006193 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
from... | :param libraries: List of addresses of `jar_library <#jar_library>`_
targets which contain .proto definitions.
:param list libraries: addresses of jar_library targets that specify the jars you want to unpack
:param list include_patterns: fileset patterns to include from the archive
:param list excl... | patterns
are processed before include_patterns.
"""
payload = payload or Payload()
payload.add_fields({
'library_specs': PrimitiveField(libraries or ()),
'include_patterns' : PrimitiveField(include_patterns or ()),
'exclude_patterns' : PrimitiveField(exclude_patterns or ()),
})
... |
likelyzhao/mxnet | example/warpctc/infer_ocr.py | Python | apache-2.0 | 2,418 | 0.006203 | # coding=utf-8
# pylint: disable=C0111,too-many-arguments,too-many-instance-attributes,too-many-locals,redefined-outer-name,fixme
# pylint: disable=superfluous-parens, no-member, invalid-name
import sys
sys.path.insert(0, "../../python")
from __future__ import print_function
import numpy as np
import mxnet as mx
from... | om
from captcha.image import ImageCaptcha
BATCH_SIZE = 32
SEQ_LENGTH = 80
def ctc_label(p):
ret = []
p1 = [0] + p
for i in range(len(p)):
c1 = p1[i]
c2 = p1[i + 1]
if c2 == 0 or c2 == c1:
continue
ret.append(c2)
return ret
def remove_blank(l):
ret = [... | int(3,4)
for i in range(max_len):
buf += str(random.randint(0,9))
return buf
if __name__ == '__main__':
num_hidden = 100
num_lstm_layer = 2
num_epoch = 10
learning_rate = 0.001
momentum = 0.9
num_label = 4
n_channel = 1
contexts = [mx.context.gpu(0)]
_, arg_params,... |
dylian94/LeapGestureControl | GestureListener.py | Python | mit | 5,620 | 0.001068 | import os
import ConfigParser
import Leap
from Leap import CircleGesture, SwipeGesture
class GestureListener(Leap.Listener):
def __init__(self):
super(GestureListener, self).__init__()
self.config = ConfigParser.ConfigParser()
self.gestures_stopped = {
"circleleft": 0,
... | gestures = None
if gesture.state == Leap.Gesture.STATE_START:
gestures = self.gestures_started
elif gesture.state == Leap.Gesture.STATE_STOP:
gestures = self.gestures_stopped
if gesture.type == Leap.Gesture.TYPE_CIRCLE:
... | > Leap.PI / 4:
gestures["circleleft"] += number_of_pointables
else:
gestures["circleright"] += number_of_pointables
elif gesture.type == Leap.Gesture.TYPE_KEY_TAP:
self.gestures_started["keytap"] += number_of_pointa... |
akhenakh/checkio_games | non-unique-element.py | Python | mit | 486 | 0.026749 |
def checkio(data):
s = | set(data)
result = []
for i in data:
if data.count(i) > 1:
result.append(i)
return result
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == "__main__":
assert isinstance(checkio([1]), list), "The result must be a list"
| assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
assert checkio([1, 2, 3, 4, 5]) == [], "2nd example"
assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
|
abetusk/www.meowcad.com | cgi/updateproject.py | Python | agpl-3.0 | 2,730 | 0.02674 | #!/usr/bin/python
import re,cgi,cgitb,sys
import os
import urllib
import meowaux as mew
import Cookie
cgitb.enable()
### DEBUG
#print "Content-type: text/html; charset=utf-8;"
#print
cookie = Cookie.SimpleCookie()
cookie_hash = mew.getCookieHash( os.environ )
if ( ("userId" not in cookie_hash) or ("sessionId" not... | cookie_hash["sessionId"] ) == 0) ):
cookie["message"] = "Session expired"
print "Location:login"
print cookie.output()
print
sys.exit(0)
form = cgi.FieldStorage()
if "projectId" not in form:
cookie["message"] = "Invalid project ID"
cookie["messageType"] = "error"
print "Location:portfolio"
print coo... | e_hash["userId"]
r = mew.updateProjectShortDescription( userId, projectId, descr )
if r is None:
cookie["message"] = "Error occured"
cookie["messageType"] = "error"
else:
cookie["message"] = "Project updated"
cookie["messageType"] = "success"
print "Location:project?projectId=" + str(project... |
epitron/youtube-dl | youtube_dl/extractor/dctp.py | Python | unlicense | 2,900 | 0.00069 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
float_or_none,
unified_strdate,
)
class DctpTvIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dctp\.tv/(?:#/)?filme/(?P<id>[^/?#&]+)'
_TEST = {
... | vers:
endpoint = next(
server['endpoint']
for server in servers
if isinstance(server.get('endpoint'), compat_str) and
'cloudfront' in server['endpoint'])
else:
endpoint = 'rtmpe://s2pqqn4u96e4j8.cloudfront.net/cfx/st/'
... | ,
'app': app,
'play_path': 'mp4:%s_dctp_0500_4x3.m4v' % video_id,
'page_url': url,
'player_url': 'http://svm-prod-dctptv-static.s3.amazonaws.com/dctptv-relaunch2012-109.swf',
'ext': 'flv',
}]
description = self._html_search_meta('DC.descriptio... |
JNeiger/robocup-software | soccer/gameplay/plays/stopped.py | Python | apache-2.0 | 2,714 | 0.001105 | import standard_play
import behavior
import tactics.defense
import tactics.stopped.circle_near_ball
import tactics.stopped.circle_on_center
import main
import enum
import robocup
import constants
## When we get the Stopped command from the referee, we run this play.
# See the rules to see what we're allowed to do whi... | nsition(behavior.Behavior.State.start,
Stopped.State.normal, lambda: True, 'immediately')
self.add_transition(Stopped.State.normal, Stopped.State.center,
lambda: self.is_in_center(),
'Switched into center mode')
self.a... | d_transition(Stopped.State.center, Stopped.State.normal,
lambda: not self.is_in_center(),
'Switched into normal mode')
self.slow_speed = 1
self.speed = 2.2
@classmethod
def score(cls):
return 0 if main.game_state().is_stopped() el... |
VisTrails/VisTrails | vistrails/core/api.py | Python | bsd-3-clause | 37,639 | 0.00093 | ###############################################################################
##
## Copyright (C) 2014-2016, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## ... | all ``vistrails.ipython_mode(True)`` to enable IPythonMode for output
modules, directing supported output to the notebook instead of files.
"""
if use_notebook:
try:
import IPython.core.dis | play
except ImportError:
raise ValueError("IPython doesn't seem to be installed!?")
from vistrails.core.modules.output_modules import IPythonMode
IPythonMode.notebook_override = use_notebook
class Vistrail(object):
"""This class wraps both Vistrail and VistrailController.
From it... |
ceph/autotest | client/tests/kvm/tests/timedrift_with_migration.py | Python | gpl-2.0 | 3,949 | 0 | import logging
from autotest_lib.client.common_lib import error
import kvm_test_utils
def run_timedrift_with_migration(test, params, env):
"""
Time drift test with migration:
1) Log into a guest.
2) Take a time reading from the guest and host.
3) Migrate the guest.
4) Take a second time readi... | me_format)
session.close()
# Run current iteration
logging.info("Migrating: iteration %d of %d...",
(i + 1), migration_iterations)
vm.migrate()
# Log in
logging.info("Logging in after migration...")
session = vm... | ng.info("Logged in after migration")
# Get time after current iteration
(ht1_, gt1_) = kvm_test_utils.get_time(session, time_command,
time_filter_re, time_format)
# Report iteration results
host_delta = ht1_ - ht0_
... |
NicoRahm/CGvsPhoto | Textures/dsift.py | Python | mit | 7,772 | 0.013381 | '''
dsift.py: this function implements some basic functions that
does dense sift feature extraction.
The descriptors are defined in a similar way to the one used in
Svetlana Lazebnik's Matlab implementation, which could be found
at:
http://www.cs.unc.edu/~lazebnik/
Yangqing Jia, jiayq@eecs.berkeley.edu
'''
import num... | / np.double(W)))
else:
positio | ns = np.vstack((gridH, gridW))
return feaArr, positions
def calculate_sift_grid(self,image,gridH,gridW):
'''
This function calculates the unnormalized sift features
It is called by process_image().
'''
H,W = image.shape
Npatches = gridH.size
feaArr = ... |
kingjr/meg_expectation_p3 | scripts/run_extract_epochs.py | Python | gpl-3.0 | 6,371 | 0 | # Author: Denis A. Engemann <denis.engemann@gmail.com>
# License: BSD (3-clause)
import mkl
import sys
import os.path as op
import numpy as np
import mne
from mne.io import Raw
from mne.preprocessing import read_ica
from mne.viz import plot_drop_log
from meeg_preprocessing.utils import setup_provenance, set_eog_ecg_c... | icas = list()
if use_ica is True:
for chan_type in chan_types:
icas.append(read_ica(
op.join(this_path, '{}-ica.fif'.format(ch | an_type['name']))))
for r in runs:
fname = op.join(this_path, raw_fname_filt_tmp.format(r))
if not op.isfile(fname):
logger.info('Could not find %s. Skipping' % fname)
continue
raw = Raw(fname)
# Set ECG EOG channels XXX again?
set_eog_ecg_channels(r... |
GeoCat/QGIS | tests/src/python/test_qgsatlascomposition.py | Python | gpl-2.0 | 14,506 | 0.001448 | # -*- coding: utf-8 -*-
'''
test_qgsatlascomposition.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
**************... | f.mAtlasMap.setAtlasMargin(0.10)
self.mAtlas.beginRender()
fo | r i in range(0, 2):
self.mAtlas.prepareForFeature(i)
self.mLabel1.adjustSizeToText()
checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1), self.mComposition)
checker.setControlPathPrefix("atlas")
myTestResult, myMessage = checker.testComposition(0, 2... |
tensorflow/examples | lite/examples/pose_estimation/raspberry_pi/utils.py | Python | apache-2.0 | 5,614 | 0.004809 | # Copyright 2021 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... | (0, 255, 0),
(0, 255, 255),
(255, 0, 255),
(30, 144, 255),
(255, 228, 181),
(255, 105, 180),
]
def visualize(
image: np.ndarray,
list_persons: List[Person],
keypoint_color: Tuple[int, ...] = None,
keypoint_threshold: float = 0.05,
instance_threshold: float = 0.1,
) -> np.ndarra... | ist_persons: The list of all "Person" entities to be visualize.
keypoint_color: the colors in which the landmarks should be plotted.
keypoint_threshold: minimum confidence score for a keypoint to be drawn.
instance_threshold: minimum confidence score for a person to be drawn.
Returns:
Image with keyp... |
heyost/django-skeleton | oauth/admin.py | Python | gpl-2.0 | 345 | 0 | #!/usr/bin/env python
# | -*- coding: utf-8 -*-
#
# mdfjr - admin.py
#
# Created by PyCharm.
# User: fajar
# Date: 5/13/17
# Time: 3:50 PM
#
#
from django.contrib import admin
from . import models |
@admin.register(models.OAuthUser)
class OAuthUserAdmin(admin.ModelAdmin):
list_display = ['__str__', 'provider', 'uid', 'email', 'user']
|
saurabh6790/test-med-app | hr/doctype/designation/test_designation.py | Python | agpl-3.0 | 215 | 0.018605 | # Copyright (c) 2013, Web Notes Technologies | Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
test_records = [[{"doctype":"Designation", "designation | _name":"_Test Designation"}]] |
cjforman/pele | pele/angleaxis/tests/test_otp.py | Python | gpl-3.0 | 11,705 | 0.01179 | import unittest
from itertools import izip
import numpy as np
from numpy import cos, sin, pi
from pele.angleaxis import RBTopology, RigidFragment, RBPotentialWrapper
from pele.potentials import LJ
from pele.angleaxis._otp_cluster import OTPCluster
from pele.thermodynamics import get_thermodynamic_information
from pel... | .02925229,
-1.64603729, 0.30701482, 0.90204992, -1.96259809, 0.06557119,
0.11010908, -0.37462588, -0.42374544, 1.97728056])
class TestOTPCluster(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.nmol = 4
self.system = OTPCluster(self.nmol)
... | = self.db.addMinimum(pot.getEnergy(_x2), _x2)
def test1(self):
pot = self.system.get_potential()
self.assertLess(np.linalg.norm(pot.getGradient(self.m1.coords)), .1)
self.assertLess(np.linalg.norm(pot.getGradient(self.m2.coords)), .1)
def test_basinhopping(self):
db = ... |
stormi/tsunami | src/primaires/scripting/fonctions/etat_singulier.py | Python | bsd-3-clause | 2,269 | 0.000443 | # -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | r 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED W... | INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR O... |
madssj/django-longer-username-and-email | longerusernameandemail/tests/__init__.py | Python | bsd-3-clause | 5,387 | 0 | import random
import string
from django.contrib.auth.models import User
from django.test import TestCase
from longerusernameandemail.forms import UserCreationForm
def get_random_string(alpha=string.ascii_letters, length=100):
"Get a 'long', randmon | string"
return ''.join([random.choice(alpha) for i in range(length)])
class LongerUsernameAndEmailTests(TestCase):
"""
Unit tests for longerusernameandemail app
"""
def setUp(self):
"""
creates a user with a terribly long username
"""
long_use | rname = ''.join([str(i) for i in range(100)])
self.user = User.objects.create_user(
'test%s' % long_username,
'%s@example.com' % long_username,
'testpassword'
)
def testUserCreation(self):
"""
tests that self.user was successfully saved, and can ... |
adelina-t/nova | nova/tests/unit/virt/libvirt/test_imagebackend.py | Python | apache-2.0 | 59,792 | 0.000452 | # Copyright 2012 G | rid Dynamics
# 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 o | btain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See t... |
bastibl/gnuradio | gr-utils/python/modtool/tools/parser_cc_block.py | Python | gpl-3.0 | 10,443 | 0.004022 | #
# Copyright 2013, 2018 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later versio... | *\(\s*(?P<inmin>[^,]+),\s*(?P<inmax>[^,]+),' + \
r'\s*(?P<intype>(\([^\)]*\)|[^)])+)\),\s*' + \
r'(?P<outcall>gr::io_signature::make[23v]?)\s*\(\s*(?P<outmin>[^,]+),\s*(?P<outmax>[^,]+),' + \
r'\s*(?P<outtype>(\([^\)]*\)| | [^)])+)\)'
iosig_match = re.compile(iosig_regex, re.MULTILINE).search(self.code_cc)
try:
iosig['in'] = _figure_out_iotype_and_vlen(iosig_match.group('incall'),
iosig_match.group('intype'))
iosig['in']['min_ports'] = iosig_matc... |
tseaver/google-cloud-python | securitycenter/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py | Python | apache-2.0 | 13,088 | 0.001528 | # -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | ed request object and returns a
deserialized response object.
"""
return self._stubs["security_center_stub"].CreateFinding
@property
def get_iam_policy(self):
"""Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`.
Gets the access control policy... | ialized response object.
"""
return self._stubs["security_center_stub"].GetIamPolicy
@property
def get_organization_settings(self):
"""Return the gRPC stub for :meth:`SecurityCenterClient.get_organization_settings`.
Gets the settings for an organization.
Returns:
... |
Meallia/robotframework-appiumlibrary | AppiumLibrary/keywords/_applicationmanagement.py | Python | apache-2.0 | 9,626 | 0.002182 | # -*- coding: utf-8 -*-
import os
import robot
from appium import webdriver
from AppiumLibrary.utils import ApplicationCache
from .keywordgroup import KeywordGroup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
class _ApplicationManagementKeywords(KeywordGroup):
def __init__(self):
... | application().session_id)
self._ca | che.close()
def close_all_applications(self):
"""Closes all open applications.
This keyword is meant to be used in test or suite teardown to
make sure all the applications are closed before the test execution
finishes.
After this keyword, the application indices returned b... |
gasongjian/ttpy | tt/ksl/setup.py | Python | mit | 1,357 | 0.023581 | #This script will build the main subpackages
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration, get_info
config = Configuration('ksl', parent_package, top_path)
tt_dir = '../tt-fort/'
exp_dir = '../tt-fort/expm'
src = ['ttals.f90','tt_ksl.f90']... | exp_src = [exp_dir + '/' + x for x in exp_src]
config.add_library('expokit',sources=exp_src)
src = [tt_dir + x for x in src]
src.append('tt_ksl.pyf')
config.add_extension('dyn_tt',so | urces=src,depends=['print_lib','expokit','mytt'],
libraries=['print_lib','expokit','mytt'],)
return config
#from distutils.core import setup
#from numpy.distutils.core import setup, Extension
#src = ['tt_f90.f90','tt_f90.pyf']
#inc_dir = ['tt-fort']
#lib = ['tt-fort/mytt.a']
#ext = Extension('tt_f90', src, ... |
klahnakoski/esReplicate | pyLibrary/queries/dimensions.py | Python | mpl-2.0 | 13,303 | 0.003608 | # encoding: utf-8
#
#
# self Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with self file,
# You can obtain one at http:# mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import unicode_literals
from __... | h:
if len(edges) > 1:
Log.error("Not supported yet")
# EACH TERM RETURNED IS A PATH INTO A PARTITION TREE
temp = Data(partitions=[])
for i, count in enumerate(parts):
a = dim.path(d.getEnd(d.partitions[i])) |
if not isinstance(a, list):
Log.error("The path function on " + dim.name + " must return an ARRAY of parts")
addParts(
temp,
dim.path(d.getEnd(d.partitions[i])),
count,
0
... |
google/gps_building_blocks | py/gps_building_blocks/ml/data_prep/ml_windowing_pipeline/feature_utils.py | Python | apache-2.0 | 3,666 | 0.005183 | # python3
# coding=utf-8
# Copyright 2021 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in | compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF A | NY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains functions to support feature generation."""
import csv
import io
from typing import List
from gps_building_blocks.ml.data_prep.ml_windowing_pipeline import feature_opt... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/opus_core/datasets/multiple_year_dataset_view.py | Python | gpl-2.0 | 18,420 | 0.015744 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
from numpy import array, int32, concatenate
from opus_core.datasets.abstract_dataset import AbstractDataset
from opus_core.datasets.dataset_pool im... | ef _get_attribute_for_year(self, dataset_name, attribute_name, year):
"""Return the attribute values for this year."""
calling_dataset_pool = SessionConfiguration().get_dataset_pool()
calling_time = SimulationState().get_current_time()
SimulationState().set_current_time(year)
... | order=calling_dataset_pool.get_package_order(),
storage=AttributeCache())
dataset = my_dataset_pool.get_dataset(dataset_name)
attribute_name = attribute_name.replace('DDDD',repr(year))
dataset.compute_variables(attribute_name, my_dataset_pool)
values ... |
zakkum42/Bosch | src/03-feature_engineering/missing_values_numeric.py | Python | apache-2.0 | 3,477 | 0.010641 | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from include.dataset_fnames import generate_station_data_fname
from include.feature_lists import numeric_features
from xgboost import XGBRegressor
def numeric_df_missing_values_summary():
for i, station_id in enumerate(s... | rain_indices, train_features]
y_train = new_df.loc[train_indices, feature]
X_test = new_df.loc[t | est_indices, train_features] # feature == null
regresor = regresor_function(X_train.values, y_train.values)
y_predict = regresor.predict(X_test.values)
iter_df.loc[test_indices, feature] = y_predict
print iter_df.loc[2342802]
print i... |
SummerCamp17/Gymkhana-Nominations | nomi/migrations/0094_auto_20170624_1845.py | Python | mit | 691 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-24 18:45
| from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nomi', '0093_userprofile_user_img'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='club',
... | ),
migrations.AlterField(
model_name='commment',
name='comments',
field=models.TextField(blank=True, max_length=1000, null=True),
),
]
|
asceth/sinan | client/libsinan/jsax.py | Python | mit | 11,711 | 0.002647 | import sys
import libsinan.sinexceptions
"""
The stream oriented parser produces a series of events that | describe the structure currently being parsed. These events are then consumed by the calling application in some manner. The actual mechanism of consumption will vary from language type to language type though a few different types of APIs are discussed in the appendix of this document.
JSON is composed of two types o... | he two types of structures remain the same, changing only in the description of the structure being described.
The events around primitive types are relatively simple and should be implemented as simply as possible. Individual API definers will choose how they want to implement it using the examples in the appendix as... |
FSI-HochschuleTrier/hacker-jeopardy | de/hochschuletrier/jpy/states/GameState.py | Python | mit | 319 | 0.028213 | __author__ = 'miko'
from Tkinter import Frame
class GameState(Frame):
def __init__(self, *args, **kwargs):
self.stateName = kwargs["stateName"]
| self.root = args[0]
self.id = kwargs["id"]
Frame.__init__(self, self. | root.mainWindow)
self.config(
background="gold"
)
self.place(relwidth=1, relheight=1)
|
ahmedaljazzar/edx-platform | lms/djangoapps/email_marketing/migrations/0004_emailmarketingconfiguration_welcome_email_send_delay.py | Python | agpl-3.0 | 552 | 0.001812 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('email_marketing', '0003_auto_20160715_1145'),
]
operations = [
migrations.AddField(
model_name='emailmarketingco... | name='welcome_email_send_delay',
field=models.IntegerField(defaul | t=600, help_text='Number of seconds to delay the sending of User Welcome email after user has been activated'),
),
]
|
bobvoorneveld/spindlechannels | map/management/commands/clearmarkers.py | Python | mit | 334 | 0 | from django.core.management.base import BaseCommand
from map.mo | dels import Marker
from map.signals import send_notification
class Command(BaseCommand):
help = 'Remove all markers'
def handle(self, *args, **options):
Marker.objects.all().delete()
send_notification({
'type': 'clear'
| })
|
USGSDenverPychron/pychron | pychron/lasers/tasks/editors/pyrometer_calibration_editor.py | Python | apache-2.0 | 4,570 | 0.000438 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# 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/licens... | ===============
from pychron.lasers.scanner import Scanner
from pychron.lasers.tasks.editors.laser_editor import LaserEditor
from pychron.managers.data_managers.csv_data_manager import CSVDataManager
from pychron.paths import paths
from six.moves import range
class PyrometerCalibrationScanner(Scanner):
_eq_tol = ... | dm = self.csv_data_manager
dm.write_to_frame(data)
def start_control_hook(self, ydict):
self.csv_data_manager = dm = CSVDataManager()
p = os.path.join(paths.data_dir, "pyrometer_calibration")
dm.new_frame(directory=p)
def _maintain_setpoint(self, t, d):
if d == "eq... |
funkring/fdoo | addons-funkring/official_holiday/wizard/official_holiday_wizard.py | Python | agpl-3.0 | 2,655 | 0.006403 | # -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
#############################################################################
#
# Copyright (c) 2007 Martin Reisenhofer <martin.reisenhofer@funkring.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | day_template_wizard(osv.osv_memory):
def do_c | reate(self, cr, uid, ids, context=None):
holiday_obj = self.pool.get("official.holiday")
template_obj = self.pool.get("official.holiday.template")
user_obj = self.pool.get("res.users")
template_ids = template_obj.search(cr,uid,[("id","in",util.active_ids(context))])
company_id =... |
berkmancenter/mediacloud | apps/topics-base/tests/python/topics_base/media/test_get_unique_media_name.py | Python | agpl-3.0 | 735 | 0.001361 | import pytest
from mediawords.db import connect_to_db
from mediawords.test.db.create import create_test_medium
from topics_base.media import get_unique_medium_name, McTopicMediaUniqueException
def test_get_unique_media_name():
"" | "Test get_unique_media_name()."""
db = connect_to_db()
num_media = 5
[create_test_medium(db, str(i)) for i in range(num_media)]
media = db.query("select * from media order by media_id").hashes()
assert get_unique_medium_name(db, ['UNIQUE']) == 'UNIQUE'
media_names = [m['name'] for m in media]... | get_unique_medium_name(db, media_names)
assert get_unique_medium_name(db, media_names + ['UNIQUE']) == 'UNIQUE'
|
seomoz/roger-mesos | aaad/aaad.py | Python | apache-2.0 | 7,585 | 0.006196 | from flask import Flask, jsonify, request, render_template, redirect, make_response, flash, Response
from flask_restful import abort, Api, Resource
from flask_login import login_user, logout_user, login_required, current_user
from webargs import fields
from webargs.flaskparser import use_args
import os
import json
impo... | handler.setFormatter(formatter)
app.logger.addHandler(handler)
log_l | evels = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
log_level = os.environ.get('LOG_LEVEL', 'warning')
app.logger.setLevel(log_levels.get(log_level, logging.NOTSET... |
jocelynj/weboob | weboob/backends/youjizz/pages/video.py | Python | gpl-3.0 | 2,211 | 0.001357 | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Roger Philibert
#
# 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, version 3 of the License.
#
# This program is distributed in the hope that it will... | ectElementException('Cou | ld not retrieve video duration')
video_file_urls = re.findall(r'"(http://media[^ ,]+\.flv)"', data)
if len(video_file_urls) == 0:
raise SelectElementException('Video URL not found')
elif len(video_file_urls) > 1:
raise SelectElementException('Many video file URL found')
... |
plotly/python-api | packages/python/plotly/plotly/validators/scatterpolargl/hoverlabel/_align.py | Python | mit | 591 | 0.001692 | import _plotly_utils.basevalidators
class AlignValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="align", parent_name="scatterpolargl.hoverlabel", **kwargs
):
super(AlignValidator, self).__init__(
plotly_name=plotly_name,
paren... | p("values", ["left", "right", "auto"]),
| **kwargs
)
|
CENDARI/portia | slyd/tests/test_spec.py | Python | bsd-3-clause | 3,884 | 0 | import json
from tempfile import mkdtemp
from os.path import join, basename
from shutil import rmtree
from distutils.dir_util import copy_tree
from twisted.trial import unittest
from twisted.internet.defer import inlineCallbacks
from slyd.projectspec import create_project_resource
from slyd.projectspec import convert_t... | :
sm = test_spec_manager()
spec_resource = create_project | _resource(sm)
self.temp_project_dir = mkdtemp(dir=SPEC_DATA_DIR,
prefix='test-run-')
self.project = basename(self.temp_project_dir)
self.specsite = TestSite(spec_resource, project=self.project)
test_project_dir = join(SPEC_DATA_DIR, 'test')
... |
bakhtout/odoo-educ | addons/openeducat_erp/op_faculty/op_faculty.py | Python | agpl-3.0 | 6,048 | 0.013558 | # -*- coding: utf-8 -*-
#/#############################################################################
#
# Tech-Receptives Solutions Pvt. Ltd.
# Copyright (C) 2004-TODAY Tech-Receptives(<http://www.tech-receptives.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under th... | ble'),
'health_faculty_lines': fields.one2many('op.health', 'faculty_id', 'Health Detail'),
'faculty_subject_ids': fields.many2many('op.subject', 'faculty_subject_rel', 'op_faculty_id', 'op_subject_id', string='Subjects'),
'emp_id': fields.many2one('hr.employee', string= | 'Employee'),
}
op_faculty()
class hr_employee(osv.osv):
_inherit = "hr.employee"
def onchange_user(self, cr, uid, ids, user_id, context=None):
work_email = False; address = False; emp_id = False
number = False
if user_id:
user = self.... |
kinglyduck/hackerspace | src/badges/models.py | Python | gpl-2.0 | 9,619 | 0.008421 | from datetime import time, date, datetime
from django.contrib.auth.models import User
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Max, Sum, Count
from django.templatetags.static import static
from django.utils import timezone
... | total_xp = self.get_ | queryset().no_game_lab().get_user(user).aggregate(Sum('badge__xp'))
xp = total_xp['badge__xp__sum']
if xp is None:
xp = 0
return xp
class BadgeAssertion(models.Model):
badge = models.ForeignKey(Badge)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
ordinal = models.P... |
scheib/chromium | tools/perf/experimental/story_clustering/gather_historical_records_and_cluster_stories.py | Python | bsd-3-clause | 5,390 | 0.011688 | # Copyright 2019 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.
from __future__ import print_function
import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
import tempfile
TOOLS... | rolling_window,
metric_name,
normalize = False):
timeseries = []
for bot_name, bot_group in all_bots_da | taframe.groupby(bots):
temp_dataframe = bot_group.pivot(index='test_case',
columns='commit_pos', values='value')
temp_dataframe_with_solling_avg = temp_dataframe.rolling(
rolling_window,
min_periods=1,
axis=1
).mean().stack().rename('value').reset_index()
temp_dataframe_with_sol... |
varnivey/genehack_2016 | simple_gui/tablewidget.py | Python | gpl-2.0 | 8,194 | 0.010984 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 19 22:57:17 2014
@author: satary
"""
from PyQt4 import QtGui,QtCore
import sys, csv, xlsxwriter
class TableWidget(QtGui.QTableWidget):
def __init__(self,parent=None):
super(TableWidget, self).__init__(parent)
self.parent=parent
#self.table = Qt... | sort()
sortNewCol.sort()
[rowOrder.append(row) for row in sortNewRow]
| [columnOrder.append(col) for col in sortNewCol]
# creating ordered list of not empty values
visibleRows = []
visibleCols = []
for row in rowOrder:
if row in newRow:
visibleRows.append(row)
for col in columnOrder:
if col in newCol:
... |
LLNL/spack | lib/spack/spack/test/cmd/external.py | Python | lgpl-2.1 | 9,697 | 0.000619 | # Copyright 2013-2021 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)
import os
import os.path
import pytest
import spack
import spack.detection
import spack.detection.path
from spack.main im... | _factory(result):
def _mock_search(path_hints=None):
return result
monkeypatch.setattr(spack.detection.path, 'executables_in_path', _mock_search)
return _factory
def test_find_external_single_package(mock_executable, executables_found):
pkgs_to_check = [spack.repo.get('cmake')]
... | e", output='echo "cmake version 1.foo"'): 'cmake'
})
pkg_to_entries = spack.detection.by_executable(pkgs_to_check)
pkg, entries = next(iter(pkg_to_entries.items()))
single_entry = next(iter(entries))
assert single_entry.spec == Spec('cmake@1.foo')
def test_find_external_two_instances_same_packa... |
botswana-harvard/microbiome | microbiome/apps/mb_lab/forms/infant_requisition_form.py | Python | gpl-2.0 | 3,819 | 0.003666 | from django import forms
from django.conf import settings
from django.contrib.admin.widgets import AdminRadioSelect, AdminRadioFieldRenderer
from edc_constants.constants import YES, NO
from lab_requisition.forms import RequisitionFormMixin
from microbiome.apps.mb.choices import STUDY_SITES
from microbiome.apps.mb_inf... | get=AdminRadioSelect(renderer=AdminRadioFieldRenderer))
def __init__(self, *args, **kwargs) | :
super(InfantRequisitionForm, self).__init__(*args, **kwargs)
self.fields['item_type'].initial = 'tube'
def clean(self):
cleaned_data = super(InfantRequisitionForm, self).clean()
self.validate_requisition_and_drawn_datetime()
self.validate_sample_swabs()
self.valida... |
bgris/ODL_bgris | lib/python3.5/site-packages/spyder/utils/vcs.py | Python | gpl-3.0 | 5,011 | 0.002196 | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""Utilities for version control systems"""
from __future__ import print_function
import sys
import os.path as osp
import subprocess
# Local imports
... | get_hg_revision(".")
('eba7273c69df+', '2015+', 'default' | )
"""
try:
assert osp.isdir(osp.join(repopath, '.hg'))
proc = programs.run_program('hg', ['id', '-nib', repopath])
output, _err = proc.communicate()
# output is now: ('eba7273c69df+ 2015+ default\n', None)
# Split 2 times max to allow spaces in branch names.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.