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 |
|---|---|---|---|---|---|---|---|---|
ProtonHackers/Incredible-Filter | web/website/forms.py | Python | lgpl-2.1 | 695 | 0 | from django import forms
from django.contrib.auth.models import User
from .models import Video
CHOICES = [('defaultKey', 'default')]
class VideosForm(forms.ModelForm):
| """
The form used to create a video
"""
class Meta(object):
"""
The fields used when creating the video form
"""
model = Video
fields = ["video_title", 'video_logo']
clas | s UserForm(forms.ModelForm):
"""
The form used to create a User
"""
password = forms.CharField(widget=forms.PasswordInput)
class Meta(object):
"""
The fields in the User form
"""
model = User
fields = ['username', 'email', 'password']
|
ucloud/uai-sdk | examples/mxnet/train/imagenet/code/symbols/googlenet.py | Python | apache-2.0 | 4,152 | 0.009393 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | mxnet as mx
def ConvFactory(data, num_filter, kernel, stride=(1,1), pad=(0, 0), name=None, suffix=''):
conv = mx.symbol.Convolution(data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, name='conv_%s%s' %(name, suffix))
act | = mx.symbol.Activation(data=conv, act_type='relu', name='relu_%s%s' %(name, suffix))
return act
def InceptionFactory(data, num_1x1, num_3x3red, num_3x3, num_d5x5red, num_d5x5, pool, proj, name):
# 1x1
c1x1 = ConvFactory(data=data, num_filter=num_1x1, kernel=(1, 1), name=('%s_1x1' % name))
# 3x3 reduce ... |
thehyve/variant | eurreca/urls.py | Python | apache-2.0 | 1,888 | 0.009534 | from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic import ListView
from django.contrib.auth import views as auth_views
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
... | ew'),
(r'^all/$', 'eurreca.views.all'),
(r'^faq/$', 'eurreca.views.faq'), |
(r'^advanced_search/$', 'eurreca.views.advanced_search_view'),
(r'^studies/$', 'eurreca.views.study_list'),
(r'^studies/create/$', 'eurreca.views.study_create'),
(r'^studies/update/(\w+)$', 'eurreca.views.study_update'),
(r'^studies/view/(\w+)$', 'eurreca.views.study_view'),
(r'^studies/remove/(... |
JaviMerino/lisa | tests/eas/hmp_parity.py | Python | apache-2.0 | 22,434 | 0.001738 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... | en(cls.env.target.bl.bigs + cls.env.target.bl.littles)
cls.populate_params()
cls.tasks = cls.params.keys()
local_setup(cls.env)
cls.run_workload()
cls.s_assert = SchedMultiAssert(
cls.trace_file,
cls.env.topology,
execnames=cls.tasks)
c... | g_fh = open(os.path.join(cls.env.res_dir, cls.log_file), "w")
@classmethod
def tearDownClass(cls):
cls.log_fh.close()
@classmethod
def populate_params(cls):
for i in range(cls.num_tasks):
task = cls.task_prefix + str(i)
cls.params[task] = Periodic(**SMALL_WORKLO... |
queria/my-tempest | tempest/api/object_storage/test_account_services.py | Python | apache-2.0 | 14,370 | 0 | # Copyright 2012 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... | 'x-timestamp', resp)
self.assertIn('x-account-bytes- | used', resp)
self.assertIn('x-account-container-count', resp)
self.assertIn('x-account-object-count', resp)
self.assertIn('content-type', resp)
self.assertIn('x-trans-id', resp)
self.assertIn('date', resp)
# Check only the format of common headers with custom matcher
... |
Charnelx/django-split-settings | tests/settings/basic/fixture_to_include.py | Python | bsd-3-clause | 115 | 0 | # -*- coding: utf-8 -*-
"""
This file only serves a | s a test fixture to be included.
"""
FIXTURE_VALUE = __file__
| |
gitsimon/tq_website | courses/models/course.py | Python | gpl-2.0 | 18,763 | 0.002825 | import datetime
from django.conf import settings
from django.contrib import auth
from django.db import models
from djangocms_text_ckeditor.fields import HTMLField
from parler.models import TranslatableModel, TranslatedFields
from courses import managers
from courses.models import PaymentMethod, Weekday, Gender, Cours... | 'unpaid': 0,
'paid_count': 0,
'not_paid_count': 0,
'paid_course': 0,
'paid_voucher': 0,
'paid_online': 0,
| 'paid_counter': 0,
}
accepted = self.subscriptions.accepted()
for s in accepted.all():
price = s.get_price_to_pay() or 0
totals['to_pay'] += price
paid = accepted.paid()
totals['paid_count'] = paid.count()
totals['not_paid_count'] = accepted.... |
ioram7/keystone-federado-pgid2013 | build/python-keystoneclient/keystoneclient/generic/client.py | Python | apache-2.0 | 8,468 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | self._get_version_info(version, url)
results[str(id)] = {"id": id,
"status": status,
"url": version_url}
return results
elif 'versions' in ... | 'message'] = "Keystone found at %s" % url
for version in body['versions']['values']:
id, status, version_url = \
self._get_version_info(version, url)
results[str(id)] = {"id": id,
... |
MrMosi/TuersystemClient | Module/Keypad/keypad.py | Python | mit | 2,815 | 0.017052 | #!/usr/bin/python
import RPi.GPIO as GPIO
class keypad():
def __init__(self):
"""
Initialisiert Key-Matrix
Angepasst von Christian Mossberg
"""
GPIO.setmode(GPIO.BOARD)
self.KEYPAD = [
[1,2,3,"A"],
[4,5,6,"B"],
[7,... | IO.IN, pull_up_do | wn=GPIO.PUD_UP)
if __name__ == '__main__':
# Initialize the keypad class
kp = keypad()
# Loop while waiting for a keypress
digit = None
while digit == None:
digit = kp.getKey()
# Print the result
print digit
|
RosalynHatcher/CFChecker | src/cfchecker/__init__.py | Python | bsd-3-clause | 598 | 0.025084 | import sys
import os
import os.path as op
__version__ = '2.0.5'
from cfchecker.cfchecks import getargs, CFChecker
def cfchecks_main():
"""c | fchecks_main is based on the main program block in cfchecks.py
"""
(badc,coards,uploader,useFileName,standardName,areaTypes,udunitsDat,version,files)=getargs(sys.argv)
inst = CFChecker(uploader=uploader, useFileName=useFileName, badc=badc, coards=coards, cfStandardNamesXML=standardName, cfAreaTypesXML... | c = inst.checker(file)
sys.exit (rc)
|
Mithrilwoodrat/Tombhub | tombhub/models.py | Python | gpl-2.0 | 1,363 | 0.007337 | import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKeyConstraint
from tombhub.database import Base
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
passwd = Column(String(50))
def __init__(se... | .id','users.name'])
def __init__(self, title=None, author_id=None, content = None):
self.title = title
self.author_id = author_id
self.author_name = User.query.get(self.author_id).name
self.content = content
| def __repr__(self):
return '<Thread %r>' % (self.title) |
supermihi/lpdec | lpdec/codes/nonbinary.py | Python | gpl-3.0 | 4,273 | 0.006787 | # -*- coding: utf-8 -*-
# Copyright 2014-2015 Michael Helmling
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation
"""This module contains classes and helper functions for non-binary cod... | tyCheckMatrix,
columns=cols, q=q)
| LinearBlockCode.__init__(self, q, name)
def flanaganEmbedding(vector, q):
"""Return the binary "Flanagan" embedding :cite:`Flanagan+09NonBinary` of a q-ary vector
:math:`\in \mathbb F_q^n` into :math:`\mathbb F_2^{(q-1)\\times n}` using the map::
0 -> 0 ... 0
1 -> 1 ... 0
2 ... |
mlperf/training_results_v0.6 | Intel/benchmarks/minigo/implementations/tensorflow-resubmit/preprocessing.py | Python | apache-2.0 | 10,709 | 0.001214 | # Copyright 2018 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 agree | d 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 under the License.
"""Utilities to create, read, write tf.Examples... | t sgf_wrapper
import symmetries
import numpy as np
import tensorflow as tf
import horovod.tensorflow as hvd
from tensorflow.python.data.experimental.ops import optimization
TF_RECORD_CONFIG = tf.python_io.TFRecordOptions(
tf.python_io.TFRecordCompressionType.ZLIB)
def _one_hot(index):
onehot = np.zeros([go... |
kshedstrom/pyroms | pyroms/pyroms/vgrid.py | Python | bsd-3-clause | 14,274 | 0.004484 | # encoding: utf-8
'''
Various vertical coordinates
Presently, only ocean s-coordinates are supported. Future plans will be to
include all of the vertical coordinate systems defined by the CF conventions.
'''
__docformat__ = "restructuredtext en"
import numpy as np
import warnings
class s_coordinate(object):
""... | = (self.s_w + self.c1)**self.Aweight * \
(self.c1 + (self.Aweight / self.Bweight) * \
(self.c1 - (self.s_w + self.c1)**self.Bweight))
self.Cs_w = Cweight * Csur + (self.c1 - Cweight) * Cbot
else:
| self.Cs_w = Csur
else:
self.Cs_w = self.s_w
class s_coordinate_4(s_coordinate):
"""
A. Shchepetkin (2005) UCLA-ROMS vertical coordinate transformation (Vtransform=2) and
stretching functions (Vstretching=4).
return an object that can be indexed to return depths
s ... |
zrhans/python | exemplos/Examples.lnk/bokeh/plotting/server/markers.py | Python | gpl-2.0 | 1,590 | 0.003774 | # The plot server must be running
# Go to http://localhost:5006/bokeh to view this plot
from numpy.random import random
from bokeh.plotting import *
def mscatter(p, x, y, typestr):
p.scatter(x, y, marker=typestr,
line_color="#6666ee", fill_color="#ee6666", fill_alpha=0.5, size=12)
def mtext(p, x, y,... | ):
p.text(x, y, text=textstr,
text_color="#449944", text_align="center", text_font_size="10pt")
output_server("markers")
p = figure(title="markers.py example")
N = 10
mscatter(p, random(N)+2, random(N)+1, "circle")
mscatter(p, random(N)+4, random(N)+1, "square")
mscatt | er(p, random(N)+6, random(N)+1, "triangle")
mscatter(p, random(N)+8, random(N)+1, "asterisk")
mscatter(p, random(N)+2, random(N)+4, "circle_x")
mscatter(p, random(N)+4, random(N)+4, "square_x")
mscatter(p, random(N)+6, random(N)+4, "inverted_triangle")
mscatter(p, random(N)+8, random(N)+4, "x")
mscatter(p, random(N)+... |
CWSL/access-cm-tools | analyse/spatial_difference_plot.py | Python | apache-2.0 | 3,634 | 0.005504 | #!/usr/bin/env python
from __future__ import print_function
import os, sys
import argparse
import datetime
import netCDF4 as nc
import numpy as np
import matplotlib
import matplotlib.colors as mcolors
from lib_util import run_ncra
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import... | b)
diff = fa.variables[args.var][:] - fb.variables[args.var][:]
fa.close()
fb.close()
os.remove(tmp_a)
os.remove(tmp_b)
if len(diff.shape) == 3:
diff = diff[0, :, :]
elif len( | diff.shape) == 4:
diff = diff[0, 0, :, :]
if not args.title:
args.title = '{}: A - B'.format(args.var)
do_global_plot(diff, args.title, lats, lons, args.output_file)
return 0
if __name__ == '__main__':
sys.exit(main())
|
ambimanus/appsim | analyze-headless.py | Python | mit | 16,543 | 0.004594 | import sys
import os
import csv
from datetime import datetime, timedelta
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.dates import drange
from matplotlib.patches import Rectangle
import scenario_factory
# http://www.javascripter.net/faq/hextorgb.htm
PRIM... | tal_seconds() | / 60 / res
P_el_unctrl = unctrl[:,0,skip:].sum(0)
P_el_ctrl = ctrl[:,0,skip:].sum(0)
P_el_sched = ctrl_sched[:,skip:].sum(0)
T_storage_ctrl = ctrl[:,2,skip:]
ft = np.array([t[0]] + list(np.repeat(t[1:-1], 2)) + [t[-1]])
P_el_ctrl_fill = np.repeat(P_el_ctrl[:-1], 2)
fig, ax = plt.subplot... |
schlegelp/pymaid | pymaid/cytoscape.py | Python | gpl-3.0 | 14,485 | 0.001588 | # This script is part of pymaid (http://www.github.com/schlegelp/pymaid).
# Copyright (C) 2017 Philipp Schlegel
#
# 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 ... | e | dict, optional
Provide a dictionary ``{group_name: [skid1, skid2, ...]}``
| to collapse sets of nodes into groups.
Returns
-------
Nothing
Examples
--------
A basic example:
>>> import pymaid
>>> import pymaid.cytoscape as cytomaid
>>> rm = pymaid.CatmaidInstance('server_url', 'api_token', 'http_user',
... ... |
futurecolors/django-confirmanager | confirmanager/tests.py | Python | mit | 10,684 | 0.004399 | # coding: utf-8
import datetime
from mock import patch, ANY
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from django.test import TestCase
from django.contrib.auth.models import User
from .utils import mock_signal_receiver
from .models import EmailConfirmation, Confirmat... | vil.com', False))
def test_no_unconfirmed(self):
latest_unconfirmed = EmailConfirmation.objects.last_email_for(self.user)
self.assertEqual(latest_unconfirmed, ('foo@bar | .com', True))
class TestSend(TestCase):
@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
DEFAULT_FROM_EMAIL='hey@bulldog.com')
def test_send(self):
user = UserFactory()
email = 'foo@bar.baz'
confirmation = EmailConfirmation.objec... |
fxa90id/up-flask-forum | app.py | Python | bsd-3-clause | 118 | 0.016949 | f | rom flask import Flask
app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
__all__ = ['app',] | |
HAYASAKA-Ryosuke/TrainInfo | traininfo.py | Python | mit | 624 | 0.017742 | #! /usr/bin/env python
#-*-coding:utf-8-*-
import BeautifulSoup
import urllib2
import codecs
import os
URL='http://www.tetsudo.com/traffic/'
html=urllib2.urlopen(URL).rea | d()
soup=BeautifulSoup.BeautifulSoup(html)
f=codecs.open('Traininfopy.cache','w','utf-8')
trableinfo=soup.findAll(id='hokai-1')[0].find('img').get('alt')
if( | trableinfo!=u"○"):
#f.write(u'道:')
f.write(' ')
f.write(soup.findAll(id='hokai-1')[0].findAll('td')[1].contents[0].contents[0])
f.write('=')
f.write(soup.findAll(id='hokai-1')[0].find('img').get('alt'))
f.write(' ')
f.close()
os.system("cat Traininfopy.cache")
|
matcatc/Test_Parser | src/TestParser_tests/Parser/BoostParser_Test.py | Python | gpl-3.0 | 6,099 | 0.00787 | '''
@date Feb 27, 2010
@author: Matthew A. Todd
This file is part of Test Parser
by Matthew A. Todd
Test Parser 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... | file = "main.cpp"
line = 10
message = "sample message"
error = "sample error"
time = 0
testCase = '<TestCase name="%(name)s"> \
<Message file="%(file)s" line="%(line)d">%(message)s</Message> \
<Error file="%(file)s" line="%(line)d">%(error)s<... | 'message' : message, 'error':error, 'time':time}
xml = ET.fromstring(testCase)
test = self.parser._parseTestCase(xml)
self.assertEqual(test.name, name)
self.assertEqual(test.timeTaken, time)
self.assertEqual(len(test.notices), 2)
for notice in te... |
s20121035/rk3288_android5.1_repo | external/chromium_org/chrome/common/extensions/docs/server2/api_schema_graph.py | Python | gpl-3.0 | 13,685 | 0.008842 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import logging
from api_models import GetNodeCategories
from collections import Iterable, Mapping
class LookupResult(object):
'''Returned fro... | gnored_categories:
return None
node_availability = self._LookupAvailability(self._lookup_path)
if node_availability is None:
logging.warning('No availability found for: %s' % self)
return None
parent_node_availability = self._LookupAvailability(self._GetParentPath())
# If the parent n... | t_node_availability is not None
# Only render this node's availability if it differs from the parent
# node's availability.
if node_availability == parent_node_availability:
return None
return node_availability
def Descend(self, *path, **kwargs):
'''Moves down the APISchemaGraph, following... |
meta-it/misc-addons | base_session_store_psql/http.py | Python | lgpl-3.0 | 500 | 0 | # -*- coding: utf-8 -*-
import logging
import odoo
from odoo.tools.func import lazy_property
from .sessi | onstore import PostgresSessionStore
_logger = logging.getLogger(__name__)
class RootTkobr(odoo.http.Root):
@lazy_property
def session_store(self):
# Setup http sessions
_logger.debug('HTTP sessions stored in Postgres')
return PostgresSessionStore(s | ession_class=odoo.http.OpenERPSession)
root = RootTkobr()
odoo.http.root.session_store = root.session_store
|
robertnishihara/ray | rllib/examples/eager_execution.py | Python | apache-2.0 | 2,627 | 0 | import argparse
import random
import ray
from ray import tune
from ray.rllib.agents.trainer_template import build_trainer
from ray.rllib.examples.models.eager_model import EagerModel
from ray.rllib.models import ModelCatalog
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.policy.tf_policy_template... | ning_achieved
tf1, tf, tfv = try_import_tf()
parser = argp | arse.ArgumentParser()
parser.add_argument("--stop-iters", type=int, default=200)
parser.add_argument("--stop-timesteps", type=int, default=100000)
parser.add_argument("--stop-reward", type=float, default=150)
parser.add_argument("--as-test", action="store_true")
def policy_gradient_loss(policy, model, dist_class, tra... |
fyffyt/pylearn2 | pylearn2/scripts/papers/maxout/tests/test_mnist.py | Python | bsd-3-clause | 1,773 | 0 | """
This file tests some of the YAML files in the maxout paper
"""
import os
import pylearn2
from pylearn2.datasets import control
from pylearn2.datasets.mnist import MNIST
from pylearn2.termination_criteria import EpochCounter
from pylearn2.testing.skip import skip_if_no_gpu
from pylearn2.utils.serial import load_tra... | axout/mnist_pi.yaml")
)
# Load fake MNIST data
init_value = control.load_data
control.load_data = [False]
train.dataset = MNIST(which_set='train', start=0, stop=100)
train.algorithm._set_monitoring_dataset(train.dataset)
control.load_data = init_value
# Train shortly and prevent saving... | |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/effective_network_security_group_list_result.py | Python | mit | 1,426 | 0 | # 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 ... | tyGroupListResult(Model):
"""Response for list effective network security groups API service call.
Variables are only populated by the server, and will be ignored when
sending a request.
:param value: A list of effective network security groups.
:ty | pe value:
list[~azure.mgmt.network.v2017_11_01.models.EffectiveNetworkSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str
"""
_validation = {
'next_link': {'readonly': True},
}
_attribute_map = {
'value': {'key': 'value', 'type':... |
hbenaouich/Learning-Python | Learning-Python3-The-Hard-Way/8-Printing, Printing/ex8.py | Python | apache-2.0 | 450 | 0 | # Assign the formatter to variable to pass on to print
formatter = "{} {} {} {}"
# display the values and pass them to formatter
print(formatter.format(1, 2, 3, 6))
print(formatter.format("one", "two", "three", "four"))
print(formatter.for | mat(True, False, False, True))
print(formatter.format( | formatter, formatter, formatter, formatter))
print(formatter.format(
"Try your",
"Own text here",
"Maybe a poem",
"or a song about fear"
))
|
odoousers2014/LibrERP | hr_document/__openerp__.py | Python | agpl-3.0 | 1,974 | 0.004053 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 Dhaval Patel (dhpatel82 at gmail.com)
# All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole ... | write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
################################## | ############################################
{
"name": "Human Resources/Documents",
"version": "0.beta",
"author": "DeneroTeam - Didotech",
"category": "Generic Modules/Human Resources",
"description": """A generic module to manage the employee documents with web gallery""",
'depends': [
'hr' ... |
lpryszcz/bin | genemark2bed.py | Python | gpl-3.0 | 1,738 | 0.043728 | #!/usr/bin/env python2
"""Convert gdata from gene mark into bedGraph.
USAGE:
genemark2bedGraph.py *.gdata [> bedGraph]
AUTHOR:
l.p.pryszcz+git@gmail.com
Barcelona, 17/07/2012
"""
import os,sys
def fn2bed( fn ):
"""Generate bed
http://genome.ucsc.edu/goldenPath/help/bedgraph.html
"""
#chromosome name is chr... | sys.argv[1:]
if not fnames:
sys.exit( "USAGE:\ngenemark2bed.py chr1.ldata [ chr2.ldata > genemark.bed ]" )
#iterate through files
print "track type=bed name=genemark"
for fn in fnames:
if not os.path.isfile( fn ):
sys.exit( "No such file: %s" % fn )
sys.stderr.write( " %s \r" % fn )
| #generate bedGraph
fn2bed( fn )
|
ndp-systemes/odoo-addons | partner_vat_improved/__openerp__.py | Python | agpl-3.0 | 1,236 | 0 | # -*- coding: utf8 -*-
#
# Copyright (C) 2014 NDP Systèmes (<http://www.ndp-systemes.fr>).
#
# This program is free software: you can redistribute it and/or modify |
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
#
# but WITHOUT ANY WARRANTY; without even the impli... | TY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
{
'name': 'Partner VAT Improved',
'version': '0.... |
jdhughes-usgs/river-eel | examples/mf6/test045_lake2tr_dev/mf2005/mf6lakeconn.py | Python | lgpl-3.0 | 3,316 | 0.004524 | import os
import numpy as np
import flopy
ml = flopy.modflow.Modflow.load('l2a_2k.nam', version='mf2005', verbose=True)
delx = ml.dis.delr.array
dely = ml.dis.delc.array
# get data from the lst file
f = open('l2a_2k.lst', 'r')
for line in f:
if 'LAYER # ROW # COLUMN # LAKE # INTERFACE TYPE LAKEBED LEA... | numerate(f):
if (len(line. | strip()) < 1):
break
cdata.append(line)
f.close()
tpth = 'mf5.conn.dat'
f = open(tpth, 'w')
for c in cdata:
f.write(c)
f.close()
dir_dict = {1:'HORIZONTAL',
2:'HORIZONTAL',
3:'HORIZONTAL',
4:'HORIZONTAL',
6:'VERTICAL'}
dtype = [('k', np.int), ('i', n... |
obozrenie/obozrenie | obozrenie/i18n.py | Python | gpl-3.0 | 311 | 0 | #!/usr/bin/env python3
import gettext
import locale
from obozrenie.global_settings import *
current_locale, | encoding = locale.getdefaultlocale()
t = gettext.translation(APPLICATION_ID, loc | aledir=LOCALE_DIR, languages=[
current_locale], codeset=encoding, fallback=True)
_ = t.gettext
|
lozadaOmr/ansible-admin | src/ansible/tests/test_forms.py | Python | bsd-3-clause | 1,795 | 0.006685 | from django.test import TestCase
from ansible.forms import AnsibleForm1, AnsibleForm2
class AnsibleCreateFormTest(TestCase):
def test_valid_ansibleform1(self):
form = AnsibleForm1({
'repository':'ansi-dst',
'username':'lozadaomr'
})
self.assertTrue(form.is_valid()... | ave()
self.assertEqual(form2.inventory, 'hosts')
self.assertEqual(form2.user, 'ubuntu')
def test_blank_ans | ibleform1(self):
form = AnsibleForm1({
'repository':'',
'username':''
})
self.assertFalse(form.is_valid())
def test_blank_ansibleform2(self):
form = AnsibleForm2({
'inventory':'',
'user':''
})
self.assertFalse(form.is_v... |
apoclyps/pyrestful | pyrestful/encoders.py | Python | apache-2.0 | 399 | 0 | import json
from decimal import Decimal
class CustomEncoder(json.JSONEncoder):
def default(self, obj | ect):
if isinstance(object, set):
return list(object)
if isinstance(object, Decimal):
if object % 1 > 0:
return float(object)
else:
return | int(object)
return super(CustomEncoder, self).default(object)
|
bmentges/brainiak_api | src/brainiak/stored_query/__init__.py | Python | gpl-2.0 | 50 | 0 | ES_INDEX_NAME = "brainiak"
ES_TY | PE_NAME | = "query"
|
MicrosoftGenomics/LEAP | leap/regression/leapUtils.py | Python | apache-2.0 | 5,785 | 0.04408 | import numpy as np
from optparse import OptionParser
import scipy.linalg as la
import scipy.linalg.blas as blas
import csv
import time
import fastlmm.util.VertexCut as vc
from pysnptools.snpreader.bed import Bed
import pysnptools.util as pstutil
import pysnptools.util.pheno as phenoUtils
np.set_printoptions(precision=3... | Set:
if (not fileSet.issuperset(bedSet)): raise Exception(fileStr + " file does not include all individuals in the bfile")
intersectSet = bedSet.intersection(fileSet)
if (len(intersectSet) != len (bedSet)):
print len(in | tersectSet), 'individuals appear in both the plink file and the', fileStr, 'file'
def symmetrize(a):
return a + a.T - np.diag(a.diagonal())
def loadRelatedFile(bed, relFile):
relatedDict = phenoUtils.loadOnePhen(relFile, vectorize=True)
checkIntersection(bed, relatedDict, 'relatedness', checkSuperSet=True... |
RedHatInsights/insights-core | insights/parsers/tests/test_nfnetlink_queue.py | Python | apache-2.0 | 2,689 | 0.000372 | import doctest
import pytest
from insights.parsers import nfnetlink_queue, ParseException
from insights.parsers.tests import skip_exception_check
from insights.tests import context_wrap
NFNETLINK_QUEUE = """
0 -4423 0 2 65535 0 0 22 1
1 -4424 0 2 65535 0 0 27 1
2 ... | fnet_link_queue.data[0]
assert row["queue_number"] == 0
assert row["peer_portid"] | == -4423
assert row["queue_total"] == 0
assert row["copy_mode"] == 2
assert row["copy_range"] == 65535
assert row["queue_dropped"] == 0
assert row["user_dropped"] == 0
assert row["id_sequence"] == 22
row = nfnet_link_queue.data[5]
assert row["queue_number"] == 5
assert row["peer_po... |
rom1sqr/miasm | test/arch/msp430/sem.py | Python | gpl-2.0 | 8,710 | 0.005855 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import unittest
import logging
from miasm2.ir.symbexec import symbexec
from miasm2.arch.msp430.arch import mn_msp430 as mn, mode_msp430 as mode
from miasm2.arch.msp430.sem import ir_msp430 as ir_arch
from miasm2.arch.msp430.regs import *
from miasm2.expression.expression im... | self.assertEqual(compute('call 1(R4)', {PC: 0x0100, SP: 0x0400, R4: 0x1F53, M(0x1F54): 0x38C4, }), {
PC: 0x38C4, SP: 0x03FE, R4: 0x1F53, M(0x1F54): 0x38C4, M(0x03FE): 0x104, })
self.assertEq | ual(compute('call @0x0000', {PC: 0x0100, SP: 0x0400 |
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/subscriptions/v2016_06_01/aio/_subscription_client.py | Python | mit | 4,453 | 0.003818 | # 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 may ... | iptions:
azure.mgmt.resource.subscriptions.v2016_06_01.aio.operations.SubscriptionsOperations
:ivar tenants: TenantsOperations operations
:vartype tenants:
azure.mgmt.resource.subscriptions.v2016_06_01.aio.operations.TenantsOperations
:param credential: Credential needed for the client to connect ... | dential
:param base_url: Service URL. Default value is 'https://management.azure.com'.
:type base_url: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
base_url: str = "https://management.azure.com",
**kwargs: Any
) -> None:
self._config = Subs... |
trygveaa/mopidy-spotify-tunigo | tests/test_backend.py | Python | apache-2.0 | 689 | 0 | from __future__ import unicode_literals
from mopidy import backend as backend_api
from mopidy_spotify_tunigo import backend, library
class TestSpotifyTunigoBackend(object):
| def get_backend(self, config):
return backend.SpotifyTunigoBackend(config=config, audio=None)
def test_uri_schemes(self, config):
backend = self.get_backend(config)
assert 'spotifytunigo' in backend.uri_schemes
def test_init_sets_up_the_providers(self, config):
backend = s... | sinstance(backend.library, backend_api.LibraryProvider)
|
stuckj/dupeguru | core_pe/exif.py | Python | gpl-3.0 | 10,797 | 0.001945 | # Created By: Virgil Dupras
# Created On: 2011-04-20
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-... | SDifferential"
}
INTEL_ENDIAN = ord('I')
MOTOROLA_ENDIAN = ord('M')
# About MAX_COUNT: It's possible to have corrupted exif tags where the entry count is way too | high
# and thus makes us loop, not endlessly, but for heck of a long time for nothing. Therefore, we put
# an arbitrary limit on the entry count we'll allow ourselves to read and any IFD reporting more
# entries than that will be considered corrupt.
MAX_COUNT = 0xffff
def s2n_motorola(bytes):
x = 0
for c in by... |
jeffh/describe | describe/flags.py | Python | mit | 5,303 | 0.004714 | """ flags.py - Various constants that have special meaning in describe.
INIT - Represents a matcher be instanciated for initialization purposes only
NO_ARG - Represents no argument. This is Noner than None.
"""
__all__ = (
'NO_ARG', 'NO_ARGS', 'ANY_ARG', 'ANYTHING', 'ANY_ARGS', 'ANY_KWARGS', 'is_flag',
... | s(DynamicFlag):
def __init__(self, cls):
self.cls = cls
def validate(self, argument):
try:
return issubclass(argument, self.cls)
except TypeError:
return False
clas | s InstanceOf(DynamicFlag):
def __init__(self, cls):
self.cls = cls
def validate(self, argument):
return isinstance(argument, self.cls)
class Contains(DynamicFlag):
def __init__(self, item):
self.item = item
def validate(self, argument):
try:
re... |
VoIP-co-uk/sftf | UserAgentBasicTestSuite/case901.py | Python | gpl-2.0 | 2,768 | 0.019147 | #
# Copyright (C) 2004 SIPfoundry Inc.
# Licensed by SIPfoundry under the GPL license.
#
# Copyright (C) 2004 SIP Forum
# Licensed to SIPfoundry under a Contributor Agreement.
#
#
# This file is part of SIP Forum User Agent Basic Test Suite which
# belongs to the SIP Forum Test Framework.
#
# SIP Forum User Agent Basic... | TestCase import | TestCase
import NetworkEventHandler as NEH
import Log
class case901 (TestCase):
def config(self):
self.name = "Case 901"
self.description = "Presence of RFC3261 branch ID in Via"
self.isClient = False
self.transport = "UDP"
self.interactRequired = True
def run(self):
self.neh = NEH.NetworkEventHandler... |
pinterb/st2 | st2auth/st2auth/controllers/auth.py | Python | apache-2.0 | 4,955 | 0.001009 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | 'standalone':
return self._handle_standalone_auth(request=request, **kwargs)
def _handle_proxy_auth(self, request, **kwargs):
remote_addr = pecan.request.headers.get('x-forwarded-for', pecan.request.remote_addr)
extra = {'remote_addr': remote_addr}
if pecan.request.remote_user... | t, 'ttl', None)
try:
token = self._create_token_for_user(username=pecan.request.remote_user, ttl=ttl)
except TTLTooLargeException as e:
self._abort_request(status_code=http_client.BAD_REQUEST,
message=e.message)
retu... |
CodethinkLabs/ofc | tools/organise-ofc-stderr-output.py | Python | apache-2.0 | 7,879 | 0.004315 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Codethink Ltd.
#
# 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 r... | dirs(dir_path)
return dir_path
def add_to_stderr_dict(stderr_dict, text):
identifier = ""
for line in text:
# The lines which end in ":" are paths to the files where the
# error or warning is. The following line to the last line which
# contains ":", is the description of the error/... | OFC output enclose some words in sigle quotes which are variable
# names or types which makes the same error/warning being different,
# removing this words creates the real identifier.
identifier = re.sub('\'(\S+?)\'', "", line.strip())
# TODO: remove ^ from the identifier, if this happ... |
DGA-MI-SSI/YaCo | deps/swig-3.0.7/Examples/python/multimap/runme.py | Python | gpl-3.0 | 358 | 0 | # file: runme.py
import example
# Cal | l our gcd() function
x = 42
y = 105
g = example.gcd(x, y)
print "The gcd of %d and %d is %d" % (x, y, g)
# C | all the gcdmain() function
example.gcdmain(["gcdmain", "42", "105"])
# Call the count function
print example.count("Hello World", "l")
# Call the capitalize function
print example.capitalize("hello world")
|
clkao/grano | grano/model/account.py | Python | mit | 2,682 | 0.002983 | from grano.core import db, url_for
from grano.model.util import make_token
from grano.model.common import IntBase
class Account(db.Model, IntBase):
__tablename__ = 'grano_account'
github_id = db.Column(db.Unicode)
twitter_id = db.Column(db.Unicode)
facebook_id = db.Column(db.Unicode)
full_name =... | ounts_api.view', id=self.id),
'display_name': self.display_name
}
def to_dict(self):
data = self.to_dict_i | ndex()
data['login'] = self.login
data['full_name'] = self.full_name
data['github_id'] = self.github_id
data['twitter_id'] = self.twitter_id
data['facebook_id'] = self.facebook_id
data['created_at'] = self.created_at
data['updated_at'] = self.updated_at
d... |
xqt2010a/Python_Study | python/01_IAR&Keil_Bat_b.py | Python | apache-2.0 | 1,670 | 0.012873 | # 说明:修改文件内容,为 IAR 工程合并前做处理
# 1. 除 “Ref_Dir”,“协议栈demo基本连接关系图”,“协议栈demo实物连接图”,“demo1_plc”
# 四个文件夹不处理,其他文件夹均做如下处理
# 2. 将每个 xml 文件里的 "$PROJ_DIR$" 替换为 "$PROJ_DIR$\.."
#
# @Author: labc
# Created on June 20 2017
#
#
import os
import shutil
d_ewp = ".ewp"
d_eww = ".eww"
d_ewt = ".ewt"
d_ewd = ".ewd"
d_icf = ".icf"
d_xml... | 议栈demo基本连接关系图"
Exclude_F2 = "协议栈demo实物连接图"
Exclude_F3 = "demo1_plc"
CurrDir = os.getcwd()
def handle_xml(path): |
for file in os.listdir(path):
if file[-4:] == d_xml: #find the xml file
file_dir = os.path.join(path,file)
print ("2:"+file_dir)
file_xml = open(file_dir,"r+")
file_xmls = file_xml.readlines()
file_xml.seek(0)
file_xml.truncate()... |
richo/groundstation | test/support/store_fixture.py | Python | mit | 783 | 0 | import unittest
import tempfile
import shutil
from groundstation.objects.root_object import RootObject
from groundstation.objects.update_object import UpdateObject
def random_path():
return tempfile.mkdtemp()
class StoreTestCase(unittest.TestCase):
storeClass = None
def setUp(self):
self.path... | ents, data):
return UpdateObject(parents, data)
| def create_root_object(self, gref):
return RootObject(gref.identifier, gref.channel, "test_protocol")
def test_create_blob(self):
blob = self.repo.create_blob("rawr lol butts")
self.assertTrue(blob in self.repo)
|
culturagovbr/sistema-nacional-cultura | gestao/models.py | Python | agpl-3.0 | 2,555 | 0.001958 | import datetime
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from simple_history.models import HistoricalRecords
from adesao.middleware import get_current_user
TIPOS_DILIGENCIA = (
('geral', 'Geral'),
... | def __str__(self):
return str(self.id)
class ArquivoHistoricalDiligenciaSimples(models.Model):
arquivo_url = models.URLField(blank=True, null=True)
class Meta:
abstract = True
class DiligenciaSimples(models.Model):
texto_diligencia = models.TextField(max_length=200)
classificaca... | ACAO_ARQUIVO, null=True, blank=True)
data_criacao = models.DateField(default=datetime.date.today)
usuario = models.ForeignKey('adesao.Usuario', on_delete=models.CASCADE)
history = HistoricalRecords(bases=[ArquivoHistoricalDiligenciaSimples, ])
class Contato(models.Model):
contatado = models.CharField(... |
biomodels/MODEL1310110042 | setup.py | Python | cc0-1.0 | 377 | 0.005305 | from setuptools import setup, find_packages
setup(name='MODEL1310110042',
version=20140916,
description='MODEL1310 | 110042 from BioModels',
url='http://www.ebi.ac.uk/biomodels-main/MODEL1310110042',
maintainer='Stanley Gu',
maintainer_url='stanleygu@gmail.com',
packages=find_packa | ges(),
package_data={'': ['*.xml', 'README.md']},
) |
FeynCalc/pyfeyncalctester | src/listcreator.py | Python | lgpl-3.0 | 44,022 | 0.00895 | #!/usr/bin/python
import itertools
class ListCreator():
current_list = None
def fcstDiracGammasInAlldimsAllIndicesContracted(self):
self.current_list = set(
list(itertools.permutations(['dirac_gamma<1>', 'dirac_gamma<1>'])) +
list(itertools.permutations(['dirac_gamma<1>', 'dirac_gamm... | mutations(['dirac_gamma<1>', 'dirac_gamm | a<1>', 'dirac_gamma<2>'])) +
list(itertools.permutations(['dirac_gamma<1>', 'dirac_gamma<1>', 'dirac_gamma<2>', 'dirac_gamma<2>', 'dirac_gamma<3>']))
+ list(itertools.permutations(['dirac_gamma<1>', 'dirac_gamma<1>', 'dirac_gamma<2>', 'dirac_gamma<2>', 'dirac_gamma<3>', 'dirac_gamma<3>', 'dirac_gamma<4>... |
BeyondTheClouds/enoslib | enoslib/infra/enos_g5k/concrete.py | Python | gpl-3.0 | 1,175 | 0 | from typing import List
from .configuration import (
ClusterConfiguration,
GroupConfiguration,
ServersConfiguration,
)
from .error import NotEnoughNodesError
class MinMixin:
def raise_for_min(self):
if self.config.min > len(self.oar_nodes):
raise NotEnoughNodesError(
... |
class ConcreteGroup(MinMixin):
"""Concretization of a cluster configuration (Base class)."""
def __init__(self, oar_nodes: List[str], config: GroupConfiguration):
self.oar_nodes = oar_nodes
self.config = config
class ConcreteClusterConf(ConcreteGroup, Min | Mixin):
"""Concretization of a cluster configuration."""
def __init__(self, oar_nodes: List[str], config: ClusterConfiguration):
super().__init__(oar_nodes, config)
class ConcreteServersConf(ConcreteGroup, MinMixin):
"""Concretization of a servers configuration."""
def __init__(self, oar_nod... |
dmlc/mxnet | ci/build_windows.py | Python | apache-2.0 | 8,069 | 0.003471 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache Licen... | CMAKE_FLAGS[args.flavour],
| mxnet_root)
logging.info("Generating project with CMake:\n{}".format(cmd))
check_call(cmd, shell=True)
cmd = "\"{}\" && jom".format(args.vcvars)
logging.info("Building with jom:\n{}".format(cmd))
t0 = int(time.time())
check_call(cmd, shell=True)
log... |
google/eclipse2017 | photo/app/app/backend/__init__.py | Python | apache-2.0 | 577 | 0 | #
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a c | opy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# | See the License for the specific language governing permissions and
# limitations under the License.
|
miing/mci_migo | api/urls.py | Python | agpl-3.0 | 3,433 | 0 | # Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from django.conf.urls import patterns, url
from piston.authentication import HttpBasicAuthentication
from piston.resource import Resource
from identityprovider.auth import (
... |
kwargs={'emitter_format': 'lazr.restful'}),
url(r'^1.0/accounts$', v10accounts, name='api-10-accounts',
kwargs={'emitter_format': 'lazr.restful'}),
# v1.1
url(r'^1.1/$', v11root,
kwargs={'emitter_format': 'lazr.restful'}),
# add backwards compatible endpoints
url(r'^1.1/cap... | ^1.1/accounts$', v10accounts,
kwargs={'emitter_format': 'lazr.restful'}),
# add overriding endpoints
url(r'^1.1/authentications$', v11auth,
kwargs={'emitter_format': 'lazr.restful'}),
# v2
url(r'^v2/accounts$', v2registration, name='api-registration'),
url(r'^v2/tokens/oauth$', v2lo... |
jlesquembre/pytag | pytag/interface.py | Python | gpl-3.0 | 2,131 | 0 | import magic
from pytag.structures import PytagDict
from pytag.constants import FIELD_NAMES
from pytag.formats import OggVorbisReader, OggVorbis, Mp3Reader, Mp3
MIMETYPE = {'application/ogg': (OggVorbisReader, OggVorbis),
'audio/mpeg': (Mp3Reader, Mp3)
}
class Tag:
"""Descriptor class.
... | name] = value
class MetaAudio(type):
"""Set all the FIELD_NAMES as class descriptors.
"""
def __init__(cls, *args, **kwargs):
super().__init__(*args, **kwargs)
for name in FIELD_NAMES:
setattr(cls, name, Tag(name))
class AudioReader(metaclass=MetaAudio):
"""High level in... | eturns a :py:exc:`pytag.FormatNotSupportedError` if not.
"""
_index = 0
def __init__(self, path):
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m:
self.mimetype = m.id_filename(path)
try:
self._format = MIMETYPE[self.mimetype][self._index](path)
except ... |
cvdlab/lar-running-demo | py/computation/old/step_convert_binarychains.py | Python | mit | 3,895 | 0.044673 | from scipy import *
import json
import scipy
import numpy as np
import time as tm
import gc
import struct
import getopt, sys
import os
import traceback
# ------------------------------------------------------------
# Logging & Timer
# ------------------------------------------------------------
logging_level = 0;
... |
log(1, ["zStart, xStart, yStart = " + str(zStart) + "," + str(xStart) + "," + str(ySta | rt)]);
# zStart, xStart, yStart = LISTA_OFFSET[i].astype(float64)
currentChain = np.zeros(chunksize,dtype=int32);
# log(1, ["chunksize = " + str(chunksize)]);
temp = file.read(chunksize);
# log(1, ["chunksize = OK"]);
i = 0
timer_start("currentChain " + str(i));
while (i < chunksize):... |
ajdawson/cartopy | lib/cartopy/mpl/feature_artist.py | Python | lgpl-3.0 | 4,936 | 0 | # (C) British Crown Copyright 2011 - 2015, Met Office
#
# This file is part of cartopy.
#
# cartopy 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)... | atplotlib paths.
paths = []
key = ax.projection
for geom in geoms:
mapping = FeatureArtist._geometry_to_path_cache.setdefault(geom,
{})
geom_paths = mapping.get(key)
| if geom_paths is None:
if ax.projection != feature_crs:
projected_geom = ax.projection.project_geometry(
geom, feature_crs)
else:
projected_geom = geom
geom_paths = cpatch.geos_to_path(projected_geom)
... |
xii/xii | src/xii/validator.py | Python | apache-2.0 | 6,612 | 0.000907 | import socket
import re
from xii import error, util
# sample validator
# keys = Dict(
# [
# RequiredKey("foo", String(), desc="A string to manipulate something"),
# Key("bar", String(), desc="something usefull")
# ],
# desc="Implement this stuff as you want"
# )
class Validator():
d... | elf.name, structure)
if not value_of_key:
raise error.ValidatorError("{} must have {} "
"defined".format(pre, self.name))
return self.schema.validate(pre + " > " + self.name, value_of_key)
class Dict(TypeCheck):
want = "dictonary"
want_type = ... | TypeCheck.__init__(self, desc)
self.schemas = schemas
def validate(self, pre, structure):
TypeCheck.validate(self, pre, structure)
def _validate(schema):
return schema.validate(pre, structure)
return sum(map(_validate, self.schemas)) >= 1
def structure(self, ... |
abingham/ackward | site_scons/ackward/namespace.py | Python | mit | 599 | 0.005008 | from .element import Element
from .trace import | trace
def to_open(ns):
return ' '.join(['namespace {0} {{'.format(n) for n in ns])
def to_close(ns):
return '}' * len(ns)
class Na | mespace(Element):
@trace
def __init__(self, *args, **kwargs):
Element.__init__(self, **kwargs)
self.ns = list(args)
@trace
def open_phase(self, mod, phase, symbols):
if phase in ('header', 'impl'):
yield to_open(self.ns)
@trace
def close_phase(self, mod, pha... |
saullocastro/pyNastran | pyNastran/bdf/dev_vectorized/cards/elements/solid/solid_element.py | Python | lgpl-3.0 | 6,927 | 0.004187 | from __future__ import print_function
from six.moves import StringIO
from numpy import zeros, searchsorted, where, asarray, array
from pyNastran.bdf.dev_vectorized.cards.elements.element import Element
class SolidElement(Element): |
def __init__(self, model):
Element.__init__(self, model)
def __getitem__(self, i):
return self.slice_by_index(i)
def slice_by_element_id(self, element_ids) | :
"""
Allows for slicing:
- elements[1:10]
- elements[4]
- elements[1:10:2]
- elements[[1,2,5]]
- elements[array([1,2,5])]
"""
try:
i = searchsorted(self.element_id, element_ids)
elements = self.slice_by_index(i)
... |
Arelle/ArelleBuilder | test/utilities/test_generate_messages_catalog.py | Python | apache-2.0 | 5,582 | 0.001433 | """
Test file for utilities/generate_messages_catalog.py
"""
from unittest import mock
import unittest
import ast
from utilities import generate_messages_catalog
class TestUtilties(unittest.TestCase):
@mock.patch(
'utilities.generate_messages_catalog.os.path.dirname', autospec=True
)
@mock.patch... | es"
)
def test_get_validation_message_str(self):
"""Checks that _get_validation_message works when msg_arg is an ast.Str"""
msg_arg = mock.Mock(spec=ast.Str)
msg_arg.s = "page"
result = generate_messages_catalog._get_validation_message(msg_arg)
self.assertEqual("page... | st.Call"""
msg_arg = mock.Mock(spec=ast.Call)
func = mock.Mock()
func.id = "_"
msg_arg.func = func
mock_arg = mock.Mock()
mock_arg.s = "trey"
msg_arg.args = [mock_arg]
result = generate_messages_catalog._get_validation_message(msg_arg)
self.assertE... |
vicente-gonzalez-ruiz/QSVC | trunk/src/texture_expand_lfb_mjpeg.py | Python | gpl-2.0 | 3,478 | 0.007763 | #!/usr/bin/python
# -*- coding: iso-8859-15 -*-
## @file texture_expand_lfb_mjpeg.py
# Expand the LFB texture data, using Motion JPEG.
# The two main steps performed are:
# - Decode components.
# - Transforms a YUV file to Raw file.
#
# @authors Vicente Gonzalez-Ruiz.
# @date Last modification: 2015, January 7... | "\n")
sys.stderr.write(" -[-f]ile | = file that contains the LFB data (\"%s\")\n" % file)
sys.stderr.write(" -[-l]layers = number of quality layers to decode (%d)\n" % layers)
sys.stderr.write(" -[-p]ictures = number of images to process (%d)\n" % pictures)
sys.stderr.write(" -[-t]emporal_levels = number of temporal levels (%d)\n" % te... |
wavesoft/cernvm-webapi | doc/tutorial/util/vmcp.py | Python | gpl-3.0 | 4,406 | 0.037676 |
import hashlib
import base64
import urllib
class _crypto_M2Crypto:
"""
[Cryptographic Routines Implementation]
Using M2Crypto Libraries (Tricky to build, but fast)
Installable using: `pip install m2crypto`
"""
def __init__( self, pkey ):
# Try to load M2Crypto
import M2Crypto
self.rsa = M2Crypto.RSA.load... | 2', payload).digest()
# Sign and return
return base64.b64encode( self.rsa.sign(digest, "sha512") )
class _cry | pto_PyCrypto:
"""
[Cryptographic Routines Implementation]
Using PyCrypto Libraries (Relatevely easy to build and fast)
Installable using: `pip install pycrypto`
"""
def __init__( self, pkey ):
# Try to load PyCrypto libraries
import Crypto.Hash.SHA512 as SHA512
import Crypto.PublicKey.RSA as RSA
import C... |
moralesjason/learnpythonthehardway | ex44inheritanceversuscomposition/ex44d.py | Python | gpl-3.0 | 519 | 0.028902 | #!/usr/bin/env python
class Parent(object):
def overrid | e(self):
print "PARENT override()"
def implicit(self):
print "PARENT implicit()"
def altered(self):
print "PARENT altered()"
class Child(Parent):
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered()
print "CHILD,AFTRE ... | Child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
|
robojamison/hello-git | lib/pocketsphinx/swig/python/test/lm_test.py | Python | mit | 3,092 | 0.004528 | # ====================================================================
# Copyright (c) 2013 Carnegie Mellon University. All rights
# reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of... | CLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
# NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDI | RECT, 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 NEGL... |
kaajavi/ninformes | escolar/__init__.py | Python | gpl-2.0 | 73 | 0.013699 | # | -*- coding: utf-8 -*-
default_app_config = 'escolar.apps.EscolarConfig' | |
turbulenz/turbulenz_tools | turbulenz_tools/utils/json_stats.py | Python | mit | 2,025 | 0.007407 | # Copyright (c) 2009-2011,2013 Turbulenz Limited
from os.path import getsize as path_getsize
from zlib import compress as zlib_compress
from simplejson import loads as json_loads
__version__ = '1.0.0'
def analyse_json(filename):
"""Utility to return the ratio of key size, punctuation size, and leaf value size.""... | compressed_size = len(zlib_compress(data, 6))
return (k | eys, punctuation, values, key_count, unique_count, total_size, compressed_size)
|
google/google-ctf | vrp/kctf/challenge-templates/xss-bot/healthcheck/healthcheck.py | Python | apache-2.0 | 353 | 0.005666 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
from pwn import *
r = remote('127.0.0.1', 1337)
l = listen()
r.readuntil(b'URL to open.', timeout=10)
r.send(bytes('http://localhost:{}/ok'.format(l.lport), 'ascii' | ))
_ = l.wait | _for_connection()
l.readuntil(b'GET /ok HTTP/1.1')
l.send(b'HTTP/1.1 200 OK\nContent-Length: 0\n\n')
exit (0)
|
JackBDu/polygon | polygon2.py | Python | apache-2.0 | 5,346 | 0.004302 | ########################################################
### Polygon ###
########################################################
__author__ = "Jack B. Du (Jiadong Du)"
__copyright__ = "Copyright 2014, DS @NYUSH"
__email__ = "JackBDu@nyu.edu"
import pygame
from pygame.locals i... | s, pMousePos, letsMove, currentCursor, inserted, fullscreen, current_screen_w, current_screen_h, background
for event in pygame.event.get():
if event.type == QUIT:
mainloop = False
| if event.type == KEYDOWN:
# handling fullscreen
if event.key == K_f:
fullscreen = not fullscreen
if fullscreen:
current_screen_w = FULLSCREEN_W
current_screen_h = FULLSCREEN_H
screen = pygame.disp... |
tmobile/jazz-installer | features/utils/jenkins.py | Python | apache-2.0 | 3,010 | 0.001993 | import requests
import subprocess
import sys
from requests.auth import HTTPBasicAuth
from utils.helper import colors
def setCredential(jenkins_url, jenkins_user, jenkins_api_token, credential_id, key, value, credtype="userpass"):
basic_auth = HTTPBasicAuth(jenkins_user, jenkins_api_token)
url = "http://{}/cre... | sys.exit(1)
def deleteCredential(jenkins_url, jenkins_user, jenkins_api_token, credid):
basic_auth = HTTPBasicAuth(jenkins_user, jenkins_api_token)
url = "http://{}/credentials/store/system/domain/_/credential/{}/doDelete".format(jenkins_url, credid)
resp = requests.post(url, auth | =basic_auth)
if resp.status_code != 200:
print("Failed to delete credential from jenkins.")
sys.exit(1)
def startJob(url, username, password, jobUrl):
requests.post(("http://%s:%s@%s/%s") % (username, password, url, jobUrl))
def startJobwithInputs(url, username, password, job, input):
do... |
cloudbase/coriolis | coriolis/conductor/rpc/utils.py | Python | agpl-3.0 | 2,235 | 0 | # Copyright 2020 Cloudbase Solutions Srl
# All Rights Reserved.
import time
from oslo_log import log as logging
from coriolis import utils
LOG = logging.getLogger(__name__)
def check_c | reate_registration_for_service(
conductor_rpc, request_context, host, binary, topic, enabled=False,
mapped_regions=None, providers=None, specs=None, retry_period=30):
""" Checks with the conductor whether or not a service has already been
registered for this host and topic and creates one if not... | ='%s'" % (host, binary, topic)
while True:
try:
# check is service already exists:
LOG.info(
"Checking with conductor if service with following porperties "
"was already registered: %s", props)
worker_service = conductor_rpc.check_service_r... |
SanPen/GridCal | src/GridCal/Engine/Core/Compilers/circuit_to_data.py | Python | lgpl-3.0 | 28,064 | 0.00139 | from GridCal.Engine.basic_structures import Logger
from GridCal.Engine.Core.multi_circuit import MultiCircuit
from GridCal.Engine.basic_structures import BranchImpedanceMode
from GridCal.Engine.basic_structures import BusMode
from GridCal.Engine.Devices.enumerations import ConverterControlType, TransformerControlType
f... | data.generator_installed_p[k] = elm.Snom
if time_ser | ies:
data.generator_p[k] = elm.P_prof
data.generator_active[k] = elm.active_prof
data.generator_pf[k] = elm.Pf_prof
data.generator_v[k] = elm.Vset_prof
if opf:
data.generator_dispatchable[k] = elm.enabled_dispatch
data.generato... |
sentriz/steely | steely/plugins/owo.py | Python | gpl-3.0 | 679 | 0.030928 | """
OwO whats this?
"""
__author__ = ('Smurphicus')
COMMAND = 'owo'
from random import choice
| substitutions = {'r':'w','R':'W','l':'w','L':'W','na':'nya','NA':'NYA','qu':'qw','QU':'QW'}
faces = [' OwO', ' owo', ' UwU', ' uwu', ' :3', ' :33', ' :333', '']
def owoify(message):
for key in substitutions.keys():
message = message.replace(key,substitutions[key])
return message + choice(faces)
def ma... | eadMessages(thread_id=thread_id, limit=2)[1]
owoified_message = owoify(message.text)
bot.sendMessage(owoified_message, thread_id=thread_id, thread_type=thread_type)
|
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/guidanceresponse_tests.py | Python | bsd-3-clause | 1,811 | 0.003313 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 on 2017-03-22.
# 2017, SMART Health IT.
import io
import json
import os
import unittest
from . import guidanceresponse
from .fhirdate import FHIRDate
class GuidanceResponseTests(unittest.TestCase):
def instantiate_from(self, fi... | eResponse(js)
self.implGuidanceResponse1(inst2)
def i | mplGuidanceResponse1(self, inst):
self.assertEqual(inst.contained[0].id, "outputParameters1")
self.assertEqual(inst.id, "example")
self.assertEqual(inst.identifier.system, "http://example.org")
self.assertEqual(inst.identifier.value, "guidanceResponse1")
self.assertEqual(inst.occ... |
joeyb182/pynet_ansible | byers-paid/exercise_week_4_1-2.py | Python | apache-2.0 | 1,154 | 0.020797 | #!/usr/bin/env python
'''
1. Use Paramiko to retrieve the entire 'show | version' output from pynet-rtr2.
2. Use Paramiko to change the 'logging buffered <size>' configuration on pynet-rtr2. This will require that you enter into configuration mode.
'''
import paramiko
from getpass import getpass
ip_addr = '50.76.53.27'
username = 'pyclass'
port = 8022
password = getpass() #reque | sts user input for password and hides it
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #tells it to auto add keys...kinda dangerous, but will get a known_hosts error without it
remote_conn_pre.connect(ip_addr, username=username, password=password, look_fo... |
googleads/google-ads-python | google/ads/googleads/v9/resources/types/ad_group_criterion.py | Python | apache-2.0 | 22,226 | 0.001665 | # -*- coding: utf-8 -*-
# Copyright 2020 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... | _name (str):
Immutable. The resource name of the ad group criterion. Ad
group criterion resource names have the form:
``customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}``
criterion_ | id (int):
Output only. The ID of the criterion.
This field is ignored for mutates.
This field is a member of `oneof`_ ``_criterion_id``.
display_name (str):
Output only. The display name of the
criterion.
This field is ignored for mutates.... |
googleapis/python-datacatalog | samples/generated_samples/datacatalog_v1_generated_policy_tag_manager_list_policy_tags_sync.py | Python | apache-2.0 | 1,525 | 0.000656 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ogle-cloud-datacatalog
# [START datacatalog_v1_generated_PolicyTagManager_ListPolicyTags_sync]
from google.cloud import datacatalog_v1
def sample_list_policy_tags():
# Create a cli | ent
client = datacatalog_v1.PolicyTagManagerClient()
# Initialize request argument(s)
request = datacatalog_v1.ListPolicyTagsRequest(
parent="parent_value",
)
# Make the request
page_result = client.list_policy_tags(request=request)
# Handle the response
for response in page_r... |
SpectraLogic/samba | python/samba/tests/subunitrun.py | Python | gpl-3.0 | 2,387 | 0.002514 | #!/usr/bin/env python
# Simple subunit testrunner for python
# NOTE: DO NOT USE THIS MODULE FOR NEW CODE.
#
# Instead, use the standard subunit runner - e.g. "python -m subunit.run
# YOURMODULE".
#
# This wrapper will be removed once all tests can be run
# without it. At the moment there are various tests which still... | g. credentials passed via command-line options to this
# script.
# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2014
#
# 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 ... | RRANTY; 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 this program. If not, see <http://www.gnu.org/licenses/>.
#
# make sure the scr... |
lantip/sms-komunitas | medkom/nonmember/migrations/0001_initial.py | Python | gpl-3.0 | 1,108 | 0.002708 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='nonmember',
fields=[
('id', models.AutoField(ve... | arField(max_length=100)),
('nama_panggilan', models.CharField(max_length=20, blank=True)),
('no_ha | ndphone', models.CharField(max_length=15, blank=True)),
('jabatan', models.CharField(max_length=255, blank=True)),
('nama_dinas', models.CharField(max_length=255)),
('wilayah', models.CharField(max_length=255)),
],
options={
'verbos... |
dims/oslo.context | tests/test_context.py | Python | apache-2.0 | 2,079 | 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 required by applicable law or agreed to in writing, software
# | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslotest import base as test_base
from oslo.context impor... |
AfricaChess/lichesshub | club/management/commands/get_teamlist.py | Python | mit | 1,601 | 0.001249 | import requests
import json
from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils import timezone
from club.models import Club, Member
class Command(BaseCommand):
help = 'Get List of players from lichess for team'
def handle(self, *args, **kwargs):
t... | ating']
mb.club = team
mb.save()
self.stdout.write('Saving {}'.format(player['username']))
# Update last_sync
team.last_sync = timezone.now()
team.save()
#import pdb;pdb.set_trace()
| #results = resp.content['paginator']['currentPageResults']
self.stdout.write(str(results))
|
thinkopensolutions/tkobr-addons | tko_cna_crm_claim_form_layout/__manifest__.py | Python | agpl-3.0 | 2,031 | 0.000492 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# Thinkopen Brasil
# Copyright (C) Thinkopen Solutions Brasil (<http://www.tkobr.com>).
#
# This ... | SE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Publ | ic License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Claim form layout',
'version': '10.0',
'category': 'customization',
'sequence': 150,
'complexity': 'normal',
'descrip... |
DMPwerkzeug/DMPwerkzeug | rdmo/projects/migrations/0030_project_views.py | Python | apache-2.0 | 523 | 0.001912 | # Generated by Django 2.2.7 on 2019-11-05 11:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('views', '0021_view_catalogs'),
('projects', '0029_remove_manager'),
]
operations = [
migrations.AddField(
model_name='pr... | used for this project.', to='views.View', | verbose_name='Views'),
),
]
|
wateraccounting/wa | Collect/MOD17/__init__.py | Python | apache-2.0 | 860 | 0.001163 | # -*- | coding: utf-8 -*-
"""
Authors: Tim Hessels
UNESCO-IHE 2016
Contact: t.hessels@unesco-ihe.org
Repository: https://github.com/wateraccounting/wa
Module: Collect/MOD17
Description:
This module downloads MOD17 GPP data from
http://e4ftl01.cr.usgs.gov/. Use the MOD17.GPP_8daily function to
download and create 8 da... |
Examples:
from wa.Collect import MOD17
MOD17.GPP_8daily(Dir='C:/Temp3/', Startdate='2003-12-01', Enddate='2003-12-20',
latlim=[41, 45], lonlim=[-8, -5])
MOD17.NPP_yearly(Dir='C:/Temp3/', Startdate='2003-12-01', Enddate='2003-12-20',
latlim=[41, 45], lonlim=[-8, -5])
"""
from .GPP_8daily imp... |
erjac77/ansible-module-f5bigip | library/f5bigip_util_get_dossier.py | Python | apache-2.0 | 5,751 | 0.002087 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2018, Eric Jacob <erjac77@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | '-i {0}'.format(self._params['inactiveKey'])
@property
def kernel_version(self):
if self._params['kernelVersion'] is None:
return None
return '-k {0}'.format(self._params['kernelVersion'])
@property
def version(self):
if self._ | params['version'] is None:
return None
return '-v "{0}"'.format(self._params['version'])
def flush(self):
result = dict(changed=False, stdout=list())
if self._check_mode:
result['changed'] = True
return result
try:
output = self._met... |
buck06191/BayesCMD | batch/wavepy/__init__.py | Python | gpl-2.0 | 176 | 0 | #! /usr/bin/ | env python
from wavepy import sample
from wavepy import filter
from wavepy import convol
from wavepy import misc
from wavepy import dwt
from wav | epy import denoise
|
C2SM-RCM/serialbox | python/serialbox/serialization.py | Python | bsd-2-clause | 24,203 | 0.002231 | # This file is released under terms of BSD license`
# See LICENSE.txt for more information
"""Internal serialization module that wraps the dynamic library of serialbox.
This module is used by the Serializer module.
"""
from __future__ import print_function
import os
import sys
from os.path import join as pjoin
impor... | er_metainfo_get_types = wrapper.fs_serializer_metainfo_get_types
fs_get_serializer_metainfo_b = wrapper.fs_get_serializer_metainfo_b
fs_get_serializer_metainfo_i = wrapper.fs_get_serializer_metainfo_i
fs_get_serializer_metainfo_f = wrapper.fs_get_serializer_metainfo_f
fs_get_serializer_metainfo_d = wrapper.fs_get_seria... | t_serializer_metainfo_s = wrapper.fs_get_serializer_metainfo_s
fs_add_serializer_metainfo_b = wrapper.fs_add_serializer_metainfo_b
fs_add_serializer_metainfo_i = wrapper.fs_add_serializer_metainfo_i
fs_add_serializer_metainfo_f = wrapper.fs_add_serializer_metainfo_f
fs_add_serializer_metainfo_d = wrapper.fs_add_seriali... |
Katello/katello-cli | test/katello/tests/core/permission/permission_create_test.py | Python | gpl-2.0 | 3,671 | 0.002179 | import unittest
from mock import Mock
import os
from katello.tests.core.action_test_utils import CLIOptionTestCase, CLIActionTestCase
from katello.tests.core.permission import permission_data
from katello.tests.core.user import user_data
import katello.client.core.permission
from katello.client.core.permission impor... |
def test_it_creates_permission(self):
self.mock_options(self.FULL_OPTIONS)
self.mock(self.act | ion, 'tags_to_ids', ['1', '2'])
self.run_action()
self.action.api.create.assert_called_once_with(self.ROLE['id'], self.PERMISSION['name'], self.PERMISSION['description'], self.PERMISSION['resource_type']['name'], ['v1', 'v2'], ['1', '2'], None, 'True', 'False')
def test_returns_error_when_permissio... |
chris-martin/hocon-python | hocon/impl/tokens.py | Python | apache-2.0 | 11,757 | 0 | """
FIXME the way the subclasses of Token are private with static isFoo and
accessors is kind of ridiculous.
"""
from .. import exceptions, ConfigOrigin, ConfigValueType
from .ResolveStatus import ResolveStatus
from .Token import Token
from .TokenType import TokenType
class Value(Token):
def __init__(self, val... | = what
self._message = message
self._suggest_quotes = suggest_quotes
self._cause = cause
def what(self):
"""
:return: String
| """
return self._what
def message(self):
"""
:return: String
"""
return self._message
def suggest_quotes(self):
"""
:return: boolean
"""
return self._suggest_quotes
def cause(self):
"""
:return: Throwable
"""
... |
DarkStarSword/StereoCropper | directx/types.py | Python | gpl-3.0 | 35,586 | 0.026331 |
from ctypes import *
from ctypes.wintypes import *
from comtypes import *
#********************************************************************
#
# Typedefs and constants
#
#********************************************************************
REFGUID = POINTER(GUID)
UINT = c_uint
INT = c_int
... | 17
TEXTURE2 = 18
TEXTURE3 = 19
TEXTURE4 = 20
TEXTURE5 = 21
TEXTURE6 = 22
TEXTURE7 = 23
WORLD = 256 + 0
class D3DRS:
ZENABLE = 7
FILLMODE = 8
SHADEMODE = 9
ZWRITEENABLE ... |
DESTBLEND = 20
CULLMODE = 22
ZFUNC = 23
ALPHAREF = 24
ALPHAFUNC = 25
DITHERENABLE = 26
ALPHABLENDENABLE = 27
FOGENABLE = 28
SPECULARENABLE ... |
surajssd/kuma | kuma/wiki/views/utils.py | Python | mpl-2.0 | 3,100 | 0 | # -*- coding: utf-8 -*-
from datetime import datetime
import newrelic.agent
import waffle
from kuma.core.cache import memcache
from ..constants import DOCUMENT_LAST_MODIFIED_CACHE_KEY_TMPL
from ..events import EditDocumentEvent
from ..models import Document, RevisionIP
from ..tasks import send_first_edit_email
def... | plit_slug(slug):
"""
Utility function to do basic slug splitting
"""
slug_split = slug.split('/')
length = len(slug_split)
root = None
seo_root = ''
bad_seo_roots = ['Web']
if length > 1:
| root = slug_split[0]
if root in bad_seo_roots:
if length > 2:
seo_root = root + '/' + slug_split[1]
else:
seo_root = root
specific = slug_split.pop()
parent = '/'.join(slug_split)
return {
'specific': specific,
'parent': parent,
... |
guilload/pyisaac | tests/fixtures.py | Python | mit | 30,816 | 0.009346 | RESULTS = [0x58759924, 0x2be2c273, 0x03165f2e, 0xe4f4832b, 0x88fa93d2, 0xcc096c83, 0xfb713a21, 0x99aa55bd,
0xeae7f35d, 0xddaf236c, 0xda0552ce, 0xd2fb442f, 0xfd1ac65e, 0xa680c86c, 0x7a9f36c0, 0xa5ccce35,
0x8060b929, 0xe2a6a2da, 0x68175335, 0x18859b40, 0xd2b4213b, 0x97a896c0, 0x119d3659, 0xbc89d7b1,... | a0c2f9, 0xc88f8227,
0x3fc2846f, 0xb733d3e8, 0x66a4d3f5, 0x1b972522, 0x84f85127, 0x630db5a0, 0xfb0df03c, 0x246352ba,
| 0xebcd2c3c, 0x04d71c76, 0x451ff5d0, 0xa24e4936, 0x63767436, 0xfea963af, 0x0fee93aa, 0x12b1392e,
0xc658d0b3, 0x8d91d5d0, 0x389f9550, 0 |
jmwright/cadquery-freecad-module | ThirdParty/cqparts_fasteners/fasteners/screw.py | Python | lgpl-3.0 | 1,975 | 0.003544 |
from cqparts.constraint import Mate, Coincident
from .base import Fastener
| from ..screws import Screw
from . | .utils import VectorEvaluator, Selector, Applicator
class ScrewFastener(Fastener):
"""
Screw fastener assembly.
Example usage can be found here: :ref:`cqparts_fasteners.built-in.screw`
"""
Evaluator = VectorEvaluator
class Selector(Selector):
ratio = 0.8
def get_components(se... |
zachjanicki/osf.io | website/util/__init__.py | Python | apache-2.0 | 6,848 | 0.002044 | # -*- coding: utf-8 -*-
import collections
import re
import urllib
import logging
import urlparse
from contextlib import contextmanager
import furl
from flask import request, url_for
from website import settings as website_settings
from api.base import settings as api_settings
# Keep me: Makes rubeus importable fr... | m_words == 2:
return ' {0} '.format(conj).join(words)
elif num_words > 2:
return ', '.join(words[:-1]) + ', {0} {1}'.format(conj, words[-1])
def _get_guid_url_for(url):
"""URL Post-processor transforms specific `/project/<pid>` or `/project/<pid>/node/<nid>`
urls into guid urls. Ex: `<nid>... | uid_url = guid_url_profile_pattern.sub('', guid_url, count=1)
return guid_url
def api_url_for(view_name, _absolute=False, _xml=False, *args, **kwargs):
"""Reverse URL lookup for API routes (that use the JSONRenderer or XMLRenderer).
Takes the same arguments as Flask's url_for, with the addition of
`_a... |
tedder/ansible | lib/ansible/modules/cloud/azure/azure_rm_managed_disk_facts.py | Python | gpl-3.0 | 6,559 | 0.00122 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Bruno Medina Bolanos Cacho <bruno.medina@microsoft.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA... | Format tags as 'key' or 'key:value'.
type: list
extends_documentation_fragment:
- azure
- azure_tags
author:
- Bruno Medina (@brusMX)
'''
EXAMPLES = r'''
- name: Get facts for one managed disk
azure_rm_managed_disk_facts:
name: Testing
resource_group: TestRG
- name: Get facts for all m... |
RETURN = r'''
azure_managed_disk:
description: List of managed disk dicts.
returned: always
type: list
contains:
id:
description:
- Resource id.
type: str
name:
description:
- Name of the managed disk.
type:... |
laserson/ibis | ibis/impala/tests/test_partition.py | Python | apache-2.0 | 7,977 | 0 | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | b = cls.con.database(cls.tmp_db)
cls.pd_name = _tmp_name()
cls.db.create_table(cls.pd_name, df)
def test_is_partitioned(self):
schema = ibis.schema([('foo', 'string'),
('year', 'int32'),
('month', 'int16')])
name = _tmp_nam... | )
self.db.create_table(name, schema=schema,
partition=['year', 'month'])
assert self.db.table(name).is_partitioned
def test_create_table_with_partition_column(self):
schema = ibis.schema([('year', 'int32'),
('month', 'int8'),
... |
legalsylvain/oca-custom | __unported__/oca_freestore/models/github_repository.py | Python | agpl-3.0 | 4,465 | 0.004703 | # -*- coding: utf-8 -*-
# Copyright (C) 2016-Today: Odoo Community Association (OCA)
# @author: Sylvain LE GAL (https://twitter.com/legalsylvain)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
from openerp import models, fields, api
_logger = logging.getLogger(__name__)
class G... | # Custom Section
def github_2_odoo(self, data):
return {
'name': data['name'],
'complete_name': data['full_name'],
'github_url': data['url'],
'website': data['homepage'],
'description': data['description'],
}
@api.multi
def _ana... | ository in self:
#### # Delete all issues versions # TODO
#### module_versions = module_version_obj.search([
#### ('repository_branch_id', '=', repository_branch.id)])
#### module_versions.with_context(
#### dont_change_repository_branch_state=True).unlink(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.