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 |
|---|---|---|---|---|---|---|---|---|
zplab/rpc-scope | scope/simple_rpc/property_client.py | Python | mit | 8,483 | 0.00224 | # This code is licensed under the MIT License (see LICENSE file for details)
import collections
import threading
import traceback
import zmq
from ..util import trie
class PropertyClient(threading.Thread):
"""A client for receiving property updates in a background thread.
The background thread is automaticall... | lback(new_value);
if valueonly is False, it will be called as callback(property_name, new_value).
Multiple callbacks can be registered for a single property_name.
"""
self.callbacks[property_name].add((callback, valueonly))
def unsubscribe(self, property_name, callback, valueonly=F... | previously registered callback. If
the same callback function is registered multiple times with identical
property_name and valueonly parameters, only one registration is removed."""
if property_name is None:
raise ValueError('property_name parameter must not be None.')
try:... |
stregoika/aislib | aisutils/uscg.py | Python | gpl-3.0 | 18,764 | 0.012737 | #!/usr/bin/env python
__version__ = '$Revision: 2275 $'.split()[1]
__date__ = '$Date: 2006-07-10 16:22:35 -0400 (Mon, 10 Jul 2006) $'.split()[1]
__author__ = 'Kurt Schwehr'
__doc__ = '''
Connect to a socket and forward what is received to another port.
Filter to a list of AIS receivers/basestations.
@author: '''+__au... | ite(out,indent+' seqId = '+match_obj.group('seqId')+'\n')
write(out,indent+' chan = '+match_obj.group('chan')+'\n')
write(out,indent+' body = '+match_obj.group('b | ody')+'\n')
write(out,indent+' fillBits = '+match_obj.group('fillBits')+'\n')
write(out,indent+' checksum = '+match_obj.group('checksum')+'\n')
write(out,indent+' slot = '+match_obj.group('slot')+'\n')
write(out,indent+' s = '+match_obj.group('s')+'\n')
write(out,i... |
BCCVL/org.bccvl.tasks | src/org/bccvl/tasks/datamover/zoatrack.py | Python | gpl-2.0 | 8,153 | 0.000981 | from __future__ import absolute_import
import logging
import io
import os
import os.path
import shutil
import tempfile
import urllib
import zipfile
import csv
from datetime import datetime
from org.bccvl import movelib
from org.bccvl.movelib.utils import build_source, build_destination
from org.bccvl.movelib.utils imp... | #'bccvlmetadata': bccvlmd,
| 'filemetadata': extract_metadata(trait_zip, 'application/zip'),
}
# Add the number of trait records to the metadata
# To do: This is a hack. Any better solution.
trait_csv_filename = os.path.join('data', 'zoatrack_trait.csv')
if trait_csv_filename in item['filemetadata']:
... |
waylan/mkdocs | mkdocs/config/defaults.py | Python | bsd-2-clause | 5,554 | 0.002161 | from mkdocs.config import config_options
# NOTE: The order here is important. During validation | some config options
# depend on others. So, if config option A depends on B, then A should be
# listed higher in the schema.
# Once we drop Python 2.6 support, this could be an OrderedDict, however, it
# isn't really needed either as we alwa | ys sequentially process the schema other
# than at initialisation when we grab the full set of keys for convenience.
def get_schema():
return (
# Reserved for internal use, stores the mkdocs.yml config file.
('config_file_path', config_options.Type(str)),
# The title to use for the docum... |
galou/symoro | pysymoro/inertia.py | Python | mit | 7,964 | 0.000377 | # -*- coding: utf-8 -*-
# This file is part of the OpenSYMORO project. Please see
# https://github.com/symoro/symoro/blob/master/LICENCE for the licence.
"""
This module contains the functions for the computation of Inertia
matrix.
"""
import sympy
from sympy import Matrix
from pysymoro.geometry import compute_r... | 0]
)
| inertia_a11 = symo.mat_replace(
inertia_a11, 'Jcomp', 0, forced=True, symmet=True
)
# setup inertia_a12 in Matrix form
a12mat = sympy.zeros(6, robo.NL)
for j in xrange(1, robo.NL):
a12mat[:, j] = inertia_a12[j]
a12mat = a12mat[:, 1:]
# setup the complete inertia matrix
in... |
dadavidson/Python_Lab | LP2THW/ex09.py | Python | mit | 418 | 0 | # ex09.py: Printing, Printing, Printing
# Here's some new strange stuff, | remember type it exactly.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFed\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days: ", days
print "Here are the months: ", months
print """
There's something going on here.
With the three double-quotes.
We'll be able to | type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
|
MyRookie/SentimentAnalyse | venv/lib/python2.7/site-packages/nltk/metrics/confusionmatrix.py | Python | mit | 7,825 | 0.001278 | # Natural Language Toolkit: Confusion Matrices
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Edward Loper <[email protected]>
# Steven Bird <[email protected]>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import print_function, unicode_literals
from nltk.... |
"""
if len(reference) != len(test):
| raise ValueError('Lists must have the same length.')
# Get a list of all values.
if sort_by_count:
ref_fdist = FreqDist(reference)
test_fdist = FreqDist(test)
def key(v): return -(ref_fdist[v]+test_fdist[v])
values = sorted(set(reference+te... |
benschmaus/catapult | telemetry/telemetry/internal/util/wp_server_unittest.py | Python | bsd-3-clause | 2,645 | 0.002647 | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this sou | rce code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import sys
import unittest
from telemetry.internal.util import wpr_server
# pylint: disable=protected-access
class CreateCommandTest(unitte | st.TestCase):
def testHasDnsGivesDnsPort(self):
expected_cmd_line = [
sys.executable, 'replay.py', '--host=127.0.0.1',
'--port=2', '--ssl_port=1', '--dns_port=0',
'--use_closest_match', '--log_level=warning', '--extra_arg', 'foo.wpr']
cmd_line = wpr_server.ReplayServer._GetCommandLine(... |
heartherumble/django-twittersync | twittersync/templatetags/twittersync_tags.py | Python | bsd-3-clause | 2,179 | 0.002295 | from django.conf import settings
from django import template
from twittersync.models import TwitterAccount, TwitterStatus
register = template.Library()
class LatestTweets(template.Node):
def __init__(self, account, limit, varname):
self.account = account
self.limit = limit
self.varname = ... | he value set in
settings.TWITTERSYNC_LATEST_TWEETS. If that
isn't set, we fall back to 5
'''
bits = token.split_contents()
if len(bits) < 4:
raise template.TemplateSyntaxError(
'"%s" tag takes at least 3 arguments' % bits[0]
)
limit = None
try:
... |
limit = getattr(settings, 'TWITTERSYNC_LATEST_TWEETS', 5)
try:
# needed because it may not be passed via the
# template token.
limit = parser.compile_filter(limit)
except TypeError:
pass
return LatestTweets(
parser.compile_filter(account),
limit,
... |
lxneng/incubator-airflow | airflow/contrib/task_runner/cgroup_task_runner.py | Python | apache-2.0 | 8,763 | 0.001141 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | ied cgroup.
:param path: The path of the cgroup to create.
E.g. cpu/mygroup/mysubgroup
:return: the Node associated with the created cgroup.
:rtype: cgroupspy.nodes.Node
"""
node = trees.Tree().root
path_split = path.split(os.sep)
for path_element in path... | s in %s", path_element, node.path)
node = node.create_cgroup(path_element)
else:
self.log.debug(
"Not creating cgroup %s in %s since it already exists",
path_element, node.path
)
node = name_to_node[path_... |
ESOedX/edx-platform | openedx/core/djangoapps/theming/storage.py | Python | agpl-3.0 | 13,828 | 0.003616 | """
Comprehensive Theming support for Django's collectstatic functionality.
See https://docs.djangoproject.com/en/1.8/ref/contrib/staticfiles/
"""
from __future__ import absolute_import
import os.path
import posixpath
import re
from django.conf import settings
from django.contrib.staticfiles.finders import find
from ... | by the given theme otherwise returns False.
Args:
name: asset name e.g. 'images/logo.png'
theme: theme name e.g. 'red-theme', 'edx.org'
Re | turns:
True if given asset override is provided by the given theme otherwise returns False
"""
if not is_comprehensive_theming_enabled():
return False
# in debug mode check static asset from within the project directory
if settings.DEBUG:
themes_locat... |
lotharwissler/bioinformatics | python/misa/exonic-ssrs-to-genes.py | Python | mit | 3,457 | 0.028348 | #!/usr/bin/python
import os, sys # low level handling, such as command line stuff
import string # string methods available
import re # regular expressions
import getopt # coman | d line argument handling
from low import * # custom functions, written by myself
from misa import Mis | aSSR
from collections import defaultdict
# =============================================================================
def show_help( ):
""" displays the program parameter list and usage information """
stdout( "usage: " + sys.argv[0] + " -e <path> -g <path> ")
stdout( " " )
stdout( " option descriptio... |
baroquebobcat/pants | tests/python/pants_test/init/test_repro.py | Python | apache-2.0 | 1,540 | 0.012987 | # 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 os
import uni... | 'bar')
add_file('baz.txt', 'baz')
add_file('qux/quux.txt', 'quux')
repro_file = os.path.join(tmpdir, 'repro.tar.gz')
repro = Repro(repro_file, fake_buildroot, ['.git', 'dist'])
repro.capture(run_info_dict={'foo': 'bar', 'baz': 'qux'})
|
extract_dir = os.path.join(tmpdir, 'extract')
TGZ.extract(repro_file, extract_dir)
assert_file = partial(self.assert_file, extract_dir)
assert_file('baz.txt', 'baz')
assert_file('qux/quux.txt', 'quux')
assert_file('repro.sh')
assert_not_exists = partial(self.assert_not_exist... |
DivineHime/seishirou | lib/multidict/__init__.py | Python | gpl-3.0 | 1,162 | 0 | """Multidict implementation.
HTTP Headers and URL query string require specific data structure:
multidict. It behaves mostly like a dict but it can have
several values for the same key.
"""
import os
__all__ = ('MultiDictProxy', 'CIMultiDictProxy',
'MultiDict', 'CIMultiDict', 'upstr', 'istr')
__version__... | IMultiDict,
upstr, istr)
except ImportError: # pragma: no cover
| from ._multidict_py import (MultiDictProxy,
CIMultiDictProxy,
MultiDict,
CIMultiDict,
upstr, istr)
|
petrjasek/superdesk-core | superdesk/macros/imperial/volume_cubic_inches_to_metric_test.py | Python | agpl-3.0 | 1,669 | 0.004194 | # -*- 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
import unitt... | 16 cu-in (16-262 cubic centimeter)")
self.assertEqual(diff["1-16 cb. in"], "1-16 cb. in (16-262 cubic centimeter)")
self.assertEqual(diff["16.7-Cubic | -in"], "16.7-Cubic-in (273.7 cubic centimeter)")
self.assertEqual(diff["16,500-cu. in"], "16,500-cu. in (0.3 cubic meter)")
self.assertEqual(res["body_html"], item["body_html"])
|
ktsaou/netdata | collectors/python.d.plugin/python_modules/pyyaml2/scanner.py | Python | gpl-3.0 | 52,661 | 0.002279 | # SPDX-License-Identifier: MIT
# Scanner produces tokens of the following types:
# STREAM-START
# STREAM-END
# DIRECTIVE(name, value)
# DOCUMENT-START
# DOCUMENT-END
# BLOCK-SEQUENCE-START
# BLOCK-MAPPING-START
# BLOCK-END
# FLOW-SEQUENCE-START
# FLOW-MAPPING-START
# FLOW-SEQUENCE-END
# FLOW-MAPPING-END
# BLOCK-ENTRY
... | er of unclosed '{' and '['. `flow_level == 0` means block
# context.
self.flow_level = 0
# List of processed tokens that are not yet emitted.
self.tokens = []
# Add the STREAM-START token.
self.fetch_stream_start()
# Number of tokens that were emitted through t... | # Variables related to simple keys treatment.
# A simple key is a key that is not denoted by the '?' indicator.
# Example of simple keys:
# ---
# block simple key: value
# ? not a simple key:
# : { flow simple key: value }
# We emit the KEY token b... |
morfeokmg/maurrepo | src/Examples/CmdClient.py | Python | gpl-2.0 | 4,875 | 0.03159 | '''
Copyright (c) <2012> Tarek Galal <[email protected]>
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, including without limitation the rights to use, copy, modify,
m... | ABLE 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.
'''
from Yowsup.connectionmanager import YowsupConnectionManager
import time, datetime, sys
if sys.version_info >... | ber, keepAlive = False, sendReceipts = False):
self.sendReceipts = sendReceipts
self.phoneNumber = phoneNumber
self.jid = "%[email protected]" % phoneNumber
self.sentCache = {}
connectionManager = YowsupConnectionManager()
connectionManager.setAutoPong(keepAlive)
#connectionManager.setAutoPong(True)
... |
maraujop/django-crispy-forms | crispy_forms/tests/test_tags.py | Python | mit | 6,908 | 0.001013 | import pytest
import django
from django.forms.boundfield import BoundField
from django.forms.formsets import formset_factory
from django.template import Context, Template
from crispy_forms.exceptions import CrispyError
from crispy_forms.templatetags.crispy_forms_field import crispy_addon
from .conftest import only_b... | igure out how to render it
# Not sure if this is expected behavior -- @kavdev
error_class = CrispyError if settings.DEBUG else AttributeError
with pytest.raises(error_class):
template.render(c)
def test_as_crispy_field_bound_field():
template = Template(
"""
{% load crispy_for... | ield|as_crispy_field }}
"""
)
form = SampleForm({"password1": "god", "password2": "god"})
form.is_valid()
c = Context({"field": form["password1"]})
# Would raise exception if not a field
html = template.render(c)
assert "id_password1" in html
assert "id_password2" not in html
de... |
alisaifee/limits | limits/aio/storage/base.py | Python | mit | 2,931 | 0.000341 | from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Tuple
from limits.storage.registry import StorageRegistry
from limits.util import LazyDependency
class Storage(LazyDependency, metaclass=StorageRegistry):
"""
Base class to extend when implementing an async storage backend.
.. ... | str) -> int:
"""
resets the rate limit key
:param key: the key to clear rate limits for
"""
raise NotImplementedError
class MovingWindowSupport(ABC):
"""
Abstract base for stora | ges that intend to support
the moving window strategy
.. warning:: This is a beta feature
.. versionadded:: 2.1
"""
async def acquire_entry(
self, key: str, limit: int, expiry: int, amount: int = 1
) -> bool:
"""
:param key: rate limit key to acquire an entry in
... |
SmartJog/spvd | share/baseplugin.py | Python | lgpl-2.1 | 11,049 | 0.001629 | """ BasePlugin definitions. """
import logging
import threading
import traceback
import os
import queue
from sjutils import threadpool
class BasePluginError(Exception):
"""Raised by BasePlugin."""
def __init__(self, error):
"""Init method."""
Exception.__init__(self, error)
class BasePlugi... | it_group = [
group.strip()
for group in self.params["limit_group"].split(",")
if group.strip()
]
if len(self.limit_group) == 1:
| self.limit_group = self.limit_group[0]
# Limiting checks
self.limit_check = None
if self.params["limit_check"]:
self.limit_check = [
check.strip()
for check in self.params["limit_check"].split(",")
if check.strip()
]
... |
ddico/server-tools | base_search_fuzzy/models/__init__.py | Python | agpl-3.0 | 136 | 0 | # -*- coding: utf-8 -*-
# Licen | se AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import ir_model
from | . import trgm_index
|
walterbender/fractionbounce | FractionBounceActivity.py | Python | gpl-3.0 | 21,894 | 0.000868 | # -*- coding: utf-8 -*-
# Copyright (c) 2011-14, Walter Bender
# Copyright (c) 2011 Paulina Clares, Chris Rowe
# Ported to GTK3 - 2012:
# Ignacio Rodríguez <[email protected]>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p... | Button
from sugar3.graphics.toolbarbox import To | olbarBox
from sugar3.graphics.toolbarbox import ToolbarButton
from sugar3.graphics.toolbutton import ToolButton
from sugar3.graphics.radiotoolbutton import RadioToolButton
from sugar3.graphics.alert import NotifyAlert
from sugar3.graphics import style
from collabwrapper import CollabWrapper
from gettext import gettex... |
amwelch/a10sdk-python | a10sdk/core/aam/aam_authentication_relay_form_based_instance_request_uri.py | Python | apache-2.0 | 3,904 | 0.008709 | from a10sdk.common.A10BaseClass import A10BaseClass
class CookieValue(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param cookie_value: {"minLength": 1, "maxLength": 127, "type": "string", "description": "Specify cookie in POST packet", "format": "string-rlx"}
:pa... | aram uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type" | : "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/aam/authentication/relay/form-based/instance/{name}/request-uri/{match_type}+{uri}`.
"""
def ... |
ikvk/imap_tools | tests/messages_data/rfc2822/example07.py | Python | apache-2.0 | 1,101 | 0.004541 | import datetime
from imap_tools import EmailAddress
DATA = dict(
subject='Re: Saying Hello',
from_='[email protected]',
to=('[email protected]',),
cc=(),
bcc=(),
re | ply_to=(),
date=datetime.datetime(1997, 11, 21, 11, 0, tzinfo=datetime.timezone(datetime.timedelta(-1, 64800))),
date_str='Fri, 21 Nov 1997 11:00:00 -0600',
text='This is a reply to your reply.\r\n',
html='',
headers={'to': ('"Mary Smith: Personal Account" <[email protected]>',), 'from': ('John Doe... | : Saying Hello',), 'date': ('Fri, 21 Nov 1997 11:00:00 -0600',), 'message-id': ('<[email protected]>',), 'in-reply-to': ('<[email protected]>',), 'references': ('<[email protected]> <[email protected]>',)},
attachments=[],
from_values=EmailAddress('John Doe', '[email protected]', 'John Doe <... |
reubano/tabutils | meza/fntools.py | Python | mit | 34,504 | 0.000058 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
meza.fntools
~~~~~~~~~~~~
Provides methods for functional manipulation of content
Examples:
basic usage::
>>> from meza.fntools import underscorify
>>>
>>> header = ['ALL CAPS', 'Illegal $%^', 'Lots of space']
... | >>> sorted(kw) == ['key_1', 'key_2', 'key_3']
True
>>> dict(kw) == {'key_1': 1, 'key_2': 2, 'key_3': 3}
True
>>> k | w.key_1
1
>>> kw['key_2']
2
>>> kw.get('key_3')
3
>>> kw.key_4
>>> kw.get('key_4')
>>> kw['key_4'] = 4
>>> kw.key_4 == kw.get('key_4') == kw['key_4'] == 4
True
>>> kw.key_4 = 5
... |
maheshcn/memory-usage-from-ldfile | openpyxl/tests/test_strings.py | Python | gpl-2.0 | 1,270 | 0 | # Copyright (c) 2010-2015 openpyxl
# package imports
from openpyxl.reader.strings import read_string_table
from openpyxl.tests.helper import co | mpare_xml
def test_read_string_table(datadir):
datadir.join('reader').chdir()
src = 'sharedStrings.xml'
with open(src) as content:
assert read_string_table(content.read()) == [
'This is cell A1 in Sheet 1', 'This is cell G5']
def test_empty_string(datadir):
datadir.jo | in('reader').chdir()
src = 'sharedStrings-emptystring.xml'
with open(src) as content:
assert read_string_table(content.read()) == ['Testing empty cell', '']
def test_formatted_string_table(datadir):
datadir.join('reader').chdir()
src = 'shared-strings-rich.xml'
with open(src) as content:
... |
bjorncooley/maleo | courses/migrations/0006_auto_20151019_1127.py | Python | mit | 552 | 0.001812 | # -*- coding: utf-8 -*-
from __future__ import uni | code_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0005_studentcourseprofile_skill_level'),
]
operations = [
migrations.AlterField(
model_name='studentcourseprofile',
name='skill_level',
... | ', choices=[('beginner', 'Beginner'), ('intermediate', 'Intermediate'), ('advanced', 'Advanced')]),
),
]
|
blurstudio/cross3d | cross3d/maya/mayascenemodel.py | Python | mit | 17,183 | 0.026712 | import re
import maya.cmds as cmds
import maya.OpenMaya as om
import cross3d
from collections import OrderedDict
from cross3d.abstract.abstractscenemodel import AbstractSceneModel
resolutionAttr = 'resolution'
#------------------------------------------------------------------------
class MayaSceneModel... | ault(key, {}).setdefault('setAttr', {}).update(value=value, command=s)
return modified
def _attrName(self):
return '{node}.{attr}'.format(n | ode=self._nativeName(), attr=resolutionAttr)
def __init__(self, scene, nativeObject):
super(MayaSceneModel, self).__init__(scene, nativeObject)
def addResolution(self, name='', path='', load=False):
if self.isReferenced():
reses = self.userProps().get('resolutions', OrderedDict())
reses[name] = ... |
SUSE/azure-sdk-for-python | azure-mgmt-web/azure/mgmt/web/models/network_access_control_entry.py | Python | mit | 1,490 | 0.000671 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | e.
:type order: int
:param remote_subnet: Remote subnet.
:type remote_subnet: str
"""
_attribute_map = {
'action': {'key': 'action', 'type': 'AccessControlEntryAction'},
'description': {'key': 'description', 'type': 'str'},
'order': {'key': 'order', 'type': 'int'},
'... | type': 'str'},
}
def __init__(self, action=None, description=None, order=None, remote_subnet=None):
self.action = action
self.description = description
self.order = order
self.remote_subnet = remote_subnet
|
satyrius/cmsplugin-articles | cmsplugin_articles/south_migrations/0002_auto__add_teaserextension.py | Python | mit | 8,573 | 0.007699 | # -*- 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):
# Adding model 'TeaserExtension'
db.create_table(u'cmsplugin_articles_tea... | ': "('tree_id', 'lft')", 'unique_together': "(('publisher_is_draft', 'application_namespace'), ('reverse_id', 'site', 'publ | isher_is_draft'))", 'object_name': 'Page'},
'application_namespace': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'application_urls': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '200', 'null': 'True', 'blank':... |
NCLAB2016/DF_STEALL_ELECTRIC | nn.py | Python | gpl-3.0 | 5,327 | 0.017646 | from __future__ import print_function
import tensorflow as tf
import numpy as np
from six.moves import cPickle as pickle
from sklearn.decomposition import PCA
from sklearn import preprocessing
import random
dataset = '/media/dat1/liao/dataset/new_new_try/'
train_data_filename = dataset + 'train_data_statis.pickle'
tra... | _subset = range(0,1200) + range(2800, 9900)
#valid_subset = range(1200, 2800)
#train_data = train_data[train_subset | ]
#train_label = train_label[train_subset]
#valid_data = train_data[valid_subset]
#valid_label = train_label[valid_subset]
#tf_test_data = tf.constant(test_data)
train_data = preprocessing.normalize(train_data, norm='l2')
#valid_data = preprocessing.normalize(valid_data, norm='l2')
print ('Training set', train_data.... |
clarkduvall/JSOL | passer.py | Python | apache-2.0 | 1,058 | 0.00189 | #!/usr/bin/env python
# Copyright 2012 Clark DuVall
#
# 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... | nt json.dumps(fib, indent=3)
print 'Passing to other instance...'
with | open('examples/jsol/part2.jsol') as f:
jsol.Eval(json.load(f), argv=fib)
|
dimoynwa/DLivescore | data/match.py | Python | gpl-2.0 | 3,878 | 0.001805 | from datetime import datetime, timedelta
import time
class Match:
def __init__(self, json):
i = (int)(json['_links']['competition']['href'].rfind('/') + 1)
self.competitionId = (int)(json['_links']['competition']['href'][i:])
ind = (int)(json['_links']['self']['href'].rfind('/') + 1)... | mins | = mins - 15
return (str)(mins) + '\''
else:
return self.status
def refresh(self, json):
if self.status == 'FINISHED':
return
newHomeGoals = json['result']['goalsHomeTeam']
newAwayGoals = json['result']['goalsAwayTeam']
self.stat... |
picoCTF/picoCTF | picoCTF-shell/hacksport/deploy.py | Python | mit | 40,196 | 0.002264 | import logging
from subprocess import CalledProcessError
import tarfile
"""
Handles deployment of an installed problem.
Deploying a problem means creating one or more instances, which are each
templated with flags, the shell server URL, etc., and assigned a port
(if required for their problem type).
Flags and assign... | instances mu | st still be created individually on each shell server,
as server URLs must be templated appropriately, dependencies potentially
need to be installed on each server, and the underlying files, users and
service definitions that make up a deployed instance are specific to each
shell server.
"""
HIGHEST_PORT = 65535
LOWES... |
UNINETT/nav | tests/unittests/eventengine/alerts_test.py | Python | gpl-2.0 | 2,574 | 0 | from unittest import TestCase
import datetime
from nav.models.event import EventQueue as Event, Subsystem, EventType
from nav.models.manage import Netbox, Device
from nav.eventengine.alerts import AlertGenerator
class MockedAlertGenerator(AlertGenerator):
def get_alert_type(self):
return None
def _fi... | lf.assertEqual(alert.subid, self.event.subid)
self.assertEqual(alert.state, | self.event.state)
self.assertEqual(alert.time, self.event.time)
self.assertEqual(alert.value, self.event.value)
self.assertEqual(alert.severity, self.event.severity)
def test_alert_from_event_copies_variables(self):
self.event.varmap = dict(foo='bar', parrot='dead')
... |
david-vavra/pyrage | pyrage/modules/dns.py | Python | gpl-2.0 | 1,216 | 0.004934 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2014 David Vavra ([email protected])
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 of the Lice... | ributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this pro... | t, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
from yapsy.IPlugin import IPlugin
class DNS(IPlugin):
def __init__(self):
self.hosts = {}
def addHost(self,id,host):
self.hosts[id] = host
def parseContext(self,context,*a... |
cloudify-cosmo/cloudify-manager | cloudify_types/cloudify_types/component/__init__.py | Python | apache-2.0 | 832 | 0 | # Copyright (c) 2017-2019 Cloudify Platform Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | ations import refresh # NO | QA
|
reidlindsay/wins | sandbox/experiments/aloha/infocom/parse-per.py | Python | apache-2.0 | 6,546 | 0.010541 | #! /usr/bin/env python
"""
Parse PER vs. SINR data from trace files.
Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2011-10-19 17:04:02 -0500 (Wed, 19 Oct 2011) $
* $LastChangedRevision: 5220 $
:author: Ketan Mandke <[email protected]>
:copyright:
Copyright 2009-2011 The Unive... | = formats[k%len(formats)]
if not trace: continue
sys.stderr.write("Parsing trace from %s ...\n"%(tfile))
# parse actual PER from trace
param, data = parse_per_info(options, trace)
if data:
parameters = copy(default_parameters)
parameters.up | date(param)
parameters['source'] = tfile
parameters['format'] = fmt[0]
assert (param['label'] is not None)
parsed_data = {'parameters': parameters, 'data': data}
sys.stdout.write("%s\n"%(parsed_data) )
# parse model PER from trace
param, data =... |
akarambir/shadow | shadow/prod_settings.py | Python | mit | 685 | 0.00292 | from .settings import *
# Enforce secret key from environment
SECRET_KEY = os.environ.get("NAINOMICS_KEY")
ALLOWED_HOSTS = [
'.nainomics.in',
]
CSRF_COOKIE_SECURE = True
SESSION_COOKIE | _SECURE = True
CONN_MAX_AGE = True
import dj_email_url
email_config = dj_email_url.config()
EMAIL_FILE_PATH = email_config['EMAIL_FILE_PATH']
EMAIL_HOST_USER = email_config['EMAIL_HOST_USER']
EMAIL_HOST_PASSWORD = email_config['EMAIL_HOST_PASSWORD']
EMAIL_HOST = email_config['EMAIL_HOST']
EMAIL_PORT = email_config['... | AIL_USE_TLS = email_config['EMAIL_USE_TLS']
#Settings for myks-contact
CONTACT_EMAILS = ['[email protected]']
|
Rignak/Scripts-Python | DeepLearning/_Others/OCR/callback.py | Python | gpl-3.0 | 2,311 | 0.000865 | from os.path import join
from keras.callbacks import Callback
import matplotlib.pyplot as plt
class PlotLearnin | g(Callback):
"""Callback generating a fitness plot in a file after each epoch"""
def __init__(self, exam | ples=False):
super().__init__()
self.i = 0
self.x = []
self.losses = []
self.val_losses = []
self.acc = []
self.val_acc = []
self.logs = []
self.examples = examples
def on_epoch_end(self, epoch, logs={}):
plt.ioff()
self.logs.a... |
iulian787/spack | var/spack/repos/builtin/packages/r-quantreg/package.py | Python | lgpl-2.1 | 1,540 | 0.003896 | # Copyright 2013-2020 Lawrence Livermore N | ational 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 RQuantreg(RPackage):
"""Estimation and inference methods for models of conditional quantiles:
Linear and nonli | near parametric and non-parametric (total variation
penalized) models for conditional quantiles of a univariate response
and several methods for handling censored survival data. Portfolio
selection methods based on expected shortfall risk are also
included."""
homepage = "https://cl... |
Smile-SA/odoo_addons | smile_api_rest/models/api_rest_path.py | Python | agpl-3.0 | 24,554 | 0.000041 | # -*- coding: utf-8 -*-
# (C) 2022 Smile (<https://www.smile.eu>)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from copy import deepcopy
from odoo import api, fields, models, _
from odoo.tools import safe_eval
MAPPING_FIELDS_SWAGGER = {
'binary': ('string', 'binary'),
'boolean': ('boolea... | lf.tag_id and [self.tag_id.name or ''] or [],
'description': self.description or '',
'deprecated': self.deprecated,
'produces': ['application/json'],
'responses': {
'200': {
'description': 'OK',
},
'401':... | '$ref': '#/definitions/ApiErrorResponse'
}
},
'403': {
'description': 'Forbidden',
'schema': {
'$ref': '#/definitions/ApiErrorResponse'
}
},
'404': {
... |
bit-bots/imagetagger | src/imagetagger/users/forms.py | Python | mit | 473 | 0 | from django import forms
from django_registration.forms i | mport RegistrationForm
from .models import Team, User
class UserRegistrationForm(RegistrationForm):
class Meta(RegistrationForm.Meta):
model = User
fields = [
'username',
'email',
'password1',
'password2',
]
| class TeamCreationForm(forms.ModelForm):
class Meta:
model = Team
fields = [
'name',
]
|
dreipol/smallinvoice | smallinvoice/time.py | Python | mit | 292 | 0.003425 | # coding=utf-8
from smallinvoice.commons import BaseJsonEncodableObject, BaseSer | vice
class Time(BaseJsonEncodabl | eObject):
def __init__(self, start, end, date):
self.start = start
self.end = end
self.date = date
class TimeService(BaseService):
name = 'time' |
NineWoranop/loadtesting-kpi | loadtesting/ThirdPartyTools/grinder-3.11/examples/ejb.py | Python | apache-2.0 | 1,893 | 0.007924 | # Enterprise Java Beans
#
# Exercise a stateful session EJB from the Oracle WebLogic Server
# examples. Additionally this script demonstrates the use of the
# ScriptContext sleep(), getThreadId() and getRunNumber() methods.
#
# Before running this example you will need to add the EJB client and
# the WebLogic classes t... | mport grinder
from net.grinder.script import Test
from weblogic.jndi import WLInitialContextFactory
tests = {
"home" : Test(1, "TraderHome"),
"trade" : Test(2, | "Trader buy/sell"),
"query" : Test(3, "Trader getBalance"),
}
# Initial context lookup for EJB home.
p = Properties()
p[Context.INITIAL_CONTEXT_FACTORY] = WLInitialContextFactory.name
home = InitialContext(p).lookup("ejb20-statefulSession-TraderHome")
tests["home"].record(home)
random = Random()
class TestR... |
petef4/payg | test_eff_min.py | Python | mit | 10,146 | 0.000591 | import eff_min
import pytest
TOL = 6 # tolerance, compare to this number of decimal places
MEAN_PER_CALL_DATA = (
# (maximum, minimum, per_minute, charge_interval, connection=0)
(30, 60, 20, 60), (60, 60, 20, 60),
(120, 60, 20, 60), (180, 60, 20, 60),
(30, 60, 20, 1), (60, 60, 20, 1),
(120, 60, 2... | ge_per_call(1, 0, 2 | 0, 6), TOL) == 0
assert round(2 - charge_per_call(6, 0, 20, 6), TOL) == 0
assert round(4 - charge_per_call(7, 0, 20, 6), TOL) == 0
assert round(4 - charge_per_call(12, 0, 20, 6), TOL) == 0
assert round(10 - charge_per_call(1, 60, 0, 600, 10), TOL) == 0
assert round(10 - charge_per_call(6, 60, 0, 60... |
kevinlee12/oppia | scripts/run_presubmit_checks.py | Python | apache-2.0 | 3,619 | 0 | # Copyright 2019 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | ng
- Backend Python tests
Only when frontend files are changed will it run Frontend Karma unit tests.
"""
from __future__ import annotations
import argparse
import subprocess
from . import common
from . import run_backend_tests
from . import run_frontend_tests
from .linters import pre_ | commit_linter
_PARSER = argparse.ArgumentParser(
description="""
Run this script from the oppia root folder prior to opening a PR:
python -m scripts.run_presubmit_checks
Set the origin branch to compare against by adding
--branch=your_branch or -b=your_branch
By default, if the current branch tip exists on rem... |
mdrasmus/argweaver | argweaver/deps/compbio/coal.py | Python | mit | 66,593 | 0.00039 | """
Coalescent methods
A note about popu | lation size. In this code all population sizes N or n are
uncorrected. If you need to | compute a coalescent for a diploid species
you must multiply N by 2 before passing it to any of these functions.
"""
#=============================================================================
# imports
from __future__ import division
# python imports
from itertools import chain, izip
from math import exp, log, ... |
ajfranke/subscrape | processtitles.py | Python | gpl-2.0 | 1,317 | 0.006834 | #!/usr/bin/python
import pandas as pd
import numpy as np
import time, datetime
# script to load data as raw csv, and add columns to data frame
infilename = "Homebrewing_titles_1214239837_1424289414.csv"
columns = ['row_id', 'post_id', 'score', 'time','title']
# row is an integer
# post_id is a alphanumeric integer. ... | estamp, in decimal
# Word is a string consisting of | a single word or symbol
frame = pd.read_csv(infilename, names=columns, sep='\t', header=1)
dayofweek = [datetime.datetime.fromtimestamp(x).isocalendar()[2] for x in frame['time']]
isoweek = [datetime.datetime.fromtimestamp(x).isocalendar()[1] for x in frame['time']]
dayofyear = [datetime.datetime.fromtimestamp(x).utc... |
cedrick-f/pySequence | src/lien.py | Python | gpl-3.0 | 36,961 | 0.016217 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
##This file is part of pySequence
#############################################################################
#############################################################################
## ##
## ... | pe that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pySequence; if not,... | *
"""
import os, sys, subprocess
import wx
import re
from util_path import toFileEncoding, toSystemEncoding, SYSTEM_ENCODING
from widgets import messageErreur, scaleImage, Grammaire, img2str, str2img
import images
from drag_file import *
from util_path import *
from file2bmp import *
# from dpi_aware import *
SSCALE ... |
tgquintela/pySpatialTools | pySpatialTools/tests/test_api.py | Python | mit | 96 | 0 |
"""
test api
--------
test for api functions to improve usability.
| """
def test(): |
pass
|
OCA/account-invoicing | account_move_exception/wizard/account_exception_confirm.py | Python | agpl-3.0 | 724 | 0 | # Copyright 2021 ForgeFlow (http://www.forgeflow.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import fields, models
class AccountExceptionConfirm(models.TransientModel):
_name = "account.exception.confi | rm"
_description = "Account exception wizard"
_inherit = ["exception.rule.confirm"]
related_model_id = fields.Many2one(
comodel_name="account.move", string="Journal Entry"
)
def action_confirm(self):
self.ensure_one()
if self.ignore:
self.related_model_id.button... | odel_id.action_post()
return super().action_confirm()
|
Bideau/SmartForrest | RaspberryPi/dataBase/oldmysql/testmultitarg.py | Python | mit | 651 | 0.012289 |
def test(*args):
if len(args) == 2:
print "le premier argument est : " + str(args[0])
print "le second arguement est : " + str(args[1])
| elif len(args) == 3:
print "le premier argument est : " + str(args[0])
print "le second arguement est : " + str(args[1])
print "le second arguement est : " + str(args[2])
else:
print "bad parameter"
#programme
arg1 = "toto"
arg2 = "titi"
arg3 = "tata"
arg4 = "rien"
print "debi... | test(arg1)
print "test 3"
test(arg1,arg2)
print "test 4"
test(arg1,arg2,arg3)
print "test 5"
test(arg1,arg2,arg3,arg4) |
UTSA-ICS/keystone-kerberos | keystone/tests/unit/test_ldap_tls_livetest.py | Python | apache-2.0 | 4,402 | 0.000227 | # Copyright 2013 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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 app... | 'name': 'fake1',
'password': 'fakepass1',
'tenants': ['bar']}
self.identity_api.create_user('fake1', user)
user_ref = self.identity_api.get_user('fake1')
self.assertEqual('fake1', user_ref['id'])
user['password'] = 'fakepass2'
self.identity_a... | self.identity_api.delete_user('fake1')
self.assertRaises(exception.UserNotFound, self.identity_api.get_user,
'fake1')
def test_tls_bad_certfile(self):
self.config_fixture.config(
group='ldap',
use_tls=True,
tls_req_cert='demand',
... |
devilry/devilry-django | devilry/devilry_import_v2database/tests/test_modelimporters/test_deliveryimporter.py | Python | bsd-3-clause | 9,808 | 0.002243 | import unittest
from django import test
from django.conf import settings
from model_bakery import baker
from devilry.devilry_group.models import FeedbackSet, GroupComment
from devilry.devilry_import_v2database.modelimporters. | delivery_feedback_importers import DeliveryImporter
from .importer_testcase_mixin import ImporterTest | CaseMixin
@unittest.skip('Not relevant anymore, keep for history.')
class TestDeliveryImporterImporter(ImporterTestCaseMixin, test.TestCase):
def _create_model_meta(self):
return {
'model_class_name': 'Delivery',
'max_id': 143,
'app_label': 'core'
}
def _cr... |
mor1/pyrt | ospf.py | Python | gpl-2.0 | 26,560 | 0.012387 | #! /usr/bin/env python2.5
## PyRT: Python Routeing Toolkit
## OSPF module: provides the OSPF listener and OSPF PDU parsers
## Copyright (C) 2010 Richard Mortier <[email protected]>
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Publ... | b routers (where metric == 0xffffff > LSInfinity, 0xffff)
# RFC 3623 -- Graceful restart
# RFC 3630 -- Traffic engineering extensions
## LSUPD/LSA notes:
# router id:
# the IP address of the router that generated the packet
# advrtr:
# the IP address of the advertising router
# src:
# the IP address of th | e interface from which the LSUPD came
# link state id (lsid):
# identifier for this link (interface) dependent on type of LSA:
# 1 (router) ID of router generating LSA
# 2 (network) IP address of DR for LAN
# 3 (summary IP) IP address of link reported as dst
# 4 (summary ASBR) IP ad... |
tanmoy7989/idp | runmd.py | Python | gpl-3.0 | 5,497 | 0.019465 | #!/usr/bin/env python
import os, sys
import numpy as np
import pickleTraj
import sim
Verbose = False
DelTempFiles = True
useREMD = True
# Basic params
TempSet = 300.0
FORCEFIELD_FILE = None
Prefix = 'modtrj'
BoxL = None
# MD settings
StepsMin = 1000
StepsEquil = 500000
StepsProd = 5000000
StepFreq = 100
StepsSwap =... | LammpsWrite, FileName = MultiTrajFn)
np.savetxt(MultiEneFn, MultiEne, fmt = '%11.4e')
return MultiTraj, MultiEne, MultiTrajFn, MultiEneFn
def ReorderAllTraj(Sys, TrajFile, LogFile):
TrajFnList = []
EneFnList = []
for i, t in enumerate(Temps):
print 'Reordering replica at temperature '... | , TrajFile = TrajFile, LogFile = LogFile,
MultiTrajFn = Prefix + '.lammpstrj.gz.%3.2f' % t,
MultiEneFn = Prefix + '.ene.dat.%3.2f' % t)
TrajFnList.append(this_TrajFn)
En... |
elba7r/system | erpnext/stock/doctype/landed_cost_voucher/landed_cost_voucher.py | Python | gpl-3.0 | 4,474 | 0.023692 | # 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.utils import flt
from frappe.model.document import Document
from erpnext.stock.doctype.serial_no.serial_no import... | r d in self.get("purchase_receipts"):
if frappe.db.get_value(d.receipt_document_type, d.receipt_document, "docstatus") != 1:
frappe.throw(_("Receipt document must be submitted"))
else:
receipt_documents.append(d.receipt_document)
for item in self.get | ("items"):
if not item.receipt_document:
frappe.throw(_("Item must be added using 'Get Items from Purchase Receipts' button"))
elif item.receipt_document not in receipt_documents:
frappe.throw(_("Item Row {idx}: {doctype} {docname} does not exist in above '{doctype}' table")
.format(idx=item.idx, doc... |
datacratic/Diamond-old | src/collectors/openstackswift/openstackswift.py | Python | mit | 3,925 | 0.00051 | # coding=utf-8
"""
Openstack swift collector.
#### Dependencies
* swift-dispersion-report commandline tool (for dispersion report)
if using this, make sure swift.conf and dispersion.conf are reable by diamond
also get an idea of the runtime of a swift-dispersion-report call and make
sure the collect interv... | t': 'swift auth acco | unt (for enable_container_metrics)',
'user': 'swift auth user (for enable_container_metrics)',
'password': 'swift auth password (for enable_container_metrics)',
'containers': 'containers on which to count number of objects, '
+ 'space separated list (for enable_container_... |
ericholscher/django | django/conf/urls/__init__.py | Python | bsd-3-clause | 2,589 | 0.003476 | from importlib import import_module
from django.core.urlresolvers import (RegexURLPattern,
RegexURLResolver, LocaleRegexURLResolver)
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
__all__ = ['handler400', 'handler403', 'handler404', 'handler500', 'include', 'patterns', 'url'... | # callable returning a namespace hint
if namespace:
raise ImproperlyConfigured('Cannot override the namespace for a dynamic module that provides a namespace')
urlconf_module, app_name, namespace = arg
else:
# | No namespace hint - use manually provided namespace
urlconf_module = arg
if isinstance(urlconf_module, six.string_types):
urlconf_module = import_module(urlconf_module)
patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
# Make sure we can iterate through the patterns (witho... |
sffjunkie/hiss | src/hiss/handler/kodi/jsonrpc/__init__.py | Python | apache-2.0 | 145 | 0.013793 | # Copyright (c) 2014 Simon Kennedy <[email protected]>.
class RPCError(Exception):
pa | ss
class RPCResponseError(RPCError):
p | ass
|
iniverno/RnR-LLC | simics-3.0-install/simics-3.0.31/amd64-linux/lib/python/mod_ppc440gx_turbo_commands.py | Python | gpl-2.0 | 293 | 0.006826 | import ppc_commands
ppc_model = | 'ppc440gx'
funcs = {}
ppc_commands.setup_local_functions(ppc_model, funcs)
class_funcs = { ppc_model: funcs }
ppc_commands.enabl | e_generic_ppc_commands(ppc_model)
ppc_commands.enable_4xx_tlb_commands(ppc_model)
ppc_commands.enable_440_tlb_commands(ppc_model)
|
lgrech/MapperPy | mapperpy/test/conversions/test_datetime_conversion.py | Python | bsd-3-clause | 6,813 | 0.003816 | import | unittest
from assertpy import assert_that
from mapperpy.test.common_test_classes import *
| from mapperpy import OneWayMapper, ObjectMapper
from datetime import datetime
__author__ = 'lgrech'
class DateTimeConversionTest(unittest.TestCase):
def test_map_from_datetime_it_target_type_not_known(self):
# given
mapper = OneWayMapper.for_target_class(TestClassSomePropertyEmptyInit2)
... |
diefans/debellator | src/implant/master.py | Python | apache-2.0 | 5,656 | 0.001768 | """Controlles a bunch of remotes."""
import asyncio
import functools
import logging
import os
import pathlib
import signal
import sys
import traceback
from implant import commands, connect, core, testing
log = logging.getLogger(__name__)
PLUGINS_ENTRY_POINT_GROUP = 'implant.plugins'
def parse_command(line):
"""... | .ensure_future(self.feed_stdin_to_remotes(remotes), loop=self.loop)
def _sigint_handler():
log.info('SIGINT...')
never_ending.cancel()
self.l | oop.add_signal_handler(signal.SIGINT, _sigint_handler)
try:
await never_ending
except asyncio.CancelledError:
log.debug('Cancelled')
pass
feeder.cancel()
await feeder
def main(debug=False, log_config=None):
log.info('deballator master process: ... |
tombstone/models | research/delf/delf/python/training/model/export_global_model.py | Python | apache-2.0 | 5,972 | 0.004856 | # Lint as: python3
# Copyright 2020 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 ... | D, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Export g | lobal feature tensorflow inference model.
This model includes image pyramids for multi-scale processing.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
import tensorflow as tf
from delf.python.tr... |
s390guy/SATK | asma/asmbase.py | Python | gpl-3.0 | 85,139 | 0.016127 | #!/usr/bin/python3.3
# Copyright (C) 2015-2017 Harold Grovesteen
#
# This f | ile is part of SATK.
#
# SATK 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.
#
# | SATK is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public Licen... |
naokiur/circle-ci-demo | backend/employee/api/views.py | Python | apache-2.0 | 863 | 0 | import time
from datetime import datetime
from logging import getLogger
# from django.contrib.auth.models import User, Group
from rest_framework.views import APIView
from employee.api.models import Employee, Login
# from employee.api.serializers import UserSerializer, GroupSerializer
from employee.api.serializers imp... | st, format=None):
self.logger.info('get method')
queryset = Login.objects.all()
self.logger.info(querys | et)
# serializer = LoginSerializer(queryset)
# return Response(serializer.data)
return Response()
|
olivierkes/bible_libre | biblification_2.py | Python | unlicense | 3,439 | 0.001459 | #!/usr/bin/python
# -*- coding: utf8 -*-
import csv
import argparse
import re
if __name__ == "__main__":
# Parsing arguments
parser = argparse.ArgumentParser(description='This generates a t2t bible.')
parser.add_argument('-p', '--plan', help='plan to be used',
default="nouveau-tes... | r':sup:`\1:\2` '
elif showMarks:
s = r"° "
else:
s = r""
t = a.sub(s, t)
return t
def getText(book, startChapter, startVerse, endChapter, endVerse):
"Renvoie le texte demandé."
r = ""
f = open('textes/' + book + ".txt", 'r')
te... | .close()
start = text.find("[{}:{}]".format(startChapter, startVerse))
end = text.find("[{}:{}]".format(endChapter, str(int(endVerse) + 1)))
if end < 0: # Chapitre suivant
end = text.find("[{}:{}]".format(str(int(endChapter) + 1), 1))
if end < 0: # Fin du livre
... |
huggingface/pytorch-transformers | src/transformers/models/bart/modeling_tf_bart.py | Python | apache-2.0 | 70,462 | 0.003917 | # coding=utf-8
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. 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/... | Model,
TFSharedEmbeddings,
TFWrappedEmbeddings,
input_processing,
keras_serializable,
shape_list,
)
from ...utils import logging
from .configuration_bart import BartConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "facebook/bart-large"
_CONFIG_FOR_DOC = "BartConfig"
_TOKENIZER_F... | decoder_start_token_id: int):
shifted_input_ids = tf.roll(input_ids, 1, axis=-1)
start_tokens = tf.fill((shape_list(shifted_input_ids)[0], 1), decoder_start_token_id)
shifted_input_ids = tf.concat([start_tokens, shifted_input_ids[:, 1:]], -1)
# replace possible -100 values in labels by `pad_token_id`
... |
clalancette/pycdlib | pycdlib/facade.py | Python | lgpl-2.1 | 36,359 | 0.001403 | # Copyright (C) 2019 Chris Lalancette <[email protected]>
# 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;
# version 2.1 of the License.
# This library is distributed in the hope th... | _ import absolute_import
from pycdlib import dr
from pycdlib import pycdlibexception
from pycdlib import udf as udfmod
from pycdlib import utils
# For mypy annotations
if False: # pylint: disable=using-constant-test
from typing import BinaryIO, Generator, Optional, Tuple # NOQA pylint: disable=unused-import
... | ylint: disable=unused-import
from pycdlib import pycdlibio # NOQA pylint: disable=unused-import
def iso_path_to_rr_name(iso_path, interchange_level, is_dir):
# type: (str, int, bool) -> str
"""
Take an absolute ISO path and generate a corresponding Rock Ridge basename.
Parameters:
iso_path ... |
ismail-s/warehouse | tests/unit/utils/test_paginate.py | Python | apache-2.0 | 2,849 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | ]))
with pytest.rai | ses(RuntimeError):
len(wrapper)
def test_elasticsearch_page_has_wrapper(monkeypatch):
page_obj = pretend.stub()
page_cls = pretend.call_recorder(lambda *a, **kw: page_obj)
monkeypatch.setattr(paginate, "Page", page_cls)
assert paginate.ElasticsearchPage("first", second="foo") is page_obj
... |
kauralasoo/Blood_ATAC | scripts/postprocessCrossmap.py | Python | apache-2.0 | 728 | 0.026099 | import subprocess
import os
import argparse
import gzip
parser = argparse.ArgumentParser(description = "Postprocess the VCF file creat | ed by the CrossMap to make it valid again.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--vcf", help = "Path to the VCF file.")
args = parser.parse_args()
vcf_file = gzip.open(args.vcf)
contigs = dict()
for line in vcf_file:
line = line.rstrip()
if(line[0] == "#"):
print(line)
i... | n contigs):
print("\t".join(fields)) #Only keep SNPs that fall into contigs mentioned in the header
|
darfire/screp | setup.py | Python | gpl-3.0 | 1,503 | 0.005323 | #!/usr/bin/env python
# Bootstrap installation of Distribute
import distribute_setup
distribute_setup.use_setuptools()
import os
from setuptools import setup
PROJECT = u'screp'
VERSION = '0.3.2'
URL = 'https://github.com/darfire/screp'
AUTHOR = u'Doru Arfire'
AUTHOR_EMAIL = u'[email protected]'
DESC = u'Command... | quires,
entry_points = {
'console_scripts': [
'screp=screp.main:main',
],
},
classifiers=[
# -*- Classifiers -*-
'License :: OSI Approved',
'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)',
"Programming Language... | ,
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Development Status :: 4 - Beta',
'Environment :: Console',
'Topic :: Internet :: WWW/HTTP',
],
)
|
amdorra/django-kvmodel | kvmodel/models.py | Python | mit | 1,100 | 0 | """
Example
-------
class SystemSetting(KVModel):
pass
setting = SystemSetting.create(key='foo', value=100)
loaded_setting = SystemSetting.get_by_key('foo')
"""
from django.db imp | ort models
|
from .fields import SerializableField
class KVModel(models.Model):
"""
An Abstract model that has key and value fields
key -- Unique CharField of max_length 255
value -- SerializableField by default could be used to store bool, int,
float, str, list, dict and date
"""
key = m... |
googlei18n/fontuley | src/third_party/fontTools/Lib/fontTools/ttLib/tables/_h_h_e_a.py | Python | apache-2.0 | 2,656 | 0.030873 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc import sstruct
from fontTools.misc.textTools import safeEval
from . import DefaultTable
hheaFormat = """
> # big endian
tableVersion: 16.16F
ascent: h
descent: ... | Y:
# No glyph has outlines.
minLeftSideBearing = 0
| minRightSideBearing = 0
xMaxExtent = 0
self.advanceWidthMax = advanceWidthMax
self.minLeftSideBearing = minLeftSideBearing
self.minRightSideBearing = minRightSideBearing
self.xMaxExtent = xMaxExtent
else:
# XXX CFF recalc...
pass
def toXML(self, writer, ttFont):
formatstring, names, fi... |
DannyLee1991/article_cosine_similarity | utils/log.py | Python | apache-2.0 | 873 | 0.00578 | import time
def progress(index, size, for | _what='当前进度', step=10):
block_size = int(size / step)
if index % block_size == 0:
crt = int(index / block_size)
print('%s ==> [%d / %d]' % (for_what, crt, step))
def log_time():
def _log_time(func):
# func()
def wrapper(*args, **kwargs):
print("start")
... | ime()
cost_time = end_time - start_time
print("[%s] cost time -> %s" % (func.__name__, cost_time))
return result
return wrapper
return _log_time
def line(log_str, style='-'):
print(style * 12 + str(log_str) + style * 12)
def block(style="-",w=100,h=5):
for _ ... |
safwanrahman/drf-spirit | drf_spirit/serializers.py | Python | mit | 975 | 0.001026 | from rest_framework.serializers import ModelSerializer, SerializerMethodField
from .fields import UserReadOnlyFiled
from .models import Topic, Category, Comment
from .relations import PresentableSlugRelatedField
class CategorySerializer(ModelSerializer):
class Meta:
model = Category
fields = '__... | l__'
class CommentSerializer(ModelSerializer):
user = UserReadOnlyFiled()
class Meta:
model = Comment
fields = | '__all__'
|
DiplomadoACL/problemasenclase | Problema2/problema2crocha.py | Python | lgpl-3.0 | 1,040 | 0.04845 | #Hecho en python 3.5
from gutenberg.acqui | re import load_etext
from gutenberg.cleanup import strip_headers
librosCodigo = {"Francés":[13735,13808],"Español":[24925,15027],"Portugés":[14904,16384],"Inglés":[10422,1013]}
dic_idiomas={}
#hola dos
for idioma in librosCodigo.keys():
| diccionario_largo_palabras={}
for indeCo in librosCodigo[idioma]:
texto= strip_headers(load_etext(indeCo))
dic_idiomas[idioma]= diccionario_largo_palabras
for caracter_especial in ['"',"...","¿","?","=","_","[","]","(",")",",",".",":",";","!","¡","«","»","*","~","' "," '","- "," -","--"]:
... |
open-mmlab/mmdetection | configs/sparse_rcnn/sparse_rcnn_r50_fpn_mstrain_480-800_3x_coco.py | Python | apache-2.0 | 853 | 0 | _base_ = './sparse_rcnn_r50_fpn_1x_coco.py'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
min_values = (480, 512, 544, 576 | , 608, 640, 672, 704, 736, 768, 800)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Resize',
img_scale=[(1333, value) for value in min_values],
multiscale_mode='value',
keep_ratio=True),
dict(type='RandomFlip',... | type='Collect', keys=['img', 'gt_bboxes', 'gt_labels'])
]
data = dict(train=dict(pipeline=train_pipeline))
lr_config = dict(policy='step', step=[27, 33])
runner = dict(type='EpochBasedRunner', max_epochs=36)
|
mirrorcoder/paramiko | paramiko/util.py | Python | lgpl-2.1 | 8,572 | 0.00035 | # Copyright (C) 2003-2007 Robey Pointer <[email protected]>
#
# 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 (a... | 0x80):
negative = 1
if len(s) % 4:
filler = zero_byte
if negative:
filler = max_byte
# never convert this to ``s +=`` because this is a string, not a number
# noinspection PyAugmentAssignment
s = filler * (4 - len(s) % 4) + s
for i in range(0, len(s),... | i + 4])[0]
if negative:
out -= long(1) << (8 * len(s))
return out
deflate_zero = zero_byte if PY2 else 0
deflate_ff = max_byte if PY2 else 0xff
def deflate_long(n, add_sign_padding=True):
"""turns a long-int into a normalized byte string
(adapted from Crypto.Util.number)"""
# after much ... |
jabooth/menpodetect | menpodetect/ffld2/detect.py | Python | bsd-3-clause | 5,711 | 0.0007 | from __future__ import division
from functools import partial
from pathlib import Path
from menpo.base import MenpoMissingDependencyError
try:
from cyffld2 import (load_model, detect_objects,
get_frontal_face_mixture_model)
except ImportError:
raise MenpoMissingDependencyError('cyffld... | fld2 detector.
Wraps an ffld2 object detector inside the menpodetect framework and
provides a clean interface to expose the ffld2 arguments.
"""
def __init__(self, model):
self._detector = _ffld2_detect(model)
def __call__(self, image, greyscale=True, image_diagonal=None,
... | ction using the cached ffdl2 detector.
The detections will also be attached to the image as landmarks.
Parameters
----------
image : `menpo.image.Image`
A Menpo image to detect. The bounding boxes of the detected objects
will be attached to this image.
g... |
UK992/servo | tests/wpt/web-platform-tests/tools/third_party/html5lib/html5lib/tests/test_sanitizer.py | Python | mpl-2.0 | 5,540 | 0.002527 | from __future__ import absolute_import, division, unicode_literals
from html5lib import constants, parseFragment, serialize
from html5lib.filters import sanitizer
def runSanitizerTest(_, expected, input):
parsed = parseFragment(expected)
expected = serialize(parsed,
omit_optional_tag... | continue # TODO
if attribute_name == 'style':
continue
attribute_value = 'foo'
if attribute_name in sanitizer.attr_val_is_uri:
attribute_value = '%s://sub.domain.tld/path/object.ext' % sanitizer.allowed_protocols[0]
yield (runSanitizerTest, "test_should_allow_%s... | _value),
"<p %s='%s'>foo <bad>bar</bad> baz</p>" % (attribute_name, attribute_value))
for protocol in sanitizer.allowed_protocols:
rest_of_uri = '//sub.domain.tld/path/object.ext'
if protocol == 'data':
rest_of_uri = 'image/png;base64,aGVsbG8gd29ybGQ='
yield (runS... |
plotly/python-api | packages/python/plotly/plotly/validators/bar/_y.py | Python | mit | 480 | 0 | import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.DataArrayValidato | r):
def __init__(self, plotly_name="y", parent_name="bar", **kwargs):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
anim=kwargs.pop("anim", True),
edit_type=kwargs.pop("edit_type", "calc+clear | AxisTypes"),
role=kwargs.pop("role", "data"),
**kwargs
)
|
catkin/catkin_tools | catkin_tools/execution/events.py | Python | apache-2.0 | 2,304 | 0.001302 | # Copyright 2016 Open Source Robotics Foundation, 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... | _id, **kwargs):
"""Create a new event.
:param event_id: One of the valid EVENT_IDS
:param **kwargs: The additional data to be passed along with this event.
"""
# Store the time this event was generated
self.time = time.time()
# Make sure the event ID is valid
... | # Store the event data
self.event_id = event_id
self.data = kwargs
|
dvdmgl/django-pg-fts | pg_fts/utils.py | Python | bsd-2-clause | 1,343 | 0.000745 |
class TranslationDictionary(object):
"""
TranslationDictionary
"""
def __init__(self, dictionaries=None, default=None):
self.dictionaries = dictionaries or {
'pt': ('portuguese', _('Portuguese')),
'en': ('english', _('English')),
'es': | ('spanish', _('Spanish')),
'de': ('german', _('German')),
'da': ('danis | h', _('Danish')),
'nl': ('dutch', _('Dutch')),
'fi': ('finnish', _('Finnish')),
'fr': ('french', _('French')),
'hu': ('hungarian', _('Hungarian')),
'it': ('italian', _('Italian')),
'nn': ('norwegian', _('Norwegian')),
'ro': ('romanian',... |
crcresearch/osf.io | tests/test_serializers.py | Python | apache-2.0 | 21,918 | 0.002327 | # -*- coding: utf-8 -* | -
import mock
import datetime as dt
from nose.tools import * # noqa (PEP8 asserts)
import pytest
from osf_tests.factories import (
ProjectFactory,
U | serFactory,
RegistrationFactory,
NodeFactory,
CollectionFactory,
)
from osf.models import NodeRelation
from tests.base import OsfTestCase, get_default_metaschema
from framework.auth import Auth
from website.project.views.node import _view_project, _serialize_node_search, _get_children, _get_readable_descen... |
clarete/storagelib | storagelib.py | Python | agpl-3.0 | 10,480 | 0.001527 | # -*- Coding: utf-8; Mode: Python -*-
#
# storagelib.py - A simple and extensible storage library
#
# Copyright (C) 2010 Lincoln de Sousa <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free... | by each storage, like ssh
for extra_attr in storage.extra_attrs:
if cfg.has_option(i, extra_attr):
setattr(storage, extra_attr, cfg.get(i, extra_attr))
self.repo_list.append(storage)
def sort_repos(self):
"""Sorts repositories in order of precede... | storages)
# let's copy the sorted list above
unordered = |
danieltellez/career | career/models.py | Python | gpl-2.0 | 2,454 | 0.007335 | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from hvad.models import TranslatableModel, TranslatedFields
from hvad.manager import TranslationManager
class Quiz(TranslatableModel):
short_description = models.CharField(max_length=128)
translations = Translated... | nManager):
def get_questions_for_quiz(self, quiz):
return self.get_query_set().filter(quiz=quiz).order_by('order')
class Question(TranslatableModel):
short_description = models.CharField(max_length=128)
quiz = models.ForeignKey('Quiz')
order = models.IntegerField(null=True, blank=True)
tran... | ion = models.TextField(null=True, blank=True),
help_text = models.TextField(null=True, blank=True)
)
objects = QuestionManager()
class QuizToCareer(models.Model):
quiz = models.ForeignKey('Quiz')
career = models.ForeignKey('Career')
passed = models.BooleanField(default=False)
due_date... |
cosmoharrigan/matrix-entropy | main.py | Python | gpl-3.0 | 1,624 | 0.000616 | """
Python implementation of the matrix information measurement examples from the
StackExchange answer written by WilliamAHuber for
"Measuring entropy/ information/ patterns of a 2d binary matrix"
| http://stats.stackexchange.com/a/17556/43909
Copyright 2014 Cosmo Harrigan
This program is free software, distributed under the terms of the GNU LGPL v3.0
"""
__author__ = 'Cosmo Harrigan'
from matplotlib import pyplot
from neighborhood_functions import avg_components
from moving_window_filter im | port moving_window_filter
from calculate_profile import profile
# Function to apply
F = avg_components
# Define the matrices as input_matrices
from data import *
# Iterate over the input matrices
for m in range(0, len(input_matrices)):
active_matrix = input_matrices[m]
print("---------\nMatrix #{0}\n--------... |
olivierkes/manuskript | manuskript/exporter/pandoc/__init__.py | Python | gpl-3.0 | 3,708 | 0.001888 | #!/usr/bin/env python
# --!-- coding: utf8 --!--
import subprocess
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import qApp, QMessageBox
from manuskript.exporter.basic import basicExporter, basicFormat
from manuskript.exporter.pandoc.HTML import HTML
from manuskript.exporter.pandoc... | exporter.pandoc.plainText import reST, markdown, latex, OPML
from manuskript.functions import mainWindow
import logging
LOGGER = logging.getLogger(__name__)
class pandocExporter(basicExporter):
name = "Pandoc"
description = qApp.translate("Export", """<p>A universal docum | ent converter. Can be used to convert Markdown to a wide range of other
formats.</p>
<p>Website: <a href="http://www.pandoc.org">http://pandoc.org/</a></p>
""")
cmd = "pandoc"
absentTip = "Install pandoc to benefit from a wide range of export formats (DocX, ePub, PDF, etc.)"
absentURL = "http://... |
selective-inference/selective-inference | selectinf/sandbox/bayesian/estimator.py | Python | bsd-3-clause | 29,896 | 0.006456 | import numpy as np
import regreg.api as rr
from selection.randomized.glm import pairs_bootstrap_glm, bootstrap_cov
from selection.randomized.query import query
from selection.randomized.randomization import split
import functools
def pairs_bootstrap_glm(glm_loss,
active,
... | = np.zeros(active.shape, np.float)
z[group] = self.initial_soln[group] / np.linalg.norm(self.initial_soln[group])
active_directions.append( | z)
initial_scalings.append(np.linalg.norm(self.initial_soln[group]))
if unpenalized_groups[i]:
unpenalized[group] = True
# solve the restricted problem
self._overall = active + unpenalized
self._inactive = ~self._overall
self._unpenalized = u... |
plotly/plotly.py | packages/python/plotly/plotly/validators/bar/marker/colorbar/title/font/_color.py | Python | mit | 455 | 0 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self,
plotly_name="color",
| parent_name="bar.marker.colorbar.title.font",
**kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent | _name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
**kwargs
)
|
fabricehong/zim-desktop | zim/stores/xml.py | Python | gpl-2.0 | 3,065 | 0.028059 | # -*- coding: utf-8 -*-
# Copyright 2008 Jaap Karssenberg <[email protected]>
'''This module reads an XML file defining zim pages.
For now the only XML tags which are supported are 'section' and 'page'. The
'section' tag serves as a container for multiple pages. The 'page' tag serves
as a container for the ... | t Path
from zim.parsing import TextBuffer
class XMLStore(zim.stores.memory.MemoryStore):
properties = {
'read-only': True
}
def __init__(self, notebook, path, file=None):
zim.stores.memory.MemoryStore.__init__(self, notebook, path)
self.file = file
if not se | lf.store_has_file():
raise AssertionError, 'XMl store needs file'
# not using assert here because it could be optimized away
self.format = get_format('wiki') # FIXME store format in XML header
if self.file.exists():
self.parse(self.file.read())
def store_page(self, page):
memory.Store.store_page(self, ... |
engineeringbird/python_tests | test.py | Python | mit | 313 | 0.009585 | print("This is a test")
answer = raw_input("Please give me an | answer ")
print("Thank you " + answer)
def print_yes():
if answer == "yes":
print("YAS!")
else:
print("Hello World!")
print_yes()
kind_message = raw_input(answer + " you are a un | ique snowflake")
print(kind_message)
|
lawsie/guizero | examples/after_repeat.py | Python | bsd-3-clause | 629 | 0.009539 | from guizero import App, PushButt | on, TextBox
def welcome():
print("Welcome")
def hi():
print("Hi")
def message(my_message):
print(my_message)
def whatever():
| # say whatever using the message function, passing the text as an argument
app.after(200, message, args=["Whatever"])
def cancel_hi():
app.cancel(hi)
app = App()
# create some buttons
hi_button = PushButton(app, cancel_hi, text="Stop hi")
what_button = PushButton(app, whatever, text="Whatever")
# after ... |
Aerojspark/PyFR | pyfr/readers/base.py | Python | bsd-3-clause | 7,767 | 0.000129 | # -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from itertools import chain
import uuid
import numpy as np
from pyfr.nputil import fuzzysort
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod... | ret = {'con_p0': np.array(con, dtype='S4,i4,i1,i1').T}
for k, v in bcon.items():
ret['bcon_{0}_p0'.format(k)] = np.array(v, dtype='S4,i4,i1,i1')
return ret
def get_shape_points(self):
spts = {}
# Global node map (node index to coords)
nodepts = self._n... | elf._felespent:
continue
# Elements and type information
eles = self._elenodes[etype, pent]
petype, nnodes = self._etype_map[etype]
# Go from Gmsh to PyFR node ordering
peles = eles[:, self._nodemaps.from_pyfr[petype, nnodes]]
# ... |
jmontleon/ansible-service-broker | scripts/create_broker_secret.py | Python | apache-2.0 | 4,268 | 0.003515 | #! /usr/bin/env python
import sys
import yaml
import subprocess
USAGE = """USAGE:
{command} NAME NAMESPACE IMAGE [KEY=VALUE]* [@FILE]*
NAME: the name of the secret to create/replace
NAMESPACE: the target namespace of the secret. It should be the namespace of the broker for most usecases
IMAGE: the do... | l to be loaded
EXAMPLE:
{command} mysecret | ansible-service-broker docker.io/ansibleplaybookbundle/hello-world-apb key1=hello key2=world @additional_keys.yml
"""
DATA_SEPARATOR="\n "
SECRET_TEMPLATE = """---
apiVersion: v1
kind: Secret
metadata:
name: {name}
namespace: {namespace}
stringData:
{data}
"""
def main():
name = sys.argv[1]
n... |
WIPACrepo/iceprod | iceprod/server/scheduled_tasks/dataset_monitor.py | Python | mit | 4,445 | 0.008774 | """
Monitor the datasets.
Send monitoring data to graphite.
Initial delay: rand(1 minute)
Periodic delay: 5 minutes
"""
import logging
import random
import time
from tornado.ioloop import IOLoop
from iceprod.server import GlobalID
logger = logging.getLogger('dataset_monitor')
def dataset_monitor(module):
"""... | logger.error('error monitoring datasets', exc_info=True)
if debug:
raise
# run again after 60 minute de | lay
stop_time = time.time()
delay = max(60*5 - (stop_time-start_time), 60)
IOLoop.current().call_later(delay, run, rest_client, statsd)
|
invisiblek/python-for-android | python3-alpha/python3-src/Lib/test/test_decimal.py | Python | apache-2.0 | 86,081 | 0.003938 | # Copyright (c) 2004 Python Software Foundation.
# All rights reserved.
# Written by Eric Price <eprice at tjhsst.edu>
# and Facundo Batista <facundo at taniquetil.com.ar>
# and Raymond Hettinger <python at rcn.com>
# and Aahz (aahz at pobox.com)
# and Tim Peters
"""
These are the test cases for the Decim... | cording to PEP 327.
Cowlishaw's tests can be downloaded from:
www2.hursley.ibm.com/decimal/dectest.zip
This test module can be called from command line with one parameter (Arithmetic
or Behaviour) to test each part, or without parameter to test both parts. If
you're working through IDLE, you can import this test ... | e corresponding argument.
"""
import math
import os, sys
import operator
import warnings
import pickle, copy
import unittest
from decimal import *
import numbers
from test.support import (run_unittest, run_doctest, is_resource_enabled,
requires_IEEE_754)
from test.support import check_warning... |
samedder/azure-cli | src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/_help.py | Python | mit | 17,789 | 0.001349 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | tails for available web app deployment profiles.
"""
helps['webapp deployment container'] = """
type: group
short-summary: Manage container-based continuous deployment.
"""
helps['webapp deployment container config'] = """
type: command
short-summary: Configure continuous deployment via containers.
"""
helps['webapp... | ow-cd-url'] = """
type: command
short-summary: Get the URL which can be used to configure webhooks for continuous deployment.
"""
helps['webapp deployment slot auto-swap'] = """
type: command
short-summary: Configure deployment slot auto swap.
"""
helps['webapp deployment slot create'] = """
type: command
short-summa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.