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 |
|---|---|---|---|---|---|---|---|---|
dbmi-pitt/DIKB-Micropublication | scripts/mp-scripts/Bio/Clustalw/__init__.py | Python | apache-2.0 | 22,263 | 0.004177 | # Clustalw modules
"""
A set of classes to interact with the multiple alignment command
line program clustalw.
Clustalw is the command line version of the graphical Clustalx
aligment program.
This requires clustalw available from:
ftp://ftp-igbmc.u-strasbg.fr/pub/ClustalW/.
functions:
o parse_file
o do_alignment... | mal SAX handler.
After parsing, the alignment object created is available as the
align attribute of the class.
"""
def __init__(self, alphabet):
"""Create a new handler ready to deal with output from Martel parsing.
Arguments:
o alphabet - The alphabet to create all of the new ... | # store sequence info in a dictionary
self.all_info = {}
self.all_keys = []
# the current id we are working with
self.cur_id = None
# info so we know how big the ids and sequences are
self.id_size = 0
self.space_size = 0
self.seq_size = 0
... |
LLNL/spack | var/spack/repos/builtin/packages/vasp/package.py | Python | lgpl-2.1 | 9,155 | 0.000983 | # 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
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
... | :
fflags.append('-w')
elif '%nvhpc' in spec:
fflags.extend(['-Mnoupcase', '-Mbackslash', '-Mlarge_arrays'])
elif '%aocc' in spec:
fflags.extend(['-fno-fortran-main', '-Mbackslash', '-ffast-math'])
spack_env.set('BLAS', spec['blas'].libs.ld_flags)
spac... | ibs.ld_flags)
spack_env.set('FFTW', spec['fftw-api'].prefix)
spack_env.set('MPI_INC', spec['mpi'].prefix.include)
if '%nvhpc' in spec:
spack_env.set('QD', spec['qd'].prefix)
if '+scalapack' in spec:
cpp_options.append('-DscaLAPACK')
spack_env.set('SC... |
ryfeus/lambda-packs | Tensorflow_Pandas_Numpy/source3.6/pandas/core/indexes/base.py | Python | mit | 170,379 | 0.000006 | from datetime import datetime, timedelta
import warnings
import operator
from textwrap import dedent
import numpy as np
from pandas._libs import (lib, index as libindex, tslib as libts,
algos as libalgos, join as libjoin,
Timedelta)
from pandas._libs.lib import is_da... | if needs_i8_conversion(self) and needs_i8_conversion(other):
return self._evaluate_compare(other, op)
from .multi import | MultiIndex
if is_object_dtype(self) and not isinstance(self, MultiIndex):
# don't pass MultiIndex
with np.errstate(all='ignore'):
result = ops._comp_method_OBJECT_ARRAY(op, self.values, other)
else:
# numpy will show a DeprecationWarning on invalid e... |
deebuls/RecommenderSystemInRobotics | code/knowledge_base_creator/recommended_learning.py | Python | mit | 4,956 | 0.011501 | from formlayout import fedit
from StringIO import StringIO
class recommended_learning:
def __init__(self):
#initalize filenames
self.skills_db = './knowledge_base/skills.csv'
self.robot_features_db = './knowledge_base/robot_features.csv'
self.environment_features_db = './knowledge_b... | n(self.templates_db, 'a') as f:
for d in data[1:]:
if d != 0:
f.write(" " + self.robot_features[d])
f.write("\n")
f.close()
def read_database(self):
self.ski | lls = []
self.robot_features = []
self.environment_features = []
self.templates = []
with open(self.skills_db, 'rb') as f:
for line in f:
self.skills.append(line.rstrip('\n'))
with open(self.robot_features_db, 'rb') as f:
for line in f:
... |
HuaweiSwitch/ansible | lib/ansible/modules/database/influxdb/influxdb_retention_policy.py | Python | gpl-3.0 | 7,662 | 0.001697 | #!/usr/bin/python
# (c) 2016, Kamil Szczygiel <kamil.szczygiel () intel.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 published by
# the Free Software Foundation, either version 3 of the License, or
# ... | retention_policy['duration'] == influxdb_duration_format or
not retention_policy['replicaN'] == int(replication) or
not retention_policy['default'] == default):
if not module.check_mode:
try:
client.alter_retention_policy(policy_name, database_name, duration, ... | )
def main():
argument_spec = influxdb_argument_spec()
argument_spec.update(
policy_name=dict(required=True, type='str'),
duration=dict(required=True, type='str'),
replication=dict(required=True, type='int'),
default=dict(default=False, type='bool')
)
module = AnsibleMo... |
opendatakosovo/municipality-procurement-visualizer | gpv/views/pages/about_page.py | Python | gpl-2.0 | 185 | 0 | from flask import render_template
from | flask.views import View
class AboutPage(View):
def dispatch_request(self):
return render_template('about.html', komuna='prishtina' | )
|
anneline/Bika-LIMS | bika/lims/browser/widgets/artemplateanalyseswidget.py | Python | agpl-3.0 | 7,475 | 0.005351 | # ../../skins/bika/bika_widgets/artemplatepartitionswidget.pt
from AccessControl import ClassSecurityInfo
from Products.Archetypes.Registry import registerWidget, registerPropertyType
from Products.Archetypes.Widget import TypesWidget
from Products.CMFCore.utils import getToolByName
from bika.lims.browser import Browse... | for s in self.fieldvalue:
if s['partition'] not in part_ids:
part_ids.append(s['partition'])
partitions = [{'ResultValue':p, 'ResultText':p} for p in part_ids]
for x in range | (len(items)):
if not items[x].has_key('obj'): continue
obj = items[x]['obj']
cat = obj.getCategoryTitle()
items[x]['category'] = cat
if cat not in self.categories:
self.categories.append(cat)
analyses = dict([(a['service_uid'], a)... |
ssamot/vgdl_competition | src/server/vgdl_mediator.py | Python | gpl-3.0 | 3,745 | 0.021629 | from subprocess import Popen, PIPE,check_output
import subprocess
import simplejson as json
from time import sleep
from vgdl.core import VGDLParser
import importlib
import sys
import os
import time
DUMMY_COMMAND = {}
DUMMY_COMMAND["Dummy"] = 1
DUMMY_COMMAND["Dummy"] = 2
END_COMMAND = "END_COMMAND\n"
MAXIMUM_TICKS =... |
if(level is None):
return None
#print game, level
g = VGDLParser.playGame(game, level, headless = True, persist_movie = True, movie_dir = "./tmp/")
#g.startGameExternalPlayer(headless = True, persist_movie = True)
return g
def compile_java(fil | e_name):
p = Popen("javac " + file_name, shell=True, bufsize=1000000,
stderr=PIPE, stdout=PIPE, close_fds=True)
out, err = p.communicate()
print out
print err
if __name__=="__main__":
#compile_java("Agent.java")
game = load_game("examples.gridphysics.frogs")
print media... |
atareao/my-weather-indicator | src/machine_information.py | Python | mit | 1,943 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of my-weather-indicator
#
# Copyright (c) 2012 Lorenzo Carbonell Cerezo <a.k.a. atareao>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | is permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SH | ALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import platform
import comun
def get_information():
informat... |
kret0s/gnuhealth-live | tryton/server/trytond-3.8.3/trytond/modules/health_nursing/setup.py | Python | gpl-3.0 | 3,333 | 0.007503 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Cédric Krier
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | description=info.get('description', 'GNU Health Nursing Module'),
author=info.get('author', 'GNU Solidario'),
author_email=info.get('email', 'health@gnusolidario.org'),
url=info.get('website', 'http://health.gnu.org/'),
download_url='http://ftp.gnu.org/gnu/health/',
package_dir={'trytond.modules.h... | tond.modules.health_nursing': info.get('xml', []) \
+ info.get('translation', []) \
+ ['tryton.cfg', 'view/*.xml', 'doc/*.rst', 'locale/*.po',
'report/*.odt', 'icons/*.svg'],
},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment ... |
buguroo/behave-cmdline | tests/unit/conftest.py | Python | lgpl-3.0 | 249 | 0 | import pytest
from argparse import Namespa | ce
from behave_cmdline import environment as env
@pytest.fixture(scope="function")
def dummy_context():
ns = Namespace()
env.before_scenario(ns, None)
yield ns
e | nv.after_scenario(ns, None)
|
arruda/amao | AMAO/apps/Aluno/views/utils.py | Python | mit | 400 | 0.0125 | # -*- coding: utf-8 -*-
from django.contrib.auth.decorators import user_passes_test
from Aluno.models import Aluno
|
def check_aluno_exist(user):
if not user.is_authenticated():
return False
try:
aluno = user.aluno_set.get()
return True
except Aluno.DoesNotExist:
return False
aluno_exist = user_passes_test(lambda u: | check_aluno_exist(u))
|
yuyan7/FamilyTree | familityTree/familityTree/wsgi.py | Python | mit | 402 | 0 | """
WSGI config for familityTree project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.co | re.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", " | familityTree.settings")
application = get_wsgi_application()
|
LLNL/spack | var/spack/repos/builtin/packages/py-pyyaml/package.py | Python | lgpl-2.1 | 2,663 | 0.00338 | # 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)
from spack import *
class PyPyyaml(PythonPackage):
"""PyYAML is a YAML parser and emitter for Python."""
homepa... | 846e8')
v | ariant('libyaml', default=True, description='Use libYAML bindings')
depends_on('python@2.7:2.8,3.5:', type=('build', 'run'))
depends_on('python@3.6:', type=('build', 'run'), when='@6.0:')
depends_on('libyaml', when='+libyaml')
depends_on('py-setuptools', when='@6.0:')
depends_on('py-cython', when='... |
dezede/dezede | libretto/api/rest/viewsets.py | Python | bsd-3-clause | 2,128 | 0 | from rest_framework.viewsets import ReadOnlyModelViewSet
from accounts.models import HierarchicUser
from ...models import *
from ...views import PublishedMixin
from .serializers import (
IndividuSerializer, EnsembleSerializer, LieuSerializer, OeuvreSerializer,
SourceSerializer, EvenementSerializer, PartieSeria... | nt.objects.all()
serializer_class | = EvenementSerializer
class PartieViewSet(PublishedMixin, ReadOnlyModelViewSet):
model = Partie
queryset = Partie.objects.all()
serializer_class = PartieSerializer
class UserViewSet(ReadOnlyModelViewSet):
model = HierarchicUser
queryset = HierarchicUser.objects.all()
serializer_class = UserS... |
nikhila05/MicroSite | employee/tests.py | Python | gpl-2.0 | 946 | 0.019027 | from django.test import TestCase
from django import forms
from django.forms.models import ModelForm
import unittest
from employee.forms import *
from | django.test import Client
class TestBasic(unittest.TestCase):
"Basic tests"
def test_basic(self):
a = 1
self.assertEqual(1, a)
class Modelforms_test(TestCase):
def test_report(self):
form = DailyReportForm(data = {'employee': 'ravi@mp.com', 'project': 'ravi', 'report':'Sample... | orm.is_valid())
class Views_test(TestCase):
def test_employee_report(self):
c = Client()
resp = c.get('/portal/staff/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/new/')
self.assertEqual(resp.status_code, 302)
resp = c.get('/portal/staff/reports/edit/1/')
self.assert... |
suutari-ai/shoop | shuup_workbench/urls.py | Python | agpl-3.0 | 734 | 0.002725 | # This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.conf import settings
from django.conf.urls import include, url
from django.con... | ite.urls)),
url(r'^sa | /', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")),
url(r'^api/', include('shuup.api.urls')),
url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
05bit/docta | docta/utils/meta.py | Python | bsd-3-clause | 1,835 | 0 | """
Documents metadata tools.
"""
from __future__ import absolute_import, print_function, unicode_literals
import yaml
DELIMITER = '---'
def stripped(stream):
"""
Read stream to strip YAML header, returns stripped data.
"""
data = []
meta_started = False
meta_ended = False
# TODO: cleane... | act(stream, **defaults):
"""
Re | ad stream and extract YAML header.
"""
meta = Meta(**defaults)
meta.load(stream)
return meta
class Meta(dict):
"""
Metadata for Markdown files loaded from YAML headers.
"""
def load(self, stream):
meta_data = []
meta_opened = False
for next_line in stream:
... |
RalfBarkow/Zettelkasten | venv/lib/python3.9/site-packages/pip/_internal/utils/subprocess.py | Python | gpl-3.0 | 9,924 | 0 | from __future__ import absolute_import
import logging
import os
import subprocess
from pip._vendor.six.moves import shlex_quote
from pip._internal.cli.spinners import SpinnerInterface, open_spinner
from pip._internal.exceptions import InstallationError
from pip._internal.utils.compat import console_to_str, str_to_di... | s None:
command_desc = format_command_args(cmd)
log_subprocess("Running comm | and %s", command_desc)
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
for name in unset_environ:
env.pop(name, None)
try:
proc = subprocess.Popen(
# Convert HiddenText objects to the underlying str.
reveal_command_args(cmd),
... |
spooky/lobby | tests/src/test_adapters.py | Python | gpl-3.0 | 1,062 | 0.000942 | def test_notifyableProperty():
from view_models.adapters import NotifyablePropertyObject, notifyableProperty
class TestSubject(NotifyablePropertyObject):
name = notifyablePro | perty(str)
code = notifyableProperty(str, signalName='kung_foo')
def __init__(self, name=None, code=None, parent=None):
super().__init__ | (parent)
self.name = name
self.code = code
self.name_changed.connect(self.on_name_changed)
def on_name_changed(self):
nonlocal was_on_name_changed_called
was_on_name_changed_called = True
was_on_name_changed_called = False # poor mans method ca... |
abousquet/lolpy | setup.py | Python | mit | 788 | 0 | from setuptools import setup
setup(name='lolpy',
version='0.2',
description='Package for Interaction with the League of | Legends API',
url='https://github.com/abousquet/lolpy',
author='Adam Bousquet',
author_email='ajbousquet6@gmail.com',
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Lan... | nse='MIT',
packages=['lolpy'],
zip_safe=False,
install_requires=["lolpy>=0.1",
"numpy==1.12.0",
"requests==2.12.4"])
|
brownian/frescobaldi | frescobaldi_app/gadgets/matcher.py | Python | gpl-2.0 | 4,304 | 0.000232 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
... | the class level,
and may be overridden by setting them as instance attributes:
matchPairs: a string of characters that match in pairs with each other
| default: "{}()[]"
format: a QTextCharFormat used to highlight matching characters with
default: a red foreground color
time: how many milliseconds to show the highlighting (0=forever)
default: 2000
"""
matchPairs = "{}()[]"
format = QTextCharFormat()
... |
aubreyrjones/libesp | scons_local/scons-local-2.3.0/SCons/Tool/386asm.py | Python | mit | 2,231 | 0.003586 | """SCons.Tool.386asm
Tool specification for the 386ASM assembler for the Phar Lap ETS embedded
operating system.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005... | .PharLapCommon import addPharLapPaths
import SCons.Util
as_module = __import__('as', globals(), locals(), [])
def generate(env):
"""Add Builder | s and construction variables for ar to an Environment."""
as_module.generate(env)
env['AS'] = '386asm'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS $SOURCES -o $TARGET'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_... |
jackkiej/SickRage | lib/pgi/codegen/funcgen.py | Python | gpl-3.0 | 11,370 | 0.000088 | # Copyright 2012,2013 Christoph Reiter
#
# This 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 Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
import re
import trac... | older than the linked
libgirepository.
https://bugzilla.gnome.org/show_bug.cgi?id=660879#c47
"""
repo = GIRepository()
repo.require("GLib", "2.0", 0)
info = repo.find_by_name("GLib", "spawn_sync")
# this argument is (allow-none) and can never be (nullable)
return not info.get_arg(8).m... | > "Gtk.Window"
[int] -> "[int]"
{int: Gtk.Button} -> "{int: Gtk.Button}"
"""
if type_ is None:
return ""
if isinstance(type_, string_types):
return type_
elif isinstance(type_, list):
assert len(type_) == 1
return "[%s]" % get_type_name(type_[0])
elif isinsta... |
reverie/jotleaf.com | jotleaf/main/migrations/0003_auto__del_field_customuser_email_on_new_foller__add_field_customuser_e.py | Python | mit | 16,495 | 0.00776 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'CustomUser.email_on_new_foller'
db.delete_column('auth_user', 'email_on_new_foller')
... | 'border_colo | r': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'border_radius': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'border_width': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),... |
Morloth1274/EVE-Online-POCO-manager | tests/test_eve.py | Python | mit | 20,398 | 0.005099 | import mock
from tests.compat import unittest
from tests.utils import APITestCase
import evelink.eve as evelink_eve
class EVETestCase(APITestCase):
def setUp(self):
super(EVETestCase, self).setUp()
self.eve = evelink_eve.EVE(api=self.api)
def test_character_names_from_ids(self):
sel... | 'isk': None,
'location': None,
'name': 'Test Character',
'race': 'Caldari',
'sec_status': 2.5,
'ship': {'name': None, 'type_id': None, 'type_name': None},
'skillpoints': None,
})
self.assertEqual(self.api.mock_calls, [
... | 12345)
self.assertEqual(expires, 67890)
def test_alliances(self):
self.api.get.return_value = self.make_api_result("eve/alliances.xml")
result, current, expires = self.eve.alliances()
self.assertEqual(result, {
1: {
'executor_id': 2,
... |
indictranstech/frappe | frappe/website/doctype/website_theme/website_theme.py | Python | mit | 2,827 | 0.024407 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class WebsiteTheme(Document):
def validate(self):
self.validate_if_customizabl... | site_theme:
website_ | theme = get_active_theme()
context.theme = website_theme and website_theme.as_dict() or frappe._dict()
if website_theme:
if website_theme.bootstrap:
bootstrap = website_theme.bootstrap
context.no_sidebar = website_theme.no_sidebar
context.web_include_css = ["website_theme.css"] + context.web_include... |
reviewboard/reviewboard | reviewboard/reviews/default_actions.py | Python | mit | 9,922 | 0 | from django.utils.translation import ugettext_lazy as _
from reviewboard.admin.read_only import is_site_read_only_for
from reviewboard.reviews.actions import (BaseReviewRequestAction,
BaseReviewRequestMenuAction)
from reviewboard.reviews.features import general_comments_feature... | iewRequestAction):
"""An action for updating/uploading a diff for the review request."""
action_id = 'upload-diff-action'
def get_label(self, context):
"""Return this action's label.
The label will change depending on whether or not the corresponding
review request already has a d... | irs from the template.
Returns:
unicode: The label that displays this action to the user.
"""
review_request = context['review_request']
draft = review_request.get_draft(context['request'].user)
if (draft and draft.diffset) or review_request.get_diffsets():
... |
wanderanimrod/family-tree | application/backend/tests/models/person_test.py | Python | gpl-2.0 | 1,433 | 0.001396 | from datetime import datetime
from unittest import TestCase
from application.backend.models.person import gender, create_person_from_dict
from application.backend.tests.test_helpers import create_person
class PersonTest(TestCase):
def test_should_jsonify_itself(self):
date_of_birth = datetime.now()
... |
surname='Nekesa', first_name='Patricia',
date_of_birth=date_of_birth, gender=gender.FEMALE
)
expected_json = {
u"surname": u"Nekesa",
u"first_name": u"Patricia",
u"date_of_birth": unicode(date_of_birt | h),
u"gender": unicode(gender.FEMALE),
u"id": unicode(None)
}
person_json = person.jsonify()
self.assertEqual(person_json, expected_json)
def test_should_construct_self_from_dict(self):
dictionary = {"surname": "Nekesa", "first_name": "Patricia", "date_of_bir... |
certsocietegenerale/fame | fame/common/utils.py | Python | gpl-3.0 | 2,422 | 0.002064 | import os
import requests
import collections
from time import sleep
from uuid import uuid4
from urllib.parse import urljoin
from datetime import datetime
from shutil import copyfileobj
from werkzeug.utils import secure_filename
from fame.common.config import fame_config
def is_iterable(element):
return isinstanc... | n(fame_config.temp_path, str(uuid4()).replace('-', ''))
try:
os.makedirs(tempdir)
except:
pass
return tempdir
def save_response(response, fi | lepath):
tmp = tempdir()
filename = secure_filename(os.path.basename(filepath))
filepath = os.path.join(tmp, filename)
with open(filepath, 'wb') as out:
copyfileobj(response.raw, out)
return filepath
def with_timeout(func, timeout, step):
started_at = datetime.now()
while starte... |
wibox/Posting-JSON-data-to-Flask-server | __init__.py | Python | mit | 541 | 0.024119 | from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/index')
def index():
#jsonObj = request.json_get('txt') non funziona perchè lo | script serverSide può essere eseguito una volta soltanto
return render_template('index.html')
@app.route('/process', methods = ['GET', 'POST'])
def processInformation():
data = request.get_json()
result = 'Your | data is: ' + str(data)
return result
if __name__ == '__main__':
app.run(host = 'localhost', port = 8080, debug = True)
|
gautamMalu/rootfs_xen_arndale | usr/lib/python3.4/distutils/unixccompiler.py | Python | gpl-2.0 | 13,694 | 0.00168 | """distutils.unixccompiler
Contains the UnixCCompiler class, a subclass of CCompiler | that handles
the "typical" Unix-style command-line C compiler:
* macros defined with -Dname[=value]
* macros undefined with -Uname
* include search directories specified with -Idir
* libraries specified with -lllib
* library search directories specified with -L | dir
* compile handled by 'cc' (or similar) executable with -c option:
compiles .c to .o
* link static library handled by 'ar' command (possibly with 'ranlib')
* link shared library handled by 'cc -shared'
"""
import os, sys, re
from distutils import sysconfig
from distutils.dep_util import newer
from distut... |
horacioibrahim/iugu-python | lib/iugu/tests.py | Python | apache-2.0 | 80,119 | 0.003857 | #coding: utf-8
__author__ = 'horacioibrahim'
import unittest, os
import datetime
from time import sleep, ctime, time
from random import randint
from hashlib import md5
from types import StringType
# python-iugu package modules
import merchant, customers, config, invoices, errors, plans, subscriptions
def check_tes... | elf.c.getitems(skip=2)
self.assertEqual(customers_list[0].name, reference_customer)
def test_getitems | _query_by_match_in_name(self):
hmd5 = md5()
hmd5.update(ctime(time()))
salt = hmd5.hexdigest()
term = 'name_inexistent_or_improbable_here_{salt}'.format(salt=salt)
# test value/term in >>name<<
customer = self.c.create(name=term)
sleep(2)
items = self.c.g... |
danydoerr/PSyCHO | scripts/visualize_overlapping_sbs.py | Python | mit | 12,540 | 0.009968 | #!/usr/bin/env python
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter as ADHF
from sys import stdout, stderr, exit, maxint, argv
from os.path import join, dirname, basename, isfile
from itertools import izip, chain
from bisect import insort
import logging
import json
import re
import matplotlib; ma... | FFSET_TJ, -GAP_Y/2.))
drawSegments(ax, tgj.intersection(tgi), 'b', scale=DRAW_SCALE,
offset=(OFFSET_TI, -GAP_Y/2.))
ax.set_xlim(min((OFFSET_SI+start_si, OFFSET_SJ+start_sj,
OFFSET_TI+start_ti, OFFSET_TJ+ | start_tj))*DRAW_SCALE,
max((end_si+OFFSET_SI, end_sj+OFFSET_SJ, end_ti+OFFSET_TI,
end_tj+OFFSET_TJ)) * DRAW_SCALE)
ax.set_ylim((-GAP_Y/2. - DRAW_SEG_HEIGHT) * DRAW_SCALE, (GAP_Y/2. +
DRAW_SEG_HEIGHT) * DRAW_SCALE)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible... |
dianchen96/gym | utils/reraise_impl_py3.py | Python | mit | 219 | 0 | # http://st | ackoverflow.com/a/338 | 22606 -- `from None` disables Python 3'
# semi-smart exception chaining, which we don't want in this case.
def reraise_impl(e, traceback):
raise e.with_traceback(traceback) from None
|
lizardsystem/lizard-reportgenerator | lizard_reportgenerator/testsettings.py | Python | gpl-3.0 | 3,058 | 0 | import os
from lizard_ui.settingshelper import setup_logging
from lizard_ui.settingshelper import STATICFILES_FINDERS
DEBUG = True
TEMPLATE_DEBUG = True
# SETTINGS_DIR allows media paths and so to be relative to this settings file
# instead of hardcoded to c:\only\on\my\computer.
SETTINGS_DIR = os.path.dirname(os.pa... | processors.
"django.contrib.auth.context_processors.a | uth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.contrib.messages.context_processors.messages"
)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
# Used for django-static... |
nKey/schematics | schematics/serialize.py | Python | bsd-3-clause | 8,765 | 0.001825 | # encoding=utf-8
from .types.compound import (
ModelType, EMPTY_LIST, EMPTY_DICT, MultiType
)
import collections
import itertools
###
### Field ACL's
###
class Role(collections.Set):
"""A Role object can be used to filter specific fields against a sequence.
The Role has a set of names and one function ... | current_context.update(expand({remaining: v}, current_context))
return expanded_dict
def flatten_to_dict(o, prefix=None, ignore_none=True):
if hasattr(o, "iteritems"):
iterator = o.iteritems()
else:
iterator = enumerate(o)
flat_dict = {}
for k, v in iterator:
if prefi... | .join(map(unicode, (prefix, k)))
else:
key = k
if v == []:
v = EMPTY_LIST
elif v == {}:
v = EMPTY_DICT
if isinstance(v, (dict, list)):
flat_dict.update(flatten_to_dict(v, prefix=key))
elif v is not None:
flat_dict[key]... |
zhlinh/leetcode | 0092.Reverse Linked List II/solution.py | Python | apache-2.0 | 1,199 | 0.004191 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*****************************************
Author: zhlinh
Email: zhlinhng@gmail.com
Version: 0.0.1
Created Time: 2016-03-03
Last_modify: 2016-03-03
************************************** | ****
'''
'''
Reverse a linked list from position m to n.
Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
'''
# Definition for singly-linked list.
class ListNode(object)... | e head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
dummy = pre = ListNode(0)
dummy.next = head
for i in range(m-1):
pre = pre.next
start = pre.next
then = start.next
for i in range(n - m):
start.next = t... |
rookies/crypto | QuotientRing.py | Python | gpl-2.0 | 398 | 0.047739 | #!/usr/bin/python
class Helpers(object):
@staticmethod
def squareAndMultiply(b, e, n): ##FIXME##
##TODO: Euler's theorem
mask = 2* | *e.bit_length()
hadFirstOne = False
res = 1
for i in range(e.bit_length(), -1, -1):
if (e & mask) == 0:
if hadFirstOne:
res = (res**2) % n
e | lse:
res = (res**2) % n
res = (res*b) % n
hadFirstOne = True
mask >>= 1
return res
|
data-tsunami/museo-cachi | cachi/migrations/0007_auto__chg_field_procedencia_pieza_conjunto__add_unique_procedencia_pie.py | Python | gpl-3.0 | 15,809 | 0.007274 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Procedencia.pieza_conjunto'
db.alter_column(u'cachi_pr... | nk': 'True'}),
' | usuario': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'cachi.fragmento': {
'Meta': {'object_name': 'Fragmento'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'numero |
yencarnacion/jaikuengine | vendor/epydoc/docwriter/html.py | Python | apache-2.0 | 145,214 | 0.003182 | #
# epydoc -- HTML output generator
# Edward Loper
#
# Created [01/30/01 05:18 PM]
# $Id: html.py 1812 2009-02-03 21:31:04Z edloper $
#
"""
The HTML output generator for epydoc. The main interface provided by
this module is the L{HTMLWriter} class.
@todo: Add a cache to L{HTMLWriter.url()}?
"""
__docformat__ = 'epyt... | minindent = min(minindent, len(line)-len(stripline))
return '\n'.join([l[minindent:] for l in lines])
######################################################################
## HTML Writer
| ######################################################################
class HTMLWriter:
#////////////////////////////////////////////////////////////
# Table of Contents
#////////////////////////////////////////////////////////////
#
# 1. Interface Methods
#
# 2. Page Generation -- write c... |
shanx/django-extensions-shell | tests/test_shellplus_command.py | Python | mit | 1,339 | 0.00224 | # -*- coding: utf-8 -*-
import os
from django import __version__
from django.core.management import call_command
from django.test import TestCase
from django.te | st.utils im | port patch_logger
class ShellPlusCommandTests(TestCase):
def setUp(self):
self.project_root = os.path.join('tests', 'testapp')
self._settings = os.environ.get('DJANGO_SETTINGS_MODULE')
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_extensions_shell.settings'
def tearDown(self):
... |
iemejia/incubator-beam | sdks/python/apache_beam/pipeline_test.py | Python | apache-2.0 | 29,763 | 0.007862 | #
# 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 us... | y to make sure that there is no label
# conflict due to replacement.
return input | 'Inner' >> beam.Map(lambda a: a * 3)
class ToStringParDo(beam.PTransform):
def expand(self, input):
# | We use copy.copy() here to make sure the typehint mechanism doesn't
# automatically infer that the output type is str.
return input | 'Inner' >> beam.Map(lambda a: copy.copy(str(a)))
class PipelineTest(unittest.TestCase):
@staticmethod
def custom_callable(pcoll):
return pcoll | '+1' >> FlatMap(lambda... |
bpsinc-native/src_third_party_chromite | cbuildbot/validation_pool.py | Python | bsd-3-clause | 106,838 | 0.006009 | # Copyright (c) 2011-2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module that handles interactions with a Validation Pool.
The validation pool is the set of commits that are ready to be validated i.e.
ready ... | 'submit one change | before realizing that a later change cannot '
'be submitted.' % (dep_error,))
class PatchSeriesTooLong(cros_patch.PatchException):
"""Exception thrown when a required dep isn't satisfied."""
def __init__(self, patch, max_length):
cros_patch.PatchException.__init__(self, patch)
self.max_length... |
ray-project/ray | rllib/agents/ddpg/ddpg_tf_policy.py | Python | apache-2.0 | 18,764 | 0.000693 | from gym.spaces import Box
from functools import partial
import logging
import numpy as np
import gym
from typing import Dict, Tuple, List
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.ddpg.ddpg_tf_model import DDPGTFModel
from ray.rllib.agents.ddpg.ddpg_torch_model imp | ort DDPGTorchModel
from ray.rllib.agents.ddpg.noop_model import NoopModel, TorchNoopModel
from ray.rllib.ag | ents.dqn.dqn_tf_policy import postprocess_nstep_and_prio, PRIO_WEIGHTS
from ray.rllib.models.catalog import ModelCatalog
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_action_dist import Deterministic, Dirichlet
from ray.rllib.models.... |
rubenvb/skia | infra/bots/recipe_modules/flavor/android.py | Python | bsd-3-clause | 21,248 | 0.006071 | # Copyright 2016 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 recipe_engine import recipe_api
from . import default
import subprocess # TODO(borenet): No! Remove this.
"""Android flavor, used for running code ... | super(Andro | idFlavor, self).__init__(m)
self._ever_ran_adb = False
self.ADB_BINARY = '/usr/bin/adb.1.0.35'
self.ADB_PUB_KEY = '/home/chrome-bot/.android/adbkey'
if 'skia' not in self.m.vars.swarming_bot_id:
self.ADB_BINARY = '/opt/infra-android/tools/adb'
self.ADB_PUB_KEY = ('/home/chrome-bot/.android/'... |
serpilliere/miasm | miasm/expression/simplifications_explicit.py | Python | gpl-2.0 | 4,228 | 0.000473 | from miasm.core.utils import size2mask
from miasm.expression.expression import ExprInt, ExprCond, ExprCompose, \
TOK_EQUAL
def simp_ext(_, expr):
if expr.op.startswith('zeroExt_'):
arg = expr.args[0]
if expr.size == arg.size:
return arg
return ExprCompose(arg, ExprInt(0, ex... | expr.is_op("CC_U>"):
op_cf, op_zf = args
return ~(op_cf | op_zf) |
elif expr.is_op("CC_U<"):
op_cf, = args
return op_cf
elif expr.is_op("CC_NEG"):
op_nf, = args
return op_nf
elif expr.is_op("CC_EQ"):
op_zf, = args
return op_zf
elif expr.is_op("CC_NE"):
op_zf, = args
return ~op_zf
elif expr.is_op(... |
itskewpie/tempest | tempest/api/compute/admin/test_quotas.py | Python | apache-2.0 | 10,071 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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.apach... | tenant_id)
self.adm_client.update_quota_set(tenant_id,
| ram='5120')
resp, quota_set = self.adm_client.get_quota_set(tenant_id)
self.assertEqual(200, resp.status)
self.assertEqual(quota_set['ram'], 5120)
# TODO(afazekas): Add dedicated tenant to the skiped quota tests
# it can be moved into the setUpClass as well
@attr(type='g... |
Cyb3rWard0g/ThreatHunter-Playbook | scripts/create_vendor_json.py | Python | gpl-3.0 | 1,040 | 0.008654 | import json
import glob
from os import path
json_files = glob.glob(path.join(path.dirname(__file__), '../../joystick/data/evaluations/apt29', "*.json"))
vendor_list = []
for jf in json_files:
vendor = path.basename(jf).split(".")[0]
with open(jf,'r') as fi:
dict = json.load(fi)
for t in dict['T... | "vendor" : vendor,
"step" : s['SubStep'].split(".")[0],
"substep" : s['SubStep'],
"techniqueid" : t['TechniqueId'],
"techniquename" : t['TechniqueName'],
"detectiontype" : d['Detect... | vals/apt29/data/vendor_results.json', 'w') as results:
json.dump(vendor_list, results)
|
direvius/yandex-tank | yandextank/plugins/bfg/worker.py | Python | lgpl-2.1 | 5,715 | 0.000875 | import logging
import time
from yandextank.stepper import StpdReader
from .zmq_reader import ZmqReader
import multiprocessing as mp
import threading as th
from Queue import Empty, Full
def signal_handler(signum, frame):
pass
class BFG(object):
"""
A BFG load generator that manages multiple workers as pr... | rrupt, SystemExit):
self.quit.set()
map(lambda x: x.join(0.2), pool)
[process.terminate() for process in pool if process.is_alive()]
map(
lambda x: x.join(),
pool) # wait for workers to finish
def _thread_worker(self):
"""
... | h.current_thread().name)
while not self.quit.is_set():
try:
task = self.task_queue.get(timeout=1)
if not task:
self.log.info(
"%s got killer task.", th.current_thread().name)
break
timesta... |
GoogleCloudPlatform/gcpdiag | gcpdiag/queries/gaes_stub.py | Python | apache-2.0 | 1,663 | 0.007216 | # 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, ... | son_dir / 'appengine_services.json',
encoding='utf-8') as j | son_file:
return json.load(json_file)
else:
with open(self.json_dir / 'versions.json', encoding='utf-8') as json_file:
return json.load(json_file)
|
skilstak/code-dot-org-python | codestudio/tkcanvas.py | Python | unlicense | 5,090 | 0.014735 | """The Canvas (game board) implemented in tkinter.
W | hile the 'board' metaphor is better for some of the puzzles, 'canvas'
works for the artist and is generally what most graphics frameworks
use when referring to the place where stuff is drawn, whether for games
or art.
Notice that all the details of the graphics framework used to implement
the canvas are hidden away in... | ses or functions in the `codestudio` module refer directly
to these implementation details. This allows these canvas classes and
modules to be implemented in any framework without breaking the rest of
the system. This separation of concerns is also the reason our Canvas
class here does not directly subclass the tk.Canv... |
cornell-brg/pydgin | pydgin/elf.py | Python | bsd-3-clause | 20,497 | 0.028687 | #=========================================================================
# elf
#=========================================================================
# A simple translator between ELF files and a sparse memory image object.
# Note that the translator is far from complete but is sufficient for use
# in our researc... | = 0 # No file type
TYPE_REL = 1 # Relocatable file
TYPE_EXEC = 2 # Executable file
TYPE_DYN = 3 # Shared object file
TYPE_CORE = 4 # Core f | ile
TYPE_LOPROC = 0xff00 # Processor-specific
TYPE_HIPROC = 0xffff # Processor-specific
#-----------------------------------------------------------------------
# Constructor
#-----------------------------------------------------------------------
#def __init__( self, data=None ):
# if data... |
manuvarkey/cmbautomiser | cmbautomiser/openpyxl/reader/drawings.py | Python | gpl-3.0 | 2,090 | 0.002871 | from __future__ import absolute_import
| # Copyright (c) 2010-2021 openpyxl
from io import BytesIO
from warnings import warn
from openpyxl.xml.functions import fromstring
from | openpyxl.xml.constants import IMAGE_NS
from openpyxl.packaging.relationship import get_rel, get_rels_path, get_dependents
from openpyxl.drawing.spreadsheet_drawing import SpreadsheetDrawing
from openpyxl.drawing.image import Image, PILImage
from openpyxl.chart.chartspace import ChartSpace
from openpyxl.chart.reader imp... |
edx-solutions/edx-platform | openedx/core/djangoapps/schedules/migrations/0012_auto_20200302_1914.py | Python | agpl-3.0 | 579 | 0.001727 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-03-02 19:14
from __future__ import unicode_ | literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('schedules', '0011_auto_20200228_2018'),
]
operations = [
migrations.AlterField(
model_name='schedule',
name='e | nrollment',
field=models.OneToOneField(db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to='student.CourseEnrollment'),
),
]
|
quasoft/adblockradio | adblockradio/utils.py | Python | gpl-3.0 | 3,350 | 0.001791 | #!/usr/bin/env python3
import random
import re
import requests
import unicodedata
import sys
import os
import pkg_resources
import config
MAX_SONG_TITLE_LENGTH = 35
is_closing = False
"""This flag is set to True when the application begins to shut down.
Parts of the program that handle events might | use this flag as a
signal to ignore some events like change of player state.
"""
def get_other_stations(uri):
return list(filter(lambda s: s['uri'] != uri, config.stations))
def get_random_station(stations):
random_idx = random.randint(0, len( | stations) - 1)
return stations[random_idx]
def get_station(uri):
station = next(filter(lambda s: s['uri'] == uri, config.stations), None)
return station
def get_station_name(uri):
name = next((station['name'] for station in config.stations if station['uri'] == uri), "")
return name
def read_ur... |
PeteAndersen/swarfarm | data_log/migrations/0009_auto_20190407_1443.py | Python | apache-2.0 | 2,137 | 0.005147 | # Generated by Django 2.1.7 on 2019-04-07 21:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('data_log', '0008_auto_20190402_2035'),
]
operations = [
migrations.AlterModelOptions(
name='cra... | name='riftraidlog',
options={'get_latest_by': 'timestamp', 'ordering': ('-timestamp',)},
),
migrations.AlterModelOptions(
name='shoprefreshlog',
| options={'get_latest_by': 'timestamp', 'ordering': ('-timestamp',)},
),
migrations.AlterModelOptions(
name='summonlog',
options={'get_latest_by': 'timestamp', 'ordering': ('-timestamp',)},
),
migrations.AlterModelOptions(
name='wishlog',
... |
OCA/sale-workflow | sale_by_packaging/tests/test_packaging_type_can_be_sold.py | Python | agpl-3.0 | 2,140 | 0.002336 | # Copyright 2020 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo.exceptions import ValidationError
from .common import Common
class TestPackagingTypeCanBeSold(Common):
@classmethod
def setUpClassSaleOrder(cls):
super().setUpClassSaleOrder()
cls.order_li... | {"product_packaging": self.packaging_cannot_be_sold.id}
)
onchange_res = self.order_line._onchange_product_packaging()
self.assertIn("warning", onchange_res)
def test_product_packaging_can_be_sold(self):
"""Check that a product.packaging can be ind | ependently set as can be sold."""
exception_msg = (
"Packaging Test packaging cannot be sold on product {} must be set "
"as 'Can be sold' in order to be used on a sale order."
).format(self.product.name)
with self.assertRaisesRegex(ValidationError, exception_msg):
... |
rejahrehim/jukebox | jukebox/jukebox_core/admin.py | Python | mit | 1,098 | 0 | # -*- coding: UTF-8 -*-
from models import Artist, Genre, Album, Song, Queue, History, Favourite
from django.contrib import admin
class ArtistAdmin(admin.ModelAdmin):
list_display = ('Name', )
search_fields = ['Name']
class GenreAdmin(admin.ModelAdmin):
list_display = ('Name', )
class AlbumAdmin(admi... | ser', 'Created', )
search_fields = ['User__username']
admin.site.register(Artist, ArtistAdmin)
admin.site.register(Genre, GenreAdmin)
admin.site.register(Album, AlbumAdmin)
admin.site.register(Song, SongAdmin)
admin.site.register(Queue, QueueAdmin)
admin.site.register(History, HistoryAdmin) |
admin.site.register(Favourite, FavouriteAdmin)
|
vileopratama/vitech | src/addons/hr_expense/models/hr_department.py | Python | mit | 735 | 0.004082 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import fields, models
class HrDepartment(models.Model):
_inherit = 'hr.department'
def _compute_expense_to_approve(self):
expense_data = self.env['hr.expense'].read_group([('department_id'... | n', self.ids), ('state', '=', 'submit')], ['department_id'], ['department_id'])
result = dict((data['department_id'][0], data['department_id_count']) for data in expense_data)
for department in self:
department.expense_to_approve_count = result.get(department.id, 0)
expense_to_approve_c... | elds.Integer(compute='_compute_expense_to_approve', string='Expenses to Approve')
|
timeyyy/PyUpdater | pyupdater/vendor/PyInstaller/hooks/hookutils.py | Python | bsd-2-clause | 22,893 | 0.001966 | #-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... | [0]
# list of directories where to look for qt_menu.nib
dirs = []
# If PyQt4 is built against | Qt5 look for the qt_menu.nib in a user
# specified location, if it exists.
if 'QT5DIR' in os.environ:
dirs.append(os.path.join(os.environ['QT5DIR'],
"src", "plugins", "platforms", "cocoa"))
dirs += [
# Qt4 from MacPorts not compiled as framework.
... |
pombredanne/pants | src/python/pants/binaries/binary_util.py | Python | apache-2.0 | 9,303 | 0.007524 | # coding=utf-8
# Copyright 2015 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
impor... | ethod
def create(cls):
"""
:API: public
"""
# NB: create is a class method to ~force binary fetch location to be global.
options = cls.global_instance().get_options()
return BinaryUtil(options.baseurls, options.fetch_timeout_secs, options.pants_bootstrapdir,
... | ptions.path_by_id)
class MissingMachineInfo(TaskError):
"""Indicates that pants was unable to map this machine's OS to a binary path prefix."""
pass
class BinaryNotFound(TaskError):
def __init__(self, binary, accumulated_errors):
super(BinaryUtil.BinaryNotFound, self).__init__(
'Faile... |
BRCDcomm/pynos | pynos/versions/ver_7/ver_7_0_0/yang/brocade_aaa.py | Python | apache-2.0 | 91,486 | 0.003793 | #!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_aaa(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def aaa_config_aaa_authentication_login_first(self, **kwargs):
"""Auto Generated Code
... | ("config")
| username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
name_key = ET.SubElement(username, "name")
name_key.text = kwargs.pop('name')
enable = ET.SubElement(username, "enable")
enable.text = kwargs.pop('enable')
callback = kwargs.pop('callback'... |
anhstudios/swganh | data/scripts/templates/object/tangible/ship/components/weapon/shared_wpn_seinar_ls1.py | Python | mit | 473 | 0.046512 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLE | S
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/weapon/shared_wpn_seinar_ls1.iff"
result.attribute_template_id = 8
result.stfName("space/space_item","wpn_seinar_ls1_n")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
r | eturn result |
theheros/kbengine | kbe/res/scripts/common/Lib/test/test_lib2to3.py | Python | lgpl-3.0 | 604 | 0.004967 | # Skipping test_parser and test_all_fixers
# because of running
from lib2to3.test | s import (test_fixers, test_pytree, test_util, test_refactor,
test_main as test_main_)
import unittest
from test.support import run_unittest
def suite():
tests = unittest.TestSuite()
loader = unittest.TestLoader()
for m in (test_fixers, test_pytree,test_util, test_refacto... | n_unittest(suite())
if __name__ == '__main__':
test_main()
|
fivunlm/sbb8 | droids.py | Python | mit | 1,525 | 0.000656 | import re
import threading
import time
import logging
from commands import COMMANDS
from message import Message
READ_WEB | _SOCKET_DELAY = 1
class Sbb8(threading.Thread):
def __init__(self, bot_id, in_queue, out_queue, group=None, target=None, name=None, args=(), kwargs=None, *,
da | emon=None):
super().__init__(group, target, name, args, kwargs, daemon=daemon)
self._bot_id = bot_id
self._in_queue = in_queue
self._out_queue = out_queue
def run(self):
while True:
if not self._in_queue.empty():
message = self._in_queue.get()
... |
hsfzxjy/wisecitymbc | site_packages/app_cache/__init__.py | Python | gpl-2.0 | 258 | 0.011628 | from django.core.exceptions import ImproperlyConfigured
from django import VERSION
if VERSION[0]<1 and VERSION[1]<7:
raise Improperl | yConfigured("""
Th | e app_config required 1.7 or higher version of django.
""")
from .core import AppCache |
dividuum/one-time-mail | otm.py | Python | bsd-2-clause | 11,740 | 0.003918 | from gevent import monkey; monkey.patch_all()
import gevent_openssl; gevent_openssl.monkey_patch()
import re
import random
import string
import pytz
import email
import email.header
import json
import time
import traceback
import smtplib
from email.mime.text import MIMEText
from imapclient import IMAPClient
from datet... | self._running = True
Greenlet.__init__(self)
self.start()
se | lf._args = args
self._kwargs = kwargs
def quit(self):
self.stop()
def stop(self):
self._running = False
def _run(self):
self.setup(*self._args, **self._kwargs)
while self._running:
event, args, kwargs = self._inbox.get()
# print type(self)._... |
robotichead/NearBeach | NearBeach/tests/tests_specific_bugs/test_new_instance.py | Python | mit | 1,174 | 0.000852 | from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
# Declaration of Username and Password
username = 'admin'
password = 'Test1234$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~
1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and log ... | NewInstanceLoginTest(TestCase):
fixtures = ['NearBeach_no_setup.json']
def setUp(self):
self.credentials = {
'username': username,
'password': password
}
def test_admin_login(self):
c = Client()
# User will be logged in
login_user(c, | self)
# Make sure the admin user can open up the project
response = c.get(reverse('dashboard'))
self.assertEqual(response.status_code, 200)
|
google/struct2tensor | struct2tensor/ops/struct2tensor_ops_test.py | Python | apache-2.0 | 30,777 | 0.002989 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | dict[parsed_field.field_name] = parsed_field
return parsed_field_dict
def _make_dict_runnable(level_as_dict):
"""Prepares output of parse_full_message_level_as_dict for evaluate."""
result = {}
for key, value in level_as_dict.items():
local_dict = {}
local_dict[INDEX] = value.index
local_dict[VALU... | able(_parse_full_message_level_as_dict(proto_list))
# TODO(martinz): test empty tensors for decode_proto_sparse more thoroughly.
@test_util.run_all_in_graph_and_eager_modes
class PrensorOpsTest(parameterized.TestCase, tf.test.TestCase):
def test_out_of_order_fields(self):
fragments = [
test_pb2.Event(q... |
eReuse/DeviceHub | ereuse_devicehub/resources/event/device/deallocate/hooks.py | Python | agpl-3.0 | 737 | 0.004071 | from contextlib import suppress
from ereuse_devicehub.resources.account.domain import AccountDomain, UserNotFound
from ereuse_devicehub.resources.device.domain import DeviceDomain
def materi | alize_actual_owners_remove(events: list):
for event in events:
properties = {'$pull': {'owners': event['from']}}
DeviceDo | main.update_raw(event.get('components', []), properties)
return DeviceDomain.update_raw(event['devices'], properties)
def set_organization(deallocates: list):
for deallocate in deallocates:
with suppress(UserNotFound, KeyError): # todo ensure organization is not always needed
dealloca... |
barrysteyn/pre-commit | pre_commit/prefixed_command_runner.py | Python | mit | 1,661 | 0 | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo... | elf):
if not os.path.exists(self.prefix_dir):
self.__makedirs(self.prefix_dir)
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd... | self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constru... |
lvoinea/recipicon-backend | api/migrations/0009_recipe_image.py | Python | agpl-3.0 | 439 | 0 | # | -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-04-22 22:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_auto_20170420_0101'),
]
operations = [
migrations.AddField(
... | ),
]
|
SimenB/thefuck | thefuck/entrypoints/fix_command.py | Python | mit | 1,556 | 0 | from pprint import pformat
import os
import sys
from difflib import SequenceMatcher
from .. import logs, types, const
from ..conf import settings
from ..corrector import get_corrected_commands
from ..exceptions import EmptyCommand
from ..ui import select_command
from ..utils import get_alias, get_all_executables
def ... | logs.debug(u'Run with settings: {}'.format(pformat(settings)))
raw_command = _get_raw_command(known_args)
try:
command = types.Command.from_raw_script(raw_command)
except EmptyCommand:
logs.debug('Empty command, nothing to do')
return
correcte... | cted_command = select_command(corrected_commands)
if selected_command:
selected_command.run(command)
else:
sys.exit(1)
|
futurely/openai-universe-agents | a3c.py | Python | mit | 11,820 | 0.009645 | from __future__ import print_function
import logging
from collections import namedtuple
import numpy as np
import tensorflow as tf
from model import LSTMPolicy
import six.moves.queue as queue
import scipy.signal
import threading
import distutils.version
use_tf12_api = distutils.version.LooseVersion(
tf.VERSION) >= ... | ut.rewards)
vpred_t = np.asarray(rollout.values + [rollout.r])
rewards_plus_v = np.asarray(rollout.rewards + [rollout.r])
batch_r = discount(rewards_plus_v, gamma)[:-1]
delta_t = rewards + gamma * vpred_t[1:] - vpred_t[:-1]
# this formula for the advantage comes "Gener | alized Advantage Estimation":
# https://arxiv.org/abs/1506.02438
batch_adv = discount(delta_t, gamma * lambda_)
features = rollout.features[0]
return Batch(batch_si, batch_a, batch_adv, batch_r, rollout.terminal,
features)
Batch = namedtuple("Batch", ["si", "a", "adv", "r", "terminal", "featur... |
googleapis/artman | artman/pipelines/pipeline_factory.py | Python | apache-2.0 | 2,529 | 0 | # Copyright 2016 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 agree... | ipelines import p | ipeline_base
# These are required to list the subclasses of pipeline_base
from artman.pipelines import sample_pipeline
from artman.pipelines import gapic_generation
from artman.pipelines import grpc_generation
from artman.pipelines import core_generation
from artman.utils.logger import logger
__all__ = (
'core_gen... |
aubreyrjones/libesp | scons_local/scons-local-2.3.0/SCons/Tool/intelc.py | Python | mit | 23,079 | 0.007409 | """SCons.Tool.icl
Tool-specific initialization for the Intel C/C++ compiler.
Supports Linux and Windows compilers, v7 and up.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 200... | except SCons.Util.RegError:
raise MissingRegistryError("%s\\%s was not found in the registry."%(K, valuename))
def get_all_compiler_versions():
"""Returns a sorted list of | strings, like "70" or "80" or "9.0"
with most recent compiler version first.
"""
versions=[]
if is_windows:
if is_win64:
keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++'
else:
keyname = 'Software\\Intel\\Compilers\\C++'
try:
k = SCons.... |
jaywink/federation | federation/hostmeta/parsers.py | Python | bsd-3-clause | 11,938 | 0.003016 | import json
import re
from copy import deepcopy
from typing import Dict
from federation.utils.network import fetch_document, send_document
WEEKLY_USERS_HALFYEAR_MULTIPLIER = 10.34
WEEKLY_USERS_MONTHLY_MULTIPLIER = 3.17
MONTHLY_USERS_WEEKLY_MULTIPLIER = 0.316
HALFYEAR_USERS_WEEKLY_MULTIPLIER = 0.097
defaults = {
... | _count'))
if "contact_account" in mastodon_document and mastodon_document.get('contact_account') is not None:
| contact_account = mastodon_document.get('contact_account', {})
else:
contact_account = {}
result['organization']['account'] = contact_account.get('url', '')
return result
def parse_nodeinfo_document(doc, host):
result = deepcopy(defaults)
nodeinfo_version = doc.get('versi... |
hufeiya/leetcode | python/283_Move_Zeroes.py | Python | gpl-2.0 | 458 | 0.00655 | import Queue
class Solution(object):
def moveZeroes(self, nums): |
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
| zeroItr = -1
for i in xrange(len(nums)):
if nums[i] == 0 and zeroItr == -1:
zeroItr = i
elif nums[i] != 0 and zeroItr != -1:
nums[zeroItr],nums[i] = nums[i],0
zeroItr += 1
|
olduvaihand/ProjectEuler | src/python/problem187.py | Python | mit | 598 | 0.003356 | # -*- coding: utf-8 -*-
# ProjectEuler/src/python/problem187.py
#
# Semiprimes
# ==========
# Published on Saturday, 22nd March 2008, 09:00 am
#
# A composite is a number containing at leas | t two prime factors. For example,
# 15 = 3 5; 9 = 3 3; 12 = 2 2 3. There are ten composites below thirty
# containing precisely two, not necessarily distinct, prime factors: 4, 6, 9,
# 10, 14, 15, 21, 22, 25, 26. How many composite integers, n 108, have
# precisely two, not necessarily distinct, prime factors?
|
import projecteuler as pe
def main():
pass
if __name__ == "__main__":
main()
|
polyaxon/polyaxon | core/polyaxon/managers/project.py | Python | apache-2.0 | 1,363 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | ng permissions and
# limitations under the License.
import sys
from polyaxon.managers.base import BaseConfigManager
from polyaxon.utils import cli_constants
from polyaxon.utils.formatting import Printer
from polyaxon_sdk import V1Project
class ProjectConfigManager(BaseConfigManager):
"""Manages project configur... | aseConfigManager.VISIBILITY_ALL
IS_POLYAXON_DIR = True
CONFIG_FILE_NAME = ".project"
CONFIG = V1Project
@classmethod
def get_config_or_raise(cls):
project = cls.get_config()
if not project:
Printer.print_error(
"No project was found, please initialize a p... |
raviqqe/tensorflow-qnd | qnd/config_test.py | Python | unlicense | 186 | 0 | import tensorflow as tf
from . import test
from . import confi | g
def test_def_config():
test | .append_argv()
assert isinstance(config.def_config()(), tf.contrib.learn.RunConfig)
|
dallascard/guac | core/external/wordnet_domains_preprocessing.py | Python | apache-2.0 | 3,036 | 0.002306 | from optparse import OptionParser
import os
import re
import glob
import numpy as np
import cPickle as pickle
from collections import defaultdict
from nltk.corpus import wordnet as wn
from nltk.corpus.reader.wordnet import WordNetError
from ..util import dirs
from ..util import file_handling as fh
"""
Convert word... | p='Keyword argument: default=%default')
(options, args) = parser.parse_args()
project = args[0]
wordnet_domains_dir = args[1]
output_dir = args[2]
dirs.make_base_dir(project)
build_wordnet | _domain_indices(wordnet_domains_dir, output_dir)
def get_synset_from_ssid(ssid):
try:
return wn._synset_from_pos_and_offset(ssid[-1:], int(ssid[:8]))
except WordNetError as e:
print "SSID %s not found" % ssid
raise e
def build_wordnet_domain_indices(wordnet_domains_dir, output_dir):
... |
benadida/helios-server | helios_auth/auth_systems/clever.py | Python | apache-2.0 | 4,586 | 0.017662 | """
Clever Authentication
"""
import base64
import urllib.parse
import httplib2
from django.conf import settings
from oauth2client.client import OAuth2WebServerFlow, OAuth2Credentials
from helios_auth import utils
# some parameters to indicate that status updating is not possible
STATUS_UPDATES = False
# display ... | CLIENT_SECRET,
scope= | 'read:students read:teachers read:user_id read:sis',
auth_uri="https://clever.com/oauth/authorize",
#token_uri="https://clever.com/oauth/tokens",
token_uri="http://requestb.in/1b18gwf1",
redirect_uri=redirect_url)
def get_auth_url(request, redirect_url):
flow = get_flow(redirect_url)
request.ses... |
osh/gr-eventsim | apps/plot_results_save2.py | Python | gpl-3.0 | 1,648 | 0.017597 | #!/usr/bin/env python
import json, sys, pprint, re
import matplotlib.pyplot as plt
import numpy as np
metrics = ["eps_final"]
fn = sys.argv[1]
print "loading %s"%(fn)
records = json.loads(open(fn,"r").read())
# Compute and extract numbers from output strings
for i in range(0,len(records)):
e = filter(lambda y: n... | records[i]['eps_final'] = float(e[-1].group(2))
records = filter(lambda x: x.has_key("eps_final"), records);
nsinks = sorted(list(set(map(lambda x: x["nsinks"], records))))
nthreads = sorted(list(set(map(lambda x: x["nthreads"], records))))
names = set(map(lambda x: x["d"], records))
handles = []
for metric in metri... | for ns in nsinks:
perf = [];
lbl = "Nsinks = %d"%(ns)
for nt in nthreads:
p = np.mean( map(lambda x: x[metric], filter( lambda y: y["d"]==name and y["nthreads"]==nt and y["nsinks"]==ns, records) ) )
perf.append(p)
print len(nthread... |
qsnake/h5py | h5py/tests/low/test_h5d.py | Python | bsd-3-clause | 529 | 0.003781 | from h5py import tests
from h5py import *
class TestCreate(tests.HTest):
def setUp(self):
self.fid, self.name = tests.gettemp()
def tearDown(self):
import os
self.fid.close() |
os.unlink(self.name)
@tests.require(api=18)
def test_create_anon(self):
""" (H5D) Anonymous dataset creation """
sid = h5s.create_simple((10,10))
dsid = h5d.create(self.fid, None, h5t | .STD_I32LE, sid)
self.assert_(dsid)
self.assertIsInstance(dsid, h5d.DatasetID)
|
LLNL/spack | var/spack/repos/builtin/packages/py-linecache2/package.py | Python | lgpl-2.1 | 592 | 0.001689 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for det | ails.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyLinecache2(PythonPackage):
"""Backports of the linecache module"""
homepage = "https://github.com/testing-cabal/linecache2"
pypi = "linecache2/linecache2-1.0.0.tar.gz"
version('1.0.0', sha256='4b26ff4e7110db76eeb6f5a... | d')
|
anlambert/tulip | doc/python/tabulate.py | Python | lgpl-3.0 | 60,926 | 0.000364 | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2019 Sergey Astanin
# https://bitbucket.org/astanin/python-tabulate
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, includ... | THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# -*- coding: utf-8 -*-
"""Pretty-print tabular data."""
from __future__ import print_function
from __future__ import unicode_literals
from collections import namedtuple
from platform import python_version_tuple
import re
import math
if python_version_tuple() >= ("3", "3"... | ions import Iterable
if python_version_tuple()[0] < "3":
from itertools import izip_longest
from functools import partial
_none_type = type(None)
_bool_type = bool
_int_type = int
_long_type = long # noqa
_float_type = float
_text_type = unicode # noqa
_binary_type = str
def _i... |
lpryszcz/rclups | rclups0.py | Python | gpl-3.0 | 9,729 | 0.011101 | #!/usr/bin/env python
desc="""Report distance matrix between proteins.
Dependencies:
- Biopython, numpy & scipy
"""
epilog="""Author: l.p.pryszcz@gmail.com
Bratislava, 28/04/2016
"""
import os, sys, gzip
import numpy as np
from datetime import datetime
from Bio import SeqIO
from multiprocessing import Pool
from scip... | pectrum(seq, transmembrane)
return name, x + y + z
def get_coords(arg):
"""Alternative approach
Hoang (2015) A new method to cluster DNA sequences using Fourier po | wer spectrum
"""
name, seq = arg
a = np.zeros((bases, len(seq)), dtype=int)
c = np.zeros(bases)
for i, aa in enumerate(seq):
if aa not in a2i:
continue
# update
a[a2i[aa]][i] = 1
c[a2i[aa]] += 1
# DFT
A = [np.fft.fft(_a) for _a in a]#; print len(... |
thatguyandy27/python-sandbox | learning-python/Ch2/variables_finished.py | Python | mit | 460 | 0.021739 | #
# Example file for variables
# | (For Python 3.x, be sure to use the ExampleSnippets3.txt file)
# Declare a variable and initialize it
f = 0;
print f
# re-declaring the variable works
f = "abc"
print f
# ERROR: variables of different types cannot be combined
#print "string type " + 123
print "string type " + str(123)
# Global vs. local variable | s in functions
def someFunction():
#global f
f = "def"
print f
someFunction()
print f
del f
print f
|
kakitone/finishingTool | experimental/finisherSCCoreLib/alignerRobot.py | Python | mit | 8,230 | 0.016889 | import os
import sys
import houseKeeper
from multiprocessing import Pool
import time
def extractMumData(folderName, fileName):
# "Format of the dataList : 1 765 | 11596 10822 | 765 775 | 84.25 | ref_NC_001133_ scf7180000000702"
f = open(folderName + fileName, 'r')
dataLis... | m(command)
for eachitem in workerList:
outputName, referenceName, queryName, specialName = eachitem[0], eachitem[1], eachitem[2] , eachitem[3]
for i in range(1, numberOfFiles+1):
for j in range(1, numberOfFiles+1):
i | f specialForRaw :
tmpRefName , tmpQryName = referenceName[0:-6] + ".part-" + zeropadding(i) +".fasta", queryName[0:-6] + "-" + zeropadding(j) + ".fasta"
else:
tmpRefName , tmpQryName = referenceName[0:-6] + ".part-" + zeropadding(i) +".fasta", query... |
pp-mo/iris-grib | iris_grib/tests/unit/load_convert/test_grid_definition_template_40.py | Python | lgpl-3.0 | 6,813 | 0 | # (C) British Crown Copyright 2015 - 2016, Met Office
#
# This file is part of iris-grib.
#
# iris-grib 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 opt... | 'latitudes': np.array([-59.44440829, -59.44440829,
-19.87571915, -19.87571915, -19.87571915,
19.87571915, 19.87571915, 19. | 87571915,
59.44440829, 59.44440829]),
'numberOfOctectsForNumberOfPoints': 1,
'interpretationOfNumberOfPoints': 1,
})
return section
def expected(self):
# Prepare the expectation.
expected = empty_metadata()
cs = iris... |
leandrotoledo/python-telegram-bot | telegram/parsemode.py | Python | lgpl-3.0 | 1,783 | 0.001122 | #!/usr/bin/env python
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public L... | onstants.PARSEMODE_ | MARKDOWN`\n
Note:
:attr:`MARKDOWN` is a legacy mode, retained by Telegram for backward compatibility.
You should use :attr:`MARKDOWN_V2` instead.
"""
MARKDOWN_V2: ClassVar[str] = constants.PARSEMODE_MARKDOWN_V2
""":const:`telegram.constants.PARSEMODE_MARKDOWN_V2`"""
HTML: ClassVar[s... |
ganga-devs/ganga | ganga/GangaCore/GPIDev/Lib/Job/__init__.py | Python | gpl-3.0 | 96 | 0 |
from .MetadataDict import MetadataDict
from .Job import | JobInfo, Job, JobStatusError, JobErro | r
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.2/Lib/lib-tk/Tix.py | Python | mit | 62,344 | 0.010683 | # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
# $Id: Tix.py,v 1.7 2001/12/13 04:53:07 fdrake Exp $
#
# Tix.py -- Tix widget wrappers.
#
# For Tix, see http://tix.sourceforge.net
#
# - Sudhir Shenoy (sshenoy@gol.com), Dec. 1995.
# based on an idea of Jean-Marc Lugrin (lug... | 'filedialog')
def tix_getbitmap(self, name):
"""Locates a bitmap file of the name name.xpm or name in one of the
bitmap directories (see the tix_addbitmapdir command above). By
using tix_getbitmap, you can avoid hard coding the pathnam | es of the
bitmap files in your application. When successful, it returns the
complete pathname of the bitmap file, prefixed with the character
'@'. The returned value can be used to configure the -bitmap
option of the TK and Tix widgets.
"""
return self.tk.call('tix', 'ge... |
lhellebr/spacewalk | backend/server/importlib/backend.py | Python | gpl-2.0 | 74,266 | 0.000687 | #
# Copyright (c) 2008--2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | d_seq',
'rhnPackage': 'rhn_package_id_seq',
'rhnSourceRPM': 'rhn_sourcerpm_id_seq',
'rhnPackageGroup': 'rhn_package_group_id_seq',
'rhnErrata': 'rhn_errata_id_seq',
'rhnChannel': 'rhn_channel_id_seq',
'rhnChannelProduct': 'rhn_channelprod_id_seq',
'rhnPackageSource': 'rhn_package_source_id_s... | id_seq',
'rhnChannelArch': 'rhn_channel_arch_id_seq',
'rhnPackageArch': 'rhn_package_arch_id_seq',
'rhnServerArch': 'rhn_server_arch_id_seq',
'rhnCPUArch': 'rhn_cpu_arch_id_seq',
'rhnErrataFile': 'rhn_erratafile_id_seq',
'rhnKickstartableTree': 'rhn_kstree_id_seq',
'rhnArchType': 'rhn_archty... |
iancze/Starfish | Starfish/grid_tools/interpolators.py | Python | bsd-3-clause | 7,056 | 0.002976 | import itertools
from collections import OrderedDict
import logging
import numpy as np
from scipy.interpolate import interp1d
from .utils import determine_chunk_log
BUFFER = 50
class IndexInterpolator: |
"""
Object to return fractional distance between grid points of a single grid variable.
:param parameter_list: list of parameter values
:type parameter_list: iterable
" | ""
def __init__(self, parameter_list):
parameter_list = np.asarray(parameter_list)
self.npars = parameter_list.shape[-1]
self.parameter_list = np.unique(parameter_list)
self.index_interpolator = interp1d(
self.parameter_list, np.arange(len(self.parameter_list)), kind="li... |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/signature.py | Python | bsd-3-clause | 3,350 | 0.007463 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/Signature) on 2017-03-22.
# 2017, SMART Health IT.
from . import element
class Signature(element.Element):
""" A digital Signature - XML DigSig, JWT, Graphical image of signature, etc..
... | presented as `str` in JSON). """
self.whoReference = None
""" Who signed.
Type `FHIRReference` referencing `Practitioner, RelatedPerson, Patient, Device, Organization` (represented as `dict` in JSON). """
self.whoUri = None
""" Who signed.
Type `str`. ""... | t=strict)
def elementProperties(self):
js = super(Signature, self).elementProperties()
js.extend([
("blob", "blob", str, False, None, False),
("contentType", "contentType", str, False, None, False),
("onBehalfOfReference", "onBehalfOfReference", fhirreference... |
noba3/KoTos | addons/plugin.video.movie25/resources/libs/plugins/mailru.py | Python | gpl-2.0 | 4,583 | 0.033639 | #-*- coding: utf-8 -*-
import urllib,re,string,urlparse,sys,os
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
from resources.libs import main
#Mash Up - by Mash2k3 2012.
addon_id = 'plugin.video.movie25'
selfAddon = xbmcaddon.Addon(id=addon_id)
art = main.art
prettyName = 'MailRu'
MAINURL='http://api.video.mail.ru/video... | ,thumb):
main.GA("MailRu","Watched")
xbmc.executebuiltin("XBMC.Notification(Please Wait!,Resolving Link,5000)")
link=main.OPENURL(murl)
ok=True
stream_url = resolve_mailru(murl)
try:
| if stream_url == False: return
infoL={'Title': mname, 'Plot': '', 'Genre': '', 'originaltitle': mname}
# play with bookmark
stream_url=stream_url.replace(' ','%20')
from resources.universal import playbackengine
play... |
bgxavier/neutron | neutron/context.py | Python | apache-2.0 | 4,387 | 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 req... | Object initialization.
:param overwrite: Set to False to ensure that the greent | hread local
copy of the index is not overwritten.
:param kwargs: Extra arguments that might be present, but we ignore
because they possibly came in from older rpc messages.
"""
super(ContextBase, self).__init__(auth_token=auth_token,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.