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 |
|---|---|---|---|---|---|---|---|---|
KL-WLCR/incubator-airflow | tests/contrib/sensors/test_bash_sensor.py | Python | apache-2.0 | 1,741 | 0 | # -*- coding: utf-8 -*-
#
# 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
... | }
dag = DAG('test_dag_id', default_args=args)
self.dag = dag
def te | st_true_condition(self):
t = BashSensor(
task_id='test_true_condition',
bash_command='freturn() { return "$1"; }; freturn 0',
output_encoding='utf-8',
poke_interval=1,
timeout=2,
dag=self.dag
)
t.execute(None)
def test_... |
mliberty1/embc | py/embc/collections/__init__.py | Python | apache-2.0 | 19 | 0 | fr | om . import | list
|
cheeseywhiz/cheeseywhiz | GUIs/Battery/graph.py | Python | mit | 2,547 | 0.000393 | import time
import os
import warnings
import matplotlib.pyplot as plt
import battery
try:
from PySide.QtCore import *
from PySide.QtGui import *
except ModuleNotFoundError: # no PySide
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# String formatting on print(t... | lf.__image_pipe)
def __save(self, file_name):
fig = plt.gcf()
axes = fig.gca()
axes.set_frame_on(False)
axes.set_xticks([])
| axes.set_yticks([])
plt.axis('off')
fig.savefig(file_name, bbox_inches='tight', pad_inches=0)
file_name = os.path.abspath('graph.png')
image = QImage(file_name)
pixmap = QPixmap.fromImage(image)
self.setPixmap(pixmap)
def flatten(self, *args):
return su... |
kevthunder/codewave-subl | codewave_core/edit_cmd_prop.py | Python | gpl-2.0 | 2,549 | 0.052962 |
import codewave_core.command as command
import codewave_core.cmds.core
class EditCmdProp(object):
def __init__(self, name,options):
self.name,options = name,options
defaults = {
'var' : None,
'opt' : None,
'funct' : None,
'dataName' : None,
'showEmpty' : False,
'carret' : False,
... |
def display(self,cmd):
if self.showForCmd(cmd):
return ("~~"+self.name+"~~\n" +
(self.valFromCmd(cmd) o | r "")+("|" if self.carret else "")+"\n" +
"~~/"+self.name+"~~")
class source(EditCmdProp):
def valFromCmd(self,cmd):
res = super(self.__class__, self).valFromCmd(cmd)
if res is not None :
res = res.replace('|', '||')
return res
def setCmd(self,cmds):
cmds[self.name] = codewave_core.cmd... |
zhaohuaw/connector | connector/unit/mapper.py | Python | agpl-3.0 | 32,917 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | =None):
""" A modifier intended to be used on the ``direct`` mappings.
For a many2one, get the ID on the backend and returns it.
When the field's relation is not a binding (i.e. it does not point to
something like ``magento.*``), the binding model needs to be provided
in the ``binding`` keyword ar... | 'country'),
(m2o_to_backend('magento_country_id'), 'country')]
:param field: name of the source field in the record
:param binding: name of the binding model is the relation is not a binding
"""
def modifier(self, record, to_attr):
if not record[field]:
... |
SPlanzer/AIMS | ElectoralAddress/Error.py | Python | bsd-3-clause | 159 | 0.037736 | class | Error ( Exception ):
"""Exception class for Address exceptions"""
def __init__( self, message ) :
Exception.__i | nit__(self,message)
|
c-automate/sequence-editing-helpers | aligne_and_correct_sequences.py | Python | mit | 7,974 | 0.018193 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from subprocess import call
from pyfasta.fasta import Fasta # Depends on fasta.py from https://github.com/brentp/pyfasta
def create_aligned_file(filename, gapopen=10, gapextend=0.5):
try:
f = Fasta(filename)
except:
print "Error: '",filename... | command = command + " -gapopen %0.2f"%gapopen # Gap opening penalty [10.0]:
command = command + " -gapextend %0.2f "%gapextend # Gap extension penalty [0.5]:
print ">This command is executed:\n\t",command
if not c | all(command, shell=True):
print "Aligned file was saved to ", filename+".needle"
return filename+".needle"
else:
print "Allignement failed :("
# ============================ correct_aligned_sequneces.py ===================
def select_from_rule(forw, rev):
forw_is_good = False
... |
Malex/FrozenFW | frozen/plugins/Getfile.py | Python | gpl-3.0 | 446 | 0.060538 | import mimetypes
def getfile(stat,head,b | ody,filename):
if filename.endswith(".py"):
return Response(stat,head,body,filename)
elif stat!='':
return Response(stat,head,body,filename)
else:
with open(File.parse(filename),'rb') as r:
ctype,cenc = mimetypes.guess_type(Fil | e.parse(filename))
return Response("200 OK",Headers("Content-Type: {}".format(ctype),"Content-Encoding: {}".format(cenc)),r.read(),filename,)
dispatch += getfile
|
NullHypothesis/atlas_tools | rest_api/query_issuer.py | Python | gpl-3.0 | 1,569 | 0.000637 | #!/usr/bin/env python
#
# | Copyright 2014 Philipp Winter <phw@nymity.ch>
#
# This file is part of atlas tools.
#
# atlas tools is free software: | you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# atlas tools is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ev... |
avanzosc/avanzosc6.1 | avanzosc_net_weight_in_lots/__init__.py | Python | agpl-3.0 | 1,119 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Avanzosc - Avanced Open Source Consulting
# Copyright (C) 2011 - 2013 Avanzosc <http://www.avanzosc.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms ... | rogram. If not, see http://www.gnu.org/licenses/.
#
############################### | ###############################################
import stock_production_lot_ext
import stock_picking_ext
import stock_move_ext
import purchase_order_ext
import stock_move_split_ext
|
mwielgoszewski/doorman | migrations/versions/0bc0a93ac867_.py | Python | mit | 1,141 | 0.014899 | """Add user table to support doorman and oauth authentication.
Revision ID: 0bc0a93ac867
Revises: fd28e46e46a6
Create Date: 2016-05-11 11:01:40.472139
"""
# revision identifiers, used by Alembic.
revision = '0bc0a93ac867'
down_revision = 'fd28e46e46a6'
from alembic import op
import sqlalchemy as sa
import doorman.d... | ), nullable=False),
sa.Column('username', sa.String(length=80), nullable=False),
sa.Column('email', sa.String(), nullable=True),
sa.Column('password', sa.String(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('social_id', sa.String(), nullable=True),
sa.Colum... | ue),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('username')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
### end Alembic commands ###
|
40323230/Pyslvs-PyQt5 | pyslvs_ui/entities/edit_point_ui.py | Python | agpl-3.0 | 9,330 | 0.002572 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pyslvs_ui/entities/edit_point.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from qtp... | ame("horizontalLayout_5")
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.name_label = QtWidgets.QLabel(Dialog)
self.name_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.name_label.setOb... |
self.name_box = QtWidgets.QComboBox(Dialog)
self.name_box.setObjectName("name_box")
self.verticalLayout.addWidget(self.name_box)
self.color_label = QtWidgets.QLabel(Dialog)
self.color_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/gtk/_gtk/PrintStatus.py | Python | gpl-2.0 | 792 | 0.007576 | # e | ncoding: utf-8
# module gtk._gtk
# from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so
# by generator 1.135
# no doc
# imports
import atk as __atk
import gio as __gio
import gobject as __gobject
import gobject._gobject as __gobject__gobject
class PrintStatus(__gobject.GEnum):
# no doc
def __init__(self... | ass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
__enum_values__ = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
5: 5,... |
ptMuta/python-node | pynode/runners/NodeRunner.py | Python | mit | 1,390 | 0 | from Naked.toolshed.shell import muterun_js
from pynode.exceptions import NodeExecutionFailedException
from pynode.runners.Runner import Runner
class NodeRunner(Runner):
def execute(self, script, *args):
result = muterun_js('-e "' + script + '"', self.args_to_string(args))
if result.exitcode == 0... | return result.stdout.decode('utf-8').strip()
else:
raise NodeExecutionFailedException(result.stderr)
def execute_silent(self, script, *args):
result = muterun_js('-e "' + script + '"', self.args_to_string(args))
if result.exitcode == 0:
return True
else:
... | |
andreaso/ansible | lib/ansible/modules/cloud/ovirt/ovirt_external_providers_facts.py | Python | gpl-3.0 | 5,936 | 0.002358 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | nal_providers = external_providers_service.list()
module.exit_json(
changed=False,
ansible_facts=dict(
ovirt | _external_providers=[
get_dict_of_struct(
struct=c,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for c in... |
moccu/django-cruditor | examples/formset/forms.py | Python | mit | 700 | 0 | from django import forms
from django.forms. | models import inlineformset_fa | ctory
from cruditor.forms import (
CruditorFormsetFormMixin, CruditorFormsetMixin, CruditorTapeformMixin)
from examples.store.models import Person, RelatedPerson
class PersonForm(CruditorTapeformMixin, forms.ModelForm):
reminder = forms.SplitDateTimeField()
class Meta:
model = Person
fi... |
nsubiron/SublimeSuricate | lib/thirdparty/duckduckgo2html.py | Python | gpl-3.0 | 8,822 | 0.000793 | #!/usr/bin/env python3
"""Retrieve results from the DuckDuckGo zero-click API in simple HTML format."""
import json as jsonlib
import logging
import re
import urllib.request, urllib.error, urllib.parse
__version__ = (1, 0, 0)
def results2html(results, results_priority=None, max_number_of_results=None,
... | else False
d | ef as_html(self):
return self.text.replace('\n', '<br>').replace('\r', '')
class Definition(_ResultItemBase):
def __init__(self, json):
super().__init__('Definition')
self.text = json['Definition']
self.url = json['DefinitionURL']
self.source = json['DefinitionSource']
... |
lidavidm/mathics-heroku | venv/lib/python2.7/site-packages/sympy/functions/elementary/piecewise.py | Python | gpl-3.0 | 22,285 | 0.001301 | from sympy.core import Basic, S, Function, diff, Tuple, Expr
from sympy.core.relational import Equality, Relational
from sympy.core.symbol import Dummy
from sympy.functions.elementary.miscellaneous import Max, Min
from sympy.logic.boolalg import And, Boolean, distribute_and_over_or, Not, Or
from sympy.core.compatibilit... | elational, Boolean)):
raise TypeError(
"Cond %s is of type %s, but must be a Relational,"
" Boolean, or a built-in bool." % (cond, type(cond)))
newargs.append(pair)
| if cond is True:
break
if options.pop('evaluate', True):
r = cls.eval(*newargs)
else:
r = None
if r is None:
return Basic.__new__(cls, *newargs, **options)
else:
return r
@classmethod
def eval(cls, *args):
... |
sahiljain/catapult | third_party/gsutil/third_party/apitools/apitools/scripts/oauth2l.py | Python | bsd-3-clause | 10,548 | 0.000095 | """Command-line utility for fetching/inspecting credentials.
oauth2l (pronounced "oauthtool") is a small utility for fetching
credentials, or inspecting existing credentials. Here we demonstrate
some sample use:
$ oauth2l fetch userinfo.email bigquery compute
Fetched credentials of type:
oauth2client.cl... | _path) as clien | t_secrets_file:
client_secrets = json.load(client_secrets_file)
if 'installed' not in client_secrets:
raise ValueError('Provided client ID must be for an installed app')
client_secrets = client_secrets['installed']
return {
'client_id': client_secrets['client_... |
grue/django-quickbooks-online | quickbooks/views.py | Python | mit | 4,488 | 0.002005 | import logging
from requests_oauthlib import OAuth1Session
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from .models import QuickbooksToken, get_quickbooks_token
from... | ['qb_oauth_token'] | = request_token
request.session['qb_oauth_token_secret'] = request_token_secret
except:
logger = logging.getLogger('quickbooks.views.request_oauth_token')
logger.exception(("Couldn't extract oAuth parameters from token " +
"request response. Response was '%s'"), re... |
JoyTeam/metagam | mg/test/testmemcached.py | Python | gpl-3.0 | 3,304 | 0.002463 | #!/usr/bin/python2.6
# -*- coding: utf-8 -*-
# This file is a part of Metagam project.
#
# Metagam 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
# any later version.
#
# Metagam is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public L... | .
#
# You should have received a copy of the GNU General Public License
# along with Metagam. If not, see <http://www.gnu.org/licenses/>.
from mg.core.memcached import Memcached, MemcachedPool, MemcachedEmptyKeyError
import unittest
from concurrence import dispatch, Tasklet
class TestMemcached(unittest.TestCase):
... |
mdhaman/superdesk-aap | server/aap/macros/sydney_traffic_test.py | Python | agpl-3.0 | 717 | 0 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from unittes... | :
self.app.config['DEFAULT_TIMEZONE'] = 'Australia/Sydney'
def test_sydney_congetsion(self):
item | = expand_sydney_traffic_congestion({'body_html': '{{alerts}}'})
self.assertNotEqual(item.get('body_html'), '{{alerts}}')
|
steppenwolf-sro/callback-schedule | callback_schedule/serializers.py | Python | mit | 675 | 0.001481 | from rest_framework import serializers
from callback_schedule.models import CallbackManager, CallbackManagerSchedule, CallbackManagerPhone
class CMScheduleSerializer(serializers.ModelSerializer | ):
class Meta:
model = CallbackManagerSchedule
fields = 'weekday', 'available_from', 'available_till'
class CMSerializer(serializers.ModelSerializer):
schedule = CMScheduleSerializer(many=True, read_only=True)
class Meta:
model = CallbackManager
fields = '__all__'
class ... | iority'
|
RedHatQE/wait_for | wait_for/__init__.py | Python | apache-2.0 | 12,038 | 0.003323 | import inspect
import logging
import time
from collections import namedtuple
from datetime import datetime, timedelta
from functools import partial
from threading import Timer
from types import LambdaType
import parsedatetime
WaitForResult = namedtuple("WaitForResult", ["out", "duration"])
calendar = parsedatetime.C... | wargs.get('num_sec', 120))
return num_sec
def is_lambda_function(obj):
return isinstance(obj, LambdaType) and obj.__name__ == "<lambda>"
def _get_context(func, message=None):
if not message:
if isinstance(func, partial):
params = ", ".join([str(arg) for arg in func.args])
... | artial function {}({})".format(func.func.__name__, params)
elif is_lambda_function(func):
try:
message = "lambda defined as `{}`".format(inspect.getsource(func).strip())
except IOError:
# Probably in interactive python shell or debugger and cannot get lamb... |
openqt/algorithms | projecteuler/pe054-poker-hands.py | Python | gpl-3.0 | 2,408 | 0.009551 | #!/usr/bin/env python
# coding=utf-8
"""54. Poker hands
https://projecteuler.net/problem=54
In the card game poker, a hand consists of five cards and are ranked, from
lowest to highest, in the following way:
* **High Card** : Highest value card.
* **One Pair** : Two cards of the same value.
* **Two Pairs** : T... | it.
* **Full House** : Three of a kind and a pair.
* **Four of a Kind** : Four cards of the same value.
* **Straight Flush** : All cards are consecutive values of same suit.
* **Royal Flush** : Ten, Jack, Queen, King, Ace, in same suit.
The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Que... | or example, a pair of eights beats a pair of fives (see example 1
below). But if two ranks tie, for example, both players have a pair of queens,
then highest cards in each hand are compared (see example 4 below); if the
highest cards tie then the next highest cards are compared, and so on.
Consider the following five ... |
morgs/poll-builder | i18n_misc_strings.py | Python | gpl-2.0 | 74 | 0 | _("Lesson 1")
_( | "Lesson 2")
_("Lesson 3")
_("Lesson 4")
_("Intr | oduction")
|
timlinux/geonode | geonode/layers/metadata.py | Python | gpl-3.0 | 7,943 | 0.000126 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | urpose'] = mdata.idinfo.descript.purpose
if mdata.idinfo.descript.supplinf is not None:
vals['supplemental_information'] = mdata.idinfo.descript.supplinf
if hasattr(mdata.idinfo, 'keywords'):
if mdata.idinfo.keywords.theme:
for theme in mdata.idinfo.keywords.theme:
... | heme['themekt'].lower()
# Owslib doesn't support extracting the Topic Category
# from FGDC. So we add support here.
# http://www.fgdc.gov/metadata/geospatial-metadata-standards
if all(
ss in lowered_themekt for ss ... |
the-blue-alliance/the-blue-alliance | src/backend/common/helpers/playoff_advancement_helper.py | Python | mit | 34,130 | 0.001641 | import copy
from collections import defaultdict
from typing import (
Any,
cast,
DefaultDict,
Dict,
List,
Mapping,
NamedTuple,
Optional,
TypedDict,
)
from pyre_extensions import none_throws
from backend.common.consts.alliance_color import AllianceColor, OPPONENT, TMatchWinner
from b... | anel Points"],
2020: [],
2021: [],
}
|
ADVANCEMENT_COUNT_2015: Dict[CompLevel, int] = {
CompLevel.EF: 8,
CompLevel.QF: 4,
CompLevel.SF: 2,
}
PLAYOFF_TYPE_TO_TEMPLATE: Dict[PlayoffType, str] = {
PlayoffType.AVG_SCORE_8_TEAM: "playoff_table",
PlayoffType.ROUND_ROBIN_6_TEAM: "playoff_round_robin_6_team",
... |
CJ-Wright/pyIID | pyiid/experiments/elasticscatter/cpu_wrappers/flat_multi_cpu_wrap.py | Python | bsd-3-clause | 5,576 | 0 | from multiprocessing import Pool, cpu_count
import psutil
from pyiid.adp import has_adp
import numpy as np
from pyiid.experiments.elasticscatter.atomics.cpu_atomics import (
cpu_k_space_fq_allocation, cpu_k_space_fq_adp_allocation, atomic_fq,
get_normalization_array, k_space_dfq_dadp_allocation,
k_space_gra... | cpu_k_space_fq_adp_allocation
master_task = [q, adps, scatter_array, qbin]
ans = cpu_multiprocessing(atomic_fq, allocation, master_ | task,
(n, qmax_bin))
# sum the answers
final = np.sum(ans, axis=0, dtype=np.float64)
final = final.astype(np.float32)
norm = np.empty((k_max, qmax_bin), np.float32)
get_normalization_array(norm, scatter_array, 0)
na = np.mean(norm, axis=0, dtype=np.float32) * np.fl... |
Azure/azure-sdk-for-python | sdk/storage/azure-mgmt-storagecache/azure/mgmt/storagecache/operations/__init__.py | Python | mit | 1,054 | 0.001898 | # 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 Mi | crosoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# ---------------------------------------- | ----------------------------------
from ._operations import Operations
from ._skus_operations import SkusOperations
from ._usage_models_operations import UsageModelsOperations
from ._asc_operations_operations import AscOperationsOperations
from ._caches_operations import CachesOperations
from ._storage_targets_operati... |
OCA/program | program_multi_menu_team/__init__.py | Python | agpl-3.0 | 1,260 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Savoir-faire Linux (<www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the t... | 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/>.
#
##############################################################################
from . import (
program_result_team_beneficiary,
program_result_team_partner_type... | partner,
program_result_team_role,
program_result_team_beneficiary_type,
)
|
realms-team/basestation-fw | libs/smartmeshsdk-REL-1.3.0.1/libs/VManagerSDK/vmanager/configuration.py | Python | bsd-3-clause | 7,415 | 0.000944 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 l... | return self.api_key_prefix[identifier] + ' ' + self.api_key[identifier]
elif self.api_key.get(identifier):
return self.api_key[identifier]
def get_basic_auth_token(self):
"""
Gets HTTP basic authentication header (string).
:return: The token for basic HTTP au... | def auth_settings(self):
"""
Gets Auth Settings dict for api client.
:return: The Auth Settings information dict.
"""
return {
'dust_basic':
{
'type': 'basic',
'in': 'header',
'key': 'Autho... |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/riskassessment_tests.py | Python | bsd-3-clause | 11,177 | 0.004116 | #!/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 riskassessment
from .fhirdate import FHIRDate
class RiskAssessmentTests(unittest.TestCase):
def instantiate_from(self, filena... | rceType"])
inst2 = riskassessment.RiskAssessment(js)
self.implRiskAssessment1(inst2)
def implRiskAssessment1(self, inst):
self.assertEqual(inst.id, "cardiac")
self.assertEqual(inst.identifier.system, "http://example.org")
s | elf.assertEqual(inst.identifier.use, "official")
self.assertEqual(inst.identifier.value, "risk-assessment-cardiac")
self.assertEqual(inst.occurrenceDateTime.date, FHIRDate("2014-07-19T16:04:00Z").date)
self.assertEqual(inst.occurrenceDateTime.as_json(), "2014-07-19T16:04:00Z")
self.asser... |
zhangg/trove | trove/guestagent/datastore/experimental/mongodb/system.py | Python | apache-2.0 | 1,819 | 0 | # Copyright (c) 2014 Mirantis, 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 re... | '.os_mongo_admin_creds.json')
MONGO_KEY_FILE = '/etc/mongo_key'
MONGOS_SE | RVICE_CANDIDATES = ["mongos"]
MONGOD_SERVICE_CANDIDATES = ["mongodb", "mongod"]
MONGODB_KILL = "sudo kill %s"
FIND_PID = "ps xaco pid,cmd | awk '/mongo(d|db|s)/ {print $1}'"
TIME_OUT = 1000
MONGO_USER = {operating_system.REDHAT: "mongod",
operating_system.DEBIAN: "mongodb",
operating_system... |
hoh/Billabong | billabong/storage/folder.py | Python | agpl-3.0 | 2,678 | 0 | # Copyright (c) 2015 "Hugo Herter http://hugoherter.com"
#
# This file is part of Billabong.
#
# Intercom 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 o... |
"""List all ids present in the blobs storage."""
for id_ in os.listdir(self.path):
yield id_
def delete(self, blob_id):
"""Delete a blob from the storage."""
os.remove(self._blob_path(blob_id))
def import_blob(self, id_, blobfile, callback=None):
"""Add an ... | by copying the file."""
copyfileobj(blobfile,
open(self._blob_path(id_), 'wb'))
if callback:
callback()
def read_in_chunks(self, id_, offset=0, chunk_size=1024):
"""Read a blob file chunk by chunk."""
path = self._blob_path(id_)
fdesc = open(p... |
bobgeis/LookOutSpacePirates | starMaker.py | Python | bsd-3-clause | 1,541 | 0.058404 | """
This is used to make star field backgrounds.
"""
import sys, random, pygame, glob, fnmatch
from pygame.locals import *
# star colors
# spectral type R G B
SPECTRA = { 'O': (225,225,255), \
'B': (225,255,255), \
'A': (255,255,255), \
'F': (255,255,225), \
'G': (255,255,200), \
'K': (25... | [type], img)
| STARS['d'][type] = new_img
img = pygame.image.load('./images/gGrey.png')
for type in SPECTRA:
new_img = replace_color((150,150,150), SPECTRA[type], img)
STARS['g'][type] = new_img
def main():
sizes = STARS.keys()
colors = SPECTRA.keys()
side = 6400
load_stars()
bg = pygame.Surface((side,side),S... |
hevvieevvie/osmc | package/mediacenter-addon-osmc/src/script.module.osmcsetting.pi/resources/lib/OSMC_REparser.py | Python | gpl-2.0 | 38,080 | 0.044328 | '''
DICT OF ITEMS IN CONFIG WHICH AFFECT THIS KODI SETTING
kodi_setting_id: {
KODI_ITEM:
{
config_get_patterns: [ LIST OF DICTS WITH AN IDENTIFY REGEX AND AN EXTRACT REGEX
IDENTIFY REGEX'S ARE THERE TO SPECIFICALLY FIND THE LINES
EXTRACT REGEXES ARE THERE TO GET THE SPECIFIC SETTING VALUE
... | kodi_setting = retrieve_default(**default)
return kodi_setting
def retrieve_default(function, value):
if function is not None:
value = function()
return value
def kodi_to_config(MASTER_SETTINGS, config, new_settings):
''' Takes the existing config.txt (as a list of lines) and constructs a new one using th... |
Returns a brand new config (list of lines)'''
for setting, new_value in new_settings.iteritems():
setting_protocols = MASTER_SETTINGS.get(setting, None)
if setting_protocols == None: continue
config = general_config_set(config, new_settings, new_value, **setting_protocols)
return config
def general_co... |
lbeltrame/bcbio-nextgen | bcbio/ngsalign/bwa.py | Python | mit | 17,449 | 0.00447 | """BWA (https://github.com/lh3/bwa)
"""
import os
import signal
import subprocess
from bcbio.pipeline import config_utils
from bcbio import bam, utils
from bcbio.distributed import objectstore
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.ngsalign import alignprep, novoalign, postali... | gnment of an input BAM file with BWA using pipes.
This avoids disk IO by piping between processes:
- samtools sort of input BAM to queryname
- bedtools conversion to interleaved FASTQ
- bwa-mem alignment
- samtools conversion to BAM
- samtools sort to coordinate
"""
| config = data["config"]
out_file = os.path.join(align_dir, "{0}-sort.bam".format(names["lane"]))
samtools = config_utils.get_program("samtools", config)
bedtools = config_utils.get_program("bedtools", config)
resources = config_utils.get_resources("samtools", config)
num_cores = config["algorithm"].... |
uwbmrb/BMRB-API | server/wsgi/bmrbapi/submodules/fasta36/scripts/get_protein.py | Python | gpl-3.0 | 1,680 | 0.02381 | #!/usr/bin/env python3
## get_protein_www.py --
## get a protein sequence from the Uniprot or NCBI/Refseq web sites using the | accession
##
import sys
import re
import textwrap
import time
import requests
ncbi_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?"
uniprot_url = "https://ww | w.uniprot.org/uniprot/"
sub_range = ''
for acc in sys.argv[1:]:
if (re.search(r':',acc)):
(acc, sub_range) = acc.split(':')
if (re.match(r'^(sp|tr|iso|ref)\|',acc)):
acc=acc.split('|')[1]
if (re.match(r'[A-Z]P_\d+',acc)): # get refseq
db_type="protein"
seq_args = "db=%s&id=" % (db_type) +... |
projectcuracao/projectcuracao | housekeeping/readTime.py | Python | gpl-3.0 | 1,716 | 0.038462 |
# reads the RC time from UTC tim | e on Arduino
# filename: readTime.py
# Version 1.0 03/11/14
#
# contains event routines for d | ata collection from the battery watchdog arduino
#
#
import sys
import time
import RPi.GPIO as GPIO
import serial
import subprocess
sys.path.append('./pclogging')
sys.path.append('./util')
import pclogging
import util
def readTime(source, delay):
print("readTime source:%s" % source)
time.sleep(delay)
# bli... |
rakeshvar/telugu_ocr_banti | tests/glyph_test.py | Python | apache-2.0 | 613 | 0.001631 | import numpy as np
from math import sin, pi, cos
from banti.glyph import Glyph
halfsize = 40
size = 2*halfsize + 1
picture = np.zeros((size, size) | )
for t in range(-135, 135):
x = round(halfsize + halfsize * cos(pi * t / 180))
y = round(halfsize + halfsize * sin(pi * t / 180))
picture[x][y] = 1
zoomsz = 1 * halfsize
b = Glyph(['O', 0, 0, size, size, 0, 0, 0, 0, None])
b.set_pix(picture)
c = Glyph()
for t in range(0, 360, 15):
x = round(zoomsz + z... | .set_xy_wh((x, y, size, size))
c = c + b
print(b)
print(c) |
hazelcast/hazelcast-python-client | tests/integration/backward_compatible/connection_strategy_test.py | Python | apache-2.0 | 4,726 | 0.000846 | from hazelcast import HazelcastClient
from hazelcast.config import ReconnectMode
from hazelcast.errors import ClientOfflineError, HazelcastClientNotActiveError
from hazelcast.lifecycle import LifecycleState
from tests.base import HazelcastTestCase
from tests.util import random_string
class ConnectionStrategyTest(Haze... | pend(event)
on_state_change.events = events
return on_state_change
event_collector = collec | tor()
self.client = HazelcastClient(
cluster_members=["localhost:5701"],
cluster_name=self.cluster.id,
reconnect_mode=ReconnectMode.OFF,
lifecycle_listeners=[event_collector],
)
m = self.client.get_map(random_string()).blocking()
# no exce... |
jdovi/drydenmusic | DrydenMusicApp/migrations/0005_teaching_link.py | Python | gpl-3.0 | 1,017 | 0.003933 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('DrydenMusicApp', '0004_auto_20160824_2150'),
]
operations = [
migrations.CreateModel(
name='teaching_link',
... | =False)),
('title', models.CharField(max_length=200)),
| ('url', models.CharField(max_length=200)),
('topic', models.CharField(max_length=200, blank=True, null=True)),
('scripture', models.CharField(max_length=200, blank=True, null=True)),
('author_or_teacher', models.CharField(max_length=200, blank=True, null=Tru... |
botswana-harvard/tshilo-dikotla | td_lab/admin/receive_admin.py | Python | gpl-2.0 | 955 | 0.005236 | from django.contrib import admin
from tshilo_dikotla.base_model_admin import MembershipBaseModelAdmin
from ..models import Receive
class ReceiveAdmin(MembershipBaseModelAdmin):
date_hierarchy = 'receive_datetime'
list_display = ("receive_identifier", "requisition", "receive_datetime", "drawn_datetime",
... | r', | 'subject_type',
"receive_identifier", "requisition_identifier",)
list_filter = ('created', "receive_datetime", "drawn_datetime", 'modified', 'import_datetime', )
list_per_page = 15
def get_readonly_fields(self, request, obj):
return (['receive_identifier', 'requisition_model_... |
tommartensen/arion-backend | arionBackend/serializers/__init__.py | Python | mit | 49 | 0 | """
This module contains all | serializers.
| """
|
phantomas1234/fbaproject | ifba/distributedFBA/networking_Test.py | Python | mit | 684 | 0.005848 | #!/usr/bin/env python
# encoding: utf-8
"""
networking_Test.py
Created by Nikolaus Sonnenschein on 2008-05-8.
Copyright (c) 2008 Jacobs University of Bremen. All rights reserved.
"""
import unittes | t
from ifba.distributedFBA import networking
class test_Networking(unittest.TestCase):
def setUp(self):
pass
def testPriorityQueue(self):
"""Tests the Priority Queue from the Python Cookbook"""
q = networking.PriorityQueue()
q.put("2", 2)
q.put("1", 1)
q... | ert_(q.get(), '3')
if __name__ == '__main__':
unittest.main() |
louisdijkstra/error-model-aligner | bin/estimate-null-insert-sizes.py | Python | gpl-3.0 | 3,976 | 0.029427 | #!/usr/bin/env python
"""
Copyright (C) 2015 Louis Dijkstra
This file is part of error-model-aligner
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... | =1):
parser.print_help()
return 1
isizes = [] # insert sizes that were observed
counts = [] # number of times these insert sizes were observed
for line in open(args[0], 'r'):
values = map(int, line.split())
isizes.append(values[0])
counts.append(values[1])
isizes = np.array(isizes)
counts = np.array(c... | args=[isizes, counts, n],
method="L-BFGS-B",
bounds=[(0, None), (0, None)],
options={'disp': options.verbose, 'maxfun': options.maxfun, 'maxiter': options.maxiter})
print("\n*** RESULTS ***\n")
print("estimated mean: %lf\t estimated STD: %lf\n"%(res.x[0], res.x[1]))
print(res.message)
if __name__... |
mathiesonsterling/DoublePump | src/implementations/stored_task_instantiator.py | Python | gpl-3.0 | 626 | 0.004792 | from src.entities import TaskInstantiator
from src.implementations.testing import MustRunTask
from src.implementations.testing import ParentTask
"""
Holds all tasks as an instance, de | livers them when asked
"""
class StoredTaskInstantiator(TaskInstantiator):
def __init__(self):
self.known_tasks = {}
def instantiate_task(self, task_name):
return self.known_tasks[task_name]
def add_task_instance(self, task):
if task | .get_name() in self.known_tasks.keys():
raise LookupError("The task " + task.get_name() + " is already stored")
self.known_tasks[task.get_name()] = task |
hdzierz/Kaka | mongcore/django_ext.py | Python | gpl-2.0 | 787 | 0.022872 | # -*- coding: utf-8 -*-
from django.db.models import Aggregate
#from django.db.models.sql.aggregates import Aggregate as SQLAggreg | ate
#class SQLConcat(SQLAggregate):
#sql_function = 'group_concat'
#@property
#def sql_template(self):
#if separator in self.extra and separator is not None:
#return '%(function)s(%(field)s, "%(separator)s")'
#else:
#return '%( | function)s(%(field)s);'
#class SQLConcat(SQLAggregate):
# sql_function = 'textcat_all'
#class Concat(Aggregate):
# def add_to_query(self, query, alias, col, source, is_summary):
# aggregate = SQLConcat(
# col,
# source=source,
# is_summary=is_summary,
# **sel... |
donama/phrasetank | sink/__init__.py | Python | apache-2.0 | 1,663 | 0.013229 | """
Sink serves just one purpose, to ensure that links are never crawled
twice during the running of the phrasetank service
all producers checks the sink to ensure that it does not crawl a link
twice
"""
import zlib
class PhrasetankSink(object):
sinks = {}
def __init__(self):
pass
@... | as well as a hash of the link reversed
"""
if uri:
hash_f = zlib.crc32(uri.strip())
hash_r = zlib.crc32(uri.strip()[::-1])
#Ensure that the link does not exists int he sink
PhrasetankSink.willAddLink(hash_f,hash_r,uri)
... | f hasSeenURI(uri):
"""
Checks to see if we have visited this uri before now
"""
if uri:
hash_f = zlib.crc32(uri.strip())
hash_r = zlib.crc32(uri.strip()[::-1])
if PhrasetankSink.sinks.has_key(str(hash_f)) or PhrasetankSink.sinks.has_key(st... |
XeCycle/indico | indico/MaKaC/webinterface/rh/reviewingAssignContributions.py | Python | gpl-3.0 | 2,181 | 0.004127 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | erface.pages.reviewing import WPConfReviewingAssignContributions
from MaKaC.webinterface.rh.reviewingModif import RCPaperReviewManager, RCReferee
from MaKaC.common.cont | ribPacker import ZIPFileHandler, ReviewingPacker
from indico.web.flask.util import send_file
class RHReviewingAssignContributionsList(RHConferenceModifBase):
_uh = urlHandlers.UHConfModifListContribToJudge
def _checkProtection(self):
if not RCPaperReviewManager.hasRights(self) and not RCReferee.hasRi... |
sarvex/tensorflow | tensorflow/lite/experimental/acceleration/mini_benchmark/metrics/blazeface_metrics.py | Python | apache-2.0 | 5,456 | 0.004765 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ivide(1.0,
1.0 + tf.math.exp(-expected_scores))
squashed_actual_scores = tf.math.divide(1.0,
1.0 + tf.math.exp(-actual_scores))
kld_metric = kl_divergence.symmetric_kl_divergence(expected_scores,
| actual_scores)
# ML Kit uses 0.5 as the threshold. We use
# 0.1 to use more possible boxes based on experimentation with the model.
high_scoring_indices = tf.math.logical_or(
tf.math.greater(squashed_expected_scores, 0.1),
tf.math.greater(squashed_actual_scores, 0.1))
... |
rasssta/librenms | services-wrapper.py | Python | gpl-3.0 | 14,784 | 0.00257 | #! /usr/bin/env python3
"""
services-wrapper A small tool which wraps around check-services.php and tries to
guide the services process with a more modern approach with a
Queue and workers.
Based on the original version of poller-wrapper.py by Job Snijders
Author: Neil Lathwo... | )
except (Keyb | oardInterrupt, SystemExit):
raise
except:
pass
poll_queue.task_done()
if __name__ == "__main__":
logger = LNMS.logger_get_logger(LOG_FILE, debug=_DEBUG)
install_dir = os.path.dirname(os.path.realpath(__file__))
LNMS.check_for_file(install_dir + "/.env")... |
weaver-viii/h2o-3 | h2o-py/tests/testdir_munging/unop/pyunit_minmax_basic.py | Python | apache-2.0 | 1,862 | 0.011278 | import sys
sys.path.insert(1, "../../../")
import h2o
import numpy as np
def minmax_basic(ip,port):
print "Uploading iris data..."
iris_h2o = h2o.import_file(h2o.locate("smalldata/iris/iris_wheader.csv"))
iris_np = np.genfromtxt(h2o.locate("smalldata/iris/iris_wheader.csv"), delimiter=",", skip_... | iris..."
irisall_min = iris_h2o[0:4].min()
print "Minimum: {0}".format(irisall_min)
| irisall_max = iris_h2o[0:4].max()
print "Maximum: {0}".format(irisall_max)
np_min = iris_np[:,0:4].min()
np_max = iris_np[:,0:4].max()
assert irisall_min == np_min, "Expected the same min value. H2O got {0}, but numpy got {1}".format(irisall_min, np_min)
assert irisall_max == np_max, "Expected the... |
nischu7/paramiko | paramiko/sftp_attr.py | Python | lgpl-2.1 | 7,833 | 0.001277 | # Copyright (C) 2003-2006 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko 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... | FTPAttributes object. All fields will be empty.
"""
self._flags = 0
self.st_size = None
self.st_uid = None
self.st_gid = None
self.st_mode = None
self.st_atime = None
self.st_mtime = None
self.attr = {}
def from_stat(cls, obj, filename=None):... | t returned by C{os.stat}).
@param obj: an object returned by C{os.stat} (or equivalent).
@type obj: object
@param filename: the filename associated with this file.
@type filename: str
@return: new L{SFTPAttributes} object with the same attribute fields.
@rtype: L{SFTPAtt... |
GoogleCloudPlatform/functions-framework-python | src/functions_framework/background_event.py | Python | apache-2.0 | 1,459 | 0 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wit | h 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 spe... |
cgroza/gEcrit | gEcritSession.py | Python | gpl-3.0 | 3,647 | 0.004113 | # Copyright (C) 2011 Gro | za Cristian
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License | as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ... |
vicky2135/lucious | src/oscar/apps/basket/migrations/0002_auto_20140827_1705.py | Python | bsd-3-clause | 1,879 | 0.002661 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
| from django.db import models, | migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('partner', '0001_initial'),
('catalogue', '0001_initial'),
('basket', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
oarriaga/single_shot_multibox_detector | src/utils/tests/modified_VGG.py | Python | mit | 4,151 | 0 | from keras.layers import Conv2D
from keras.layers import Input
from keras.layers import MaxPooling2D
from keras.layers import ZeroPadding2D
from keras.models import Model
def modified_VGG16(input_shape=(300, 300, 3), num_classes=21,
weights_path=None, frozen_layers=None, randomize_top=False):
... | FC6 ------------------------------------------------
pool5z = ZeroPadding2D(padding=(6, 6), name='pool5z')(pool5)
fc6 = Conv2D(1024, (3, 3),
| name='fc6',
dilation_rate=(6, 6),
padding='valid',
activation='relu'
)(pool5z)
# FC7 ------------------------------------------------
fc7 = Conv2D(1024, (1, 1),
name='fc7',
padding='same',
ac... |
martiinsiimon/dogtail | examples/gedit-test-utf8-procedural-api.py | Python | gpl-2.0 | 3,778 | 0.003176 | #!/usr/bin/env python3
# Dogtail demo script
from dogtail.config import config
#config.debugSleep = True
#config.debugSearching = True
#config.debugTranslation = True
import dogtail.tc
from dogtail.procedural import *
from dogtail.utils import screenshot
from dogtail.predicate import GenericPredicate
# These next tw... | Start gedit.
run('gedit')
# Set focus on gedit
focus.application('gedit')
# Focus gedit's text buffer.
focus.text()
# Load the UTF-8 demo file. Use codecs.open() instead of open().
from codecs import open
from sys import path
utfdemo = open(path[0] + '/data/UTF-8-demo.txt')
# Load the UTF-8 demo file into the text ... | Focus gedit's Save As... dialog
try:
focus.widget.findByPredicate(GenericPredicate(roleName='file chooser'))
except FocusError:
try:
# This string changed somewhere around gedit 2.13.2.
# This is the new string
focus.dialog('Save As\u2026')
except FocusError:
# Fall back to ... |
alucardlockon/LearnCode | 01PythonTest/05_trunBasedRpg.py | Python | gpl-3.0 | 5,415 | 0.033795 | #trun based rpg
import random
import time
class role:
name=""
lv=1
exp=0
nextLv=1000
hp=100
mp=30
stra=5
inte=5
spd=5
defe=5
rest=5
void=5
dropItems=[None]
dropPrecent=[100]
command=['attack','void','def','fireball']
def __init__(self,name,lv):
sel... | print roleself.name+'\'s attack:deal '+str(damage)+' damage to '+roleattacked.name
#methods:
def expolore(stage):
while True:
r=int(random.random()*100);
precentnew=0;
for (precent,emeny) in zip(stage.emenyPrecent,stage.emenyLIst):
stage.startPos+=int(4*random.random())+1;
... | "stage clear!"
precentold=precentnew
precentnew+=precent
if r>=precentold and r<precentnew :
while True:
print time.strftime("%Y-%m-%d-%H-%M-%S",\
time.localtime(time.time())),\
... |
moreati/pyscard | smartcard/Card.py | Python | lgpl-2.1 | 2,621 | 0.000763 | """Card class.
__author__ = "gemalto http://www.gemalto.com"
Copyright 2001-2012 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
This file is part of pyscard.
pyscard is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser Gener | al Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
pyscard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See t... | U Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with pyscard; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""
from smartcard.reader.Reader import Reader
from smartcard.Syst... |
dadwyer/oklo | oklo/tests/test_ids.py | Python | gpl-3.0 | 2,910 | 0.011684 | import unittest
from oklo.core.ids import NuclideId, ReactionId
from oklo.core.defs import ReactionType
class TestNuclideId(unittest.TestCase):
def setUp(self):
self.fixture = NuclideId(Z='Yttrium',A=96,M=0)
def tearDown(self):
del self.fixture
def test_nuclide_Z(self):
... | f.fixture = {'reac1': ReactionId(NuclideId('Yttrium_96'),
ReactionType.BetaDecay | ),
'reac2': ReactionId(NuclideId('Strontium_96'),
ReactionType.BetaDecay),
'reac3': ReactionId(NuclideId(Z='Yttrium',A=96),
ReactionType.BetaDecay)}
def t... |
p/pycurl-archived | tests/write_to_file_test.py | Python | lgpl-2.1 | 779 | 0.003851 | #! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vi:ts=4:et
from __future__ import with_statement
import unittest
import pycurl
import tempfile
from . import app
from . import runwsgi
fr | om . import util
setup_module, teardown_module = runwsgi.app_runner_setup((app.app, 8380))
class WriteToFileTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
def tearDown(self):
self.curl.close()
def test_get_to_file(self):
self.curl.setopt(pycurl.URL, '... | |
michaelBenin/pep8ify | pep8ify/fixes/fix_whitespace_before_inline_comment.py | Python | apache-2.0 | 1,952 | 0 | from __future__ import unicode_literals
from lib2to3.fixer_base import BaseFix
from .utils import node_text
|
def ge | t_previous_node(node):
"""
Return the node before this node.
"""
if node.prev_sibling:
return node.prev_sibling
if node.parent:
return get_previous_node(node.parent)
class FixWhitespaceBeforeInlineComment(BaseFix):
'''
Separate inline comments by at least two spaces.
A... |
zamazaljiri/django-mailer | mailer/migrations/0002_auto__chg_field_message_updated.py | Python | mit | 1,493 | 0.006698 | # -*- 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 'Message.updated'
db.alter_column(u'mailer_message', 'u... | models.fields.PositiveSmallIntegerField', [], {'default': '2'}),
'recipients': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'defaul | t': '0'}),
'subject': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
}
}
complete_apps = ['mailer'] |
UnrememberMe/pants | src/python/pants/pantsd/pants_daemon.py | Python | apache-2.0 | 15,867 | 0.009138 | # 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... | oot = get_buildroot()
native = Native.create(bootstrap_options_values)
legacy_graph_helper = cls._setup_legacy_graph_helper(native, bootstrap_options_values)
services, port_map = cls._setup_services(
build_root,
bootstrap_options_values | ,
legacy_graph_helper,
watchman
)
return PantsDaemon(
native=native,
build_root=build_root,
work_dir=bootstrap_options_values.pants_workdir,
log_level=bootstrap_options_values.level.upper(),
services=services,
socket_map=port_map,
... |
pronexo-odoo/odoo-argentina | l10n_ar_pyafipws/pyafipws/formato_cot.py | Python | agpl-3.0 | 3,236 | 0.001855 | #!/usr/bin/python
# -*- coding: latin-1 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 3, or (at your option) any later
# version.
#
# This program is distributed in t... | (sys.argv[1])
for l in f:
reg = l[0:2]
if reg in registros:
print "Registro: ", registros[reg]
campos = l.strip("\r").strip("\n").split("|")
for | i, campo in enumerate(campos):
print " * %s: |%s|" % (formato[reg][i], campo, )
else:
print "registro incorrecto:", l
|
dheerajgoudb/Hackerrank | Python/Introduction/Reading_raw_input.py | Python | apache-2.0 | 33 | 0.030303 | input = raw | _in | put();
print input
|
teeple/pns_server | work/install/Python-2.7.4/Demo/tkinter/ttk/roundframe.py | Python | gpl-2.0 | 5,601 | 0.000179 | """Ttk Frame with rounded corners.
Based on an example by Bryan Oakley, found at: http://wiki.tcl.tk/20152"""
import Tkinter
import ttk
root = Tkinter.Tk()
img1 = Tkinter.PhotoImage("frameFocusBorder", data="""
R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq
rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1... | QABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq
rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO
zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd
QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA
sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA
AHwAAIXYAOfxAIESAHwAAAB... | 8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA
AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA
AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL
AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF
APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A
AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6... |
PaulSonOfLars/tgbot | tg_bot/modules/translation.py | Python | gpl-3.0 | 1,574 | 0.000635 | import json
from pprint import pprint
import requests
from telegram import Update, Bot
from telegram.ext import CommandHandler
from tg_bot import dispatcher
# Open API key
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
URL = "http://services.gingersoftware.com/Ginger/correct/json/GingerTheText"
def translate(bot... |
sugg_str = suggestions[0].get('Text') # should look at this list more
curr_string += | msg.text[prev_end:start] + sugg_str
prev_end = end
curr_string += msg.text[prev_end:]
print(curr_string)
update.effective_message.reply_text(curr_string)
__help__ = """
- /t: while replying to a message, will reply with a grammar corrected version
"""
__mod_name__ = "Transl... |
carawarner/grasp | python/scripts/brute_searcher.py | Python | mit | 3,110 | 0.002572 | # pylint: disable=no-else-return
"""Adapted from an exercise in "Coding the Matrix". This script ingests
a text file, produces an index of the words in that text file, and allows
a user to search that index for one of more words. Validation is minimal.
"""
from string import punctuation
def make_inverse_index(strlist... | e.translate(None, punctuation + '\n').lower()
def search(index, query, operator='OR'):
"""Take a list of search terms and | return a set containing the line
numbers where all (output='AND') or some (output='OR') of the terms
can be found.
"""
values = []
sanitized_input = []
for term in query:
sanitized_input.append(sanitize(term))
for term in sanitized_input:
if term in index:
values... |
kamcpp/tensorflow | tensorflow/python/training/supervisor_test.py | Python | apache-2.0 | 33,571 | 0.01126 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | isor(logdir=logdir)
last_step = None
with sv.managed_session("") as sess:
for step in xrange(10):
last_step = step
if step == 3:
raise tf.errors.OutOfRangeError(my_op.op.node_def, my_op.op,
"all done")
else:
| sess.run(my_op)
# Supervisor has been stopped. OutOfRangeError was not thrown.
self.assertTrue(sv.should_stop())
self.assertEqual(3, last_step)
def testManagedSessionDoNotKeepSummaryWriter(self):
logdir = _test_dir("managed_not_keep_summary_writer")
with tf.Graph().as_default()... |
totalgood/nlpia | src/nlpia/book/examples/ch4_fix_accuracy_discrepancy.py | Python | mit | 2,729 | 0.001832 | """
>>> import pandas as pd
>>> from nlpia.data.loaders import get_data
>>> pd.options.display.width = 120 # <1>
>>> sms = get_data('sms-spam')
>>> | index = ['sms{}{}'.format(i, '!'*j) for (i,j) in\
... zip(range(len(sms)), sms.spam)] # <2>
>>> sms = pd.DataFrame(sms.values, columns=sms.columns, index=index)
>>> sms['spam'] = sms.spam.astype(int)
>>> len(sms)
"""
import pandas as pd
from nlpia.data.loaders import get_data
pd.options.display.width = 120 # <1>
... | s = pd.DataFrame(sms.values, columns=sms.columns, index=index)
sms['spam'] = sms.spam.astype(int)
len(sms)
"""
>>> import numpy as np
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> from nltk.tokenize import casual_tokenize
>>> np.random.seed(42)
>>> counter = CountVectorizer(tokenizer=casual_toke... |
rohitranjan1991/home-assistant | homeassistant/components/zwave_js/services.py | Python | mit | 21,186 | 0.001652 | """Methods and classes related to executing Z-Wave commands and publishing these to hass."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
import voluptuous as vol
from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import CommandStatus
from zw... | t[ZwaveNode] = set()
# Convert all entity IDs to n | odes
for entity_id in expand_entity_ids(self._hass, val.pop(ATTR_ENTITY_ID, [])):
try:
nodes.add(
async_get_node_from_entity_id(
self._hass, entity_id, self._ent_reg, self._dev_reg
)
... |
adukic/nd101 | tf-stanford-tutorials/assignments/chatbot/data.py | Python | mit | 9,394 | 0.004471 | """ A neural chatbot using sequence to sequence model with
attentional decoder.
This is based on Google Translate Tensorflow model
https://github.com/tensorflow/models/blob/master/tutorials/rnn/translate/
Sequence to sequence model by Cho et al.(2014)
Created by Chip Huyen as the starter code for assignment 3,
cla... | th open('config.py', 'ab') as cf:
if filename[-3:] == 'enc':
cf.write('ENC_VOCAB = ' + str(index) + '\n')
else:
cf.write('DEC_VOCAB = ' + str(index) + '\n')
break
f.write(word + '\n')
index +=... | with open(vocab_path, 'rb') as f:
words = f.read().splitlines()
return words, {words[i]: i for i in range(len(words))}
def sentence2id(vocab, line):
return [vocab.get(token, vocab['<unk>']) for token in basic_tokenizer(line)]
def token2id(data, mode):
""" Convert all the tokens in the data into th... |
zstackorg/zstack-woodpecker | integrationtest/vm/basic/vga/test_vm_vga.py | Python | apache-2.0 | 1,174 | 0.005111 | '''
New Integration Test for VM vga mode.
@author: quarkonics
'''
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.operations.config | _operations as conf_ops
impor | t zstackwoodpecker.test_util as test_util
test_stub = test_lib.lib_get_test_stub()
_config_ = {
'timeout' : 360,
'noparallel' : False
}
vm = None
default_mode = None
def test():
global vm
global default_mode
# default_mode = conf_ops.get_global_config_value('kvm', 'vi... |
cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/ARB/direct_state_access.py | Python | mit | 13,788 | 0.010371 | from OpenGLCffi.GL import params
@params(api='gl', prms=['n', 'ids'])
def glCreateTransformFeedbacks(n, ids):
pass
@params(api='gl', prms=['xfb', 'index', 'buffer'])
def glTransformFeedbackBufferBase(xfb, index, buffer):
pass
@params(api='gl', prms=['xfb', 'index', 'buffer', 'offset', 'size'])
def glTransformFeed... | ', prms=['framebuffer', 'src'])
def glNamedFramebufferReadBuffer(framebuffer, src):
pass
@params(api='gl', prms=['framebuffer', 'numAttachments', 'attachments'])
def glInvalidateNam | edFramebufferData(framebuffer, numAttachments, attachments):
pass
@params(api='gl', prms=['framebuffer', 'numAttachments', 'attachments', 'x', 'y', 'width', 'height'])
def glInvalidateNamedFramebufferSubData(framebuffer, numAttachments, attachments, x, y, width, height):
pass
@params(api='gl', prms=['framebuffer'... |
olivierverdier/SpecTraVVave | travwave/equations/kdv.py | Python | bsd-3-clause | 676 | 0.004438 | from __future__ import division
from .base import Equation
class KDV(Equation):
"""
The | equation is : -c*u + 3/4u^2 + (u + 1/6u")=0
"""
def degree(self):
return 2
def compute_kernel(self, k):
return 1.0-1.0/6*k**2
def flux(self, u):
return 0.75*u*u
def flux_prime(self, u):
return 1.5*u
class KDV3 (KDV):
def degree(self):
return 3
... |
class KDV5 (KDV):
def degree(self):
return 5
def flux(self, u):
return 0.5*u**5
def flux_prime(self, u):
return 2.5*u**4
|
xuru/restler | setup.py | Python | mit | 789 | 0.021546 | import os
from setuptools import setup
setup(
name = " | restler-serialization",
version = "0.3",
author = "Curtis Thompson",
author_email = "curtis.thompson@gmail.com",
description = "Restler provides flexible and configurable JSON and XML object serialization for the web",
license = "MIT",
keywords = "serialization json xml",
| url = "https://bitbucket.org/curtis/restler",
packages=['restler'],
long_description=open("README.txt").read(),
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP",
"To... |
bertmcmeyer/opti_ssr | opti_ssr_demo_headtracker.py | Python | mit | 1,936 | 0.002583 | """
A python module for demonstrating head orientation tracking for
binaural synthesis.
Usage: python opti_ssr_demo.py [SSR_IP] [SSR_port] [optitrack ip] [multicast address] [optitrack port] [end_message]
"""
import sys
from time import sleep
import opti_ssr
def demo(ssr_ip='localhost', ssr_port=4711, opti_unicast_... | i_port : int, optional
Port of the Motive network interface.
ssr_end_message : str, optional
Symbol to terminate the XML message sent to SSR. By default, a binary zero.
| """
# setting arguments if executed in command line
if sys.argv[1:]:
ssr_ip = str(sys.argv[1])
if sys.argv[2:]:
ssr_port = int(sys.argv[2])
if sys.argv[3:]:
opti_unicast_ip = str(sys.argv[3])
if sys.argv[4:]:
opti_multicast_ip = str(sys.argv[4])
if sys.argv[5:]:
... |
dnaextrim/django_adminlte_x | adminlte/static/plugins/datatables/extensions/ColReorder/examples/fixedheader.html.py | Python | mit | 17,099 | 0.036903 | XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX XXXXXXX X XXXXXXXXXXX XXXXXXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXX... | XXXXX
XXXX
XXXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXX XXXXXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXX
XXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX
XXXXX
XXXX
XXXXXXXXX XXXXXXXXXXXX
XXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXX
XX... | XXXXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX
XXXXX
XXXX
XXXXXXXXXXX XXXXXXXXXX
XXXXXXXXXXXXX XXXXXXXXXXXXX
XXXXXXXXXXXXXXX
XXXXXXXXXXX
XXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXX
XXXXX
XXXX
XXX... |
openstack/networking-l2gw | networking_l2gw/db/l2gateway/db_query.py | Python | apache-2.0 | 4,670 | 0 | # Copyright 2015 OpenStack Foundation
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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/LI... | elf, query, model, filters):
"""Apply filters to query for the models."""
if filters:
for key, value in | filters.items():
column = getattr(model, key, None)
if column:
query = query.filter(column.in_(value))
return query
def _model_query(self, context, model):
"""Query model based on filter."""
query = context.session.query(model)
qu... |
TextusData/Mover | thirdparty/protobuf-2.2.0/gtest/test/gtest_env_var_test.py | Python | gpl-3.0 | 3,472 | 0.005472 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# | All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted | provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following discla... |
tbarrongh/cosc-learning-labs | src/learning_lab/01_device_mounted.py | Python | apache-2.0 | 1,302 | 0.006912 | #!/usr/bin/env python2.7
# Copyright 2015 Cisco Systems, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | plain
import settings
def main():
print(plain(doc(mounted)))
device_names = settings.config['network_device'].keys()
if not device_names:
pri | nt('There are no devices configured in the settings.')
else:
device_name = next(iter(device_names))
print('is mounted(%s):' % device_name, mounted(device_name))
if __name__ == "__main__":
main()
|
holgern/pyyawt | pyyawt/__init__.py | Python | mit | 565 | 0 | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Holger Nahrstaedt
# See COPYING for license details.
|
"""
wavelet toolbox
"""
from __future__ import division, print_function, absolute_import
from .dwt import *
from .utility import *
from ._pyyawt import *
from .dwt1d import *
from .dwt2d import *
from .dwt3d import *
from .cowt import *
from .cwt import *
from .swt import *
from .denoising import *
from pyyawt.ver... | ith('_')]
test = Tester().test
|
MicroPyramid/Django-CRM | events/urls.py | Python | mit | 335 | 0 | from django.urls import pa | th
from events import views
app_name = "api_events"
urlpatterns = [
path("", views.EventListView.as_view()),
path("<int:pk>/", views.EventDetailView.as_view()),
path("comment/<int:pk>/", views.EventCommentView.as_view()),
path("attachment/<int:pk>/", views.EventAttac | hmentView.as_view()),
]
|
tboyce021/home-assistant | homeassistant/components/heos/config_flow.py | Python | apache-2.0 | 3,211 | 0.000934 | """Config flow to configure Heos."""
from urllib.parse import urlparse
from pyheos import Heos, HeosError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import ssdp
from homeassistant.const import CONF_HOST
from .const import DATA_DISCOVERED_HOSTS, DOMAIN
def format... | # Return form
host_type = (
str
if not self.hass.data[DATA_DISCOVERED_HOSTS]
| else vol.In(list(self.hass.data[DATA_DISCOVERED_HOSTS]))
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Required(CONF_HOST, default=host): host_type}),
errors=errors,
)
|
mrstu/flowbc_hamlee | scripts/nc2cell.flowsites.py | Python | gpl-2.0 | 2,528 | 0.021756 | #!/usr/bin/env python
import os
import os.path
import sys
import numpy as np
import pandas as pd
from netCDF4 import Dataset
from netCDF4 import num2date, date2num
def main(args):
ncfilein = args[0]
dimens = args[1].split(',') #"time,x" "Time,Index"
selvars = args[2].split(',')#"streamflo... | args[3].split(',') #"Index,5,8,20"
timefmt = args[4] # "%Y-%m-%d"
print args
kwargs={'dimens':dimens,
'selvars':selvars,
'seldim':seldim,
'timefmt':timefmt}
readnc(ncfilein,**kwargs)
def readnc(ncfilein,**kwargs):
'''Read nc file'''
rgrp = Dataset(ncfilein... | s=times.units, calendar=times.calendar)
dummy = np.zeros((ntimes,1))
df = pd.DataFrame(dummy,index=[date.strftime(kwargs['timefmt']) for date in dates])
dfs={}
if kwargs['seldim']:
seldimname=kwargs['seldim'][0]
selinds=kwargs['seldim'][1:]
if len(selinds) == 0 or no... |
MapofLife/MOL | earthengine/google-api-python-client/tests/test_model.py | Python | bsd-3-clause | 2,180 | 0.005963 | #!/usr/bin/python2.4
#
# Copyright 2010 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ions under the License.
"""Model tes | ts
Unit tests for model utility methods.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import unittest
from apiclient.model import makepatch
TEST_CASES = [
# (message, original, modified, expected)
("Remove an item from an object",
{'a': 1, 'b': 2}, {'a': 1}, {'b': ... |
linea-it/dri | api/product/migrations/0005_auto_20171212_1723.py | Python | gpl-3.0 | 523 | 0.001912 | # -*- coding: utf-8 -*-
# Generat | ed by Django 1.9.4 on 2017-12-12 17:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0004_auto_20171212_1252'),
]
operations = [
migrations.AlterField(
model_name='product... | me='prd_is_public',
field=models.BooleanField(default=False, help_text='Is Public default True', verbose_name='Is Public'),
),
]
|
varunarya10/python-openstackclient | openstackclient/shell.py | Python | apache-2.0 | 12,311 | 0.000081 | # Copyright 2012-2013 OpenStack Foundation
#
# 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 la... | ll, self).configure_logging()
root_logger = logging.getLogger('')
# Set logging to the requested level
if self.options.verbose_level == 0:
# --quiet
root_logger.setLevel(logging.ERRO | R)
elif self.options.verbose_level == 1:
# This is the default case, no --debug, --verbose or --quiet
root_logger.setLevel(logging.WARNING)
elif self.options.verbose_level == 2:
# One --verbose
root_logger.setLevel(logging.INFO)
elif self.options.v... |
IDSIA/sacred | tests/test_config/test_config_scope.py | Python | mit | 8,409 | 0.001308 | #!/usr/bin/env python
# coding=utf-8
import pytest
import sacred.optional as opt
from sacred.config.config_scope import (
ConfigScope,
dedent_function_body,
dedent_line,
get_function_body,
is_empty_or_comment,
)
from sacred.config.custom_containers import DogmaticDict, DogmaticList
@pytest.fixtu... | dedent_line(line, indent, expected):
assert dedent_line(line, indent) == expected
@pytest.mark.parametrize("line,expected", [
('', True),
(' ', True),
('\n', True),
(' \n', True),
(' \t \n', True),
('#comment', True),
(' #comment', True),
(' a=5 # not comment', False),
| ('a=5', False),
('"""', False),
("'''", False)
])
def test_is_empty_or_comment(line, expected):
assert is_empty_or_comment(line) == expected
def evil_indentation_func(a,
b,
c, d): # test comment
# Lets do the most evil things with indentation
# 1
# 2
# ran
... |
plotly/plotly.py | packages/python/plotly/plotly/validators/candlestick/_xsrc.py | Python | mit | 388 | 0.002577 | import _plotly_utils.basevalidators
class XsrcValidator(_plotly_utils.basevalid | ators.SrcValidator):
| def __init__(self, plotly_name="xsrc", parent_name="candlestick", **kwargs):
super(XsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
sonchang/python-agent | cattle/plugins/docker/__init__.py | Python | apache-2.0 | 3,232 | 0.000309 | import logging
from docker.utils import kwargs_from_env
from cattle import default_value, Config
log = logging.getLogger('docker')
_ENABLED = True
class DockerConfig:
def __init__(self):
pass
@staticmethod
def docker_enabled():
return default_value('DOCKER_ENABLED', 'true') == 'true'
... | def url_base():
return default_value('DOCKER_URL_BASE', None)
@staticmethod
def api_version():
return default_value('DOCKER_API_VERSION', '1 | .18')
@staticmethod
def docker_required():
return default_value('DOCKER_REQUIRED', 'true') == 'true'
@staticmethod
def delegate_timeout():
return int(default_value('DOCKER_DELEGATE_TIMEOUT', '120'))
@staticmethod
def use_boot2docker_connection_env_vars():
use_b2d = def... |
michal-ruzicka/archivematica | src/MCPServer/lib/RPCServer.py | Python | agpl-3.0 | 4,756 | 0.005046 | #!/usr/bin/python -OO
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica 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, e... |
databaseInterface.sqlLock.release()
return None
def getJobsAwaitingApproval():
ret = etree.Element("choicesAvailableForUnits")
dbStatus = verifyDatabaseIsNotLocked()
if dbStatus:
#print etree.tostring(dbStatus)
return etree.tostring(dbStatus)
for UUID, choice in choicesAvail... | hoice.xmlify())
return etree.tostring(ret, pretty_print=True)
def approveJob(jobUUID, chain, agent):
print "approving: ", jobUUID, chain, agent
if jobUUID in choicesAvailableForUnits:
choicesAvailableForUnits[jobUUID].proceedWithChoice(chain, agent)
return "approving: ", jobUUID, chain
def ge... |
lucarebuffi/OASYS1 | oasys/widgets/tools/ow_surface_file_merger.py | Python | gpl-3.0 | 8,735 | 0.003892 | import os, sys
import numpy
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtWidgets import QApplication, QMessageBox, QLabel, QSizePolicy
from PyQt5.QtGui import QTextCursor, QFont, QPalette, QColor, QPixmap
from matplotlib import cm
from oasys.widgets.gui import FigureCanvas3D
from matplotlib.figure import Figure
f... | z_2 = data.zz
else:
QMessageBox.critical(self, "Error",
"Data Type #2 not recognized",
QMessageBox.Ok)
def compute(self, plot_data=False):
try:
if not self.xx_1 is None and not self.xx_2 is Non... | yy_1 = self.yy_1
zz_1 = self.zz_1
xx_2 = self.xx_2
yy_2 = self.yy_2
zz_2 = self.zz_2
if not (len(xx_1) == len(xx_2) and
len(yy_1) == len(yy_1) and
round(xx_1[0], 6) == round(xx_2[0]... |
polyaxon/polyaxon-api | polyaxon_lib/processing/input_data.py | Python | mit | 4,360 | 0.001147 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import tensorflow as tf
from tensorflow.python.estimator.inputs.numpy_io import numpy_input_fn
from tensorflow.python.estimator.inputs.pandas_io import pandas_input_fn
from polyaxon_lib.libs import getters
def create_input_dat... | An input function that returns `(feature_batch, labels_batch)`
tuples when called.
"""
pipeline_config = pipeline_config
if input_type == 'NUMPY':
# setup_train_data_feeder
return numpy_input_fn(x, y,
| batch_size=pipeline_config.batch_size,
num_epochs=pipeline_config.num_epochs,
shuffle=pipeline_config.shuffle,
num_threads=pipeline_config.num_threads)
if input_type == 'PANDAS':
# setup_train_da... |
timothydmorton/transit | setup.py | Python | mit | 4,320 | 0 | #!/usr/bin/env python
# encoding: utf-8
import re
import os
try:
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
except ImportError:
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext as _build_ext
de... | ecial_functions",
"ellint_3.hpp")
if os.path.exists(path):
# Determine the version.
vf = os.path.join(d, "boost", "version.hpp")
if not os.path.exists(vf):
continue
src = open(vf, "r").read()
v = | re.findall("#define BOOST_LIB_VERSION \"(.+)\"", src)
if not len(v):
continue
v = v[0]
if verbose:
print("Found Boost version {0} in: {1}".format(v, d))
return d
return None
class build_ext(_build_ext):
"""
A custom extension ... |
samuel/kokki | kokki/cookbooks/librato/metadata.py | Python | bsd-3-clause | 560 | 0.028571 |
__description__ = "Librato Silverline process monitoring and management"
__confi | g__ = {
"librato.api_token": dict(
description = "API token for account",
default = "0",
),
"librato.server_id_cmd": dict(
description = "Command to run to generate server ID",
d | efault = None,
),
"librato.template_id": dict(
description = "Template ID for this server",
default = None,
),
"librato.email_address": dict(
description = "Email address of account",
default = None,
),
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.