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
adamziel/django_translate
examples/example_basic/example_basic/settings.py
Python
mit
2,421
0.002065
# Customize django settings: DEBUG = True INSTALLED_APPS = ( 'django_translate', 'example_basic.translate' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django_translate.middleware.LocaleMiddleware', ) SEC...
r - it reloads # your translations on-the-fly so it's very easy to work with them # It will also throw an exception whenever there is any problem # with your translations (e.g. a translation is not found) - no more # guessing "why my translations are not used?" if DEBUG: from python_translate.translations import De...
ers are enabled, # but we want to use "po" files in this example from python_translate import loaders TRANZ_LOADERS = { "po": loaders.PoFileLoader(), "yml": loaders.YamlFileLoader() } # All settings below are the default ones: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ...
LaurentClaessens/phystricks
testing/demonstration/phystricksENQZooVqRaIv.py
Python
gpl-3.0
1,151
0.085143
# -*- coding: utf8 -*- from phystricks import * def rotation(angle,pts): ptsp=[ x.rotation(angle) for x in pts ] return tuple(ptsp) def truc(A,B,C,D,p
oints_names,angle,pspicts,n): A,B,C,D=rotation(angle,[A,B,C,D]) quadri=Polygon(A,B,C,D) quadri.put_mark(0.2,points_names=points_names,pspicts=pspicts) no_symbol(A,B,C,D) pspicts[n].DrawGraphs(quadri) def ENQZooVqRaIv(): pspicts,figs = IndependentPictures("ENQZooVqRaIv",4) for psp in...
oint(-3,-2) truc(A,B,C,D,points_names="ABCD",angle=30,pspicts=pspicts,n=0) E=Point(0,0) F=Point(3,0) G=F+(-2,-2) H=E+G-F truc(E,F,G,H,points_names="EFGH",angle=64,pspicts=pspicts,n=1) I=Point(0,0) J=Point(2,0) K=J+(0,-3) L=I+K-J truc(I,J,K,L,points_names="IJKL",angle=-12,...
valohai/valohai-cli
valohai_cli/commands/lint.py
Python
mit
1,886
0.002121
import os from typing import List import click from valohai_yaml.lint import lint_file from valohai_cli.ctx import get_project from valohai_cli.exceptions import CLIException from valohai_cli.messages import success, warn from valohai_cli.utils import get_project_directory def validate_file(filename: str) -> int: ...
filenames', nargs=-1, type=click.Path(file_okay=True, exists=True, dir_okay=False)) def lint(filenames: List[str]) -> None: """ Lint (syntax-check) a valohai.yaml file. The return code of this
command will be the total number of errors found in all the files. """ if not filenames: project = get_project() directory = (project.directory if project else get_project_directory()) config_file = os.path.join(directory, 'valohai.yaml') if not os.path.exists(config_file): ...
etherkit/OpenBeacon2
macos/venv/lib/python3.8/site-packages/_pyinstaller_hooks_contrib/hooks/stdhooks/hook-google.cloud.translate.py
Python
gpl-3.0
527
0
# -----------------
------------------------------------------------- # Copyright (c) 2020 PyInstaller Development Team. # # This file is distributed under the terms of the GNU General Public # License (version 2.0 or later). # # The full license is available in LI
CENSE.GPL.txt, distributed with # this software. # # SPDX-License-Identifier: GPL-2.0-or-later # ------------------------------------------------------------------ from PyInstaller.utils.hooks import copy_metadata datas = copy_metadata('google-cloud-translate')
aerialhedgehog/VyPy
trunk/VyPy/optimize/gradients/FiniteDifference.py
Python
bsd-3-clause
3,032
0.023417
# ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- from VyPy.data import OrderedBunch as obunch from VyPy.tools import atleast_2d_row, atleast_2d_col, array_type from copy import deepcopy import numpy ...
if not step.shape[0] == 1: step = step.T
values_run = np.vstack([ values_init , np.tile(values_init,[nx,1]) + np.diag(step[0]) ]) variables_run = [ deepcopy(variables).unpack_array(val) for val in values_run ] # run the function #for i in variables_run: print i results = se...
clarkperkins/stackdio
stackdio/api/cloud/utils.py
Python
apache-2.0
2,418
0.000827
# -*- coding: utf-8 -*- # Copyright 2017, Digital Reasoning # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
unicode_literals import importlib import logging import re from django.conf import settings from stackdio.core.config import StackdioConfigException logger = logging.getLogger(__name__) def get_provider_driver_class(provider): provider_classes = get_c
loud_providers() for provider_class in provider_classes: if provider_class.SHORT_NAME == provider.name: return provider_class return None def check_cloud_provider_settings(): if not hasattr(settings, 'CLOUD_PROVIDERS'): raise StackdioConfigException( 'settings.CLOU...
gilbertpilz/solum
solum/api/controllers/camp/v1_1/datamodel/extensions.py
Python
apache-2.0
1,139
0.002634
# # 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...
rom solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types #from solum.openstack.common import log as logging #LOG = logging.getLogger(__name__) class Extensions(api_types.Base): """extensions resource""" extension_links = [common_types.Link] """Thi...
information about the extensions supported by this Platform.""" def __init__(self, **kwds): # LOG.debug("extensions constructor: %s" % kwds) super(Extensions, self).__init__(**kwds)
santisiri/popego
envs/ALPHA-POPEGO/lib/python2.5/site-packages/SQLAlchemy-0.4.5-py2.5.egg/sqlalchemy/orm/dependency.py
Python
bsd-3-clause
26,274
0.005557
# orm/dependency.py # Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Bridge the ``PropertyLoader`` (i.e. a ``relation()``) and the ``UOWTransaction`` togeth...
n which, with r
egards to the two or three mappers handled by this ``PropertyLoader``. Also register itself as a *processor* for one of its mappers, which will be executed after that mapper's objects have been saved or before they've been deleted. The process operation manages attributes and d...
Frky/scat
src/shell/data/clangextractor.py
Python
mit
1,769
0.004522
#-*- coding: utf-8 -*- import os from clang.cindex import Config, Index, TypeKind class ClangExtractor(object): def __init__(self, libclang_path, srcdir): if Config.library_file != libclang_path: Config.set_library_file(libclang_path) self.srcdir = srcdir def extract(self): ...
protos[node.spelling].append("void *") else: protos[node.spelling].append(node.result_type.get_canonical().spelling) for c in node.get_arguments(): if (c.type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *") else: protos[node.spelling].append(c.type.get_canonical().spelling) if node.type.is_function_variadic(): protos[node.spelling].append("...") for c in node.get_children(): ...
arsgeografica/kinderstadt-registry
test/unit/test_pass_spec.py
Python
gpl-3.0
1,112
0
import pytest from registry.utils import pass_spec_parser, pass_spec_builder PASS_SPECS = { '': [], ' ': [], 'a': [], '111': [111], '111,112': [111, 112], '111, 112': [111, 112], '111-113': [111, 112, 113], '111 - 113': [111, ...
ef test_pass_spec_parser(spec): spec, expected
= spec assert pass_spec_parser(spec) == expected def test_pass_spec_builder(reverse_spec): expected, spec = reverse_spec assert pass_spec_builder(spec) == expected
bluegenes/MakeMyTranscriptome
scripts/util/KGML_pathway.py
Python
bsd-3-clause
28,215
0.003544
# (c) The James Hutton Institute 2013 # Author: Leighton Pritchard # # Contact: # leighton.pritchard@hutton.ac.uk # # Leighton Pritchard, # Information and Computing Sciences, # James Hutton Institute, # Errol Road, # Invergowrie, # Dundee, # DD6 9LH, # Scotland, # UK # # This program is free software: you can redistri...
reaction._pathway = self # Let the reaction know about the pathway self
._reactions[reaction.id] = reaction def remove_reaction(self, reaction): """ Remove an Reaction element from the pathway """ assert isinstance(reaction.id, (int, long)), \ "Node ID must be an integer, got %s (%s)" % (type(reaction.id), ...
tomi77/django-evostream
evostream/management/commands/listconfig.py
Python
mit
310
0
from evostream.default import api from evostream.managem
ent.base import BaseEvoStreamCommand class Command(BaseEvoStreamCommand): help = 'Returns a list with all push/pull configurations.' requires_syst
em_checks = False def get_results(self, *args, **options): return api.list_config()
Hasimir/pyjs
pyjswidgets/pyjamas/ui/FileUpload.py
Python
apache-2.0
1,721
0.002905
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # 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/...
ass FileUpload(Widget): _props = [("name", "Name", "Name", None), ("filename", "File Name", "FileName", None), ] def __init__(self, **kwargs): kwargs['StyleName'] = kwargs.get('StyleName', "gwt-FileUpload") element = kwargs.pop('Element', None) or DOM.createElement("in...
self.setElement(element) Widget.__init__(self, **kwargs) @classmethod def _getProps(self): return Widget._getProps() + self._props def getFilename(self): return DOM.getAttribute(self.getElement(), "value") def setFilename(self, value): DOM.setAttribute(self.get...
erigones/esdc-ce
vms/models/base.py
Python
apache-2.0
22,882
0.001573
import re from django.db import models, transaction from django.utils import timezone from django.utils.six import iteritems, with_metaclass from django.utils.translation import ugettext_lazy as _ from django.core.cache import cache from django.core.exceptions import SuspiciousOperation from django.contrib.contenttype...
o tracks changes of status property and updates the status_change attribute if changed. Status information is cached - the key is PK:status. """ _lock = False # Cannot be saved when True _cache_status = False # Should we cache the status into redis after calling save()? _orig_status = None # Orig...
s')) # You need this in descendant status_change = models.DateTimeField(_('Last status change'), default=None, null=True, editable=False) created = models.DateTimeField(_('Created'), editable=False) changed = models.DateTimeField(_('Last changed'), editable=False) class Meta: app_label = 'vms'...
hlzz/dotfiles
graphics/VTK-7.0.0/Imaging/Core/Testing/Python/TestMapToWindowLevelColors.py
Python
bsd-3-clause
933
0
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() RANGE = 150 MAX_ITERATIONS_1 = RANGE MAX_ITERATIONS_2 = RANGE XRAD = 2
00 YRAD = 200 mandelbrot1 = vtk.vtkImageMandelbrotSource() mandelbrot1.SetMaximumNumberOfIterations(150) mandelbrot1.SetWholeExtent(0, XRAD - 1, 0, YRAD - 1, 0, 0) mandelbrot1.SetSampleCX(1.3 / XRAD, 1.3 / XRAD, 1.3 / XRAD, 1.3 / XRAD) mandelbrot1.SetOriginCX(-0.72, 0.22, 0.0, 0.0) mandelbrot1.SetProjectionAxe...
mapToWL = vtk.vtkImageMapToWindowLevelColors() mapToWL.SetInputConnection(mandelbrot1.GetOutputPort()) mapToWL.SetWindow(RANGE) mapToWL.SetLevel(RANGE / 3.0) # set the window/level to 255.0/127.5 to view full range viewer = vtk.vtkImageViewer() viewer.SetInputConnection(mapToWL.GetOutputPort()) viewer.Set...
mtkwock/Genome-Matching
code/plot_chances.py
Python
mit
690
0.013043
import numpy as np import matplotlib.pyplot as plt import sys fname = sys.argv[1] exes = [0] * 101 wise = [0] * 101 f = open(fname, 'r') for i in range(101): split = f.readline().split(" ") exes[i] = split[0] wise[i] = split[1] x = np.asarray(exes) y = np.asarray(wise) fig, ax = plt.subplots() ax.set_xlabel("...
-4].split(" ") # remove .txt inte = "S_{err}= |, \sigma_{err}= |, S_{read}= |, \sig
ma_{err}= |, S_{curve}= ".split("|") title = "$" + inte[0] + tit[0] + inte[1] + tit[1] + inte[2] + tit[2] + inte[3] + tit[3] + inte[4] + tit[4] + "$" ax.set_title(title) line, = ax.plot(x, y) plt.show()
Anlim/decode-Django
Django-1.5.1/django/forms/widgets.py
Python
gpl-2.0
36,017
0.002467
""" HTML Widget classes 组件 """ from __future__ import absolute_import, unicode_literals import copy import datetime from itertools import chain try: from urllib.parse import urljoin except ImportError: # Python 2 from urlparse import urljoin from django.conf import settings from django.forms.util import ...
es of seeing whether something has changed, None is # the same as an e
mpty string, if the data or inital value we get # is None, replace it w/ ''.
gmimano/commcaretest
corehq/apps/users/forms.py
Python
bsd-3-clause
11,739
0.00247
from crispy_forms.bootstrap import FormActions from crispy_forms.helper import FormHelper from crispy_forms.layout import ButtonHolder, Div, Fieldset, HTML, Layout, Submit from django import forms from django.core.validators import EmailValidator, email_re from django.core.urlresolvers import reverse from django.forms....
th=50, required=False) email = forms.EmailField(label=ugettext_lazy("E-mail"), max_length=75, required=False) language = forms.ChoiceField( choices=(), initial=None, required=False, help_text=mark_safe_lazy( ugettext_lazy( "<i class=\"icon-info-sign\">...
n, fr (partial), and hin (partial)." ) ) ) def load_language(self, language_choices=None): if language_choices is None: language_choices = [] self.fields['language'].choices = [('', '')] + language_choices class UpdateMyAccountInfoForm(BaseUpdateUserForm, BaseU...
agilefall/aws-tools
sqs_metrics.py
Python
apache-2.0
3,242
0.01388
#!/usr/bin/python import argparse import boto.sqs import boto.ec2.cloudwatch import os import csv from datetime import datetime, timedelta from collections import defaultdict import pandas as pd import matplotlib.pyplot as plt import StringIO class SqsMetrics: default_metrics= ["ApproximateNumberOfMessagesVisible...
type=int, help="num hours to retrieve", default=24) args = parser.parse_args() sm = SqsMetrics(args.region) if args.metrics: metrics_name = args.metrics.split(',') else: metrics_name = SqsMetrics.default_metrics metrics = sm.get_queue_metrics(args.queue_name, metrics_name, arg...
to_graph }[args.output](metrics) if __name__ == "__main__": main()
andymckay/addons-server
src/olympia/users/cron.py
Python
bsd-3-clause
1,853
0
from django.db import connections import commonware.log import mul
tidb from celery.task.sets import TaskSet import cronjobs from olympia.amo import VALID_STATUSES from olympia.amo.utils import chunked from .models import UserProfile from .tasks import update_user_ratings_task task_log = commonware.log.getLogger('z.task') @cronjobs.register def update_user_ratings(): """Updat...
onnections[multidb.get_slave()].cursor() # We build this query ahead of time because the cursor complains about data # truncation if it does the parameters. Also, this query is surprisingly # quick, <1sec for 6100 rows returned q = """ SELECT addons_users.user_id as user_id, ...
rohitwaghchaure/New_Theme_Erp
erpnext/config/hr.py
Python
agpl-3.0
5,045
0.045986
from frappe import _ def get_data(): return [ { "label": _("Documents"), "icon": "icon-star", "items": [ { "type": "doctype", "name": "Employee", "description": _("Employee records."), }, { "type": "doctype", "name": "Leave Application", "description": _("Applicati...
": "Deduction Type", "description": _("Tax and other salary deductions.") }, { "type": "doctype", "name": "Leave Allocation", "description": _("Allocate leaves for a period.") }, { "type": "doctype", "name":"Leave Type", "description": _("Type of leaves like casual, si...
ave Block List", "description": _("Block leave applications by department.") }, { "type": "doctype", "name": "Appraisal Template", "description": _("Template for performance appraisals.") }, { "type": "doctype", "name": "Expense Claim Type", "description": _("Types of ...
bxlab/bx-python
scripts/bed_extend_to.py
Python
mit
1,068
0.001873
#!/usr/bin/env python """ Read BED file and extend each record to the specified minimum length. If chromosome size information is provided trim extended intervals. usage: %prog amount [ chrom_file ] < bed_file """ import sys from bx.intervals.io import GenomicIntervalReader length = int(sys.argv[1]) chrom_len = No...
end = start + length else: start = end - length # Trim if start < 0: start = 0 if chrom_len and end > chrom_len[interval.chrom]: end = chrom_len[interval.chrom] # Set new start and end interval.start = start interva...
t possibly adjusted interval print(interval)
armbrustlab/seaflowpy
src/seaflowpy/cli/commands/dayofyear_cmd.py
Python
gpl-3.0
1,025
0.001951
import click from seaflowpy import seaflowfile from seaflowpy import errors @click.command() @click.option('-v', '--verbose', is_flag=True, help='Print 3 columns: input path, file name, day of year dir.') @click.argument('files', nargs=
-1, type=click.Path()) def dayofyear_cmd(verbose, files): """ Gets calculated day of year dir from filename timestamp. File paths must be new-style datestamped paths. Any part of the file path except for the filename will be ignored. The filename may include a '.gz' extension. Outputs to STDOUT. ...
ile(file) except errors.FileError as e: click.echo("%s %s" % (file, e), err=True) continue if verbose: output.append([file, sfile.file_id, sfile.filename, sfile.dayofyear]) else: output.append([sfile.dayofyear]) if output: click.echo("\...
ucoin-io/cutecoin
src/sakia/gui/sub/password_input/view.py
Python
mit
1,433
0.000698
from PyQt5.QtWidgets import QWidget, QDialogButtonBox from PyQt5.QtCore import QEvent, Qt from .password_input_uic import Ui_PasswordInputWidget class PasswordInputView(QWidget, Ui_PasswordInputWidget): """ The model of Navigation component """ def __init__(self, parent): # construct from qtDe...
lf.tr("Password is val
id")) self.button_box.button(QDialogButtonBox.Ok).setEnabled(True) def changeEvent(self, event): """ Intercepte LanguageChange event to translate UI :param QEvent QEvent: Event :return: """ if event.type() == QEvent.LanguageChange: self.retranslat...
palankai/xadrpy
src/xadrpy/core/workers/management/commands/worker_stop.py
Python
lgpl-3.0
441
0.006803
from django.core.management.base import NoArgsCommand, CommandError import sys from xadrpy.core.workers.daemon import DaemonHandler class Command(NoArgsCommand): def handle(self, **options): daemon_handler = DaemonHandler("daemon.pid", "daemon.sock") try: daemon_handler.stop() ...
raise CommandError(e)
DePierre/owtf
tests/testing_framework/base_test_cases.py
Python
bsd-3-clause
14,964
0.002339
from io import BytesIO as StringIO from os import path from tests.testing_framework.server import HandlerBuilder, WebServerProcess from tests.testing_framework.utils import ExpensiveResourceProxy from hamcrest.library.text.stringcontains import contains_string from hamcrest.core.assert_that import assert_that from hamc...
gin_output = self.core_instance.PluginHandler.ProcessPlugin(plugin_dir, plugin, {}) result.append(str(plugin_output)) except: result.append(str(sys.exc_info()[0])) finally: stdout_output = self.get_recorded_stdout_and_close() result.append(stdout_output) ...
output.count(self.BUG_FOUND_BANNER) > 0: print self.owtf_output self.fail(self.BUG_FOUND_MESSAGE) def assert_external_tool_started(self, times): """Assert that the plugin started a given number of tools.""" self.assert_that_output_contains(self.PLUGIN_START_TEXT, times) ...
wddwycc/tifa
tifa/cli.py
Python
mit
1,220
0
import os import click from tifa.core import Template, File from tifa.errors im
port ValidationError from tifa.prompt import Prompt from tifa.validation import normalize_config here = os.path.abspath(os.path.dirname(__file__)) @click.group() def main(): pass @main.command(help='Generate a tifa configuration yaml') @click.option('--name', prompt='project name') def init(name): file = F...
te project through configuration') @click.option( '--config', '-c', type=click.Path(exists=True), help='Specific configuration file path', ) def gen(config): config_path = config or './tifa.yaml' try: config = normalize_config(config_path) except ValidationError as e: Prompt.warn(str...
BeenzSyed/tempest
tempest/api/compute/security_groups/test_security_groups.py
Python
apache-2.0
8,626
0
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
thod def setUpClass(cls): super(SecurityGroupsTestJSON, cls).setUpClass() cls.client = cls.security_groups_client def _delete_security_group(self, securitygroup_id): resp, _ = self.client.delete_security_group(securitygroup_id) self.
assertEqual(202, resp.status) @test.attr(type='gate') def test_security_groups_create_list_delete(self): # Positive test:Should return the list of Security Groups # Create 3 Security Groups security_group_list = list() for i in range(3): s_name = data_utils.rand_name...
galaxy-genome-annotation/python-apollo
arrow/commands/annotations/get_feature_sequence.py
Python
mit
692
0.001445
import click from arrow.cli import pass_context, json_loads from arrow.decorators import custom_exception, dict_output @click.command('get_feature_sequence') @click.argument("feature_id", type=str) @click.option( "--organism", help="Organism Common Name", type=str ) @click.option( "--sequence", he...
A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.get_feature_sequence(feature_id, organis
m=organism, sequence=sequence)
valexandersaulys/airbnb_kaggle_contest
venv/lib/python3.4/site-packages/scipy/optimize/tests/test_tnc.py
Python
gpl-2.0
11,264
0.000444
""" Unit tests for TNC optimization routine from tnc.py """ from numpy.testing import (assert_allclose, assert_equal, TestCase, run_module_suite) from scipy import optimize import numpy as np from math import pow class TestTnc(TestCase): """TNC non-linear optimization. These test...
(x[2], 2), 2) + pow(1.0 - x[2], 2) + 10.1 * (pow(x[1] - 1.0, 2) + pow(x[3] - 1.0, 2)) + 19.8 * (x[1] - 1.0) * (x[3] - 1.0)) * 1.0e-5 def g38(self, x): dif = [0, 0, 0, 0] dif[0] = (-400.0 * x[0] * (x[1] - pow(x[0], 2)) - ...
2.0 * (1.0 - x[0])) * 1.0e-5 dif[1] = (200.0 * (x[1] - pow(x[0], 2)) + 20.2 * (x[1] - 1.0) + 19.8 * (x[3] - 1.0)) * 1.0e-5 dif[2] = (- 360.0 * x[2] * (x[3] - pow(x[2], 2)) - 2.0 * (1.0 - x[2])) * 1.0e-5 dif[3] = (180.0 * (x[3] - pow(x[2], 2)) + 20.2 * (...
cfe-lab/Kive
kive/container/serializers.py
Python
bsd-3-clause
14,645
0.000341
from django.db import transaction from rest_framework import serializers from rest_framework.fields import URLField from container.models import ContainerFamily, Container, ContainerApp, ContainerRun, Batch, ContainerDataset, \ ContainerArgument, ContainerLog from kive.serializers import AccessControlSerializer fr...
d', 'apps') class ContainerFamilyChoiceSerializer(AccessControlSerializer, serializers.ModelSerializer): containers = ContainerChoiceSerializer(many=True, read_only=True) class Meta: model = ContainerFamily field
s = ( "id", "url", "name", "description", "git", "user", "users_allowed", "groups_allowed", "containers") class ContainerDatasetSerializer(serializers.ModelSerializer): run = serializers.HyperlinkedRelatedF...
repotvsupertuga/tvsupertuga.repository
script.vodextende/scrapers/ninemovies_proxy.py
Python
gpl-2.0
5,303
0.003771
# -*- coding: utf-8 -*- """ SALTS XBMC Addon Copyright (C) 2014 tknorris This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) a...
des = [] show_url = self.base_url + show_url for item in scraper_u
tils.get_files(self, show_url, cache_limit=1): if re.search('[._ -]S%02d[._ -]?E%02d[._ -]' % (int(video.season), int(video.episode)), item['title'], re.I): episodes.append(item) return episodes def search(self, video_type, title, year, season=''): # @UnusedVari...
jeffrimko/PopPage
_Check_Versions.py
Python
mit
949
0.015806
##==============================================================# ## SECTION: Imports # ##==============================================================# import verace ##==============================================================# ## SECTION: Global Definitions ...
=======================# VERCHK = verace.VerChecker("PopPage", __file__) VERCHK.include(r"app\setup.py", match="version = ", splits=[('"',1)]) VERCHK.include(r"app\poppage.py", match="__version__ = ", splits=[('"',1)]) VERCHK.include(r"CHANGELOG.adoc", match="poppage-", spli
ts=[("-",1),(" ",0)], updatable=False) ##==============================================================# ## SECTION: Main Body # ##==============================================================# if __name__ == '__main__': VERCHK.prompt()
FreekingDean/home-assistant
tests/components/stream/test_worker.py
Python
apache-2.0
29,172
0.000926
"""Test the stream worker corner cases. Exercise the stream worker functionality by mocking av.open calls to return a fake media container as well a fake decoded stream in the form of a series of packets. This is needed as some of these cases can't be encoded using pyav. It is preferred to use test_hls.py for example...
m(self.audio_packets) return FakeAvOutputStream(self.video_packets) def mux(self, packet): """Capture a packet for tests to examine.""" # Forward to appropriate FakeStream packet.stream.mux(packet) # Make new init/part dat
a available to the worker self.memory_file.write(b"0") def close(self): """Close the buffer.""" # Make the final segment data available to the worker self.memory_file.write(b"0") def capture_output_segment(self, segment): """Capture the output segment for tests to inspe...
mozillazg/redis-py-doc
redis/exceptions.py
Python
mit
4,645
0
"Core exceptions raised by the Redis client" class RedisError(Exception): pass class ConnectionError(RedisError): pass class TimeoutError(RedisError): pass class AuthenticationError(ConnectionError): pass class AuthorizationError(ConnectionError): pass class BusyLoadingError(ConnectionEr...
will accept all queries that pertain to this hash slot, but only if the key i
n question exists, otherwise the query is forwarded using a -ASK redirection to the node that is target of the migration. src node: MIGRATING to dst node get > ASK error ask dst node > ASKING command dst node: IMPORTING from src node asking command only affects next command ...
gesellkammer/pyliblo
test/unit.py
Python
lgpl-2.1
8,818
0.003176
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pyliblo - Python bindings for the liblo OSC library # # Copyright (C) 2007-2011 Dominic Sacré <dominic.sacre@gmx.de> # # 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 F...
== 'i' assert self.cb.data == "data" assert matchHost(self.cb.src.get_url(), 'osc\.udp://.*:1234/') def testSendBlob(self): self.server.add_method('/blob', 'b', self.callback) self.server.send('1234', '/blob', [4, 8, 15, 16, 23, 42]) assert self.server.recv() == True ...
assert list(self.cb.args[0]) == [4, 8, 15, 16, 23, 42] else: assert self.cb.args[0] == b'\x04\x08\x0f\x10\x17\x2a' def testSendVarious(self): self.server.add_method('/blah', 'ihfdscb', self.callback) if sys.hexversion < 0x03000000: self.server.send(1234, '/blah'...
hhhaiai/synergy
ext/toolchain/__init__.py
Python
gpl-2.0
702
0.002849
# synergy -- mouse and keyboard sharing utility # Copyright (C) 2012 Synergy Si Ltd. # Copyright (C) 2009 Nick Bolton # # This package is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # found in the file LICENSE that should have accompanied this file. # # ...
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 program. If not, see <http...
u.org/licenses/>.
LaoZhongGu/kbengine
demo/res/scripts/cell/Monster.py
Python
lgpl-3.0
3,929
0.039932
# -*- coding: utf-8 -*- import random import math import time import KBEngine import wtimer from KBEDebug import * from interfaces.Combat import Combat from interfaces.Spell import Spell from interfaces.Motion import Motion from interfaces.State import State from interfaces.Flags import Flags from interface...
ethod. 检查自己是否在可活动领地中 """ return AI.checkInTerritory(self) def isMonster(self): """ virtual method. """ return True # ---------------------------------------------------------------- # callback # ---------------------------------------------------------------- def onWitnessed(self, i...
ed): """ KBEngine method. 此实体是否被观察者(player)观察到, 此接口主要是提供给服务器做一些性能方面的优化工作, 在通常情况下,一些entity不被任何客户端所观察到的时候, 他们不需要做任何工作, 利用此接口 可以在适当的时候激活或者停止这个entity的任意行为。 @param isWitnessed : 为false时, entity脱离了任何观察者的观察 """ AI.onWitnessed(self, isWitnessed) def onForbidChanged_(self, forbid, isInc): """ ...
wichmann/UpLoad
languages/de.py
Python
gpl-2.0
16,769
0.022555
# -*- coding: utf-8 -*- { ' (late)': ' (verspätet)', '!=': '!=', '!langcode!': 'de', '!langname!': 'Deutsch (DE)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '""Update" ist ein optionaler Ausdruck wie "Feld1 = \'newvalue". JOIN Ergebnisse können n...
'db': 'db', 'DB Model': 'Muster-DB', 'Delete': 'Löschen', 'Delete:': 'Löschen:', 'Demo': 'Demo', 'Deployment Recipes': 'Entwicklungsrezepte', 'Description': 'Beschreibung', 'design': 'Design', 'Design': 'Design', 'DISK': 'D
ISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk gelöscht', 'Documentation': 'Dokumentation', "Don't know what to do?": 'Wissen Sie nicht weiter?', 'done!': 'Fertig!', 'Download': 'Download', 'Download all uploaded files...': 'Alle hochgeladenen Dateien herunterladen...', 'Download files': 'Dateien her...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractVodkatranslationsCom.py
Python
bsd-3-clause
671
0.028316
def extractVodkatranslationsCom(item): ''' Parser for 'vodkatr
anslations.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostf
ix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('Ordinary I and Extraordinary Them', 'Ordinary I and Extraordinary Them', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', ...
mdhaman/superdesk-core
apps/desk_routing.py
Python
agpl-3.0
2,361
0.001694
import superdesk from superdesk.notification import push_notification from apps.content import push_content_notification from superdesk import get_resource_service PRIVILEGE = 'desk_routing' class ClosedDeskResource(superdesk.Resource): """Custom resource to change desk.is_closed Allowing users without de...
_id=original.get('_id'),
_etag=updates.get('_etag')) def remove_marks(self, desk_id): """Remove "mark for desk" attribute :param ObjectId desk_id: id of the desk being re-opened """ for service_name in ('archive', 'published'): service = get_resource_service(service_name) ...
richtier/alexa-voice-service-client
alexa_client/alexa_client/connection.py
Python
mit
4,979
0
import json import http from requests_toolbelt import MultipartEncoder from requests.exceptions import HTTPError from hyper import HTTP20Connection from alexa_client.alexa_client import constants, helpers class ConnectionManager: connection = None # TODO: in next breaking change release rename to `base_url`...
geId': '' }, 'payload': {} } } multipart_data = MultipartEncoder( fields=[ (
'metadata', ( 'metadata', json.dumps(payload), 'application/json', {'Content-Disposition': "form-data; name='metadata'"} ) ), ], boundary='boundary' ...
great-expectations/great_expectations
great_expectations/render/renderer/content_block/validation_results_table_content_block.py
Python
apache-2.0
10,949
0.002283
import logging import traceback import warnings from copy import deepcopy from great_expectations.core.expectation_configuration import ExpectationConfiguration from great_expectations.expectations.core.expect_column_kl_divergence_to_be_less_than import ( ExpectColumnKlDivergenceToBeLessThan, ) from great_expectat...
0] .expectation_config.kwargs["meta_properties_to_render"] .keys()
) return sorted(custom_columns) @classmethod def _process_content_block(cls, content_block, has_failed_evr, render_object=None): super()._process_content_block(content_block, has_failed_evr) content_block.header_row = ["Status", "Expectation", "Observed Value"] content_block....
Hernanarce/pelisalacarta
python/main-classic/channels/tupornotv.py
Python
gpl-3.0
10,969
0.024911
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para tupornotv # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re import sys import urlparse from core import config...
itemlist.append( Item( channel=item.channel , title="Año" , action="novedades" , url="http://tuporno.tv/ano" , folder=True ) ) return itemlist def categorias(item): logger.info("[tupornotv.py] categorias") url=item.url # ------------------------------------------------------ # Descarg...
------------------------------------------------- # Extrae las entradas # ------------------------------------------------------ # seccion categorias # Patron de las entradas if url == "http://tuporno.tv/categorias/": patronvideos = '<li><a href="([^"]+)"' # URL patronvideos +=...
nickzuber/ClusterRunner
test/unit/master/test_cluster_runner_config.py
Python
apache-2.0
5,849
0.002394
from genty import genty, genty_dataset import sys from app.master.atomizer import Atomizer from app.master.job_config import ConfigValidationError from app.master.cluster_runner_config import ClusterRunnerConfig, ConfigParseError from test.framework.base_unit_test_case import BaseUnitTestCase @genty class TestCluste...
'The output of {}() should match the expected value.'.format(method_name)) @genty_dataset( ('max_executors', sys.maxsize), ('setup_build', None), ) def test_undefined_conf_properties_return_default_values(self, conf_method_name, expected_value): config
= ClusterRunnerConfig(self._MINIMAL_CONFIG) job_config = config.get_job_config() actual_value = getattr(job_config, conf_method_name) self.assertEqual(actual_value, expected_value, 'The default output of {}() should match the expected value.'.format(conf_method_name)) ...
bstinsonmhk/python-template
{{cookiecutter.project_repo}}/setup.py
Python
mit
1,796
0.000557
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ # TODO: put package requireme...
tion=__d
oc__, packages=find_packages(exclude=['tests']), include_package_data=True, zip_safe=False, platforms='any', install_requires=requirements, classifiers=[ # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers 'Development Status :: 1 - Planning', # 'Development...
ESOedX/edx-platform
common/lib/xmodule/xmodule/tests/xml/test_policy.py
Python
agpl-3.0
1,216
0.004112
""" Tests that policy json files import correctly when loading XML """ from __future__ import absolute_import import pytest from xmodule.tests.xml import XModuleXmlImportTest from xmodule.tests.xml.fact
ories import CourseFactory class TestPolicy(XModuleXmlImportTest): """ Tests that policy json files import correctly when loading xml """ def test_no_attribute_mapping(self): # Policy files are json, and thus the values aren't passed through 'deserialize_fiel
d' # Therefor, the string 'null' is passed unchanged to the Float field, which will trigger # a ValueError with pytest.raises(ValueError): course = self.process_xml(CourseFactory.build(policy={'days_early_for_beta': 'null'})) # Trigger the exception by looking at the imp...
nextcloud/appstore
nextcloudappstore/core/caching.py
Python
agpl-3.0
1,819
0
from typing import List, Tuple, Any from django.db.models import Max, QuerySet from semantic_version import Version from nextcloudappstore.core.models import App, AppReleaseDeleteLog, Category, \ AppRating, NextcloudRele
ase def create_etag(pairs: List[Tuple[QueryS
et, str]]) -> str: """ Turn a list of queryset and timestamp pairs into an etag. The latest timestamp will be chosen as the etag :param pairs: a list of queryset and attribute which holds a timestamp :return: an etag """ result = map(lambda p: p[0].aggregate(m=Max(p[1]))['m'], pairs) res...
LearnPythonAndMakeGames/ecs
examples/combat_sim/run.py
Python
apache-2.0
3,303
0.000908
#!/usr/bin/env python ''' Description: Runs a combat simulator -- Cowboys vs Aliens Usage: run [options] [--memory | --compute] Options: -c --cowboys NUMBER Number of cowboys [default: 10] -a --aliens NUMBER Number of aliens [default: 10] -q --quiet Reduces verbosity -m --memory...
in entities['cowboys']) aliens_alive = sum(e.health.alive for e in entities['aliens']) if cowboys_alive == 0 or aliens_alive == 0: break if not quiet: results = "Round: {} -- {} | {}" print(results.format(combat_round, cowboys_alive, aliens_alive)) co...
alive = { 'cowboys': sum(e.health.alive for e in entities['cowboys']), 'aliens': sum(e.health.alive for e in entities['aliens']) } print('Cowboys alive: {}'.format(alive['cowboys'])) print('Aliens alive: {}'.format(alive['aliens'])) print('-'*40) if alive['cowboys'] > 0: prin...
jmgilman/Neolib
neolib/inventory/UserInventory.py
Python
mit
2,623
0.009531
""":mod:`UserInventory` -- Provides an interface for a user inventory .. module:: UserInventory :synopsis: Provides an interface for a user inventory .. moduleauthor:: Joshua Gilman <joshuagilman@gmail.com> """ from neolib.exceptions import parseException from neolib.exceptions import invalidUser from neolib.inven...
es contain extra information encapsulated in paranthesis if "(" in name: name = name.split("(")[0] tmpItem = Item(name) tmpItem.id = item.a['onclick'].split("(")[1].replace(");", "") tmpItem.img ...
m.desc = item.img['alt'] tmpItem.usr = self.usr self.items[name] = tmpItem except Exception: logging.getLogger("neolib.inventory").exception("Unable to parse user inventory.", {'pg': pg}) raise parseException
dpgettings/ezgal
ezgal/scripts/convert_pegase2.py
Python
mit
2,688
0.007068
#!/usr/bin/python import sys,os,pyfits,math import numpy as np import ezgal if len(sys.argv) < 3: print '\nconvert pegase2 sps models to EzGal fits format' print 'Usage: convert_pegase2.py pegase.fits output.model\n' sys.exit(2) filein = sys.argv[1] fileout = sys.argv[2] if not os.path.isfile(filein): r...
ry_hdu.header.update('model', 'p2', comment='meta data') primary_hdu.header.update('met', met, comment='meta data') primary_hdu.header.update('imf', imf, comment='meta data') primary_hdu.header.update('sfh', sfh, comment='meta data') # fetch fits extension which contains age/mass info info = fits['ETS_PARA...
list of frequencies in a table vs_hdu = pyfits.new_table(pyfits.ColDefs([pyfits.Column(name='vs', array=vs[sinds], format='D', unit='hertz')])) # and the list of ages + masses ages_hdu = pyfits.new_table(pyfits.ColDefs([pyfits.Column(name='ages', array=info['age']*1e6, format='D', unit='years'), pyfits.Column(name='mas...
allansp84/license-plate
modules/utils/util.py
Python
bsd-3-clause
5,029
0.004375
import os import sys import operator import numpy as np import itertools as it from glob import glob from multiprocessing import Pool from .config import * def start_process(): pass def do_something(d): result = d.run() return result def retrieve_samples(input_path, file_type): dir_names = [] ...
configs = replace_from_list(configs, 'correlation_phase', 'PC') configs = replace_from_list(configs, 'correlation_mag', 'MC')
reverse = False if 'hter' in measure else True results = sorted(zip(configs, values), key=operator.itemgetter(1), reverse=reverse) fname = "{0}/{1}.{2}.csv".format(output_path, test_set, measure) f_csv = open(fname, 'w') f_csv.write("N,LGF,M,CS,SDD,DS,CP,C,%s\n" % str(measure).upper()) for r in re...
cpatrick/comic-django
django/comic/wsgi.py
Python
apache-2.0
1,360
0.002206
""" WSGI config for comic project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` se...
SITE_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) sys.path.append(SITE_ROOT) sys.path.append(os.path.join(SITE_ROOT,"comic")) os.environ.setdefault("PYTHON_EGG_CACHE", "/tmp/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "comic.settings") #
This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import ...
jedie/django-secure-js-login
tests/test_utils/manipulators.py
Python
gpl-3.0
1,102
0.009982
class Manipulator(object): KINDS=() SEPERATOR="$" def __call__(self, txt, **kwargs): data = {} splitted = txt.split("$")
for kind, part in zip(self.KINDS, splitted): data[kind]=part for info, new_value in kwargs.items(): kind, position = info.rsplit("_",1) part = data[kind] if position=="start": part = new_value + part[1:] elif position=="mid": ...
[:-1] + new_value else: raise AssertionError data[kind] = part return "$".join([data[kind] for kind in self.KINDS]) class CryptManipulator(Manipulator): KINDS = ("algorithm", "iterations", "salt", "hash", "data") xor_crypt_manipulator = CryptManipulator() class ...
areriff/pythonlearncanvas
Python Script Sample/sqlite_check.py
Python
mit
1,034
0.001934
# Script Name : sqlite_check.py # Author : Craig Richards # Created : 20 May 2013 # Last Modified : # Version : 1.0 # Modifications : # Description : Runs checks to check my SQLITE database import sqlite3 as lite import sys import os dropbox = os.getenv("dropbox") dbfile = ("Databases\jarvis.db") master_db = os...
() con = lite.connect(master_db) cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table'") rows = cur.fetchall() for row in rows: print row con = lite.connect(master_db) cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table'") while True: row = cur.fetc...
row == None: break print row[0]
jlec/coot
python-tests/05_rna_ghosts.py
Python
gpl-3.0
4,736
0.00549
# 05_rna_ghosts.py # Copyright 2008 by The University of York # Author: Bernhard Lohkamp # Copyright 2007, 2008 by The University of Oxford # Author: Paul Emsley # 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 Soft...
(imol): atom_attribute_settings = [] for chain_id in chain_ids(imol): if (not is_solvent_chain_qm(imol, chain_id)): n_residues = chain_n_residues(chain_id, i
mol) print " There are %s residues in chain %s" %(n_residues, chain_id) for serial_number in range(n_residues): res_name = resname_from_serial_number(imol, chain_id, serial_number) res_no = seqnum_from_serial_number (imol, cha...
edx-solutions/edx-platform
common/djangoapps/util/prompt.py
Python
agpl-3.0
1,137
0.00088
""" Enables interactivity for CLI operations """ import sys def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be...
alue is one of "yes" or "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n
": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice...
gunan/tensorflow
tensorflow/python/data/kernel_tests/list_files_test.py
Python
apache-2.0
8,979
0.005346
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ath.join(self.tmp_dir, '*'), shuffle=False) self.assertDatasetProduces( dataset, expected_output=[ compat.as_bytes(path.join(self.tmp_dir, filename)) for filename in sorted(filenames) ]) def testFixedSeedResultsInRepeatableOrder(self): filenames = ['a', 'b', 'c...
p_dir, '*'), shuffle=True, seed=37) expected_filenames = [ compat.as_bytes(path.join(self.tmp_dir, filename)) for filename in filenames ] all_actual_filenames = [] for _ in range(3): actual_filenames = [] next_element = self.getNext(dataset_fn(), requires_initialization=Tru...
chiara-paci/santaclara-pages
santaclara_pages/santaclara_languages.py
Python
gpl-3.0
5,795
0.02623
from django.conf import settings import santaclara_editor.languages from santaclara_editor.santaclara_lang import tags from santaclara_editor.santaclara_lang import factories from santaclara_pages.models import Page,Image,File import re class IUrlTag(tags.Tag): def __init__(self,lang,padre): tags.Tag._...
tion"): caption="" self.args["caption"]="" else: caption=self.args["caption"] url="" if not self.args.has_key("url"): name=self.args[0].split("=")[1] if name: try: f=File.objects.get(name__iexact=name...
.media_root,"") if not caption: caption=f.description except File.DoesNotExist, e: pass if url: url=self.media_url+url self.args["url"]=url if (not self.args["caption"]) and caption: self.args...
olafhauk/mne-python
examples/connectivity/plot_mne_inverse_envelope_correlation_volume.py
Python
bsd-3-clause
3,736
0
""" ==================================================== Compute envelope correlations in volume source space ==================================================== Compute envelope correlations of orthogonalized activity :footcite:`HippEtAl2012,KhanEtAl2018` in source space using resting state CTF data in a volume sour...
_dir, subject, 'bem', subject + '-5120-bem-sol.fif') raw_fname = op.join(data_path, 'MEG', 'bst_resting', 'subj002_spontaneous_20111102_01_AUX.ds') crop_to = 60. ######################################
######################################## # Here we do some things in the name of speed, such as crop (which will # hurt SNR) and downsample. Then we compute SSP projectors and apply them. raw = mne.io.read_raw_ctf(raw_fname, verbose='error') raw.crop(0, crop_to).pick_types(meg=True, eeg=False).load_data().resample(80)...
endlessm/endless-ndn
demo/mock-usb-producer.py
Python
lgpl-3.0
1,550
0.003226
# -*- Mode:python; coding: utf-8; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ # # Copyright (C) 2016 Endless Mobile, Inc. # Author: Niv Sardi <xaiki@endlessm.com> # # 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 # ...
logger = logging.getLogger(__name__) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument("dir") args = parser.parse_args() store = simple_s
tore.Producer( prefix=SUBSCRIPTIONS_SOMA, base=path.realpath(args.dir)) logger.info('creating store: %s', args.__dict__) store.start() GLib.MainLoop().run()
henriquegemignani/randovania
randovania/gui/dialog/base_cosmetic_patches_dialog.py
Python
gpl-3.0
516
0
from PySide2.QtWidgets import QDialog from randovania.l
ayout.base.cosmetic_patches import BaseCosmeticPatches class BaseCosmeticPatchesDialog(QDialog): def connect_signals(self): self.accept_button.clicked.connect(self.accept) self.cancel_button.clicked.connect(self.reject) self.reset_button.clicked.connect(self.reset) def reset(self): ...
: raise NotImplementedError()
trickv/fspot_browser
urls.py
Python
bsd-3-clause
1,469
0.004765
from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^render/(?P<photo_id>\d+)/$', 'render.views.raw'), url(r'^render/(?P<photo_id>\d+)/thumbnail/$', 'render.views...
'browser.views.tag_list'), url(r'^tag/(?P<tag_id>\d+)/$', 'browser.views.tag'), url(r'^photo/(?P<photo_id>\d+)/$', 'browser.views.photo'), url(r'^time/$', 'browser.views.time'), url(r'^time/month/(?P<year_int>\d+)-(?P<month_int>\d+)/$', 'browser.views.month'), url(r'^hack/tag-best-2011/(?P<photo_id>...
/remove_tag/(?P<photo_id>\d+)/(?P<tag_id>\d+)/$', 'browser.views.hack_remove_tag'), url(r'^hack/remove-best-tag/(?P<photo_id>\d+)/$', 'browser.views.hack_remove_best'), # Examples: # url(r'^$', 'fspot_browser.views.home', name='home'), # url(r'^fspot_browser/', include('fspot_browser.foo.urls')), #...
explosion/catalogue
catalogue/__init__.py
Python
mit
8,348
0.001318
from typing import Sequence, Any, Dict, Tuple, Callable, Optional, TypeVar, Union import inspect try: # Python 3.8 import importlib.metadata as importlib_metadata except ImportError: from . import _importlib_metadata as importlib_metadata # type: ignore # Only ever call this once for performance reasons AVA...
ry point is
available for a given name in the namespace and load it. Otherwise, return the default value. name (str): Name of entry point to load. default (Any): The default value to return. RETURNS (Any): The loaded entry point or the default value. """ for entry_point in AVAILABL...
miguelinux/vbox
src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/GenFds/FdfParser.py
Python
gpl-2.0
184,268
0.006664
## @file # parse FDF file # # Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found a...
e(File, Line) self.FileName = FileLineTuple[0]
self.LineNumber = FileLineTuple[1] self.Message = Str self.ToolName = 'FdfParser' def __str__(self): return self.Message ## The MACRO class that used to record macro value data when parsing include file # # class MacroProfile : ## The constructor # # @param self ...
yvaucher/stock-logistics-workflow
__unported__/stock_move_backdating/__openerp__.py
Python
agpl-3.0
1,678
0
# -*- coding:
utf-8 -*- ############################
################################################## # # Copyright (C) 2012+ BREMSKERL-REIBBELAGWERKE EMMERLING GmbH & Co. KG # Author Marco Dieckhoff # Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.com>) # # This program is free software: you can redistribute it and/or modify # it unde...
COSMOGRAIL/COSMOULINE
pipe/modules/src/deconv_simult.py
Python
gpl-3.0
6,598
0.010003
#!/usr/bin/python import sys, time, scipy.optimize, scipy.ndimage.interpolation import scipy.ndimage.filters as filt import src.lib.utils as fn import src.lib.wsutils as ws import src.lib.Algorithms as alg import scipy.signal.signaltools as sig from src.lib.PSF import * from src.lib.AImage import * from src.lib.wavel...
_lambda) # if not thresh: # thresh = params['SIGMA_SKY'] dec = DecSrc(objs, sigmas, masks, psfs, r, conv, img_shifts, _lambda, gres, thresh, nb_src, srcini, box_size, src_range, force_ini, bkg_ini, bkg_ratio) ########## Deconvolution ##########
bak, src_par = dec.deconv(itnb, minstep_px, maxstep_px, maxpos_range, max_iratio_range, stepfact, nbruns) out(2, 'Initial sources parameters [x,y,I]:', dec.src_ini) out(2, 'Final sources parameters [x,y,I]:', src_par) out(2, 'offsets:', dec.shifts) ############ Prepare output ##...
bheesham/PyLinkChecker
hosts/fileserve_com.py
Python
bsd-3-clause
1,325
0.056604
# Copyright (C) 2011 Bheesham Persaud # The license is available in LICENSE from __future__ import division import re from includes.functions import * class fileserve_com: def init( self ): self.url_pattern = re.compile( r'(http://www\.fileserve\.com/file/([A-Za-z0-9]+))', re.I ) self.result_pattern = re.compile...
.join( files ) params = urllib.urlencode({ 'urls': files_joined, 'submit': ' Check Urls ' }) browser = urllib.urlopen( "http://fileserve.com/link-checker.php", params ) res_urls = browser.read() res_urls = res_urls.replace( "\r", '' ) res_urls = res_urls.replace( "\n", '' ) res_urls = res_urls.replace...
.remove( res_url[0] ) return [ self.url, files_list, dead ]
mirror/cvsps
git-cvsimport.py
Python
gpl-2.0
17,145
0.000525
#!/usr/bin/env python # # Import CVS history into git # # Intended to be a near-workalike of Matthias Urlichs's Perl implementation. # # By Eric S. Raymond <esr@thyrsus.com>, December 2012 # May be redistributed under the license of the git project. import sys if sys.hexversion < 0x02060000: sys.stderr.write("git...
If the next character isn't a colon, this is a flag. flag = (i + 1 == len(optstring)) or (optstring[i + 1] != ':') if flag: cmd.append("--bool")
cmd.extend(["--get", "cvsimport.%s" % key]) try: result = capture_or_die(cmd).strip() except subprocess.CalledProcessError: continue if not flag or result != "false": options.append(("-%s" % c, result)) return options def _get_ref_times(): """G...
aaxelb/osf.io
website/settings/defaults.py
Python
apache-2.0
47,085
0.000913
# -*- coding: utf-8 -*- """ Base settings file, common to all environments. These settings can be overridden in local.py. """ import datetime import os import json import hashlib import logging from datetime import timedelta from collections import OrderedDict os_env = os.environ def parent_dir(path): '''Return...
', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'object', 'ol', 'param', 'pre', 'p', 'q', 's', '
samp', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'th', 'thead', 'tr', 'tt', 'ul', 'u', 'var', 'wbr', ], 'attributes': [ 'align', 'alt', 'border', 'cite', 'class', 'dir', 'height', 'href', 'id', 'src', 'style', 'title', 'type', 'width', 'fa...
MatthieuMichon/densim
densim/service.py
Python
gpl-3.0
2,446
0.002862
import json from pprint import pprint class Event: """Event class""" def __init__(self, time, station, action): if action not in self.supported_actions: raise ValueError("unknown action: " + action) self.time = time self.station = station self.action = action d...
: self.display_event(event) print("") # TODO: Move in new file event.py def display_event(self, event): """Display a given event""" time = event['time'] station = event['station'] action = event['action'] event = Event(time,
station, action) event.display()
radinformatics/som-tools
som/utils.py
Python
mit
8,265
0.007985
#!/usr/bin/env python ''' utils.py: part of som package Copyright (c) 2017 Vanessa Sochat 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 ri...
ger import bot import sys import subprocess import tempfile import tarfile import zipfile # Python less than version 3 must import OSError if sys.version_info[0] < 3: from exceptions import OSError ################
###################################################################### # Local commands and requests ###################################################################################### def get_installdir(): '''get_installdir returns the installation directory of the application ''' return os.path.abspat...
BeenzSyed/tempest
tempest/services/compute/xml/hypervisor_client.py
Python
apache-2.0
3,235
0
# Copyright 2013 IBM Corporation # 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 ...
.""" resp, body = self.get('os-hy
pervisors/%s/servers' % hyper_name, self.headers) hypervisors = self._parse_array(etree.fromstring(body)) return resp, hypervisors def get_hypervisor_stats(self): """Get hypervisor statistics over all compute nodes.""" resp, body = self.get('os-hypervis...
gangadharkadam/office_erp
erpnext/projects/doctype/field_level_explanation/field_level_explanation.py
Python
agpl-3.0
283
0.010601
#
Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors and contributors # For license information, please see license.txt from __future__ import unico
de_literals import frappe from frappe.model.document import Document class FieldLevelExplanation(Document): pass
Azurras/Survithon
survive/game/gamecontroller.py
Python
mit
2,082
0.00048
from survive.player.playermodel import Player from survive.activities.crafting.craftingcontroller import CraftingController from survive.inventory.inventorycontroller import InventoryController from survive.activities.hunting.huntingcontroller import HuntingController from survive.generic.controller import Controller f...
} def start(self, name): view = View(self._view) player = Player(name) crafting_controller = CraftingController() inventory_controller = Inventory
Controller() huntingController = HuntingController() player_input = -1 while True: try: view.start() player_input = int(input("Enter an action.\n")) super().clear_screen() if(player_input == 0): pri...
matthewalbani/scipy
scipy/spatial/tests/test_distance.py
Python
bsd-3-clause
56,454
0.001081
#! /usr/bin/env python # # Author: Damian Eads # Date: April 17, 2008 # # Copyright (C) 2008 Damian Eads # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copy...
i', p=3.8, w=w) _assert_within_tol(Y1, Y2, eps, verbose > 2) def test_cdist_wminkowski_random_p4d6(self): eps = 1e-07
X1 = eo['cdist-X1'] X2 =
allenlavoie/tensorflow
tensorflow/contrib/learn/python/learn/utils/saved_model_export_utils.py
Python
apache-2.0
34,967
0.004261
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may
not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDI...
ions under the License. # ============================================================================== """Utilities supporting export to SavedModel (deprecated). This module and all its submodules are deprecated. See [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md) for mi...
Schevo/kiwi
examples/hyperlink/hyperlink_demo.py
Python
lgpl-2.1
5,936
0.000505
# # Kiwi: a Framework and Enhanced Widgets for Python # # Copyright (C) 2005 Async Open Source # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (a...
active_bold def _on_m2_activated(self, menuitem): self.log('menuitem 2 activated') self._hl3.normal_underline = not self._hl3.normal_underline self._hl3.hover_underline = not self._hl3.hover_underline self._hl3.active_underline = not self._hl3.active_
underline def log(self, msg): buf = self._logger.get_buffer() timestr = time.strftime('%H:%M:%S') buf.insert(buf.get_start_iter(), '%s...%s\n' % (timestr, msg)) def main(): a = App() a.start() if __name__ == '__main__': main()
wbphelps/WxData
wxdata.py
Python
gpl-3.0
5,036
0.010127
#!/usr/bin/python # # weewx extension service to collect Loop & Archive packets and share them with other processes # via a python Multiprocessing connection # # Copyright (c) 2015 William B. Phelps <wm@usa.net> # See the file LICENSE.txt for your full rights. import weewx import weewx.engine import weeutil.weeutil f...
o()[0])) listener.close() syslog.syslog(syslog.LOG_INFO, "wxdata: server ended") def shutdown(self): syslog.syslog(syslog.LOG_INFO, "wxdata: server shutdown") self.exit.set() class WXDATA(weewx.engine.StdService): def __init__(self, engine, config_dict): super(WXDATA, ...
name', 'WX Data') self.address = d.get('address', '') self.port = int(d.get('port', 6000)) self.key = d.get('key', 'wxdata key') self.bind(weewx.NEW_ARCHIVE_RECORD, self.handle_new_archive) self.bind(weewx.NEW_LOOP_PACKET, self.handle_new_loop) syslog.syslog(syslog.LOG_IN...
bitsydarel/DebiaTranslator
utils/app_util.py
Python
gpl-3.0
1,724
0.003501
# coding=utf-8 import platform import
sqlite3 from utils.constant_holder import * from pages import add_word, translate_word, welcome, modify_word, remove_word def get_welcome_page(): return welcome.WelcomeWindow def get_translate_page(): return translate_word.TranslatePage def get_add_word_page(): return add_word.AddWordPage def get_...
t_remove_word_page(): return remove_word.RemoveWordPage def get_database(): if platform.system() == "Windows": if (os.path.isdir(DISK_NAME + "\DTranslator")): os.chdir(DISK_NAME + "\DTranslator") else: os.mkdir(DISK_NAME + "\DTranslator") os.chdir(DISK_NAME ...
rven/odoo
addons/account_edi/models/account_journal.py
Python
agpl-3.0
2,505
0.002794
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields, _ from odoo.exceptions import UserError class AccountJournal(models.Model): _inherit = 'account.journal' edi_format_ids = fields.Many2many(comodel_name='account.edi.format...
compute='_compute_edi_format_ids', readonly=False, store=True) compatible_edi_ids = fields.Many2many(comodel_name='account.edi.format', compute='_compute_compatible_edi_ids', ...
def write(self, vals): # OVERRIDE # Don't allow the user to deactivate an edi format having at least one document to be processed. if vals.get('edi_format_ids'): old_edi_format_ids = self.edi_format_ids res = super().write(vals) diff_edi_format_ids = old_ed...
maicao/diffmaker
diffMaker.py
Python
apache-2.0
2,356
0.010187
#!/usr/bin/env python import pygtk pygtk.require("2.0") import gtk import gtk.glade import difflib class DiffMakerGTK: """This is an Hello World GTK application""" def __init__(self): #Set the Glade file self.gladefile = "MainWindow.glade" self.wTree = gtk.glade.XML(self.gladefil...
ndow, and connect the "destroy" event self.window = self.wTree.get_widget("MainWindow") if (self.window): self.window.connect("destroy", self.destroy) self.window.connect("delete_event", self.delete_event) #Create our dictionay and connect it dic = {"on_b...
clear_clicked, "on_button_do_clicked" : self.on_button_do_clicked, "on_MainWindow_destroy" : gtk.main_quit} self.wTree.signal_autoconnect(dic) self.txt1 = self.wTree.get_widget("textview1") self.txt2 = self.wTree.get_widget("textview...
linduine/RobotVYE
Test/PyQtTest/ObjectsDetector.py
Python
mit
1,964
0.015784
#from StreamReader import * import numpy import cv2 class ObjectDetecor : #stream = None #def __init__(self, stream) : #self.stream = stream minRadius = 15; minContourArea = 500; def findObjects(self, frame, npLower, npUpper) : #convert image and colors to HSV #hsvFrame = ...
center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) #
only proceed if the radius meets a minimum size if radius > self.minRadius: objects.append([int(x), int(y), int(radius)]) # draw the circle and centroid on the frame cv2.circle(frame, (int(x), int(y)), int(radius), (255, 0, 0), 1) #cv2.circle(f...
ezarko/cfn-init
comtypes/test/test_excel.py
Python
apache-2.0
3,729
0.007241
# -*- coding: latin-1 -*- import unittest import comtypes.test comtypes.test.requires("ui") import datetime from comtypes.client import CreateObject xlRangeValueDefault = 10 xlRangeValueXMLSpreadsheet = 11 xlRangeValueMSPersistXML = 12 class Test(unittest.TestCase): def test_earlybound(self): ...
c.l.p sh = wb.Worksheets[1] sh.Cells.Item[1,1].Value[()] = "Hello World!" sh.Cells.Item[3,3].Value[()] = "Hello World!" sh.Range[sh.Cells.Item[1,1],sh.Cells.Item[3,3]].Copy(sh.Cells.Item[4,1]) sh.Range[sh.Cells.Item[4,1],sh.Cells.Item[6,3]].Select() def tearDown(sel...
t excel. for wb in self.xl.Workbooks: wb.Close(0) self.xl.Quit() if __name__ == "__main__": unittest.main()
malancas/CUNY-CoLAG-Sims-2016-17
Fodor-Sakas-model/tests/test_runSimulation.py
Python
gpl-3.0
1,576
0.002538
from .. import runSimulation import pytest, os def test_makeS
electedSentences(): infoFile = open(os.path.dirname(__file__) + '/../EngFrJapGerm.txt') runSim1 = runSimulation.runSimulation(infoFile.readlines(), 611) infoFile.close() # These four ids are present in EngFrJapGerm: French=584, English=611, German=2253, Japanese=3856 # Check that ma...
(runSim1.selectedSentences) == 540 runSim1.targetGrammar = 584 runSim1.selectedSentences = [] runSim1.makeSelectedSentenceList() assert len(runSim1.selectedSentences) == 756 runSim1.targetGrammar = 2253 runSim1.selectedSentences = [] runSim1.makeSelectedSentence...
open-mmlab/mmdetection
mmdet/models/necks/yolo_neck.py
Python
apache-2.0
5,431
0
# Copyright (c) OpenMMLab. All rights reserved. # Copyright (c) 2019 Western Digital Corporation or its affiliates. import torch import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.runner import BaseModule from ..builder import NECKS class DetectionBlock(BaseModule): """Detection block in ...
elf.conv5(tmp) return out @NECKS.register_module() class YOLOV3Neck(BaseModule): """The neck of YOLOV3. It can be treated as a simplified version of FPN. It will take the result from Darknet backbone and do some upsampling and concatenation. It will finally output the detection result. N...
The input feats should be from top to bottom. i.e., from high-lvl to low-lvl But YOLOV3Neck will process them in reversed order. i.e., from bottom (high-lvl) to top (low-lvl) Args: num_scales (int): The number of scales / stages. in_channels (List[int]): The ...
minlexx/pyevemon
esi_client/models/get_universe_system_kills_internal_server_error.py
Python
gpl-3.0
3,107
0.000644
# coding: utf-8 """ EVE Swagger Interface An OpenAPI for EVE Online OpenAPI spec version: 0.4.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class GetUniverseSystemKillsInternalServerError(object): """...
x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to...
ue.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` ...
turbokongen/home-assistant
homeassistant/components/socialblade/__init__.py
Python
apache-2.0
33
0
"""The so
cialblade component.""
"
RJTK/dwglasso_cweeds
src/data/sinusoid_regression.py
Python
mit
2,984
0
''' This file loads in data from /data/interim/interim_data.hdf and then applies a sinusoidal regression model to the temperature data to remove the yearly predictable variation. NOTE: This file is intended to be executed by make from the top level of the project directory hierarchy. We rely on os.getcwd() and it wil...
ore(ghdf_path, mode='r') as hd
f: D = hdf[key] # Read D from disk t = D.index T = D['T'].values unix_birth = datetime.datetime(1970, 1, 1) def time_in_days(t): # Convert time to raw numbers # 86400 = datetime.timedelta(days=1).total_seconds() return (t - unix_birth).total_seconds() / 86400 t_days = np....
gojomo/gensim
gensim/test/test_word2vec.py
Python
lgpl-2.1
55,488
0.003298
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Automated tests for checking transformation algorithms (the models package). """ from __future__ import division import logging imp...
orpus_file, vector_size=10, min_count=0, seed=42, hs=1, negative=0) model_neg = word2vec.Word2Vec(corpus_file=corpus_file, vector_size=10, mi
n_count=0, seed=42, hs=0, negative=5) self.assertTrue(len(model_hs.wv), 12) self.assertTrue(model_hs.wv.get_vecattr('graph', 'count'), 3) model_hs.build_vocab(corpus_file=new_corpus_file, updat
kivhift/qmk
src/commands/browse.py
Python
mit
426
0.00939
# # Copyright (c) 2009-2012 Joshua Hughes <kivhift@gmail.com> # import webbrowser import qmk class BrowseCommand(qmk.Command): '
''Open the supplied URL in the default web browser.''' def __init__(self): self._name = 'browse' self._help = self.__doc__ @qmk.Command.actionRequiresArgument def
action(self, arg): webbrowser.open_new_tab(arg) def commands(): return [ BrowseCommand() ]
begoldsm/azure-data-lake-store-python
azure/datalake/store/utils.py
Python
mit
5,211
0.002879
# -*- coding: utf-8 -*- # 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. # ---------------------------------------------...
ATA'], 'azure-datalake-store') else: datadir = os.sep.join([os.path.expanduser("~"), '.config', 'azure-datalake-store
']) try: os.makedirs(datadir) except: pass def ensure_writable(b): if PY2 and isinstance(b, array.array): return b.tostring() return b def write_stdout(data): """ Write bytes or strings to standard output """ try: sys.stdout.buffer.write(data) except AttributeError: ...
lspvic/jupyter_tensorboard
jupyter_tensorboard/api_handlers.py
Python
mit
2,197
0
# -*- coding: utf-8 -*- import json import os from tornado import web from notebook.base.handlers import APIHandler from .handlers import notebook_dir def _trim_notebook_dir(dir): if not dir.startswith("/"): return os.path.join( "<notebook_dir>", os.path.relpath(dir, notebook_...
elf.get_json_body() reload_interval = data.get("reload_interval", None)
entry = ( self.settings["tensorboard_manager"] .new_instance(data["logdir"], reload_interval=reload_interval) ) self.finish(json.dumps({ 'name': entry.name, 'logdir': _trim_notebook_dir(entry.logdir), 'reload_time'...
pschmitt/home-assistant
homeassistant/components/tado/__init__.py
Python
apache-2.0
8,954
0.00067
"""Support for the (unofficial) Tado API.""" import asyncio from datetime import timedelta import logging from PyTado.interface import Tado from requests import RequestException import requests.exceptions import voluptuous as vol from homeassistant.components.climate.const import PRESET_AWAY, PRESET_HOME from homeass...
IN]: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IM
PORT}, data=conf, ) ) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Tado from a config entry.""" _async_import_options_from_data_if_missing(hass, entry) username = entry.data[CONF_USERNAME] password = entry.data[CONF_PASSWORD] ...
crmccreary/openerp_server
openerp/addons/account/wizard/account_report_common_journal.py
Python
agpl-3.0
2,970
0.003367
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyr
ight (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free softw
are: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITH...
murrown/cyder
cyder/cydhcp/build/views.py
Python
bsd-3-clause
614
0
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from cyder.base.views import cy_render from cyder.cydhcp.network.models import Network def build_network(request, network_pk): network = get_object_or_4
04(Network, pk=network_pk) if request.GET.get('raw', False): DEBUG_BUILD_STRING = network
.build_subnet(raw=True) return HttpResponse(DEBUG_BUILD_STRING) else: DEBUG_BUILD_STRING = network.build_subnet(raw=False) return cy_render( 'build/sample_build.html', {'data': DEBUG_BUILD_STRING, 'network': network})
NaviNet/ImageFeeder
imagefeeder/imagefeeder.py
Python
apache-2.0
19,421
0.000103
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2014 NaviNet 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 # # ...
R.warn('Not a directory: {}'.
format(src_path)) def _watch(self, src_path): """Watches a directory to send new images to Eyes. Args: src_path: The path to watch. """ host_os, host_app = _get_app_environment(src_path, self._sep) watchdir.watch(src_path, WindowMatchingEventHandler, ...
h-hirokawa/swampdragon
swampdragon/models.py
Python
bsd-3-clause
3,323
0.000903
from .pubsub_providers.base_provider import PUBACTIONS from .model_tools import get_property from .pubsub_providers.model_publisher import publish_model from .serializers.serializer_importer import get_serializer from django.db.models.signals import pre_delete, m2m_changed from django.dispatch.dispatcher import receive...
s(): val = get_property(self, k) if val != v: changed_fields.append(k) ret
urn changed_fields def serialize(self): return self._serializer.serialize() def _publish(self, action, changed_fields=None): publish_model(self, self._serializer, action, changed_fields) def save(self, *args, **kwargs): if not self.pk: self.action = PUBACTIONS.created ...
bswartz/cinder
cinder/interface/volume_management_driver.py
Python
apache-2.0
3,264
0
# Copyright 2016 Dell Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
a storage object that the driver should somehow associate with the newly-created cinder volume structure.
There are two ways to do this: 1. Rename the backend storage object so that it matches the, volume['name'] which is how drivers traditionally map between a cinder volume and the associated backend storage object. 2. Place some metadata on the volume, or somewhere in the back...
aselle/tensorflow
tensorflow/python/distribute/distribute_coordinator.py
Python
apache-2.0
13,612
0.005583
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
: an integer indicating id of the corresponding task. It can be None if it is local training or `between_graph` is False. between_graph: whether it is between-graph replication or not. rpc_layer: optional string specifying the RPC protocol for communication with worker masters. If None or em...
ValueError: if task_type or task_id is Node or empty and it is distributed between-graph replicated training. """ if cluster_spec and between_graph: if not task_type or task_id is None: raise ValueError("`task_type` and `task_id` must be set in the " "distribu...