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 |
|---|---|---|---|---|---|---|---|---|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/ubuntuone-client/ubuntuone/syncdaemon/sdreactor.py | Python | gpl-3.0 | 2,727 | 0.001467 | """
The SyncDaemon reactor -- a less power-hungry version of twisted's gtk2reactor
"""
#
# This is the quickest way to make twisted's Gtk2Reactor use
# timeout_add_seconds instead of timeout_add; the former uses high-resolution
# timers, which are more power-intensive.
# It's pretty much verbatim from their source.
fr... | t.
self.__iteration(1) # block
# note: with the .simulate timer below, delays > 0.1 will always be
# woken up by the .simulate timer
if self.doIterationTimer:
# if woken by IO, need to cancel the timer
gobject.source_remove(self.doIterationTimer)
self.... | rCore.run
"""
self.startRunning(installSignalHandlers=installSignalHandlers)
gobject.timeout_add_seconds(0, self.simulate)
if self._started:
self.__run()
def simulate(self):
"""
Run simulation loops and reschedule callbacks.
"""
if self._... |
nerdvegas/rez | src/rez/cli/_entry_points.py | Python | apache-2.0 | 6,916 | 0.001012 | # SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
"""
Entry points.
"""
import os
import os.path
import sys
### Utility functions
def get_specifications():
"""Get entry point specifications
See:
* https://pythonhosted.org/distlib/reference.html#distlib.scripts.ScriptMak... | .
"""
specs = {}
for attr, obj in sys.modules[__name__].__dict__.items():
scriptname = getattr(obj, "__scriptname__", None)
if scriptname:
spec = "%s = rez.cli._entry_points:%s" % (scriptname, attr)
specs[scriptname] = spec
return specs
|
def scriptname(name):
def decorator(fn):
setattr(fn, "__scriptname__", name)
return fn
return decorator
def check_production_install():
path = os.path.dirname(sys.argv[0])
filepath = os.path.join(path, ".rez_production_install")
if not os.path.exists(filepath):
sys.stderr... |
FreekingDean/home-assistant | homeassistant/components/yeelight/__init__.py | Python | apache-2.0 | 26,347 | 0.001177 | """Support for Xiaomi Yeelight WiFi color bulb."""
from __future__ import annotations
import asyncio
import contextlib
from datetime import timedelta
from ipaddress import IPv4Address, IPv6Address
import logging
from urllib.parse import urlparse
from async_upnp_client.search import SSDPListener
import voluptuous as v... | update_listener(_async_update_listener))
entry.async_on_unload(
async_dispatcher_connect(
hass, DEVICE_INITIALIZED.format(host), _async_load_platforms
)
)
# fetch initial state
asyncio.create_task(device.async_update())
@callback
def _async_normalize_config_entry(hass: Hom... | , entry: ConfigEntry) -> None:
"""Move options from data for imported entries.
Initialize options with default values for other entries.
Copy the unique id to CONF_ID if it is missing
"""
if not entry.options:
hass.config_entries.async_update_entry(
entry,
data={
... |
shubham2892/prize-fall-notifier | prize_fall_notifier.py | Python | gpl-2.0 | 817 | 0.025704 | #!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
from gi.repository import Notify
from time import sleep
url = "http://www.amazon.in/gp/offer-listing/B00VBH9G8S/ref=dp_olp_new?ie=UTF8&condition=new"
threshold_prize = 95000
print("Fetching rates..")
while True:
try:
r = requests.get(url)
... | Scorer")
scorer = Notify.Notifi | cation.new("mac Book Pro Amazon:", data, "dialog-information")
scorer.show()
sleep(500)
except KeyboardInterrupt:
break;
|
influence-usa/pupa | pupa/utils/topsort.py | Python | bsd-3-clause | 4,925 | 0.000203 | from collections import defaultdict
from itertools import chain
class CyclicGraphError(ValueError):
"""
This exception is raised if the graph is Cyclic (or rather, when the
sorting algorithm *knows* that the graph is Cyclic by hitting a snag
in the top-sort)
"""
pass
class Network(object):
... | .edges[fro].remove(node)
def sort(self):
"""
Return an iterable of nodes, toplogically sorted to correctly import
dependencies before leaf nodes.
"""
while self.nodes:
iterated = False
for node in self.leaf_nodes():
iterated = True
... | found a cyclic graph.")
def dot(self):
"""
Return a buffer that represents something dot(1) can render.
"""
buff = "digraph graphname {"
for fro in self.edges:
for to in self.edges[fro]:
buff += "%s -> %s;" % (fro, to)
buff += "}"
... |
SteveViss/readthedocs.org | readthedocs/core/management/commands/update_api.py | Python | mit | 851 | 0 | import logging
from django.core.management.base import BaseCommand
from readthedocs.projects import tasks
from readthedocs.api.client import api
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Build do | cumentation using the API and not hitting a database.
Usage::
./manage.py update_api <slug | >
"""
def add_arguments(self, parser):
parser.add_argument('--docker', action='store_true', default=False)
parser.add_argument('projects', nargs='+', type=str)
def handle(self, *args, **options):
docker = options.get('docker', False)
for slug in options['projects']:
... |
torbjoernk/easybuild-framework | easybuild/toolchains/mpi/craympich.py | Python | gpl-2.0 | 3,417 | 0.002341 | ##
# Copyright 2014-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | er the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild 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 G | eneral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
MPI support for the Cray Programming Environment (craype).
@author: Petar Forai (IMP/IMBA, Austria)
@author: Kenneth Hoste (Ghent Uni... |
kjedruczyk/phabricator-tools | py/phl/phlsys_daemonize.py | Python | apache-2.0 | 4,136 | 0 | """Daemonize the current process."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# phlsys_daemonize
#
# Public Functions:
# do
#
# ------------------------------------------------------------... | backgrounding' a process in such a way that if the
originating terminal exits, this process will continue running.
It also detaches the process from the original stdin, stdout, stderr
so that this process can continue to function after the originating
terminal ceases to be.
Note that it's a good i... | e as stdout
:stderr_path: path to write as stderr
:returns: None
"""
# eliminate possible race condition if current process is a session leader
# with a controling terminal: SIGHUP can be delivered if parent process
# exits before the child process has created its own session via
# os.sets... |
johanvdw/Fiona | tests/test_crs.py | Python | bsd-3-clause | 2,552 | 0.01058 |
from fiona import crs
def test_ | proj_keys():
assert len(crs.all_proj_keys) == 86
assert 'init' in crs.all_proj_keys
assert 'proj' in crs.all_proj_keys
| assert 'no_mayo' in crs.all_proj_keys
def test_from_string():
# A PROJ.4 string with extra whitespace.
val = crs.from_string(
" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +foo " )
assert len(val.items()) == 4
assert val['proj'] == 'longlat'
assert val['ellps'] == 'WGS84'
asse... |
chubbymaggie/reverse | plasma/lib/memmap.py | Python | gpl-3.0 | 3,739 | 0.00214 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# 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 ... | conv_ad_to_x(ad, cont[0])
qp.fillRect(x, 10, sz + 1, 80, col | )
for s in self.binary.iter_sections():
qp.fillRect(self.section_coords[s.start][0], 0, 1, 100, COLOR_SEP)
class ThreadMemoryMap(threading.Thread):
def __init__(self, db, binary):
self.db = db
self.binary = binary
threading.Thread.__init__(self)
def run(self):
... |
kapilt/ansible | lib/ansible/plugins/action/pause.py | Python | gpl-3.0 | 6,707 | 0.004175 | # Copyright 2012, Tim Bielawa <tbielawa@redhat.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... | return result
########################################################################
# Begin the hard work!
start = time.time | ()
result['start'] = str(datetime.datetime.now())
result['user_input'] = ''
fd = None
old_settings = None
try:
if seconds is not None:
# setup the alarm handler
signal.signal(signal.SIGALRM, timeout_handler)
signal.alar... |
adazey/Muzez | libs/nltk/stem/lancaster.py | Python | gpl-3.0 | 11,544 | 0.001819 | # Natural Language Toolkit: Stemmers
#
# Copyright (C) 2001-2016 NLTK Project
# Author: Steven Tomcavage <stomcava@law.upenn.edu>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
A word stemmer based on the Lancaster stemming algorithm.
Paice, Chris D. "Another Stemmer." ACM SIGIR Foru... | on > -
"nai3>", # -ian > -
"na2>", # -an > -
"nee0.", # protect -een
"ne2>", # -en > -
"nn1.", # -nn > -n
"pihs4>", # -ship > -
"pp1.", # -pp > -p
"re2>", # -er > -
"rae0.", # protect - | ear
"ra2.", # -ar > -
"ro2>", # -or > -
"ru2>", # -ur > -
"rr1.", # -rr > -r
"rt1>", # -tr > -t
"rei3y>", # -ier > -y
"sei3y>", # -ies > -y
"sis2.", # -sis > -s
"si2>", # -is > -
"ssen4>", ... |
deisi/home-assistant | tests/components/thermostat/test_heat_control.py | Python | mit | 7,976 | 0 | """The tests for the heat control thermostat."""
import unittest
from homeassistant.bootstrap import _setup_component
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
STATE_OFF,
TEMP_CELSIUS,
)
from homeassistant.components import thermost... | ual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_OFF, call.service)
self.assertEqual(ENT_SWITCH, call.data['entity_id'])
def test_set_temp_change_heater_on(self):
"""Test if temperature change turn heater on."... | t_temperature(self.hass, 30)
self.hass.pool.block_till_done()
self._setup_sensor(25)
self.hass.pool.block_till_done()
self.assertEqual(1, len(self.calls))
call = self.calls[0]
self.assertEqual('switch', call.domain)
self.assertEqual(SERVICE_TURN_ON, call.service)
... |
sajadkk/odoo-addons | payment_authorize_net/controllers/main.py | Python | agpl-3.0 | 1,263 | 0.003959 | # -*- coding: utf-8 -*-
import logging
import pprint
import werkzeug
from openerp import http, SUPERUSER_ID
from openerp.http import request
_logger = logging.getLogger(__name__)
class AuthorizeController(http.Controller):
_relay_url = '/payment/authorize_net/complete'
_cancel_url = '/payment/authorize_net/... | return werkzeug.util | s.redirect('/') |
isislovecruft/python-gnupg | docs/conf.py | Python | gpl-3.0 | 10,098 | 0.006437 | # -*- coding: utf-8 -*-
#
# python-gnupg documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 5 22:38:47 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... | erwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%A, %d %B %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct ent | ities.
html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# ... |
bkuczenski/lca-tools | antelope_catalog/catalog/__init__.py | Python | gpl-2.0 | 32 | 0.03125 | from .catalog | import LcC | atalog
|
treemo/circuits | docs/source/tutorials/woof/001.py | Python | mit | 73 | 0 | #!/usr/bin/env python
from | circuits import Component
Component(). | run()
|
ateska/striga2-pocs | greenev/pyge/evloop.py | Python | unlicense | 406 | 0.041872 | import sys
import _pygeapi
class event_loop(object):
def __init__(self):
pass
def run(self):
while True:
cmd = _pygeapi.py_thr | ead_next_cmd(sys.pygeapi_py_thread, 1000)
if cmd is None: continue
print(">", sys.pygeapi_py_thread, cmd)
if cmd == 1: break
def listen(self, hostname, port, backlog=10):
_pygeapi.io_thread_listen(sys.pygeapi_p | y_thread, hostname, str(port), backlog)
|
frappe/erpnext | erpnext/accounts/doctype/pos_profile_user/test_pos_profile_user.py | Python | gpl-3.0 | 157 | 0.006369 | # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import unittest
class TestPOSProfileUser(unittest.TestCase):
pas | s
| |
schmirob000/2016-Stronghold | src/org/usfirst/frc/team4915/stronghold/vision/jetson/imgExplore2/networktables2/server.py | Python | mit | 10,070 | 0.002681 | import threading
import time
from . import _impl
from .common import *
from .connection import *
from .networktablenode import NetworkTableNode
from .type import NetworkTableEntryTypeManager
import logging
logger = logging.getLogger('nt')
__all__ = ["NetworkTableServer"]
class ServerConnectionState:
"""Represen... | CTION_FROM_CLIENT:
raise BadMessageError("A server should not receive a client hello after it has already connec | ted/entered an error state")
if protocolRevision != PROTOCOL_REVISION:
self.connection.sendProtocolVersionUnsupported()
raise BadMessageError("Client Connected with bad protocol revision: 0x%x" % protocolRevision)
else:
self.entryStore.sendServerHello(self.connection)... |
YuHuaCheng/sklearn-pmml | sklearn_pmml/convert/test/test_gradientBoostingConverter.py | Python | mit | 3,136 | 0.002232 | from unittest import TestCase
from sklearn.ensemble import GradientBoostingClassifier
import numpy as np
from sklearn_pmml.convert.test.jpmml_test import JPMMLClassificationTest, JPMMLTest, TARGET_NAME
from sklearn_pmml.convert import TransformationContext, Schema
from sklearn_pmml.convert.features import *
from skle... | ([[0, 1]])[0, 0], 'output': self.est.predict([[0, 1]])},
{'x1': 1, 'x2': 'zero', 'output#1': self.est.predict_proba([[1, 0]])[0, 1], 'output#0': self.est.predict_proba([[1, 0]])[0, 0], 'output': self.est.predict([[1, 0]])},
{'x1': 1, 'x2': 'one', 'output#1': self.est.predict_proba([[1, 1]])[0, 1... | self.est.predict([[1, 1]])},
])
mm = p.MiningModel[0]
assert mm.MiningSchema is not None, 'Missing mining schema'
assert len(mm.MiningSchema.MiningField) == 2, 'Wrong number of mining fields'
assert mm.Segmentation is not None, 'Missing segmentation root'
class TestGradientBoos... |
ksrajkumar/openerp-6.1 | openerp/addons/base_action_rule/base_action_rule.py | Python | agpl-3.0 | 24,051 | 0.003995 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | model_name: |
mod_name = model_name[0]['model']
res['domain'] = {'filter_id': [('model_id','=',mod_name)]}
else:
res['value'] = {'filter_id':False}
return res
def post_action(self, cr, uid, ids, model, context=None):
# Searching for action rules
cr.exe... |
openstack/manila | manila/db/migrations/alembic/versions/fdfb668d19e1_add_gateway_to_network_allocations_table.py | Python | apache-2.0 | 1,178 | 0.001698 | # 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... | ONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""add_gateway_to_network_allocations_table
Revision ID: fdfb668d19e1
Revises: 221a83cfd85b
Create Date: 2016-04-19 10:07:16.224806
"""
# revision identifiers, used by A... | 'fdfb668d19e1'
down_revision = '221a83cfd85b'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'network_allocations',
sa.Column('gateway', sa.String(64), nullable=True))
op.add_column(
'share_networks',
sa.Column('gateway', sa.String(64), nullable=T... |
EmreAtes/spack | var/spack/repos/builtin/packages/vecgeom/package.py | Python | lgpl-2.1 | 1,985 | 0 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL- | CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOT | ICE and LICENSE files for our notice and the LGPL.
#
# 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will ... |
peterjoel/servo | tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/protocol.py | Python | mpl-2.0 | 10,206 | 0.001176 | import traceback
from abc import ABCMeta, abstractmethod
class Protocol(object):
"""Backend for a specific browser-control protocol.
Each Protocol is composed of a set of ProtocolParts that implement
the APIs required for specific interactions. This reflects the fact
that not all implementaions will... | otocolPart(ProtocolPart):
"""Protocol part for performing trusted clicks"""
__metaclass__ = ABCMeta
name = "send_keys"
@abstractmethod
def send_keys(self, element, keys):
"""Send keys to a specific element.
:param element: A protocol-specific handle to an element.
:param k... | : A protocol-specific handle to a string of input keys."""
|
jastination/software-engineering-excercise-repository | seer_python/dp/MaxArithmeticProgression.py | Python | mit | 440 | 0.018182 | '''
Created on May 20, 2012
@author: Jason Huang
'''
#Given an array of integers A, give an algorithm to find the longest Arithmetic progression in it, i.e find a sequence i1 < i2 < ¡ < ik, such that
#A[i1], A[i2], ¡, A[ik] forms an arithmetic progression, and k is the largest possible.
#The sequence S1, S2... | progression if
#Sj+1 ¨C Sj is a constant
if __name__ == '__main__':
pass | |
huzq/scikit-learn | sklearn/feature_extraction/tests/test_feature_hasher.py | Python | bsd-3-clause | 5,351 | 0.000934 | import numpy as np
from numpy.testing import assert_array_equal
import pytest
from sklearn.feature_extraction import FeatureHasher
from sklearn.utils._testing import ignore_warnings, fails_if_pypy
pytestmark = fails_if_pypy
def test_feature_hasher_dicts():
h = FeatureHasher(n_features=16)
assert "dict" == h... | assert X.shape[1] == n_features
assert X[0].sum() == 4
assert X[1].sum() == 3
assert X.nnz == 6
def test_hashing_transform_seed():
# check the influence of the seed when computing the hashes
# import is here to avoid importing on pypy
fro | m sklearn.feature_extraction._hashing_fast import transform as _hashing_transform
raw_X = [
["foo", "bar", "baz", "foo".encode("ascii")],
["bar".encode("ascii"), "baz", "quux"],
]
raw_X_ = (((f, 1) for f in x) for x in raw_X)
indices, indptr, _ = _hashing_transform(raw_X_, 2 ** 7, str,... |
SergeyPirogov/selene | selene/conditions.py | Python | mit | 9,603 | 0.001145 | from abc import ABCMeta, abstractmethod
import operator
from future.utils import with_metaclass, lmap
from selene.abctypes.conditions import IEntityCondition
from selene.abctypes.webdriver import IWebDriver
from selene.abctypes.webelement import IWebElement
from selene.exceptions import ConditionMismatchException
c... | it__(self, partial_value):
self.expected = partial_value
def fn(self, webdriver):
# type: (IWebDriver) -> bool
actual = webdriver.title
if actual not in self.expected:
raise ConditionMismatchException(
expected=self.expected,
actual=actual... | webdriver):
actual = webdriver.current_url
if not self.expected == actual:
raise ConditionMismatchException(
expected=self.expected,
actual=actual)
url = Url
class UrlContaining(WebDriverCondition):
def __init__(self, partial_value):
self.expe... |
hchim/stockanalyzer | simulator/StrategyEvaluator.py | Python | mit | 2,074 | 0.007232 | from simulator.BaseEvaluator import BaseEvaluator
from simulator.TradeSimulator import TradeSimulator
from utils.csvdata import get_data_of_symbol
from analysis.portfolio import get_portfolio_stats
import importlib
import numpy as np
class StrategyEvaluator(BaseEvaluator):
def __init__(self, start_date, end_date... | Sharpe ratio: AVG:{} MIN:{} MAX:{} MEDIAN:{}" \
.format(
np.average(cum_ret), cum_ret.min(), cum_ret.max(), np.median(cum_ret),
np.average(sharpe_rat | io), sharpe_ratio.min(), sharpe_ratio.max(), np.median(sharpe_ratio)
) |
johnny-bui/pygments-sablecc | scripts/find_error.py | Python | bsd-2-clause | 5,593 | 0.000715 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Lexing error finder
~~~~~~~~~~~~~~~~~~~
For the source files given on the command line, display
the text where Error tokens are being generated, along
with some context.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:licens... | else:
assert False, 'wrong state def: %r' % new_state
statetokens = tokendefs[self.statestack[-1]]
break
else:
try:
if text[self.pos] == '\n':
# at EOL, reset state to 'roo... | ['root']
yield self.pos, Text, u'\n'
continue
yield self.pos, Error, text[self.pos]
self.pos += 1
except IndexError:
break
def main(fn, lexer=None):
if lexer is not None:
lx = get_le... |
duncanmmacleod/gwpy | gwpy/table/io/fetch.py | Python | gpl-3.0 | 4,325 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) Duncan Macleod (2014-2020)
#
# This file is part of GWpy.
#
# GWpy 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)... | all from :meth:`EventTable.fetch`
force : `bool`, optional
overwrite existing registration for ``data_format`` if found,
default: `False`
"""
key = (data_format, data_class)
if key not in _FETCHERS or force:
_FETCHERS[key] = (function, usage)
else:
raise io_registry.... | mat '{0}' and class '{1}' has already "
"been defined".format(data_format, data_class),
)
_update__doc__(data_class)
def get_fetcher(data_format, data_class):
"""Return the :meth:`~EventTable.fetch` function for the given format
Parameters
----------
data_format : `str`
... |
spektom/incubator-airflow | airflow/providers/google/cloud/operators/pubsub.py | Python | apache-2.0 | 28,015 | 0.001499 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | oject
| super().__init__(*args, **kwargs)
self.project_id = project_id
self.topic = topic
self.fail_if_exists = fail_if_exists
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
self.labels = labels
self.message_storage_policy = message_storage_policy
... |
tobiasgoecke/django-messages | django_messages/migrations/0001_initial.py | Python | bsd-3-clause | 2,049 | 0.005857 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_M | ODEL),
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
| ('subject', models.CharField(max_length=120, verbose_name='Subject')),
('body', models.TextField(verbose_name='Body')),
('sent_at', models.DateTimeField(null=True, verbose_name='sent at', blank=True)),
('read_at', models.DateTimeField(null=True, verbose_name='read at', bl... |
asaini/algo-py | algos/graph_reachable.py | Python | mit | 803 | 0.043587 | class Graph:
def __init__(self, V, adj={}):
self.V = V
self.ad | j = adj
def add_edge(self, i, j):
if i in self.adj.keys():
self.adj[i].add(j)
else:
self.adj[i] = set([j])
def is_reachable(self, i, j):
if i == j:
return T | rue
visited = [False]*self.V
stack = [i]
while len(stack) > 0:
s = stack.pop(0)
if not visited[s]:
visited[s] = True
neighbours = list(self.adj[s])
for n in neighbours:
if n == j:
return True
if not visited[n]:
stack.append(n)
return False
if __name__ == '__main__':... |
ailove-dev/django-event | django_event/backends/base/settings.py | Python | mit | 307 | 0.003257 | # -*- coding: utf-8 -*-
"""
Base backend specific settings module.
"""
from __future__ import unicode_literals
from django_event im | port settings
HOST = settings.BACKEND_OPTIONS.get('HOST', 'localhost')
PORT = settings.BACKEND_OPTIONS.get('PORT')
PASSWORD = settings.BACKEN | D_OPTIONS.get('PASSWORD', '') |
jonanone/APIProject | vagrant/restaurant_menu/database_helper.py | Python | mit | 5,732 | 0.000698 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import inspect
from models import Base, Restaurant, MenuItem, User
# Init database session
def db_init():
engine = create_engine('sqlite:///restaurantmenuwithusers.d | b')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
return session
# Get restaurants ordered alphabetically by name
def get_restaurants(session):
all_restaurants = session.query(Restaurant).order_by(Restaurant.name)
return all_restaurants
# Get restaur... | aurants(session, ordering_attr):
all_restaurants = None
if ordering_attr == 'name':
all_restaurants = session.query(Restaurant).order_by(Restaurant.name)
elif ordering_attr == 'id':
all_restaurants = session.query(Restaurant).order_by(Restaurant.id)
return all_restaurants
# Get restaur... |
rogerhu/django | tests/migrations/test_loader.py | Python | bsd-3-clause | 4,238 | 0.002124 | from unittest import skipIf
from django.test import TestCase
from django.test.utils import override_settings
from django.db import connection
from django.db.migrations.loader import MigrationLoader, AmbiguityError
from django.db.migrations.recorder import MigrationRecorder
from django.utils import six
class Recorder... | r, fake-apply one migration and it should now use the old two
recorder.record_applied("migrations", "0001_initial")
migration_loader.build_graph()
self.assertEqual(
len(migration_loader.graph.nodes),
| 2,
)
recorder.flush()
|
webostin/django-btc | tests/select_related_regress/tests.py | Python | bsd-3-clause | 9,397 | 0.00298 | from __future__ import unicode_literals
from django.test import TestCase
from django.utils import six
from .models import (Building, Child, Device, Port, Item, Country, Connection,
ClientStatus, State, Client, SpecialClient, TUser, Person, Student,
Organizer, Class, | Enrollment, Hen, Chick | , A, B, C)
class SelectRelatedRegressTests(TestCase):
def test_regression_7110(self):
"""
Regression test for bug #7110.
When using select_related(), we must query the
Device and Building tables using two different aliases (each) in order to
differentiate the start and en... |
hinesmr/mica | util/pydevd/pysrc/pydevd_constants.py | Python | apache-2.0 | 6,291 | 0.01526 | '''
This module holds the constants used for specifying the states of the debugger.
'''
DEBUG_TRACE_LEVEL = -1
DEBUG_TRACE_BREAKPOINTS = -1
STATE_RUN = 1
STATE_SUSPEND = 2
try:
__setFalse = False
except:
import __builtin__
setattr(__builtin__, 'True', 1)
setattr(__builtin__, 'False', 0)
class Deb... |
thread.__pydevd_id__ = 'pid%s_seq%s' % (pid, _nextThreadId())
finally:
_nextThreadIdLock.release()
return thread.__pydevd_id__
#===============================================================================
# Null
#================================================... | ======
class Null:
"""
Gotten from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
"""
def __init__(self, *args, **kwargs):
return None
def __call__(self, *args, **kwargs):
return self
def __getattr__(self, mname):
return self
def __setattr__(self, ... |
locuslab/dreaml | setup.py | Python | apache-2.0 | 710 | 0.021127 | from setuptools import setup
setup(
name='dreaml',
version='0.0.7',
author = 'Zico Kolter, Eric Wong, Terrence Wong',
author_email = 'zkolter@cs.cmu.edu, ericwong@cs.cmu.edu, tw@andrew.cmu.edu',
packages = ['dreaml',
'dreaml.dataframe',
'dreaml.loss',... | 'dreaml.transf | ormations',
'dreaml.frontend'],
package_dir = {'dreaml': 'dreaml'},
url="http://www.bitbucket.org",
install_requires = ["networkx >= 1.9.1",
"numpy >= 1.9.2",
"scipy >= 0.15.1",
"pandas >= 0.16.2"],
i... |
flav-io/flavio | flavio/physics/bdecays/lambdablambdagamma.py | Python | mit | 143 | 0 | r"""F | unctions for the radiative baryonic decay $\Lambda_b\to\Lambda\gamma."""
def BR(wc_obj, par):
return prefac * | (ff)**2 * (abs(C)**2)
|
aragaer/partner | features/environment.py | Python | mit | 2,713 | 0.000369 | #!/usr/bin/python3
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
from types import SimpleNamespace
from unittest.mock import DEFAULT, Mock, patch
class MockScheduler(object):
def __init__(self):
self.events = []
def schedule_at(self, interval, callback, *args, **kwargs):
position = ... | ge
return
change -= | event.delay
self.events.pop(0)
event.callback(*event.args, **event.kwargs)
def get_timeout_for(self, filter_func):
timeout = 0
for event in self.events:
timeout += event.delay
if filter_func(event):
return timeout
def before_all(con... |
rspavel/spack | var/spack/repos/builtin/packages/gmake/package.py | Python | lgpl-2.1 | 2,212 | 0.00226 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import re
class Gmake(AutotoolsPackage, GNUMirrorPackage):
"""GNU Make is a tool which controls the generation of ex... | 4b4291929788ebaf77e2a4de7eaca95e31f3634ef7d4932051f69')
variant('guile', default=False, description='Support GNU Guile for embedded scripting')
variant('nls', default=True, description='Enable Native Language Support')
depends_on('gettext', when='+nls')
depends_on('guile', when='+guile')
depends_... | ms/make/raw/519a7c5bcbead22e6ea2d2c2341d981ef9e25c0d/f/make-4.2.1-glob-fix-2.patch', level=1, sha256='fe5b60d091c33f169740df8cb718bf4259f84528b42435194ffe0dd5b79cd125', when='@4.2.1')
patch('https://src.fedoraproject.org/rpms/make/raw/519a7c5bcbead22e6ea2d2c2341d981ef9e25c0d/f/make-4.2.1-glob-fix-3.patch', level=1,... |
KeitaNakamura/highlighter.nvim | rplugin/python3/highlighter/__init__.py | Python | mit | 4,405 | 0.003405 | # FILE: highlighter.py
# AUTHOR: Keita Nakamura
# License: MIT license
import os
import re
import subprocess
import neovim
@neovim.plugin
class Highlighter:
def __init__(self, vim):
self.vim = vim
self.is_started = False
def init_members(self):
self.vim.call('g:highlighter#initiali... | ']
template = 'syn | tax match {} /{}/ containedin=ALLBUT,{}'
cmd = template.format(s['hlgroup'], keywords, s['syntax_ignore'])
commands.append(cmd)
return ' | '.join(commands)
def make_syntax_clear_commands(self, ftype):
commands = []
for s in self.syntax[ftype]:
... |
ricmoo/pyaes | setup.py | Python | mit | 850 | 0.025882 | #!/usr/bin/env python
from distutils.core import setup
LONG_DESCRIPTION = | '''A pure-Python implementation of the AES (FIPS-197)
block-cipher algorithm and common modes of operation (CBC, CFB, CTR, ECB,
OFB) with no dependencies beyond standard Python libraries. See README.md
for API reference and details.'''
setup(name = 'pyaes',
version = '1.6.1',
description = 'Pure-Python Imp... | author = 'Richard Moore',
author_email = 'pyaes@ricmoo.com',
url = 'https://github.com/ricmoo/pyaes',
packages = ['pyaes'],
classifiers = [
'Topic :: Security :: Cryptography',
'License :: OSI Approved :: MIT License',
],
license = "License :: OSI Approved :: M... |
jelovirt/dita-generator | src/ditagen/dita/v1_2.py | Python | apache-2.0 | 32,591 | 0.003805 | # -*- coding: UTF-8; indent-tabs-mode:nil; tab-width:4 -*-
# This file is part of DITA DTD Generator.
#
# Copyright 2009 Jarno Elovirta <http://www.elovirta.com/>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | ion-atts"),
Attribute("outputclass", "CDATA", "#IMPLIED"),
]
class LearningAssessmentElement(ditagen.dita.DitaElement):
"""Learning Assessment element."""
name = u"learningAssessment"
cls = u"- topic/topic learningBase/learningBase learningAssessment/learningAssessment "
model = Seq([
... | eterEntity("title")),
Choice(ParameterEntity("titlealts"), OPTIONAL),
Choice([ParameterEntity("shortdesc"), ParameterEntity("abstract")], Param("shortdesc")),
Choice(ParameterEntity("prolog"), OPTIONAL),
Choice(ParameterEntity("learningAssessmentbody"), OPTIONAL),
Choice(Paramete... |
RalfJung/dudel | dudel/__init__.py | Python | gpl-3.0 | 1,320 | 0.006818 | from raven.contrib.flask import Sentry
from flask import Flask
from flask.ext.babel import Babel
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.markdown import Markdown
from flask.ext.login import LoginManager
from flask.ext.gravatar import Gravatar
from flask.ext.migrate import Migrate, MigrateCommand
from... | pytz
app = Flask(__name__)
app.config.from_pyfile("../config.py.example", silent=True)
app.config.from_pyfile("../config.py", silent=True)
app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
manager = Manager(app)
db = SQLAlchemy(app)
markdown = Markdown(app, safe_mode="escape")
login_manager = LoginManag... | =True, base_url=None)
babel = Babel(app)
supported_languages = ['en', 'de']
migrate = Migrate(app, db)
manager.add_command("db", MigrateCommand)
mail = Mail(app)
default_timezone = pytz.timezone(app.config["DEFAULT_TIMEZONE"])
from dudel.util import load_icons
ICONS = load_icons("dudel/icons.txt")
import dudel.assets... |
nkalodimas/invenio | modules/bibformat/lib/elements/bfe_photo_resources_brief.py | Python | gpl-2.0 | 1,594 | 0.013802 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2010, 2011 CERN.
##
## Invenio 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
## Licens... | f HTML picture and links to resources
"""
__revision__ = "$Id$"
def format_element(bfo):
"""
Prints html image and link to photo resources.
"""
from invenio.config import CFG_SITE_URL, CFG_SITE_RECORD
resources = bfo.fields("8564_")
out = ""
for resource in resources:
if resource.... | '+CFG_SITE_URL+'/'+ CFG_SITE_RECORD +'/'+bfo.control_field("001")+ \
'?ln='+ bfo.lang + '"><img src="' + resource.get("u", "").replace(" ","") \
+ '" alt="" border="0"/></a>'
return out
def escape_values(bfo):
"""
Called by BibFormat in order to check if output of thi... |
DeppSRL/open_bilanci | bilanci_project/bilanci/settings/staging.py | Python | mit | 1,991 | 0.010547 | """Production settings and globals."""
from base import *
########## HOST CONFIGURATION
# See: https://docs.djangoproject.com | /en/1.5/releases/1.5/#allowed-hosts-required-in-production
MAIN_HOST = ['openbilanci.staging.deppsviluppo.org',]
# Allowed hosts expansion: needed for servizi ai Comuni
HOSTS_COMUNI = [
'novara.comuni.deppsviluppo.org',
'rapallo.comuni.deppsviluppo.org',
'castiglionedellestiviere.comuni.deppsviluppo.org',
'firenze.com... | ngoproject.com/en/dev/ref/settings/#email-backend
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
########## END EMAIL CONFIGURATION
########## TOOLBAR CONFIGURATION
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
INSTALLED_APPS += (
'debug_toolbar',
)
# See: https:... |
repology/repology | repology/parsers/parsers/freebsd.py | Python | gpl-3.0 | 2,078 | 0.001444 | # Copyright (C) 2016-2019 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology 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 optio... | see <http://www.gnu.org/licenses/>.
from typing import Iterable
from repology.logger import Logger
from repology.packagemaker import NameType, PackageFactory, PackageMaker
from repology.parsers import Parser
from repology.parsers.maintainers import extract_maintainers
from repology.parsers.versions import VersionStr... | :
normalize_version = VersionStripper().strip_right(',').strip_right('_')
with open(path, encoding='utf-8') as indexfile:
for line in indexfile:
pkg = factory.begin()
fields = line.strip().split('|')
if len(fields) != 13:
... |
charlesweir/BrickPython | ExamplePrograms/SimpleApp.py | Python | mit | 990 | 0.014141 | # Very simple example application for BrickPython.
#
# Copyright (c) 2014 Charles Weir. Shared under the MIT Licence.
import sys, os # Python path kludge - omit these 2 lines if BrickPython is installed.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
from BrickPython.CommandLineAp... | tine( self.doActivity() )
def doActivity(self):
'Coroutine to rotate a motor forward and backward'
motorA = self.motor('A')
motorA.zeroPosition()
while True:
print 'Moving forward'
| for i in motorA.moveTo( 2*90 ):
yield
print 'Moving back'
for i in motorA.moveTo( 0 ):
yield
if __name__ == "__main__":
SimpleApp().mainloop() |
eaobservatory/hedwig | lib/hedwig/view/base.py | Python | gpl-3.0 | 2,453 | 0 | # Copyright (C) 2015-2020 East Asian Observatory
# All Rights Reserved.
#
# 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 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. See the GNU General Public... |
bebraw/pynu | pynu/node.py | Python | mit | 10,922 | 0.000641 | # -*- coding: utf-8 -*-
"""
Helper classes.
"""
"""
Pynu - Python Node Utilities
Copyright (c) 2014 Juho Vepsäläinen
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
... | ED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE... |
Noahs-ARK/ARKcat | src/scripts_and_misc/process_json.py | Python | apache-2.0 | 2,711 | 0.008853 | # directory = 'Congressional_Bill_Corpus.v1.00/raw/'
directory = ''
text_file = directory + 'billtext_org.json'
labels_file = directory + 'train.json'
output_dir = '/Users/katya/datasets/congress_bills_2/'
import sys
#pcogennen noah's congress_bills_2 into useable format
#to dict:
def skip_ahead_n_quotes(line, char... | if '\"body\"' in line:
char_counter = skip_ahead_n_quotes(line, char_counter, 2)
# print 'skip ahead'
char_counter += 3
body, char_counter = parse_inside_char(line, char_counter, '\"')
# pr | int 'parsed'
else:
body = ''
char_counter = skip_ahead_n_quotes(line, char_counter, 3)
char_counter += 3
# print 'skip 2'
title, char_counter = parse_inside_char(line, char_counter, '\"')
# print 'parsed2'
d[name] = rm_newlines(title) + ' ' + rm_newlin... |
sacharya/nova | nova/tests/api/openstack/compute/contrib/test_floating_ips.py | Python | apache-2.0 | 29,801 | 0.000738 | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Eldar Nugaev
# 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://... | ONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import floating_ips
from nova.api.openstack import extensions
from nova impo... | import db
from nova import exception
from nova import network
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests import fake_network
FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
def network_api_get_floating_ip(self, context, id):
r... |
partofthething/home-assistant | tests/components/smhi/test_weather.py | Python | apache-2.0 | 9,580 | 0.000209 | """Test for the smhi weather entity."""
import asyncio
from datetime import datetime
import logging
from unittest.mock import AsyncMock, Mock, patch
from smhi.smhi_lib import APIURL_TEMPLATE, SmhiForecastException
from homeassistant.components.smhi import weather as weather_smhi
from homeassistant.components.smhi.con... | TR_FORECAST_CONDITION] is None
# pylint: disable=protected-access
async def test_refresh_weather_forecast_exceeds_retries(hass) -> None:
"""Test the refresh weather forecast function."""
with patch.object(
hass.helpers.event, "async_call_later"
) as call_later, patch.object(
weather_smhi.... | "17.0022", "62.0022")
weather.hass = hass
weather._fail_count = 2
await weather.async_update()
assert weather._forecasts is None
assert not call_later.mock_calls
async def test_refresh_weather_forecast_timeout(hass) -> None:
"""Test timeout exception."""
weather = weat... |
uclouvain/osis_louvain | assessments/tests/views/test_scores_responsible.py | Python | agpl-3.0 | 8,565 | 0.001752 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | TICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
####################################################################... | ntenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.test import TestCase
from attribution.business.attribution import get_attributions_list
from attribution.models import attribution
from attribution.tests.models import test_attribution
from base import models as mdl_base
from... |
jpsingleton/screenly-ose | queries.py | Python | gpl-2.0 | 540 | 0.014815 |
comma = ','.join
quest = lambda | l: '=?,'.join(l) + '=?'
exists_table = "SELECT name F | ROM sqlite_master WHERE type='table' AND name='assets'"
read_all = lambda keys: 'select ' + comma(keys) + ' from assets order by play_order'
read = lambda keys: 'select ' + comma(keys) + ' from assets where asset_id=?'
create = lambda keys: 'insert into assets (' + comma(keys) + ') values (' + comma(['?'] * len(keys))... |
LeoOsipovHSE/vkca | vk_api/searching.py | Python | apache-2.0 | 1,261 | 0.007137 | # coding: utf8
__author__ = 'Lev'
import requests
import json
import re
from datetime import datetime
from domain.user import User
from settings import VK_SEARCHING_TOKEN
from util import log
from resources import GENDERS
gender_dict_vk = {0: GENDERS['undef'], 1: GENDERS['F'], 2: GENDERS['M']}
date_pat... | r_id, r_date):
log('getting info for {}'.format(user_id))
method_url = 'https://api.vk.com/method/users.get?'
param | s = dict(access_token=VK_SEARCHING_TOKEN, user_ids=user_id, fields='bdate,sex')
response = requests.get(method_url, params=params)
result = json.loads(response.text)
if 'error' in result:
error = 'searching error({}): {}'.format(result['error']['error_code'], result['error']['error_msg'])
... |
houssine78/vertical-travel-porting-v8-wip | motor_vehicle/vehicle_category.py | Python | agpl-3.0 | 1,375 | 0 | # -*- encoding: utf-8 -*-
############################################################ | ##################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfaireli | nux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in th... |
guidosarducci/plugin.video.youtube | resources/lib/kodion/impl/xbmc/xbmc_context.py | Python | gpl-2.0 | 9,558 | 0.001569 | import sys
import urllib
import urlparse
import weakref
import datetime
import json
import xbmc
import xbmcaddon
import xbmcplugin
import xbmcvfs
from ..abstract_context import AbstractContext
from .xbmc_plugin_settings import XbmcPluginSettings
from .xbmc_context_ui import XbmcContextUI
from .xbmc_system_version imp... | String(int(text_id))
if result is not None and result:
return utils.to_unicode(result)
return utils.to_unicode(default_text)
def set_content_type(self, conte | nt_type):
self.log_debug('Setting content-type: "%s" for "%s"' % (content_type, self.get_path()))
xbmcplugin.setContent(self._plugin_handle, content_type)
pass
def add_sort_method(self, *sort_methods):
for sort_method in sort_methods:
xbmcplugin.addSortMethod(self._plugi... |
jelly/calibre | src/calibre/__init__.py | Python | gpl-3.0 | 22,869 | 0.003061 | ''' E-book management software'''
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys, os, re, time, random, __builtin__, warnings
__builtin__.__dict__['dynamic_property'] = lambda func: func(None)
from math import floor
from functools im... | p1 or not p2:
return False
return d(p1) == d(p2)
def unicode_path(path, abs=False):
if isinstance(path, bytes):
path = path.decode(filesystem_encoding)
if abs:
path = | os.path.abspath(path)
return path
def osx_version():
if isosx:
import platform
src = platform.mac_ver()[0]
m = re.match(r'(\d+)\.(\d+)\.(\d+)', src)
if m:
return int(m.group(1)), int(m.group(2)), int(m.group(3))
def confirm_config_name(name):
return name + '_... |
archmoo/MSSim | lib/bosslib.py | Python | gpl-2.0 | 19,411 | 0.001752 | class BossLib:
m_counter = {
#attempt, attempt, defeat, defeat
'Zakum': ('day', 2, 'day', 2),
'Horntail': ('day', 2, 'day', 2),
'Pink Bean': ('day', 1, 'day', 1),
'Von Leon': ('day', 1, 'day', 1),
'Cygnus': ('day', 1, 'week', 1),
'Arkarium': ('day', 1, 'day', ... | the Black Mage, something went wrong and he instead summoned Pink Bean.",
'AP cost': 10,
},
'Chaos Pink Bean': {
'counter': 'Pink Bean',
| 'dps': 2000000,
'defense': 1.8,
'resistance': 0.5,
'reward': {
'Boss Coin': (100, 0.1),
'Meso': (50000000, 0.1),
},
'description': "Pink Bean is a unspecified Transcendent from Bean World. He is a overall pink crea... |
m364nm/final-project-cis399 | CONFIG.base.py | Python | artistic-2.0 | 910 | 0.021978 | """
Configuration of 'memos' Flask app.
Edit to fit development or deployment environment.
"""
import random
### My local development environment
PORT=5000
DEBUG = True
### On ix.cs.uoregon.edu (Michal Young's instance of MongoDB)
#PORT=random.randint(5000,8000)
#DEBUG = False # Because it's unsafe to run outside l... | 27017 # modify to where your mongodb is listening, ex: 27017 or 4570
### The following are for a Mongo user you create for accessing your
### memos database. It should not be the same as your database administrator
### account.
MONGO_PW = "iremember"
MONGO_USER = "meetme"
#MONGO_URL on localhost
MONGO_URL = "mongodb... | eetme".format(MONGO_USER,MONGO_PW,MONGO_PORT)
#MONGO_URL for ix
#MONGO_URL = "mongodb://{}:{}@ix.cs.uoregon.edu:{}/meetme".format(MONGO_USER,MONGO_PW,MONGO_PORT)
|
harwee/electrum-xvg-tor | lib/daemon.py | Python | gpl-3.0 | 8,206 | 0.00195 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2014 Thomas Voegtlin
#
# 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 y... | eful,
# 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 program. If not, see <http://www.gnu. | org/licenses/>.
import socket
import time
import sys
import os
import threading
import traceback
import json
import Queue
from collections import defaultdict
import util
from network import Network
from util import print_error, print_stderr, parse_json
from simple_config import SimpleConfig
DAEMON_SOCKET = 'daemon.s... |
OCA/multi-company | intercompany_shared_contact/tests/models.py | Python | agpl-3.0 | 515 | 0 | # Copyright 2021 Akretion (https://www.akretion.com).
# @author Sébastien BEAU <sebastien.beau@akretion.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/ | agpl).
from odoo import api, fields, models
class ResPartner(models.Model):
_inherit = "res.partner"
foo_company_dependent_field = fields.Char(company_dependent=True)
@api.model
def _commercial_fields(self):
self.check_access_rule("write")
return super()._commercial_fields() + ["foo... | mpany_dependent_field"]
|
OCA/account-invoicing | account_invoice_mode_weekly/tests/__init__.py | Python | agpl-3.0 | 90 | 0 | from . import test_invoice_mode_weekly
from . import | test_invoice_m | ode_weekly_is_it_today
|
EricSchles/veyepar | dj/scripts/ck_setup.py | Python | mit | 10,966 | 0.00766 | #!/usr/bin/python
# ck_setup.py - checks the veyepar setup - reports what features are ready.
from process import process
from main.models import Show, Location, Client
from django.conf import settings
import pw
import rax_uploader
import archive_uploader
import steve.richardapi
import os
import xml.etree.Elemen... | p_okg("client_slug: {}".format(client_slug))
try:
self.client = Client.objects.get(slug=client_slug)
except Client.DoesNotExist as e:
p_fail("client slug not found in db.")
raise e
return
def ck_s | how(self):
try:
show_slug = self.options.show
except AttributeError as e:
p_fail("No show set in config file or command line.")
raise e
p_okg("show_slug: {}".format(show_slug))
try:
self.show = Show.objects.get(slug=show_slug)
exce... |
mike-rg/MyGoalTracker | myGoalTracker/usuario/models.py | Python | gpl-3.0 | 388 | 0.012887 | from django.db i | mport models
from django.contrib.auth.models import User
from PIL import Image
class Usuario(models.Model):
""" Este modelo one-to-one es frecuentemente llamado modelo Perfil """
usuario = models.OneToOneField(User, on_delete=models.CASCADE)
| # pip install Pillow
foto = models.ImageField(upload_to = 'imagenes/', default = 'imagenes/None/no-img.jpg')
|
tadhg-ohiggins/regulations-parser | regparser/test_utils/node_accessor.py | Python | cc0-1.0 | 802 | 0 | class NodeAccessor(object):
"""Wrapper class around a node that allows us to navigate the tree via
dictionary access"""
def __init__(self, node):
self.node = node
self.child_labels = [c.label[-1] for c in node.children]
self._memoized = {}
def __getattr__(self, name):
""... | elf.node.children:
if child.label[-1] == labe | l:
return NodeAccessor(child)
raise KeyError()
|
ajdiaz/mole | mole/action/parser.py | Python | gpl-3.0 | 983 | 0.005086 | #! /usr/bin/env python
# -*- encoding: utf-8 -*-
# vim:fenc=utf-8:
from mole.event import Event
from mole.action impo | rt Action, ActionSyntaxError
from mole.parser import Parser
class ActionParser(Parser):
"""This action parse the pipeline using specific parser
:param `name`: a list with string representation of the parser to be load | ed.
"""
def __init__(self, name,*args, **kwargs):
if len(name) > 1:
raise ActionSyntaxError("parser command only allow one single parameter")
self.item = None
self.name = name[0]
def _init_item(self):
if self.item is None:
if self.context:
... |
mikeengland/fireant | fireant/tests/dataset/test_filter_totals_from_share_results.py | Python | apache-2.0 | 3,701 | 0.003513 | from datetime import timedelta
from unittest import TestCase
import pandas as pd
import pandas.testing
from fireant.dataset.modifiers import Rollup
from fireant.dataset.totals import scrub_totals_from_share_results
from fireant.tests.dataset.mocks import (
dimx0_metricx2_df,
dimx1_str_df,
dimx1_str_totals... | ):
result = scrub_totals_from_share_results(
dimx2_date_str_totalsx2_df, [mock_dataset.fields.timestamp, Rollup(mock_dataset.fields.political_party)]
)
expected = dimx2_date_str_totalsx2_df.l | oc[:TIMESTAMP_UPPERBOUND]
pandas.testing.assert_frame_equal(result, expected)
def test_do_not_remove_totals_for_rollup_dimensions_with_multiindex_and_higher_dimension_totals(self):
result = scrub_totals_from_share_results(
dimx2_date_str_totalsx2_df, [Rollup(mock_dataset.fields.timesta... |
nitzmahone/ansible | test/units/template/test_templar.py | Python | gpl-3.0 | 18,842 | 0.002335 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | nsafe, wrap_var
from units.mock.loader import DictDataLoader
class BaseTemplar(object):
def se | tUp(self):
self.test_vars = dict(
foo="bar",
bam="{{foo}}",
num=1,
var_true=True,
var_false=False,
var_dict=dict(a="b"),
bad_dict="{a='b'",
var_list=[1],
recursive="{{recursive}}",
some_var="b... |
ipashchenko/jetsim | jetsim/nfields.py | Python | mit | 800 | 0 | class NField(object): |
"""
Basic class that represents particle density in observer rest frame.
"""
def n(self, x, y, z):
raise NotImplementedError
def n_vec(self, ps):
raise NotImplementedError
class BKNField(NField):
"""
Class that describes Blandford-Konigle particle density with r**(-2)
... | 00.):
self.z_0 = z_0
self.n_0 = n_0
def n(self, x, y, z):
return self.n_0 * (self.z_0 / z) ** 2.
def n_vec(self, ps):
"""
:param ps:
Numpy array with shape (N, 3,) where N is the number of points.
:return:
Numpy array of values in N point... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/numpy/f2py/tests/test_array_from_pyobj.py | Python | mit | 22,124 | 0.00009 | from __future__ import division, absolute_import, print_function
import unittest
import os
import sys
import copy
from numpy import (
array, alltrue, ndarray, zeros, dtype, intp, clongdouble
)
from numpy.testing import (
run_module_suite, assert_, assert_equal, SkipTest
)
from numpy.core.multiarray import typ... | TEABLE',
'UPDATEIFCOPY', 'BEHAVED', 'BEHAVED_RO',
'CARRAY', 'FARRAY'
]:
if abs(flags) & getattr(wrap, flagname, 0):
info.append(flagname)
return info
class Intent(object):
def __init__(self, intent_list=[]):
self.inten... | for i in intent_list:
if i == 'optional':
flags |= wrap.F2PY_OPTIONAL
else:
flags |= getattr(wrap, 'F2PY_INTENT_' + i.upper())
self.flags = flags
def __getattr__(self, name):
name = name.lower()
if name == 'in_':
name ... |
lmregus/Portfolio | python/design_patterns/env/lib/python3.7/site-packages/pygments/lexers/xorg.py | Python | mit | 887 | 0 | # -*- coding: utf-8 -*-
"""
pygments.lexers.xorg
~~~~~~~~~~~~~~~~~~~~
Lexers for Xorg configs.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygment | s.lexer import RegexLexer, bygroups
from pygments.token import Comment, String, Name, Text
__all__ = ['XorgLexer']
class XorgLexer(RegexLexer):
"""Lexer for xorg.conf file."""
name = 'Xorg'
aliases = ['xorg.conf']
filenames = ['xorg.conf']
mimetypes = []
tokens = {
'root': [
... | bygroups(String.Escape, Text, String.Escape)),
(r'(End(|Sub)Section)', String.Escape),
(r'(\w+)(\s+)([^\n#]+)',
bygroups(Name.Builtin, Text, Name.Constant)),
],
}
|
jMyles/hendrix | examples/django_hx_chatserver/example_app/chat/models.py | Python | mit | 1,505 | 0.001993 | from django.db import models
from django.template import Context, loader
from django.utils import timezone
from hendrix.experience import hey_joe
from hendrix.contrib.concurrency.signals import message_signal
# Create your models here.
class ChatMessage(models.Model):
"""
a model that stores chat histor... | a = kwargs.get('data')
if data.get('message') and data.get('channel'):
cm = ChatMessage.objects.create(
sender=data.get('sender'),
content=data.get('message'),
channel=data.ge | t('channel')
)
t = loader.get_template('message.html')
# now send broadcast a message back to anyone listening on the channel
hey_joe.send({'html': t.render({'message': cm})}, cm.channel)
message_signal.connect(save_chat_message)
|
bblacey/FreeCAD-MacOS-CI | src/Mod/Fem/PyGui/_CommandFemMeshGmshFromShape.py | Python | lgpl-2.1 | 3,534 | 0.001981 | # ***************************************************************************
# * *
# * Copyright (c) 2016 - Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * Th... | len(sel) == 1):
if(sel[0].isDerivedFrom("Part::Feature")):
mesh_obj_name = sel[0].Name + "_Mesh"
FreeCADGui.addModule("ObjectsFem")
FreeCADGui.doCommand("ObjectsFem.makeMeshGmsh('" + mesh_obj_name + "')")
FreeCADGui.doCommand("App.Active | Document.ActiveObject.Part = App.ActiveDocument." + sel[0].Name)
if FemGui.getActiveAnalysis():
FreeCADGui.addModule("FemGui")
FreeCADGui.doCommand("FemGui.getActiveAnalysis().Member = FemGui.getActiveAnalysis().Member + [App.ActiveDocument.ActiveObject]")
... |
rossdylan/cumuliform | setup.py | Python | mit | 531 | 0.00565 | from setuptools import setup
setup(
name='Cumuliform',
version='0.1.0',
author="Ross Delinger",
author_email="rdelinger@helixoide.com",
packages=['cumuliform'],
license='license.txt' | ,
description='Listen to the latest sound cloud tracks on hypem spy',
long_description=open('README.txt').read(),
install_requires=[
"tornado",
"beautifulsoup4",
"soundcloud"],
entry_points={
| 'console_scripts': [
'cumuliform = cumuliform:run',
],
},
)
|
solvebio/solvebio-python | solvebio/resource/datasetfield.py | Python | mit | 876 | 0 | """Solvebio DatasetField API Resource"""
from .solveobject import convert_to_solve_object
from .apiresource import CreateableAPIResource
from .apiresource import ListableAPIResource
from .apiresource import UpdateableAPIResource
from .apiresource import DeletableAPIResource
class DatasetField(CreateableAPIResource,
... | different set of fields, some of
which can be used as filters. Dataset field resources provide
users with documentation about each field.
"""
RESOURCE_VERSION = 2
def facets(self, **params):
response = self._client.get(self.facets_url, params)
return convert_to_solve_object(respons... | help(self):
return self.facets()
|
mapan1984/Hidden-Island | app/utils/searcher.py | Python | mit | 6,047 | 0.000733 | import jieba
from collections import defaultdict
from app import db, create_app
from app.models import Words, Article
def build_query(word_values):
""" 构造查询字符串
假设word_values为一个单词,单词id为10
则fullquery为:
select w0.article_id, w0.location
from wordlocation w0
where w0.word_id=10
假... | )
return fullquery, wordids
def get_match_rows(query):
"""
Returns:
rows: [(article_id, word1location, word2location, ...), ....]
wordids: [word_id_1, word_id_2, ...]
"""
# 拆分查询关键词
word_values = [value.lower() for value in jieba.cut(query) if not Words._should_ignore(value)]
... | 字符串
fullquery, wordids = build_query(word_values)
if len(wordids) > 0:
cur = db.session.execute(fullquery).cursor
articleid_locations = [row for row in cur]
# print(wordids)
# print(articleid_locations[:10])
return articleid_locations, wordids
else:
return N... |
tedi3231/openerp | openerp/addons/crm/crm.py | Python | agpl-3.0 | 10,604 | 0.006601 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | ember_id', 'Team Members'),
'reply_to': fields.char('Reply-To', size=64, help="The email address put in the 'Reply-To' of all emails sent by OpenERP about cases in this sales team"),
'parent_id': fields.many2one('crm.case.section', 'Parent Team'),
'child_ids': fields.one2many('crm.case.section',... | s"),
'note': fields.text('Description'),
'working_hours': fields.float('Working Hours', digits=(16,2 )),
'stage_ids': fields.many2many('crm.case.stage', 'section_stage_rel', 'section_id', 'stage_id', 'Stages'),
'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="cascade", requir... |
pgmillon/ansible | lib/ansible/modules/cloud/vmware/vmware_vm_shell.py | Python | gpl-3.0 | 13,224 | 0.002344 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015-16, Ritesh Khadgaray <khadgaray () gmail.com>
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__... | type: bool
version_added: 2.7
timeout:
description:
- Timeout in seconds.
- If set to positive integers, then C(wait_for_process) will honor this parameter and will exit after this timeout.
defau | lt: 3600
version_added: 2.7
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Run command inside a virtual machine
vmware_vm_shell:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ datacenter ... |
amosnier/python_for_kids | book_code/appendixb/ch18-game-over.py | Python | gpl-3.0 | 9,143 | 0.003609 | from tkinter import *
import random
import time
class Game:
def __init__(self):
self.tk = Tk()
self.tk.title("Mr. Stick Man Races for the Exit")
self.tk.resizable(0, 0)
self.tk.wm_attributes("-topmost", 1)
self.canvas = Canvas(self.tk, width=500, height=500, highlightthickn... | ite.move()
else:
time.sleep(1)
self.canvas.itemconf | ig(self.game_over_text, state='normal')
self.tk.update_idletasks()
self.tk.update()
time.sleep(0.01)
class Coords:
def __init__(self, x1=0, y1=0, x2=0, y2=0):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
def within_x(co1, co2)... |
archatas/whoosh | whoosh/store.py | Python | apache-2.0 | 1,132 | 0.010601 | #===============================================================================
# Copyright 2007 Matt Chaput
#
# 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/li... | guage governing permissions and
# limitations under the License.
#===============================================================================
class LockError(Exception):
pass
class Storage(object):
"""Abstract base class for storage objects.
"""
def create_ind | ex(self, schema, indexname=None):
raise NotImplementedError
def open_index(self, indexname=None, schema=None):
raise NotImplementedError
def close(self):
pass
def optimize(self):
pass
|
shiroyuki/Tori | docs/source/conf.py | Python | mit | 11,697 | 0.006583 | # -*- coding: utf-8 -*-
#
# Tori documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 17 21:37:41 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | ing the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that s... | f false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is Tru... |
MichalKononenko/T1erminator | models/abstract_models.py | Python | mit | 1,959 | 0.00051 | """
Contains abstractions for simulations
"""
from abc import ABCMeta, abstractmethod, abstractproperty
__author__ = 'Michal Kononenko'
__all__ = ['AbstractSystemModel', 'AbstractNoiseDistribution']
class AbstractSystemModel(object):
"""
Base class for all models in the simulations
"""
__metaclass__ ... |
Nxl where l depends on if there are multiple outputs for a model
(ie. two channels on an NMR spectrometer)
:rtype np.ndarray
"""
raise NotImplementedError
class AbstractNoiseModel(object):
"""
Contains models for adding noise to data
"""
__metaclass__ =... | dd_noise(self, data):
raise NotImplementedError
class AbstractNoiseDistribution(object):
__metaclass__ = ABCMeta
@abstractmethod
def sample(self, list_to_sample):
"""
Sample the noise distribution in order to obtain a list of random
variables corresponding to the noise
... |
timothy1191xa/project-epsilon-1 | code/utils/functions/t_stat.py | Python | bsd-3-clause | 1,887 | 0.014838 | """
"""
import sys, os, pdb
import numpy as np
import numpy.linalg as npl
from scipy.stats import t as t_dist
sys.path.append(os.path.join(os.path.dirname(__file__), "./"))
from glm_func import *
def t_stat(data, X_matrix):
"""
Return the estimated betas, t-values, degrees of freedom,
and p-values for t... | d beta values
t: t-values of the betas
df: degrees of freedom
p: p-values corresponding to the t-values and degrees of freedom
"""
beta = glm_beta(data, X_matrix)
# Calculate the parameters - b hat
beta = np.reshape(beta, (-1, beta.shape | [-1])).T
fitted = X_matrix.dot(beta)
# Residual error
y = np.reshape(data, (-1, data.shape[-1]))
errors = y.T - fitted
# Residual sum of squares
RSS = (errors**2).sum(axis=0)
df = X_matrix.shape[0] - npl.matrix_rank(X_matrix)
# Mean residual sum of squares
MRSS = RSS / df
# ca... |
GrotheFAF/client | src/model/playerset.py | Python | gpl-3.0 | 2,197 | 0 | from PyQt5.QtCore import QObject, pyqtSignal
from model.player import Player
class Playerset(QObject):
"""
Wrapper for an id->Player map
Used to lookup players either by id or by login.
"""
playerAdded = pyqtSignal(object)
playerRemoved = pyqtSignal(object)
def __init__(self):
Q... | ror
if key in self: # disallow overwriting existing players
raise ValueError
if key != value.id:
raise ValueError
self._players[key] = value
self._logins[value.login] = value
self.playerAdded.emit(value)
def __delitem__(self, item):
try... | f.playerRemoved.emit(player)
def clear(self):
oldplayers = list(self.keys())
for player in oldplayers:
del self[player]
|
leviroth/bernard | test/test_system.py | Python | mit | 2,784 | 0.003233 | from contextlib import redirect_stderr
from io import StringIO
from pathlib import Path
from bernard.actors import (
AutomodDomainWatcher,
AutomodUserWatcher,
Banner,
Modmailer,
Notifier,
Nuker,
ToolboxNoteAdder,
)
from bernard.loader import load_yaml_config
from .helper import BJOTest
c... | f test_ba | nner(self):
browser = self.basic_test("Banner")
assert any(isinstance(actor, Banner) for actor in browser.rules[0].actors)
def test_modmailer(self):
browser = self.basic_test("Modmailer")
assert any(isinstance(actor, Modmailer) for actor in browser.rules[0].actors)
def test_not... |
manics/omero-mpcli | examples/tag-image.py | Python | gpl-2.0 | 1,939 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 University of Dundee & Open Microscopy Environment.
# All rights reserved.
#
# 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;... | t wrap, unwrap
def get(client, common):
qs = client.getSession().getQueryService()
params = omero.sys.ParametersI()
params.addIds(common)
rs = qs.p | rojection(
'SELECT link.child.id FROM DatasetImageLink link '
'WHERE link.parent.id in (:ids)', params)
return [unwrap(r[0]) for r in rs]
def process(client, common, params):
us = client.getSession().getUpdateService()
dt = datetime.now().strftime('%Y-%m-%d-%H:%M:%S.%f')
tag = omero.mo... |
patricklaw/pants | src/python/pants/backend/python/util_rules/lockfile_metadata.py | Python | apache-2.0 | 14,210 | 0.003589 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Iterable, Set, TypeVar
from pkg_re... | can be used in the current execution
context."""
raise NotImplementedError("call `is_valid_for` on subclasses only")
@_lockfile_metadata_version(1)
@dataclass(frozen=True)
class LockfileMetadataV1(LockfileMetadata):
requirements_invalidation_digest: str
@classmethod
def _from_json_dict(... | error_suffix: str,
) -> LockfileMetadataV1:
metadata = _get_metadata(json_dict, lockfile_description, error_suffix)
interpreter_constraints = metadata(
"valid_for_interpreter_constraints", InterpreterConstraints, InterpreterConstraints
)
requirements_digest = metada... |
forYali/yali | yali/gui/ScrKeyboard.py | Python | gpl-2.0 | 2,959 | 0.006085 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2010 TUBITAK/UEKAE
#
# 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 License, or (at your option)
# any later version.
#
# ... | keymap = dict(map(lambda x: (str(x[0]), unicode(x[1])), keymap.iteritems()))
ctx.installData.keyData = keymap
ctx.interface.informationWindow.hide()
if "," in keymap["xkblayout"]:
message = _("Use Alt- | Shift to toggle between alternative keyboard layouts")
ctx.interface.informationWindow.update(message, type="warning")
else:
ctx.interface.informationWindow.hide()
yali.util.setKeymap(keymap["xkblayout"], keymap["xkbvariant"])
def execute(self):
ctx.interface.inform... |
pseyfert/pyexiv2-scripts | dumpPHOTO.py | Python | gpl-2.0 | 997 | 0 | #!/usr/bin/python3
import sys
from gi.repository import GExiv2
phototags = {
'Exif.Photo.ExposureTime': "Belichtung:\t",
'Exif.Photo.FNumber': "Blende:\t\tF",
# 'Exif.Photo.ExposureProgram',
'Exif.P | hoto.ISOSpeedRatings': "ISO:\t\t",
# 'Exif.Photo.SensitivityType',
# 'Exif.Photo.ExifVersion',
# 'Exif.Photo.DateTimeOriginal',
# 'Exif.Photo.DateTimeDigitized',
# 'Exif.Photo.ComponentsConfiguration',
# 'Exif.Photo.CompressedBitsPerPixel',
# 'Exif.Photo.ExposureBiasValue',
# 'Exif.Photo... | 'Exif.Photo.Flash',
'Exif.Photo.FocalLength': "Brennweite:\t"
# 'Exif.Photo.MakerNote'
}
for i in range(1, len(sys.argv)):
metadata = GExiv2.Metadata(sys.argv[i])
print("file: {}".format(sys.argv[i]))
for key in phototags:
try:
print("{}: {}".format(phototags[key], metadata[key... |
adafruit/micropython | py/makeqstrdefs.py | Python | mit | 5,324 | 0.002066 | """
This script processes the out | put from the C preprocessor and extracts all
qstr. Each qstr is transformed into a qstr definition of the form 'Q(...)'.
This script works with Python 2.6, 2.7, 3.3 and 3.4.
"""
from __future__ import print_function
import re
import sys
import os
# Python 2/3 compatibility:
# - iterating through bytes is differen... | enc=None: bytearray(val)
from htmlentitydefs import name2codepoint
elif platform.python_version_tuple()[0] == '3':
bytes_cons = bytes
from html.entities import name2codepoint
unichr = chr
# end compatibility code
# Blacklist of qstrings that are specially handled in further
# processing and should be ... |
cryptobanana/ansible | lib/ansible/modules/network/nxos/nxos_vrf_af.py | Python | gpl-3.0 | 4,746 | 0.001686 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | append('route-target both auto evpn')
elif have a | nd not want:
commands.append('address-family %s unicast' % module.params['afi'])
commands.append('no route-target both auto evpn')
else:
commands.append('address-family %s unicast' % module.params['afi'])
if module.params['route_target_both_auto_evpn']:
... |
imsally/redash | redash/handlers/embed.py | Python | bsd-2-clause | 3,983 | 0.002762 | import json
import logging
import time
import pystache
from authentication import current_org
from flask import current_app, render_template, request, safe_join, send_file
from flask_login import current_user, login_required
from flask_restful import abort
from funcy import project
from redash import models, serialize... | t()
full_path = safe_join(settings.STATIC_ASSETS_PATHS[-2], 'index.html')
return send_f | ile(full_path, **dict(cache_timeout=0, conditional=True))
|
Jozhogg/iris | lib/iris/tests/unit/fileformats/grib/save_rules/test_data_section.py | Python | lgpl-3.0 | 7,789 | 0 | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | Check the use of a mask has been turned on via:
# gribapi.grib_set(grib_message, 'bitmapPresent', 1)
# gribapi.grib_set_double(grib_message, 'missingValue', ...)
# and that a suitable fill value has been chosen.
grib_api.grib_set.assert_called_once_with(GRIB_MESSAGE,
... | tmapPresent', 1)
args, = grib_api.grib_set_double.call_args_list
(message, key, fill_value), kwargs = args
self.assertIs(message, GRIB_MESSAGE)
self.assertEqual(key, 'missingValue')
self.assertTrue(fill_value < min_data or fill_value > max_data,
'Fill valu... |
TeamAADGT/CMPUT404-project-socialdistribution | social/app/migrations/0015_auto_20170410_1648.py | Python | apache-2.0 | 489 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-04-10 22:48
from __future__ import unicode_literals
from dja | ngo.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0014_merge_20170410_1409'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='origin',
),
migrations.RemoveField(
mo | del_name='post',
name='source',
),
]
|
moccu/django-storelocator | docs/source/conf.py | Python | mit | 8,054 | 0.007326 | # -*- coding: utf-8 -*-
#
# Django Storelocator documentation build configuration file, created by
# sphinx-quickstart on Wed May 22 11:52:39 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated f... | '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is use | d as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.