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
jmesteve/saas3
openerp/addons/purchase/res_config.py
Python
agpl-3.0
5,643
0.010455
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms o...
'default_invoice_method': 'manual', } def onchange_purchase_analytic_plans(self, cr, uid, ids, module_purchase_analytic_plans, context=None): """ change group_analytic_account_for_purchases following module_purchase_analytic_plans """ if not module_purchase_analytic_plans: r...
chases': module_purchase_analytic_plans}} class account_config_settings(osv.osv_memory): _inherit = 'account.config.settings' _columns = { 'module_purchase_analytic_plans': fields.boolean('Use multiple analytic accounts on orders', help='Allows the user to maintain several analysis plans....
arenadata/ambari
ambari-server/src/main/resources/stacks/BigInsights/4.0/services/stack_advisor.py
Python
apache-2.0
891
0.002245
#!/usr/bin/env ambari-python-wrap """ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with thi
s work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Vers
ion 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, WITHOU...
yugangw-msft/azure-cli
src/azure-cli-core/azure/cli/core/auth/persistence.py
Python
mit
2,517
0.001986
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # ----------
---------------------------------------------------------------------------------- # This file is modified from # https://github.com/AzureAD/microsoft-authentication-extensions-
for-python/blob/dev/sample/token_cache_sample.py import json import sys from msal_extensions import (FilePersistenceWithDataProtection, KeychainPersistence, LibsecretPersistence, FilePersistence, PersistedTokenCache, CrossPlatLock) from msal_extensions.persistence import PersistenceNotFou...
jcelliott/inquire
inquire/extraction/entity/__init__.py
Python
mit
65
0
# answer extraction: entity from extractors import get_extracto
r
amadeusproject/amadeuslms
themes/migrations/0007_themes_high_contrats_logo.py
Python
gpl-2.0
597
0.001675
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-09-21 00:22 from __future__ import unico
de_literals from django.db import migrations, models import themes.models class Migration(migrations.Migration): dependencies = [ ('themes', '0006_auto_20170610_1512'), ] operations = [ migrations.AddField( model_name='themes', name='high_contrats_logo', ...
null=True, upload_to='themes/', validators=[themes.models.validate_img_extension], verbose_name='High Contrast Logo'), ), ]
glibersat/firmware
test_results/plot_all.py
Python
agpl-3.0
2,367
0.00676
import glob import re import csv import numpy as np import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf pdf = matplotlib.backends.backend_pdf.PdfPages("test
-results-plots.pdf") # each name in the header is of format like: 5b#beer temp # 5: subplot number # b: optional plot type specifier # after #: legend name class header_decoder: def __init__(self): self.matcher = re.compile("\s*([0-9]+)([a-z]*)#(.*)\s*") self.names = [] self.indices = [] ...
es = [] self.indices = [] self.types = [] for name in names: match = self.matcher.match(name) if match: self.indices.append(match.group(1)) self.types.append(match.group(2)) self.names.append(match.group(3)) els...
gpg/gpgme
lang/python/tests/initial.py
Python
lgpl-2.1
1,513
0
#!/usr/bin/env python # Copyright (C) 2016 g10 Code GmbH # # This file is part of GPGME. # # GPGME 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. # # GPGME is distributed in the hope that it w
ill be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, see <https...
kanosaki/PicDump
picdump/app.py
Python
mit
1,670
0.001198
import weakref class App: """Application root context""" def __init__(self, config): self.config = config inject_app(self) def start(self): for folder in self.config.folders: folder.start_dump() class HasAppMixin: def __init__(self): self.__app = None ...
d(app) def on_app_injected(self, app): pass class AppInjector: def __init__(self): self.targets = weakref.WeakSet() self.previous_injected = None self.allow_reinjection = False def inject(self, app): prev_app = self.previous_injected if prev_app is not Non...
-injection detected') for target in self.targets: if hasattr(target, '_inject_app'): target._inject_app(app) else: target.app = app self.previous_injected = app def register(self, target): self.targets.add(target) ROOT_INJECTOR = App...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/urbansim/person_trip_x_zone/from_origin_to_destination_travel_data_SSS.py
Python
gpl-2.0
665
0.004511
# Op
us/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from urbansim.abstract_variables.abstract_travel_time_variable import abstract_travel_time_variable class from_origin_to_destination_travel_data_SSS(abstract_travel_time_variable): """""" ...
self.location_zone_id = "zone.zone_id" self.travel_data_attribute = "travel_data." + attribute_name self.direction_from_home = True abstract_travel_time_variable.__init__(self)
showell/zulip
zerver/migrations/0054_realm_icon.py
Python
apache-2.0
674
0.001484
# Generated by Django 1.10.5 on 2017-02-15 06:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zerver', '0053_emailchangestatus'), ] operations = [ migrations.AddField( model_name='realm', name='icon_source', ...
field=models.CharField( choices=[('G',
'Hosted by Gravatar'), ('U', 'Uploaded by administrator')], default='G', max_length=1), ), migrations.AddField( model_name='realm', name='icon_version', field=models.PositiveSmallIntegerField(default=1), ), ]
miguelgrinberg/python-socketio
tests/performance/text_packet.py
Python
mit
400
0
impo
rt time from socketio import packet def test(): p = packet.Packet(packet.EVENT, 'hello') start = time.time() count = 0 while True: p = packet.Packet(encoded_packet=p.encode()) count += 1 if time.time() - start >= 5: break return count if __name__ == '__main__'...
ilovecode1/Pyfancy-2
pyfancy/demo.py
Python
mit
787
0
from pyfancy import pyfancy pyfancy().red("Hello").raw(", ").blue("world!").output() pyfancy().multi("Multicolored text").output() pyfancy().rainbow("Rainbow text").output() pyfancy("{red foo {bold bar}
baz}").output() pyfancy().black_bg("Black background").output() pyfancy().green_bg("Green background").output() pyfancy().red_bg("Red background")
.output() pyfancy().black().yellow_bg("Yellow background").output() pyfancy().blue_bg("Blue background").output() pyfancy().purple_bg("Purple background").output() pyfancy().cyan_bg("Cyan background").output() pyfancy().black().gray_bg("Gray background").output() pyfancy().read("pyfancy/demo/import.txt").output() pyfan...
efiop/dvc
tests/unit/stage/test_utils.py
Python
apache-2.0
624
0
import os from dvc.stage.utils import resolve_paths def test_resolve_paths(): p = os.path.join("dir", "subdir") file_path = o
s.path.join(p, "dvc.yaml") path, wdir = resolve_paths(path=file_path, wdir="dir") assert path == os.path.abspath(file_path) assert wdir == os.path.abspath(os.path.join(p, "dir")) path, wdir = resolve_paths(path=file_path) assert path == os.path.abspath(file_path) assert wdir == os.path.abspath...
sert wdir == os.path.abspath("some-dir")
seanastephens/communityshare
update_scripts/make_sql.py
Python
mpl-2.0
261
0
from sqlalchemy.schema import CreateTable from community_share import store, config, setup from community_share.mode
ls.user import UserReview config.load_from_environment() table_sql = Cr
eateTable(UserReview.__table__).compile(store.engine) print(table_sql)
ideascube/ideascube
ideascube/conf/idb_bdi_kavumu.py
Python
agpl-3.0
98
0
"""Kavumu box in Burundi""" fro
m .idb_bdi impor
t * # pragma: no flakes IDEASCUBE_NAME = "Kavumu"
wesleykendall/django-activatable-model
setup.py
Python
mit
1,680
0.002976
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215) import multiprocessing assert multiprocessing import re from setuptools import setup, find_packages def get_version(): """ Extract
s the version number from the version.py file. """ VERSION_FILE = 'activatable_model/version.py' mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M) if mo: return mo.group(1) else: raise RuntimeError('Unable to find version string in {0}.'.for...
version=get_version(), description='Django Activatable Model', long_description=open('README.md').read(), url='https://github.com/ambitioninc/django-activatable-model', author='Wes Kendall', author_email='opensource@ambition.com', keywords='Django, Model, Activatable', packages=find_pac...
Martin819/salt-formula-horizon
horizon/files/horizon_settings/_horizon_settings.py
Python
apache-2.0
4,809
0.005199
{%- from "horizon/map.jinja" import server with context %} {%- if server.app is defined %} {%- set app = salt['pillar.get']('horizon:server:app:'+app_name) %} {%- else %} {%- set app = salt['pillar.get']('horizon:server') %} {%- endif %} # Specify a regular expression to validate user passwords. # HORIZON_CONFIG["pas...
pute': 'nova_policy.json', 'network': 'neutron_policy.json', 'image': 'glance_policy.json', 'volume': 'cinder_policy.json' } LOGGING = { 'version': 1, # When set to True this will disable al
l logging except # for loggers specified in this configuration dictionary. Note that # if nothing is specified here and disable_existing_loggers is True, # django.db.backends will still log unless it is disabled explicitly. 'disable_existing_loggers': False, 'handlers': { 'null': { ...
cl9200/nbase-arc
smr/test/integrated/Cm.py
Python
apache-2.0
1,132
0.00265
# # Copyright 2015 Naver Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
tributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
. # See the License for the specific language governing permissions and # limitations under the License. # import os import tempfile import shutil import Pg, Pgs, Conf, Log class CM: def __init__(self, name): self.name = name self.dir = None def create_workspace(self): base_dir = Conf...
NICTA/dora
dora/active_sampling/delaunay_sampler.py
Python
apache-2.0
4,870
0
""" Delaunay Sampler Module. Provides the Delaunay Sampler Class which contains the strategies for active sampling a spatial field """ from dora.active_sampling.base_sampler import Sampler, grid_sample import numpy as np from scipy.spatial import Delaunay as ScipyDelaunay class Delaunay(Sampler): """ Delau...
Index location in the data lists 'Delaunay.X' and 'Delaunay.y' corresponding to the job being updated """ return self._update(uid, y_true) def pick(self): """ Pick the next feature location for the next observation to be taken. This uses the recursive De...
str A random hexadecimal ID to identify the corresponding job """ n = len(self.X) # -- note that we are assuming the points in X are not reordered by # the scipy Delaunay implementation n_corners = 2 ** self.dims if n < n_corners + 1: #...
liyongyue/dnsspider
dns/rdtypes/ANY/DNSKEY.py
Python
isc
881
0.001135
# Copyright (C) 2004, 2005 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND...
IAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE O
R PERFORMANCE OF THIS SOFTWARE. import dns.rdtypes.keybase class DNSKEY(dns.rdtypes.keybase.KEYBase): """DNSKEY record""" pass
syscoin/syscoin2
test/functional/rpc_blockchain.py
Python
mit
14,422
0.001733
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPCs related to blockchainstate. Test the following RPCs: - getblockchaininfo - gettxouts...
n_test(self): self.mine_chain() self.restart_node(0, extra_args=['-stopatheight=207'
, '-prune=1']) # Set extra args with pruning after rescan is complete self._test_getblockchaininfo() self._test_getchaintxstats() self._test_gettxoutsetinfo() self._test_getblockheader() self._test_getdifficulty() self._test_getnetworkhashps() self._test_stopath...
eayunstack/neutron-qos
neutron_qos/db/qos/qos_db.py
Python
apache-2.0
35,231
0
# Copyright (c) 2015 Eayun, 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 ...
d', uselist=True), primaryjoin='Qos.id==QosQueue.qos_id') parent_queue = orm.relationship( "QosQueue", remote_side='QosQueue.id', backref=orm.backref( 'subqueues', cascade='all,delete', lazy='joined', uselist=True), primaryjoin='QosQueue.id==QosQueue.parent_id') ...
sa.ForeignKey('eayun_qoss.id', ondelete='CASCADE'), nullable=False) queue_id = sa.Column(sa.String(36), sa.ForeignKey('eayun_qosqueues.id', ondelete='SET NULL')) prio = sa.Column(sa.Integer, nullable=Fal...
mouadino/pyes
pyes/es.py
Python
bsd-3-clause
67,840
0.002241
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import with_statement try: # For Python >= 2.6 import json except ImportError: # For Python < 2.6 or people using a newer version of simplejson import simplejson as json import random from datetime imp...
e converted into datetime strings. """ if isinstance(value, datetime): return value.isoformat() elif isinstance(value, date): dt = datetime(value.year, value.month, value.day, 0, 0, 0) return dt.isoformat() elif isinstance(value, Decimal): ...
ecial encoding and hope for the best return value class ESJsonDecoder(json.JSONDecoder): def __init__(self, *args, **kwargs): kwargs['object_hook'] = self.dict_to_object json.JSONDecoder.__init__(self, *args, **kwargs) def string_to_datetime(self, obj): """Decode a datetim...
tkukushkin/asynqp-consumer
src/asynqp_consumer/helpers.py
Python
mit
397
0.002519
import asyncio from collections.abc import Coroutine from typing import Any, Awaitable async def gather(*coros_or_futures: Awaitable[Any], loop: asyncio.BaseEve
ntLoop = None): try: return await asyncio.gather(*coros_or_futures, loop=loop) except Exception: for obj in coros_or_futures: if isinstance(obj, Coroutine): obj.close()
raise
gmr/apiary
apiary/mappers/mixin.py
Python
bsd-3-clause
723
0.001383
""" Base Mixin Class for Dynamic Attributes """ from sqlalchemy.ext import declarative import re FIRST_PASS = re.compile(r'(.)([A-Z][a-z]+)') LAST_PASS = re.compile(r'([a-z0-9])([A-Z])') class MapperMixin(object): __columns__ = [] __primary_key__
= None __tablename__ = None @declarative.declared_attr def primary_key(cls): return '%s.%s' % (cls.__tablename__, cls.__primary_key__) @declarative.declared_attr def table_name(cls): return cls.__tablename__ class AutoNameMapperMixin(MapperMixin): @declarative.declared_attr ...
): temp = FIRST_PASS.sub(r'\1_\2', cls.__name__) return '%s' % LAST_PASS.sub( r'\1_\2', temp).lower()
sanguinariojoe/FreeCAD
src/Mod/Fem/femtools/femutils.py
Python
lgpl-2.1
14,528
0.000688
# *************************************************************************** # * Copyright (c) 2017 Markus Hovorka <m.hovorka@live.de> * # * Copyright (c) 2018 Bernd Hahnebach <bernd@bimstatik.org> * # * * # * Th...
eturns: reference to new object """ obj = doc.addObject(proxy.BaseType, name) proxy(obj) if FreeCAD.GuiUp and viewProxy is not None: viewProxy(obj.ViewObject) return obj # typeID and object type defs def type_of_obj(obj): """ Return type of *obj* honoring the special typesyst...
TypeId`` value. :para obj: a document object """ if hasattr(obj, "Proxy") and hasattr(obj.Proxy, "Type"): return obj.Proxy.Type return obj.TypeId def is_of_type(obj, ty): """ Compare type of *obj* with *ty* honoring Fems typesystem. See :py:func:`type_of_obj` for more info about the ...
amitjamadagni/sympy
sympy/printing/tests/test_latex.py
Python
bsd-3-clause
36,468
0.002002
from sympy import ( Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial, FiniteSet, Float, FourierTransform, Function, Integral, Interval, InverseCosineTransform, InverseFourierTransform, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, Lambda, LaplaceTransform, Limit...
, Rational, RisingFactorial, RootOf, RootSum, S, Shi, Si, SineTransform, Subs, Sum, Symbol, TransformationSet, Tuple, Union, arg, asin, assoc_laguerre, assoc_legendre, binomial, catalan, ceiling, chebyshevt, chebyshevu, conjugate, cot, coth, diff, dirichlet_eta, exp, expint, factorial, factorial2, f...
meijerg, oo, polar_lift, polylog, re, re, root, sin, sqrt, symbols, uppergamma, zeta, subfactorial) from sympy.abc import mu, tau from sympy.printing.latex import latex from sympy.utilities.pytest import XFAIL, raises from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita from sympy.log...
greggian/TapdIn
django/core/serializers/__init__.py
Python
apache-2.0
3,648
0.005208
""" Interfaces for serializing Django objects. Usage:: from django.core import serializers json = serializers.serialize("json", some_query_set) objects = list(serializers.deserialize("json", json)) To add your own serializers, use the SERIALIZATION_MODULES setting:: SERIALIZATION_MODULES ...
load_serializers() return _serializers[format].Serializer def get_serializer_formats(): if not _serializers: _load_serializers() return _serializers.keys() def get_public_serializer_formats
(): if not _serializers: _load_serializers() return [k for k, v in _serializers.iteritems() if not v.Serializer.internal_use_only] def get_deserializer(format): if not _serializers: _load_serializers() return _serializers[format].Deserializer def serialize(format, queryset, *...
open-craft/dalite-ng
peerinst/rationale_choice.py
Python
agpl-3.0
8,107
0.005057
# -*- coding: utf-8 -*- """Selection algorithms for rationales shown during question review. Each algorithm is a callable taking these arguments: rng: The random number generator to use. first_answer_choice: The first choice of the student. entered_rationale: The rationale text entered by the student. ques...
"""Raised when an error occurs during rationale selection. The message attached to this exception will be shown to the user. """ def _base_selection_algorithm( rng, first_answer_choice, unused_entered_rationale, question, selectio
n_callback ): """Select the rationales at random.""" from . import models # Local import to avoid circular dependency first_choice = first_answer_choice answer_choices = question.answerchoice_set.all() # Find all public rationales for this question. all_rationales = models.Answer.objects.fi...
sbidoul/pip
src/pip/_vendor/rich/prompt.py
Python
mit
11,307
0.002034
from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload from . import get_console from .console import Console from .text import Text, TextType PromptType = TypeVar("PromptType") DefaultType = TypeVar("DefaultType") class PromptError(Exception): """Exception base class for prompt relat...
., stream: Optional[TextIO] = None, ) -> Any: """Shortcut to construct and run a prompt loop and return the result. Example: >>> filename = Prompt.ask("Enter a filename") Args: prompt (TextType, optional): Prompt text. Defaults to "". console (Co...
use global console. Defaults to None. password (bool, optional): Enable password input. Defaults to False. choices (List[str], optional): A list of valid choices. Defaults to None. show_default (bool, optional): Show default in prompt. Defaults to True. show_choices (boo...
charlie1404/gopalhtmlparser
igiworld.py
Python
unlicense
4,906
0.017326
#!/usr/bin/python import sys import urllib2 import csv import re import time import traceback from bs4 import BeautifulSoup from difflib import SequenceMatcher #################### Importing Liraries ######################## if ( len(sys.argv) != 3 ) : print "Only 2 arguments are allowed" quit() if ( sys.ar...
" except Exception as ex: try: EX_FILE = "ex/" + str(report
_no) + ".html" file_handler = open(EX_FILE,"w") file_handler.write(str(table_data_soup)) file_handler.close() print str(report_no) + " Failure With Exception" file_handler = open(LOG_FILENAME,"w") file_handler.write(str(report_no) + " :--\n" + st...
eirki/script.service.koalanetflix
lib/mediatypes.py
Python
mit
11,547
0.002511
#! /usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import (unicode_literals, absolute_import, division) import abc import os import json import xml.etree.ElementTree as ET import xml.dom.minidom from lib import constants as const from lib import utils from lib import kodi class BaseLibEntry(object): ...
rt = ET.SubElement(root, "fanart") ET.SubElement(fanart, "thumb").text = self.metadata["fanart"] as_string = ET.tostring(root, method='xml') pretty_xml_as_string = xml.dom.minidom.parseString(as_str
ing).toprettyxml() with open(utils.os_join(self.path, self.nfofilename), "w") as nfo: nfo.write(pretty_xml_as_string.encode("utf-8")) def get_lib_entry(self): moviesdict = kodi.rpc("VideoLibrary.GetMovies", properties=["file", 'playcount'], ...
quaintm/octopus
migrations/versions/46344110fc9a_.py
Python
bsd-3-clause
2,983
0.009051
"""empty message Revision ID: 46344110fc9a Revises: 4ca315186aa0 Create Date: 2014-12-17 13:19:06.478167 """ # revision identifiers, used by Alembic. revision = '46344110fc9a' down_revision = '4ca315186aa0' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - pl...
lembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('tasks')
op.create_table('tasks', sa.Column('id', sa.Integer(), nullable=False), sa.Column('task_name', sa.Text(), nullable=True), sa.Column('task_desc', sa.Text(), nullable=True), sa.Column('start_date', sa.Date(), nullable=False), sa.Col...
muralidcis/git-cola
cola/widgets/patch.py
Python
gpl-2.0
6,379
0.00047
from __future__ import division, absolute_import, unicode_literals import os from PyQt4 import QtCore from PyQt4 import QtGui from PyQt4.QtCore import Qt from cola import core from cola import cmds from cola import hotkeys from cola import qtutils from cola.i18n import N_ from cola.widgets import defs from cola.widg...
return [] paths = map(lambda x: ustr(x.path()), urls) return get_patches_from_paths(paths) def get_patches_from_dir(path):
"""Find patches in a subdirectory""" patches = [] for root, subdirs, files in core.walk(path): for name in [f for f in files if f.endswith('.patch')]: patches.append(core.decode(os.path.join(root, name))) return patches class ApplyPatches(Dialog): def __init__(self, parent=None)...
googleapis/python-game-servers
google/cloud/gaming_v1beta/services/game_server_clusters_service/pagers.py
Python
apache-2.0
6,239
0.002404
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
ver_clusters`` fie
ld. If there are more pages, the ``__aiter__`` method will make additional ``ListGameServerClusters`` requests and continue to iterate through the ``game_server_clusters`` field on the corresponding responses. All the usual :class:`google.cloud.gaming_v1beta.types.ListGameServerClustersResponse` ...
mikitex70/pelican-plugins
photos/test_photos.py
Python
agpl-3.0
5,353
0.001681
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from pelican.generators import ArticlesGenerator from pelican.tests.support import unittest, get_settings from tempfile import mkdtemp from shutil import rmtree import photos CUR_DIR = os.path.dirname(__file__) class TestPhotos(unittest.TestC...
llery[1], ('night.png', 'photos/agallery/night.jpg', 'photos/agallery/nightt.jpg', 'EXIF-night', '')) def test_filename_article_body(self): expected = ('<p>Here is my best photo, again.</p>\n' ...
ef test_queue_resize(self): expected = [ ('photos/agallery/best.jpg', (self.settings['PATH'] + '/agallery/best.jpg', (1024, 768, 80))), ('photos/agallery/besta.jpg', (self.settings['PATH'] + '/agallery/best.jpg', (760, 506, 80))), ('photos/agal...
jmlong1027/multiscanner
modules/Metadata/ExifToolsScan.py
Python
mpl-2.0
3,516
0.001422
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import division, absolute_import, with_statement, print_function, unicode_literals import os import sys i...
essError as e: output = e.output e.returncode else: try: output = sshexec(host, list2cmdline(cmd), port=port, use
rname=user, key_filename=conf["key"]) except Exception as e: # TODO: log exception return None output = output.decode("utf-8", errors="ignore") output = output.replace('\r', '') reader = output.split('\n') data = {} fname = filelist[0] for row in reader: ...
Chasego/codi
comp/zenefits/skype/WordCombinations.py
Python
mit
386
0
# not optimized yet, should be optimized by dp def combine(word, k): if k < 1
or k > len(word): return [] if k == 1: return [word[i] for i in range(len(word))] res = combine(word[:-1], k) tmp = combine(word[:-1
], k - 1) for t in tmp: res.append(t + word[-1]) return res res = combine('love', 2) print res for r in res: print r
armstrong/armstrong.core.arm_layout
armstrong/core/arm_layout/templatetags/layout_helpers.py
Python
apache-2.0
4,598
0.00087
from django.conf import settings from django import template from django.template.defaulttags import token_kwargs from django.template.base import TemplateSyntaxError from ..utils import render_model as render_model_backend register = template.Library() class RenderObjectNode(template.Node): def __init__(self, ...
s[1]),
parser.compile_filter(bits[2]), extra_context=namemap, isolated_context=isolated_context) @register.simple_tag(takes_context=True) def render_list(context, obj_list, template_name): return ''.join( render_model_backend(obj, template_name, context_instance=context) for obj in...
chengyongyuan/dcs
lightin/lightin/urls.py
Python
mit
443
0.004515
from django.conf.urls import patterns, include, url from django.contrib import admin ad
min.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'mobiconf.views.index', name='index'), # url(r'^blog/', include('blog.urls')), url(r'^mobi/', include('mobiconf.urls', namespace='mobiconf')), url(r'^datapanel/', include('datapanel.urls', namespace='datapanel')),
url(r'^admin/', include(admin.site.urls)), )
pombredanne/kunai-1
tanuki.py
Python
mit
3,694
0.00758
import os import sys import argparse import requests as rq import socket # DO NOT FORGEET: # sysctl -w net.core.rmem_max=26214400 from kunai.cluster import Cluster from kunai.log import logger parser = argparse.ArgumentParser(description='Tanuki options') parser.add_argument('-p' , dest='port', action='store', ...
default='', help='Configuration files directories') parser.add_argument('--libexec-dir' , dest='libexec_dir', action='store', default='libexec', help='Check plugins directory') parser.add_argument('--encryption' , dest='encryption_key', action='store', default='...
: print 'hello', port, name, bootstrap, seeds, tags, cfg_dir, libexec_dir c = Cluster(int(port), name, bootstrap, seeds, tags, cfg_dir, libexec_dir) #node = c.get_boostrap_node() #c.set_alive(node, bootstrap=True) c.link_services() c.link_checks() c.launch_listeners() c.join() c.laun...
deanhiller/databus
webapp/play1.3.x/python/Lib/dbhash.py
Python
mpl-2.0
543
0.007366
"""Provide a (g)dbm-compatible interface to bsddb.hashopen.""" import sys if sys.py3kwarning: import warnings warnings.warnpy3k("in 3.x, dbhash has been removed", Deprec
ationWarning, 2) try: import bsddb except ImportError: # prevent a second import of this module from spuriously succeeding del sys.modules[__name__]
raise __all__ = ["error","open"] error = bsddb.error # Exported for anydbm def open(file, flag = 'r', mode=0666): return bsddb.hashopen(file, flag, mode)
hj3938/FPGA-Imaging-Library
LocalFilter/ThresholdLocal/SoftwareSim/MeanFilter.py
Python
lgpl-2.1
2,206
0.023572
""" Project FPGA-Imaging-Library Design MeanFilter Function Local filter - Mean filter, it always used for smoothing images. Module Software simulation. Version 1.0 Modified 2015-05-19 Copyright (C) 2015 Tianyu Dai (dtysky) <dtysky@outlook.com> This library is free software; you can redistribute it and/or modif...
s library is distributed in the hope that it wil
l be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Softw...
luca76/QGIS
python/plugins/processing/algs/grass/GrassAlgorithm.py
Python
gpl-2.0
23,620
0.000466
# -*- coding: utf-8 -*- """ *************************************************************************** GrassAlgorithm.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ************************...
***************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os import time import uuid import importlib from qgis.core import * from PyQt4.QtCore import * fr...
GeoAlgorithm from processing.core.ProcessingConfig import ProcessingConfig from processing.core.ProcessingLog import ProcessingLog from processing.core.WrongHelpFileException import WrongHelpFileException from processing.core.GeoAlgorithmExecutionException import \ GeoAlgorithmExecutionException from processing.p...
kaleidos/intranet
backend/intranet/management/commands/sample_data.py
Python
apache-2.0
6,529
0.000613
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django.utils.dates import MONTHS from calendar import monthrange from datetime import date, timedelta from sampledatahelper.helper import SampleDataHelper from intranet.models import * class Command(BaseCommand): args = '' he...
for
project in u.projects.all(): project_data = {day+1: self.sd.int(8) for day in range(monthrange(part.year, part.month)[1])} part.data[project.id] = project_data part.save() # handle def handle(self, *args, **options): self.sd = SampleDataHelper(s...
appleseedhq/gaffer
python/GafferUI/BackdropUI.py
Python
bsd-3-clause
4,084
0.023751
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
SE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import imath import IECore import Gaffer import GafferUI ## A command
suitable for use with NodeMenu.definition().append(), to add a menu # item for the creation of a backdrop for the current selection. We don't # actually append it automatically, but instead let the startup files # for particular applications append it if it suits their purposes. def nodeMenuCreateCommand( menu ) : g...
avalikarvamus/pinguinvoice
db_create.py
Python
bsd-2-clause
211
0
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 Madis Veskimeister <madis@pingviinitiivul.ee> #
from app.config import SQLALCHEMY_DATA
BASE_URI from app import db import os.path db.create_all()
JonnyWong16/plexpy
plexpy/log_reader.py
Python
gpl-3.0
3,708
0.001079
# -*- coding: utf-8 -*- # This file is part of Tautulli. # # Tautulli 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. # # Tautul...
/a/13790289/2405162 def tail(f, lines=1, _buffer=4098): """Tail a file and get X lines from the end""" # place holder for the lines found lines_found = [] # block counter will be multiplied by buffer # to get the block size from the end block_counter = -1 # loop until we find X lines w...
len(lines_found) < lines: try: f.seek(block_counter * _buffer, os.SEEK_END) except IOError: # either file is too small, or too many lines requested f.seek(0) lines_found = f.readlines() break lines_found = f.readlines() # we found enough...
certeu/do-portal
app/api/abusehelper.py
Python
bsd-3-clause
5,478
0
from flask import request, current_app, url_for from flask_jsonschema import validate from .. import db from ..models import AHBot as Bot from .decorators import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """Return a list of available abusehel...
tion status status :status 200: Bot was deleted :status 404: Bot was not found """ a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots d
eleted'}
chienlieu2017/it_management
odoo/addons/note/models/note.py
Python
gpl-3.0
6,066
0.003297
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.tools import html2plaintext class Stage(models.Model): _name = "note.stage" _description = "Note Stage" _order = 'sequence' name = fields.Char('Stage ...
ge_ids.id', '=', stage.id)], 'stage_id': (stage.id, stage.name), 'stage_id_count': self.search_count(domain + [('stage_ids', '=', stage.id)]), '__fold': stage.fold, } for stage in stages] # note without user's stage ...
f nb_notes_ws: # add note to the first column if it's the first stage dom_not_in = ('stage_ids', 'not in', stages.ids) if result and result[0]['stage_id'][0] == stages[0].id: dom_in = result[0]['__domain'].pop() ...
sostenibilidad-unam/sleuth_automation
bin/create_sleuth_condor_batch.py
Python
gpl-3.0
1,461
0
#!/usr/bin/env python import os import argparse from os.path import join, abspath from sh import which import sleuth_automation as sleuth from jinja2 import Environment, PackageLoader description = """ This
script will create a condor submit file for a batch of SLEUTH runs. """ parser = argparse.ArgumentParser(description=description) parser.add_argument('--sleuth_path', required=True, help
='path to SLEUTH directory') parser.add_argument('--region_dir', required=True, help='path to region dir containing locations') parser.add_argument('--mpi_cores', default=0, type=int, help="""number of cores available for MPI, if 0 ...
andmos/ansible
lib/ansible/modules/cloud/vmware/vmware_vmkernel.py
Python
gpl-3.0
47,337
0.002725
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2015, Joseph Callen <jcallen () csc.com> # Copyright: (c) 2017-18, Ansible Project # Copyright: (c) 2017-18, Abhijeet Kasurde <akasurde@redhat.com> # Copyright: (c) 2018, Christian Kotte <christian.kotte@gmx.de> # GNU General Public License v3.0+ (see COPYING ...
or vxlan. (default: default)' type: dict default: { type: 'static', tcpip_stack: 'default', } version_added: 2.5 ip_address: description: - The IP Address for the VMKernel interface. - Use C(network) parameter with C(ip_address) instead. - Depreca...
work) parameter with C(subnet_mask) instead. - Deprecated option, will be removed in version 2.9. mtu: description: - The MTU for the VMKernel interface. - The default value of 1500 is valid from version 2.5 and onwards. default: 1500 device: description: - Search VMker...
jimpriest/pylinkvalidator
pylinkvalidator/included/bs4/builder/_htmlparser.py
Python
bsd-3-clause
9,495
0.000843
"""Use the HTMLParser library to parse HTML files that aren't too bad.""" import sys if sys.version_info[0] < 3: __all__ = [ 'HTMLParserTreeBuilder', ] from HTMLParser import ( HTMLParser, HTMLParseError, ) import sys import warnings # Starting in Python 3...
(name.lstrip('x
'), 16) elif name.startswith('X'): real_name = int(name.lstrip('X'), 16) else: real_name = int(name) try: data = unichr(real_name) except (ValueError, OverflowError), e: data = u"\N{REPLACEMENT CHARACTER}" ...
pbvarga1/qimage2ndarray
test/test_imsave.py
Python
bsd-3-clause
630
0.003175
import qimage2ndarray, os, numpy, tempfile from nose.tools import assert_equal from test_imread import all_test_ima
ges, _locate_test_image def test_imsave(): fh, tempFilename = tempfile.mkstemp('.png') os.close(fh) try: for filename in all_test_images: filename = _locate_test_image(filename) a = qimage2ndarray.imread(filename) ok = qimage2ndarray.imsave(tempFilename, a) ...
a == b) finally: os.unlink(tempFilename)
Tanych/CodeTracking
340-Longest-Substring-with-At-Most-K-Distinct-Characters/solution.py
Python
mit
1,759
0.02672
class Solution(object): def followup(self,s,k): """
the question follow up is data char, only can read one char """ if not s or k==0: return 0 # using the maxheap to save the lastoccurence of the char maxheap=[] # window size rec
ord the k distince char inwindow={} j,maxlen=0,1 # also can read char from the api for i in xrange(len(s)): ch=s[i] if len(inwindow)==k and (ch not in inwindow): idx,first=heapq.heappop(maxheap) del inwindow[first] j...
batermj/algorithm-challenger
code-analysis/programming_anguage/python/source_codes/Python3.8.0/Python-3.8.0/Lib/importlib/metadata.py
Python
apache-2.0
16,174
0
import io import os import re import abc import csv import sys import email import pathlib import zipfile import operator import functools import itertools import collections from configparser import ConfigParser from contextlib import suppress from importlib import import_module from importlib.abc import MetaPathFind...
discover(cls, **kwargs): """Return an iterable of Distribution objects for all packages. Pass a ``context`` or pass keyword arguments for constructing a context. :context: A ``DistributionFinder.Context`` object. :return: Iterable of Distribution objects for all packages. ...
text = kwargs.pop('context', None) if context and kwargs: raise ValueError("cannot accept context and kwargs") context = context or DistributionFinder.Context(**kwargs) return itertools.chain.from_iterable( resolver(context) for resolver in cls._discover_resol...
gelab/mainr
tests/cext/test_cext_connection.py
Python
gpl-2.0
4,342
0.000461
# -*- coding: utf-8 -*- # MySQL Connector/Python - MySQL driver written in Python. # Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. # MySQL Connector/Python is licensed under the terms of the GPLv2 # <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most # MySQL Connectors. Th...
info) rows = self.cnx.get_rows()
vars = [ row[0] for row in rows ] self.assertEqual(2, len(rows)) vars.sort() exp = ['Aborted_clients', 'Aborted_connects'] self.assertEqual(exp, vars) exp = ['Value', 'Variable_name'] fields = [fld[0] for fld in info['columns']] fields.sort() self...
changsiyao/mousestyles
mousestyles/path_diversity/tests/test_smooth_noise.py
Python
bsd-2-clause
2,526
0
from __future__ import (absolute_import, division, print_function, unicode_literals) import pandas as pd from mousestyles import path_diversity def test_smooth_noise(): movement = {'t': pd.Series([0., 0.02, 0.04, 0.06], index=[0, 1, 2, 3]), 'x': pd.Series([0., 0., 0.1, 0....
s = path_diversity.path_index(movement, 1, 1
) # Check if function produces the correct outputs. smoothed = path_diversity.smooth_noise(movement, paths, 120, 1) assert smoothed['y'][1] == 0.5 movement = {'t': pd.Series([0., 0.02, 0.04, 0.06], index=[0, 1, 2, 3]), 'x': pd.Series([0., 0., 0.1, 0.2], index=[0, 1, 2, 3]), ...
Q14022/OpenLab
src/face_to_face3.py
Python
gpl-3.0
1,687
0.022525
#!/usr/bin/env python #encoding: utf8 import rospy, cv2 from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError class FaceToFace(): def __init__(self): sub = rospy.Subscriber("/cv_camera/image_raw", Image, self.get_image) self.bridge = CvBridge() self.image_org = Non...
are/opencv/haarcascades/haarcascade_frontalface_default.xml" cascade =cv2.CascadeClassifier(classifier) face = cascade.detectMultiScale(gimg,1.1,1,cv2.CASCADE_FIND_BIGGEST_OBJECT) if len(face) == 0: self.monitor(None,org) return None r = face[0] ...
rg) return "detected" if __name__ == '__main__': rospy.init_node('face_to_face') fd = FaceToFace() rate = rospy.Rate(10) while not rospy.is_shutdown(): rospy.loginfo(fd.detect_face()) rate.sleep()
tensorflow/datasets
tensorflow_datasets/text/race/__init__.py
Python
apache-2.0
685
0
#
coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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 appli...
ND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Race dataset.""" from tensorflow_datasets.text.race.race import Race
muccc/upay
upay/client/__init__.py
Python
gpl-3.0
174
0.005747
from session import SessionManager, Session, SessionConnectionError,
NotEnoughCreditError, RollbackError, CashTimeou
tError, SessionError from token_client import TokenClient
thinkopensolutions/server-tools
base_kanban_stage/tests/test_base_kanban_abstract.py
Python
agpl-3.0
2,793
0
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo import models from odoo.tests.common import SavepointCase class BaseKanbanAbstractTester(models.TransientModel): _name = 'base.kanban.abstract.tester' _inherit = 'base.kanban.a...
anbanAbstract, cls).tearDownClass() def setUp(self): super(TestBaseKanbanAbstract, self).setUp() test_stage_1 = self.env['base.kanban.stage'].create({ 'name': 'Test Stage 1', 'res_model_id': self.test_model_record.id, }) test_stage_2 = self.env['base.kanban.s...
.create({ 'name': 'Test Stage 2', 'res_model_id': self.test_model_record.id, 'fold': True, }) self.id_1 = test_stage_1.id self.id_2 = test_stage_2.id def test_read_group_stage_ids(self): """It should return the correct recordset. """ self...
lordkman/burnman
examples/example_build_planet.py
Python
gpl-2.0
7,538
0.01446
# This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for the Earth and Planetary Sciences # Copyright (C) 2012 - 2015 by the BurnMan team, released under the GNU # GPL v2 or later. ''' example_build_planet -------------------- For Earth we have well-constrained one-dimensional density models. ...
f inertia print() print("mass/Earth= %.3f, moment of inertia= %.3f" % (Plan.mass/5.97e24, Plan.mome
nt_of_inertia_factor)) #And here's the mass of the individual layers: for layer in Plan.layers: print("%s mass fraction of planet %.3f" %(layer.name, layer.mass/Plan.mass)) print() #Now let's plot everything up # Do you like pretty, but slow plotting figures? Try Burnman's patented pretty...
mathLab/RBniCS
rbnics/utils/factories/reduced_problem_factory.py
Python
lgpl-3.0
2,797
0.003218
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later from logging import DEBUG, getLogger from rbnics.utils.decorators.customize_reduced_problem_for import _cache as customize_reduced_problem_cache from rbnics.utils.decorators.reduced_problem_f...
decorators = ") for Deco
rator in type(truth_problem).ProblemDecorators: logger.log(DEBUG, "\t\t" + str(Decorator)) logger.log(DEBUG, "") TypesList = list() # Generate ReducedProblem types based on Problem and ReductionMethod type logger.log(DEBUG, "Generate ReducedProblem types based on Problem and ReductionM...
miurahr/seahub
tests/api/test_dir_revert.py
Python
apache-2.0
1,897
0.003163
import os import json from seaserv import seafile_api from django.urls import reverse from seahub.test_utils import BaseTestCase class DirRevertTest(BaseTestCase): def setUp(self): self.repo_id = self.repo.id self.folder_path = self.folder self.parent_dir = os.path.dirname(self.folder_path...
i.del_file(self.repo_id, self.parent_dir, self.folder_name, self.username) def get_trash_dir_commit_id(self): deleted_file = seafile_api.get_deleted(self.repo_id, 0, '/', None)
return deleted_file[0].commit_id def get_lib_folder_name(self): url = reverse('list_lib_dir', args=[self.repo_id]) resp = self.client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') json_resp = json.loads(resp.content) if len(json_resp['dirent_list']) == 0: retu...
marduk191/plugin.video.movie25
resources/libs/plugins/watchseries.py
Python
gpl-3.0
22,128
0.030595
# -*- coding: cp1252 -*- import urllib,re,string,sys,os import xbmc,xbmcgui,xbmcaddon,xbmcplugin from resources.libs import main #Mash Up - by Mash2k3 2012. addon_id = 'plugin.video.movie25' selfAddon = xbmcaddon.Addon(id=addon_id) art = main.art prettyName = 'WatchSeries' def MAINWATCHS(): main.addDir('Sear...
578,'','','','','','') main.addLink('[COLOR red]Most Popular Documentaries[/COLOR]','',art+'/link.png') for url, name in match[24:36]: main.addDirT(name,'http://watchseries.lt'+url,578,'','','','','','') main.addLink('[COLOR red]Most Popular Shows[/COLOR]','',art+'/link.png') ...
Sports[/COLOR]','',art+'/link.png') for url, name in match[48:60]: main.addDirT(name,'http://watchseries.lt'+url,578,'','','','','','') def GENREWATCHS(): main.addDir('Action','http://watchseries.lt/genres/action',576,art+'/act.png') main.addDir('Adventure','http://watc...
wwrechard/pydlm
pydlm/tests/base/testKalmanFilter.py
Python
bsd-3-clause
5,458
0.003664
import numpy as np import unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(disc...
self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self): dlm = builder() dlm.add(s
elf.trend0) dlm.initialize() # with mean being 0 and observe 1 and 0 consectively, one shall # expect the smoothed mean at 1 will be 1/3, for discount = 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \ ...
devGregA/code
scrapy/tests/test_spidermanager/__init__.py
Python
bsd-3-clause
2,747
0.005825
import sys import os import shutil from zope.interface.verify import verifyObject from twisted.trial import unittest # ugly hack to avoid cyclic imports of scrapy.spider when running this test # alone from scrapy.interfaces import ISpiderManager from scrapy.spidermanager import SpiderManager from scrapy.http import ...
this')), ['spider3']) def test_load_spider_module(self): self.spiderman = SpiderManager(['scrapy.tests.test_spidermanager.test_spiders.spider1']) assert len(self.spiderman._spiders) == 1 def test_load_base_spider(self): self.spiderman = SpiderManager(['scrapy.tests.test_spi...
def test_load_from_crawler(self): spider = self.spiderman.create('spider4', a='OK') self.assertEqual(spider.a, 'OK')
ArcheProject/arche_pas_social
arche_pas_social/models.py
Python
gpl-2.0
3,574
0.004477
from BTrees.OOBTree import OOBTree from arche.interfaces import IObjectWillBeRemovedEvent from arche.interfaces import IRoot from arche.interfaces import IUser from pyramid.traversal import find_root from zope.component import adapter from zope.interface import implementer from arche_pas_social.interfaces import ISoci...
turn si_userid @property def userid_to_services(self): try: userid_si = self.context._userid_to_services except AttributeError: userid_si = self.context._userid_to_services = OOBTree() return userid_si def add(self, userid, service_name, identifier): ...
if (service_name, identifier) not in self.userid_to_services[userid]: self.userid_to_services[userid].append((service_name, identifier)) self.service_identifier_to_userid[(service_name, identifier)] = userid def remove(self, userid, service_name, identifier = None): if identifier ...
nerdvegas/rez
src/rez/data/tests/builds/packages/hello/1.0/package.py
Python
apache-2.0
258
0.003876
name = 'hello' version = '1.0' autho
rs = ["dr.foo"] uuid = "110c80c135c142479d47e756bdbbddf8" description = "A very simple C++ project." tools = ['hai'] build_com
mand = "make -f {root}/Makefile {install}" def commands(): env.PATH.append('{root}/bin')
voipir/python-sii
src/sii/lib/printing/barcode/Barcode.py
Python
lgpl-3.0
331
0
""" Barcode Creation (PDF4
17) """ import os basedir = os.path.split(__file__)[0] bcdelib = os.path.join(basedir, 'psbcdelib.ps') class Barcode(object):
__lib__ = open(bcdelib, 'r').read() @property def ps(self): raise NotImplementedError @property def eps(self): raise NotImplementedError
dbbaleva/ERP-Forwarding
erp/reports/util.py
Python
gpl-2.0
1,516
0.001319
import os from glob import glob from pyramid.path import AssetResolver from reportlab.lib.units import mm from reportlab.pdfgen import canvas from ..models import generate_random_digest __all__ = [ 'generate_random_filename', 'delete_files', 'NumberedCanvas' ] def generate_random_filename(path=None, ext...
olver('erp') path = path or r.resolve('static/temp').abspath() if not os.path.exists(path): os.mkdir(path) filename = generate_random_digest() return '/'.join([path, '{filename}.{extension}'.format(filename=filename, extension=extension)]) def delete_files(expression): files = glob(express...
iles: os.remove(*files) class NumberedCanvas(canvas.Canvas): def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self._saved_page_states = [] def showPage(self): self._saved_page_states.append(dict(self.__dict__)) self._startPage() d...
jcshen007/cloudstack
systemvm/patches/debian/config/opt/cloud/bin/cs/CsStaticRoutes.py
Python
apache-2.0
1,649
0.002426
#!/usr/bin/python # -- coding: utf-8 -- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Vers...
the License. from CsDatabag import CsDataBag from CsRedundant import * class CsStaticRoutes(CsDataBag): def process(self): logging.debug("Processing CsStaticRoutes file ==> %s" % self.dbag)
for item in self.dbag: if item == "id": continue self.__update(self.dbag[item]) def __update(self, route): if route['revoke']: command = "ip route del %s via %s" % (route['network'], route['gateway']) CsHelper.execute(command) else: ...
ThreatConnect-Inc/tcex
tests/app_config/copy_ij_files.py
Python
apache-2.0
1,233
0.000811
"""Tool to copy all install.json files from App to testing directory.""" # standard library import os from shutil import copyfile def walklevel(some_dir, level=1): """.""" some_dir = some_dir.rstrip(os.path.sep) if os.path.isdir(some_dir): num_sep = some_dir.count(os.path.sep) for root_, d...
TCVA', 'TCVC', 'TCVW']: os.makedirs(os.path.join(dst_ba
se, project.lower()), exist_ok=True) prj_dir = os.path.join(src_base, project) for root, dirs, files in walklevel(prj_dir): src_fqfn = os.path.join(root, filename) if not os.path.isfile(src_fqfn): continue base_name = os.path.basename(root) dst_fqfn = os.path.join(d...
JasonKessler/scattertext
scattertext/features/PhraseMachinePhrases.py
Python
apache-2.0
1,370
0.032117
from collections import Counter from scat
tertext.external.phrasemachine import phrasemachine from scattertext.features.FeatsFromSpacyDoc import FeatsFromSpacyDoc class PhraseMachinePhrases(FeatsFromSpacyDoc): ''' Returns unigrams and phrase machi
ne phrases ''' def get_feats(self, doc): ''' Parameters ---------- doc, Spacy Doc Returns ------- Counter noun chunk -> count ''' ngram_counter = Counter() for sent in doc.sents: ngram_counter += _phrase_counts(sent) return ngram_counter class PhraseMachinePhrasesAndUnigrams(FeatsFromSpac...
enthought/traitsgui
enthought/pyface/preference/preference_node.py
Python
bsd-3-clause
2,478
0.001614
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions describe...
ses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description:
<Enthought pyface package component> #------------------------------------------------------------------------------ """ Abstract base class for a node in a preference dialog. A preference node has a label and an image which are used to represent the node in a preference dialog (usually in the form of a tree). """ ...
s-trinh/visp
platforms/android/build-tests/test_ndk_build.py
Python
gpl-2.0
5,331
0.005065
#!/usr/bin/env python import unittest import os, sys, subprocess, argparse, shutil, re TEMPLATE_ANDROID_MK = '''\ LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) {cut} LOCAL_MODULE := mixed_sample LOCAL_SRC_FILES := {cpp1} LOCAL_LDLIBS += -llog -ldl include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) {cut} L...
ce", help="Working dir
ectory (and output)") parser.add_argument("opencv_mk_path", help="Path to folder with OpenCV.mk file (usually <SDK>/sdk/native/jni/") args = parser.parse_args() if args.ndk_path is not None: os.environ["ANDROID_NDK"] = os.path.abspath(args.ndk_path) print("Using NDK: %s" % os.environ["ANDROID...
s-gogna/JST
mips/configurations.py
Python
gpl-3.0
904
0.003319
# This file is part of JST. # # JST is free software: you can redistribute it an
d/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. # # JST 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 PARTIC...
kelvan/gotoVienna
gotovienna/errors.py
Python
gpl-3.0
344
0.014535
class LineNotFoundError(Exception): def __init__(self, msg="Unknown line"): self.message = msg
def __str__(self): return self.message class StationNotFoundError(Exception): def __init__(self, msg="Unknown station"): self.message = msg
def __str__(self): return self.message
nejstastnejsistene/gardendb
pg_test.py
Python
bsd-3-clause
1,750
0.006857
import psycopg2 import gardendb import gardendb.postgres with open('.dbconfig') as f
: conn = psycopg2.connect(f.read()) ThisIsACucumber= gardendb.cucumber('ThisIsACucumber', 'a b c') pool = gardendb.postgres.dummy_pool(conn) my_garden = gardendb.postgres.PgGarden('my_garden', pool) import random test = ThisIsACucumber(*(random.getrandbits(32) for i in range(3))) my_garden['ahoj'] = test p...
en['not_a_cucumber'] my_garden[1, 2, 3] = "key isn't a string".split() print my_garden[1, 2, 3] import pprint pprint.pprint(my_garden.getall()) del my_garden['ahoj'] pprint.pprint(my_garden.getall()) dct = { x: x**2 for x in range(20) } my_garden.putmany(dct) pprint.pprint(my_garden.getall()) typed_garden = gardend...
sebdelsol/pyload
module/plugins/crypter/LixIn.py
Python
gpl-3.0
2,104
0.006179
# -*- coding: utf-8 -*- import re from module.plugins.Crypter import Crypter class LixIn(Crypter): __name__ = "LixIn" __type__ = "crypter" __version__ = "0.22" __pattern__ = r'http://(?:www\.)?lix\.in/(?P<ID>.+)' __config__ = [("use_subfolder", "bool", "Save package to subfolder", True),...
a("http://lix.in/" + m.group("image")) self.html = self.load(url, decode=True, post={"capt": captcharesult, "submit": "submit", "tiny": id}) else: self.logDebug("No captcha/captcha solved")
else: self.html = self.load(url, decode=True, post={"submit": "submit", "tiny": id}) m = re.search(self.LINK_PATTERN, self.html) if m is None: self.error(_("Unable to find destination url")) else: self.urls = [m.group("link")] self.logDebug("Fo...
deepchem/deepchem
examples/chembl/chembl_graph_conv.py
Python
mit
1,294
0.002318
""" Script that trains graph-conv models on ChEMBL dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np from deepchem.models import GraphConvModel np.random.seed(123) import tensorflow as tf tf.random.set_seed(123) import deepc...
rint("Evaluating model") train_scores = model.evaluate(train_dataset, [metric], transformers) valid_scores = model.evaluate(valid_dataset, [metric], transformers) test_scores = model.evaluate(test_dataset, [metric], transformers) print("Train scores") print(train_scores) pr
int("Validation scores") print(valid_scores) print("Test scores") print(test_scores)
bundgus/python-playground
matplotlib-playground/examples/pylab_examples/major_minor_demo1.py
Python
mit
1,698
0
""" Demonstrate how to use major and minor tickers. The two relevant userland classes are Locators and Formatters. Locators determine where the ticks are a
nd formatters control the formatting of ticks. Minor ticks are off by default (NullLocator and NullFormatter). You can turn minor ticks on w/o labels by setting the minor locator. You can also turn labeling on for the minor ticker by setting the minor formatter Make a plot with major ticks that are multiples of 20 ...
that are multiples of 5. Label major ticks with %d formatting but don't label minor ticks The MultipleLocator ticker class is used to place ticks on multiples of some base. The FormatStrFormatter uses a string format string (e.g., '%d' or '%1.2f' or '%1.1f cm' ) to format the tick The pyplot interface grid command ...
Wen777/beets
test/test_pipeline.py
Python
mit
6,779
0.001623
# This file is part of beets. # Copyright 2013, Adrian Sampson. # # Permission is hereby granted, free of charge
, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish
, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. """Test the "pi...
ostree/plaso
tests/parsers/asl.py
Python
apache-2.0
2,820
0.001418
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for Apple System Log file parser.""" import unittest from plaso.formatters import asl as _ # pylint: disable=unused-import from plaso.lib import timelib from plaso.parsers import asl from tests.parsers import test_lib class AslParserTest(test_lib.ParserTestCase):...
f.assertEqual(event_object.time
stamp, expected_timestamp) self.assertEqual(event_object.record_position, 442) self.assertEqual(event_object.message_id, 101406) self.assertEqual(event_object.computer_name, u'DarkTemplar-2.local') self.assertEqual(event_object.sender, u'locationd') self.assertEqual(event_object.facility, u'com.app...
eaybek/nymph
IP.py
Python
gpl-3.0
489
0.06544
from Nymph import * ismail=nymphdata("ismail","127.0.0.1",8592) erdem=nymphdata('erdem','127.0.0.1',7711) ferhat=nymphdata('ferhat','127.0.0.1',8812) alptug=nymphdata('alptug','127.0.0.1',8813) ali=nymphdata('ali','127.0.0.1',8890) veli=nymphdata('veli','127.0.0.1',8891) firuze
=nymphdata('firuze','127.0.0.1',8892) halil=nymphdata('halil','127.0.0.1',8893) nihal=nymphdata('nihal','127.
0.0.1',8894) nuran=nymphdata('nuran','127.0.0.1',8895) #create a nymph example #ismail=nymph(ismail)
bird-house/pyramid-phoenix
phoenix/monitor/views/details.py
Python
apache-2.0
711
0.002813
from pyramid.view import view_config, view_defaults from phoenix.views import MyView @view_defaults(permission='view', layout='default') class Details(MyView): def __init__(self, request): super(Details, self).__init__(request, name='job_details', title='Job Details') self.tab = self.request.matc...
self.collection = self.request.db.jobs @view_config(route_name='job_details', renderer='phoenix:monitor/templates/monitor/details.pt') def view(self): job = self.collection.find_one({'identifier': self.job_id})
return dict(active=self.tab, job_id=self.job_id, status=job['status'])
GoogleCloudPlatform/bigquery-utils
tools/unsupervised_dataset/sql_crawler/extractor.py
Python
apache-2.0
2,295
0.00305
""" Contains the logic to extract links and SQL queries from HTML content. This file contains functions to extract links or queries when given an HTML response. It also dynamically extracts links based on the URL of the response. """ import urllib import bs4 import re import sql_crawler.extraction_modules.gen...
content = bs4.BeautifulSoup(html.text, "html.parser")
except Exception as e: print(html.url) link_tags = content.find_all("a") links = set([]) for link in link_tags: if link.has_attr('href'): # Fix relative paths and anchor links absolute_path = urllib.parse.urljoin(html.url, link['href']) if "github.com" in...
efiop/dvc
dvc/testing/conftest.py
Python
apache-2.0
65
0
from .fixtures
import * # noqa,
pylint: disable=wildcard-import
realpython/flask-skeleton
{{cookiecutter.app_slug}}/project/tests/test_user.py
Python
mit
4,811
0
# project/server/tests/test_user.py import datetime import unittest from flask_login import current_user from base import BaseTestCase from project.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correc...
"/login", data=dict(email="ad@min.com", password="admin_user"), follow_redirects=True, ) user = User.query.filter_by(email="ad@min.com").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # ...
bcrypt.check_password_hash(user.password, "admin_user") ) self.assertFalse(bcrypt.check_password_hash(user.password, "foobar")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = se...
jia200x/RIOT
dist/tools/backport_pr/backport_pr.py
Python
lgpl-2.1
10,731
0
#!/usr/bin/env python3 # Copyright (C) 2018 Freie Universitat Berlin # Copyright (C) 2018 Inria # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. # # @author Koen Zandberg <koen@bergzand.net> """S...
file.read().strip() github_api = GitHub(token=gittoken) # TODO: exception handling status, user = github_api.user.get() if status != 200:
print(f'Could not retrieve user: {user["message"]}') sys.exit(1) # Token-scope-check: Is the token is powerful enough to complete # the Backport? response_headers = dict(github_api.getheaders()) # agithub documentation says it's lower case header field-names but # at this moment it's not ...
bdilday/nflMarkov
nflMarkov.py
Python
bsd-2-clause
59,379
0.007006
#!/usr/bin/env python import os, sys import re import pickle import numpy as np import copy from scipy import interpolate import scipy.sparse from matplotlib.backends.backend_pdf import PdfPages from matplotlib import pyplot as plt import matplotlib from matplotlib import pyplot as plt ############################ cl...
self.modelFunctions[k][dwn][iytg][icol] = interpFunc if dwn==0: for idwn in [1,2,3,4]: if not k in self.modelFunctions: se
lf.modelFunctions[k] = {} if not idwn in self.modelFunctions[k]: self.modelFunctions[k][idwn] = {} if not iytg in self.modelFunctions[k][idwn]: self.modelFunct
scampion/pimpy
pimpy/discover.py
Python
agpl-3.0
2,809
0.008544
#!/usr/bin/env python # -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # gstfile.py # (c) 2005 Edward Hervey <edward at fluendo dot com> # Discovers and prints out multimedia information of files # This example shows how to use gst-python: # _ in an object-oriented way (Discoverer class) # _ subclassing a gst.Pipeli...
ttrs['audio.caps'] = str(d.audiocaps) self.attrs['audio.format'] = d.audiofloat and 'floating-point' or 'integer' self.attrs['audio.samplerate'] = d.audiorate self.attrs['audio.samplewidth'] = d.audiowidth self.attrs['audio.sampledepth'] = d.audiodepth se...
self.current = None if len(self.files): print "\n" gobject.idle_add(self._discover_one) def _discover_one(self): if not len(self.files): gobject.idle_add(self.mainloop.quit) return False filename = self.files.pop(0) if not os.pat...
dsarkozi/care4care-sdp-grp4
Care4Care/C4CApplication/views/MemberDetailsView.py
Python
agpl-3.0
1,577
0.007609
from django.views.generic import DetailView from django.core.exceptions import PermissionDenied from C4CApplication.views.utils import create_user from C4CApplication.models.member import Member class MemberDetailsView(DetailView): model = Member context_object_name = "member_shown" templ...
for v in Member.TAG_CHOICE: if v[0] & db_member.tag == v[0]: tag += "%s & " % (v[1]) return tag[:-3] def get_context_data(self, **kwargs): context = {} context = super(MemberDetailsView, self).get_context_data(**context) context[...
ember'] = MemberDetailsView.get_tag_member(context['member_shown']) context['connected'] = 'email' in self.request.session context['is_branch_officer'] = self.member.is_branch_officer(context['member_shown']) return context def get_object(self): member_shown = super(...
pjohansson/flowtools
setup.py
Python
gpl-3.0
1,324
0
#!/usr/bin/env pyth
on from distutils.core import setup setup( name="flowtools", description="Tools for flow maps from modified Gromacs simulations", long_description="See README.md", license='GPLv3', version='0.2.30', url="https://github.com/pjohansson/flowtools", author="Petter J...
'numpy (>=1.7.0)', 'matplotlib (>=1.2.0)', 'pandas (>=0.10.1)', 'scipy (>=0.11.0)' ], scripts=[ 'scripts/f_collect_spread.py', 'scripts/f_combine_maps.py', 'scripts/f_flowmaps.py', 'scripts/f_print.py', ...
poffey21/edge
src/manage.py
Python
mit
469
0.002132
#!/usr/bin/en
v python import os import sys if __name__ == "__main__": # CHANGED manage.py will
use development settings by # default. Change the DJANGO_SETTINGS_MODULE environment variable # for using the environment specific settings file. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings.development") from django.core.management import execute_from_command_line...
ZimDeveloper/FundCenter
FundCenter/manage.py
Python
mit
253
0
#!
/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "FundCenter.settings") from django.core.man
agement import execute_from_command_line execute_from_command_line(sys.argv)
pytorch/fairseq
scripts/average_checkpoints.py
Python
mit
6,075
0.001975
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import collections import os import re import torch from fairseq.file_io import PathManager def aver...
t file paths.') parser.add_argument('--output', required=True, metavar='FILE', help='Write the new checkpoint containing the averaged weights to this path.') num_group = parser.add_mutually_exclusive
_group() num_group.add_argument('--num-epoch-checkpoints', type=int, help='if set, will try to find checkpoints with names checkpoint_xx.pt in the ' 'path specified by input, and average last this many of them.') num_group.add_argument('--num-update-checkpoi...
redwoodsystems/GoogleCalendar-Connector
reaper/admin.py
Python
apache-2.0
2,987
0.012722
from reaper.models import ReaperConfig, RoomConfig, RoomStatus, ReaperLog from django.contrib import admin class RoomConfigAdmin(admin.ModelAdmin): fields = ['id','name', 'g_calendar_id', 'rw_location_id', 'rw_location_name', 'motion_enabled', 'creation_date','last_modified_date'] readonly_fields = ('id','crea...
pi_url', 'rw_api_user', 'rw_api_pwd', 'last_modified_date') actions = None def has_delete_permission(self, request, obj=None): return False admin.site.register(ReaperConfig, ReaperConfigAdmin) class ReaperLogAdmin(admin.ModelAdmin): fields = ['id','g_event_id', 'rsv_begin_time', 'rsv_end_tim...
id','g_event_id', 'rsv_begin_time', 'rsv_end_time', 'rsv_owner_email', 'rsv_owner_name', 'room', 'room_calendar_id', 'room_name', 'reap_date', 'creation_date','last_modified_date') list_display = ('id','room_name','rsv_begin_time', 'rsv_end_time', 'rsv_owner_name', 'reap_date') ...
rootsradics/castback
resources/lib/resolvers/livestreamer.py
Python
gpl-3.0
975
0.046154
from resources.lib.modules import control,client from resources.lib.modules.log_utils import log import xbmc,os,re,urllib,base64 def resolve(url): initial = url libPath = os.path.join(control.addonPath, 'resources/lib/modules') serverPath = os.path.join(libPath, 'livestreamerXBMCLocalProxy.py') try: imp...
' + serverPath + ')')
url = re.findall('[\"\']([^\"\']+)',url)[0] try: headers = re.findall('-http-headers=([^\s]+)',url)[0] except: headers = urllib.urlencode({'User-agent':client.agent()}) url += '|' + headers try: cookies = re.findall('-http-cookie=([^\s]+)',initial)[0] url += '|' + cookies except: pass ...