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
woutdenolf/spectrocrunch
scraps/ffnoisesimul.py
Python
mit
9,053
0.00232
# -*- coding: utf-8 -*- import os, sys sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from spectrocrunch.materials.compoundfromformula import compoundfromformula from spectrocrunch.materials.compoundfromname import compoundfromname from spectrocrunch.materials.mixture import mixture ...
ralene = compoundfromname("vacuum") # sfreetape = compoundfromname("vacuum") m = [ultralene, paint, sfreetape] thickness = [4, paintthickness, 10] # m = [compoundfromname("vacuum"),compoundfromname("vacuum"),compoundfromname("vacuum")] self.composition = materials.factory( ...
ss=thickness, anglein=0, angleout=0, azimuth=0, ) self.paintindex = 1 def set_wpigment(self, wpigment): w = self.composition.material[self.paintindex].massfractions() w["verdigris"] = wpigment / 100.0 w["linseed oil"] = 1 - wpigment / 100....
islamgulov/libcloud.rest
libcloud_rest/api/urls.py
Python
apache-2.0
704
0
# -*- coding:utf-8 -*- from werkzeug.routing import Map, Submount import libcloud from libcloud_rest.api.handlers import app_handler from libcloud_rest.api.handlers.compute import compute_handler from libcloud_rest.api.handlers.dns import dns_handler from libcloud_rest.api.handlers
.loadbalancer import lb_handler from libcloud_rest.api.handlers.storage import storage_handler from libcloud_rest.api.versions import versions api_version = '/%s' % (versions[libcloud.__version__]) urls = Map([ app_handler.get_rules(), Submount(api_version, [ compute_handler.get_rules(), dns...
lb_handler.get_rules(), storage_handler.get_rules(), ]) ])
uniite/pyirc
test_msg.py
Python
mit
63
0
from models.pusher impor
t push print re
pr(push("Bazinga..."))
Lyleo/OmniMarkupPreviewer
OmniMarkupLib/Renderers/libs/python3/docutils/transforms/universal.py
Python
mit
10,307
0.001067
# $Id$ # -*- coding: utf8 -*- # Authors: David Goodger <goodger@python.org>; Ueli Schlaepfer; Günter Milde # Maintainer: docutils-develop@lists.sourceforge.net # Copyright: This module has been placed in the public domain. """ Transforms needed by most or all documents: - `Decorations`: Generate a document's header &...
, node): return not isinstance(node, nodes.Text) def apply(self): if self.document.settings.expose_internals: for no
de in self.document.traverse(self.not_Text): for att in self.document.settings.expose_internals: value = getattr(node, att, None) if value is not None: node['internal:' + att] = value class Messages(Transform): """ Place any syst...
tbabej/freeipa
ipaserver/install/otpdinstance.py
Python
gpl-3.0
948
0
# Authors: Tomas Babej <tbabej@redhat.com> # # Copyri
ght (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ver...
y of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from ipaserver.install import service class OtpdInstance(...
StarbuckBG/BTCGPU
test/functional/rest.py
Python
mit
15,085
0.00822
#!/usr/bin/env python3 # Copyright (c) 2014-2016 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 the REST API.""" from test_framework.test_framework import BitcoinTestFramework from test_framewo...
.FORMAT_SEPARATOR+'json', json_request, True) assert_equal(response.status, 400) #must be a 400 because we send an invalid json request json_request
= '{"checkmempool' response = http_post_call(url.hostname, url.port, '/rest/getutxos'+self.FORMAT_SEPARATOR+'bin', json_request, True) assert_equal(response.status, 400) #must be a 400 because we send an invalid bin request response = http_post_call(url.hostname, url.port, '/rest/getutxos/chec...
jerryzhenleicai/lattice
lattice/topo_sort.py
Python
apache-2.0
3,768
0.00345
# Original topological sort code written by Ofer Faigon (www.bitformation.com) and used with permission # Permission is hereby granted to copy, modify and use this source code for any purpose as long as the above comment line is included with it. """ Loop detection and depth calculation added by Zhenlei Cai (c) 2010...
graph. Removing # a node may convert some of the node's direct children into roots. # Whenever that happens, we append the new roots to the list of # current roots. sorted = [] while len(roots) != 0: # If len(roots)
is always 1 when we get here, it means that # the input describes a complete ordering and there is only # one possible output. # When len(roots) > 1, we can choose any root to send to the # output; this freedom represents the multiple complete orderings # that satisfy the input ...
tox-dev/tox
src/tox/util/lock.py
Python
mit
1,295
0.002317
"""holds locking
functionality that works across processes""" from __future__ import absolute_import, unicode_literals from contextlib import contextmanager import py from filelock import FileLock, Timeout from tox.reporter import verbosity1 @contextmanager def hold_
lock(lock_file, reporter=verbosity1): py.path.local(lock_file.dirname).ensure(dir=1) lock = FileLock(str(lock_file)) try: try: lock.acquire(0.0001) except Timeout: reporter("lock file {} present, will block until released".format(lock_file)) lock.acquire()...
Sriee/epi
data_structures/lib/__init__.py
Python
gpl-3.0
21
0
__
all__ = ['stack']
egabancho/invenio
invenio/modules/sequencegenerator/backend.py
Python
gpl-2.0
2,606
0.00614
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version ...
n the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have r
eceived a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from invenio.legacy.dbquery import run_sql, IntegrityError # Number of retries to insert a value in the DB storage MAX_DB_RETRY = 10 ...
aelk/loga
math/exgcd.py
Python
mit
429
0
def exgcd(a, b): """Uses the extended Euclidean algorithm to return the gcd as well as the solutions to Bézout's identity:
coefficients x and y such that ax + by = gcd(a, b).""" x, y = 0,
1 u, v = 1, 0 while a != 0: quo = b // a rem = b % a m = x - (quo * u) n = y - (quo * v) b, a = a, rem x, y = u, v u, v = m, n gcd = b return gcd, x, y
janeen666/mi-instrument
mi/dataset/driver/wc_wm/cspp/wc_wm_cspp_telemetered_driver.py
Python
bsd-2-clause
1,972
0.002535
#!/usr/bin/env python """ @package mi.dataset.driver.wc_wm.cspp @file mi/dataset/driver/wc_wm/cspp/wc_wm_cspp_telemetered_driver.py @author Jeff Roy @brief Driver for the wc_wm_cspp instrument Release notes: Initial Release """ from mi.dataset.dataset_parser import DataSetDriverConfigKeys from mi.dataset.dataset_dr...
_handler class WcWmCsppRecoveredDriver(SimpleDatasetDriver): """ Derived wc_wm_cspp driver class All this needs to do is create a concrete _build_parser method """ def _build_parser(self, stream_handle): parser_config = { DataSetDriverConfigKeys.PARTICLE_CLASS: None, ...
cWmEngTelemeteredDataParticle } } parser = WcWmCsppParser(parser_config, stream_handle, self._exception_callback) return parser
ascension/angular-flask-mongo
angular_flask/core.py
Python
mit
298
0.013423
import os from angu
lar_flask import app from flask.ext.restless import APIManager from flask.ext.mongoengine import MongoEngine app.config["MONGODB_S
ETTINGS"] = {'DB':os.environ.get('MONGODB_DB'),"host":os.environ.get('MONGODB_URI')} mongo_db = MongoEngine(app) api_manager = APIManager(app)
parpg/parpg
tools/map_editor/scripts/gui/input.py
Python
gpl-3.0
1,824
0.016447
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2009 by the FIFE team # http://www.fifengine.de # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # ...
####
######### from fife.extensions import pychan import fife.extensions.pychan.widgets as widgets class InputDialog(object): """ Input supplies a text box for entering data. The result is passed to onEntry. onEntry - the function to call when a input is complete. Accepts one argument: a string of text. """ def __ini...
xuru/pyvisdk
pyvisdk/do/action.py
Python
mit
1,144
0.009615
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def Action(vim, *args, **kwargs): '''This data object type defines the action initiated b...
+ len(kwargs)) < 0: raise IndexError('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optional = [ 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg)
for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
openstack/compute-hyperv
compute_hyperv/nova/volumeops.py
Python
apache-2.0
33,067
0
# Copyright 2012 Pedro Navarro Perez # Copyright 2013 Cloudbase Solutions Srl # 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...
nfo) def
detach_volume(self, context, connection_info, instance, update_device_metadata=False): LOG.debug("Detaching volume: %(connection_info)s " "
nfredrik/pyModelStuff
samples/abp/test_graphics.py
Python
bsd-3-clause
613
0.004894
""" ABP analyzer and graphics tests "
"" cases = [ ('Run Pymodel Graphics to generate dot file from FSM model, no need use pma', 'pmg.py ABP'), ('Generate SVG file from dot', 'dotsvg ABP'), # Now display ABP.dot in browser ('Run PyModel Analyzer to generate FSM from original FSM, should be the same', 'pma.py ABP'), (...
'dotsvg ABPFSM'), # Now display ABPFSM.svg in browser, should look the same as ABP.svg ]
ksigorodetskaya/Python_Ifmo
Part1/url-shorter/url_shorter/converter.py
Python
apache-2.0
675
0.017483
from string import digits, ascii_letters valid_values = list(digits + ascii_letters) # приводим строку к списку radix = len(valid_values) #основание def convert(number): result =[] #будем сюда складывать остатки от деления while number: result.insert
(0,valid_values[number % radix]) number //= radix return ''.join(result) def inverse(number): result = 0 for p, i in enumerate(reversed(number)): n = valid_values.index(i)
# получаем индекс нужного нам элемента списка result += n * radix ** p return result
cynapse/cynin
src/ubify.viewlets/ubify/viewlets/browser/sitetitle.py
Python
gpl-3.0
2,433
0.011919
############################################################################### #cyn.in is an open source Collaborative Knowledge Management Appliance that #enables teams to seamlessly work together on files, documents and content in #a secure central environment. # #cyn.in v2 an open source appliance is distribut...
f the detailed Additional Terms License with this program. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General #Public License for more details. # #You should h...
c License along with #this program. If not, see <http://www.gnu.org/licenses/>. # #You can contact Cynapse at support@cynapse.com with any problems with cyn.in. #For any queries regarding the licensing, please send your mails to # legal@cynapse.com # #You can also contact Cynapse at: #802, Building No. 1, #Dh...
niavlys/kivy
kivy/core/image/img_pil.py
Python
mit
3,319
0.000904
''' PIL: PIL image loader ''' __all__ = ('ImageLoaderPIL', ) try: from PIL import Image as PILImage except: import Image as PILImage from kivy.logger import Logger from kivy.core.image import ImageLoaderBase, ImageData, ImageLoader class ImageLoaderPIL(ImageLoaderBase): '''Image loader based on the PIL...
tively supported by the PIL library. As a general rule, try to use gifs that have no transparency. Gif's with transpar
ency will work but be prepared for some artifacts until transparency support is improved. ''' @staticmethod def can_save(): return True @staticmethod def extensions(): '''Return accepted extensions for this loader''' # See http://www.pythonware.com/library/pil/hand...
aaxelb/osf.io
api/preprint_providers/serializers.py
Python
apache-2.0
5,102
0.001176
from guardian.shortcuts import get_perms from rest_framework import serializers as ser from rest_framework.exceptions import ValidationError from reviews.workflow import Workflows from api.actions.serializers import ReviewableCountsRelationshipField from api.base.utils import absolute_reverse, get_user_auth from api....
dationError('All reviews fields must be set at once: `{}`'.format('`, `'.join(required_fields))) return data def update(self, instance, validated_data): instance.reviews_workflow = validated_data['reviews_workflow'] instance.reviews_comments_private = validated_data['reviews_comments_privat...
omments_anonymous'] instance.save() return instance
hackcyprus/junior
game/migrations/0001_initial.py
Python
mit
4,851
0.007627
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Problem' db.create_table(u'game_problem', ( (u'id', self.gf('django.db.models.fi...
', 'blank': 'True'}) }, u'teams.team': { 'Meta': {'object_name': 'Team'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name'
: ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'token': ('django.db.models.fields.CharField', [], {'default': "'6e61d7a5cfc2462d8f1637f9464dd1b5'", 'max_length': '32'}) } } complete_apps = ['game']
fatho/kos-c
docs/source/conf.py
Python
bsd-3-clause
4,828
0.000621
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # kOS-C documentation build configuration file, created by # sphinx-quickstart on Tue Apr 4 18:06:04 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # auto...
e cases. language = None # List of patterns, relative to source director
y, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they p...
roadmapper/ansible
test/units/modules/network/cloudengine/test_ce_is_is_instance.py
Python
gpl-3.0
2,883
0.001041
# (c) 2019 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is dis...
ngineModule, load_fixture from units.modules.utils import set_module_args class TestCloudEngineLacpModule(TestCloudEngineModule): module = ce_is_is_instance def setUp(self): super(TestCloudEngineLacpModule, self).setUp() self.mock_get_config = patch('ansible.modules.n
etwork.cloudengine.ce_is_is_instance.get_nc_config') self.get_nc_config = self.mock_get_config.start() self.mock_set_config = patch('ansible.modules.network.cloudengine.ce_is_is_instance.set_nc_config') self.set_nc_config = self.mock_set_config.start() self.set_nc_config.return_value = ...
BamX/dota2-matches-statistic
run.py
Python
mit
191
0.031414
#!env/bin/python from app import
app import sys port = 5000 debug = True if len(sys.argv) == 3: debug = sys.argv[1] == 'debug' port = int(sys.argv[2]) app.run(debug = debug, po
rt = port)
ccubed/Dyslexml
dyslexml/__init__.py
Python
mit
157
0
from .todict import * from .toxml import * class Dyslexml: def __init__(self):
self.toDict = to
dict.parse self.toXml = toxml.translate
dims/neutron
neutron/tests/unit/api/rpc/agentnotifiers/test_bgp_dr_rpc_agent_api.py
Python
apache-2.0
3,575
0
# Copyright 2016 Huawei Technologies India Pvt. Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl
e law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from neutron.api
.rpc.agentnotifiers import bgp_dr_rpc_agent_api from neutron import context from neutron.tests import base class TestBgpDrAgentNotifyApi(base.BaseTestCase): def setUp(self): super(TestBgpDrAgentNotifyApi, self).setUp() self.notifier = ( bgp_dr_rpc_agent_api.BgpDrAgentNotifyApi()) ...
mugurrus/superdesk-core
superdesk/text_utils.py
Python
agpl-3.0
5,251
0.001905
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2017 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import re f...
rd</hl2><p>another</p> (like in NITF) being counted as one word. :return int: count of words inside the text """ if no_html: return get_text_word_count(get_text(markup, content='xml', space_on_elements=True)) els
e: return get_text_word_count(get_text(markup, content='html', lf_on_block=True)) def update_word_count(update, original=None): """Update word count if there was change in content. :param update: created/updated document :param original: original document if updated """ if update.get('bod...
systemcrash/service.subtitles.subs_com_ru
resources/lib/scrutest.py
Python
gpl-2.0
2,013
0.000994
# -*- coding: utf-8 -*- from shutil import rmtree from tempfile import mkdtemp from omdbapi import OMDbAPI from scrusubtitles import ScruSubtitles from scrusubtitles import ScruSubtitlesListener from scrusubtitles import ScruSubtitlesLogger class TestService(ScruSubtitlesListener, ScruSubtitlesLogger): def __in...
e(self._scrusubtitles.workdir) def lookup(self, title, year): return self._omdbapi.search(title, year) def download(self, url, filename): self._num_subtitles_downloaded = 0 self._scrusubtitles.download(url, filename) self.info(u'{0} subtitles downloaded'.format(self._
num_subtitles_downloaded)) def search(self, imdb_id, languages): self._num_subtitles_found = 0 self._scrusubtitles.search(imdb_id, languages) self.info(u'{0} subtitles found'.format(self._num_subtitles_found)) def on_subtitle_found(self, subtitle): self._num_subtitles_found += ...
openhatch/new-mini-tasks
vendor/packages/Django/tests/regressiontests/middleware/models.py
Python
apache-2.0
287
0
from djang
o.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Band(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name',) def __str__(self): return self.na
me
JonathanPierce/Algae
preprocessors/tokenizer/main.py
Python
mit
1,473
0.007468
# -*- coding: utf-8 -*- import sys import tokenizer import os import re import helpers.io as io # just tokenizes the file def simple(filepath): tok = tokenizer.Tokenizer(filepath) results = tok.full_tokenize() return tokenizer.compress_tokens(results) # smartly tokenizes a function for modified token edi...
nterested in. # If compres sis true, each token will be reduced to a single character. Good for edit distance! def mted
(tokenPath, sources, compress): tok = tokenizer.Tokenizer(tokenPath) functions = tok.split_functions(False) # sort them appropriately def comp(a,b): lena = len(a[1]) lenb = len(b[1]) if lena == lenb: # if lengths are tied, sort alphabetically based on function na...
lightopa/Aiopa-Battles
updater.py
Python
mit
9,215
0.007271
import urllib.request import pickle import sys import ast try: import variables as v except: class var(): def __init__(self): self.screen = None v = var() import pygame as py class textLabel(py.sprite.Sprite): def __init__(self, text, pos, colour, font, size, variable ...
ed: self.rect.topleft =
self.pos if self.centred: self.rect.center = self.pos if not self.size[0] == 0: self.rect.width = self.size[0] if not self.size[1] == 0: self.rect.height = self.size[1] def pressed(self): mouse = py.mouse.get_pos() if ...
gaeun/open-event-orga-server
app/views/users/export.py
Python
gpl-3.0
2,211
0.003166
from flask import Blueprint from flask import flash from flask import make_response, render_template from flask_login import current_user from markupsafe import Markup from app.helpers.data_getter import DataGetter from app.helpers.auth import AuthManager from app.helpers.exporters.ical import ICalExporter from app.he...
response.headers["Content-Disposition"] = "attachment; filename=pentabarf.xml" return response @event_export.route('/calendar.ical') @can_access def ical_export_view(event_id): response = make_response(ICalExporter.export(event_id)) response.headers["Content-Type"] = "text/calendar" response
.headers["Content-Disposition"] = "attachment; filename=calendar.ics" return response @event_export.route('/calendar.xcs') @can_access def xcal_export_view(event_id): response = make_response(XCalExporter.export(event_id)) response.headers["Content-Type"] = "text/calendar" response.headers["Content-Di...
rutherford/tikitiki
tikitiki/__init__.py
Python
bsd-3-clause
255
0.003922
from .working_gif import working_enco
ded from .splash import SplashScreen, Spinner, CheckProcessor from .multilistbox import MultiListbox from .utils
import set_widget_state, set_binding, set_button_action, set_tab_order from .tooltip import ToolTip
cbeck88/fifengine
tests/extension_tests/loaders_tests.py
Python
lgpl-2.1
2,394
0.012949
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU L...
ects("id", "15201") self.assertEqual(len(query), 1) query = self.model.getMaps("id", "OfficialMap") self.assert
Equal(len(query), 1) self.map = query[0] # self.assertEqual(self.map.get("Name"), "official_map.xml") self.assertEqual(self.map.get("Version"), '1') self.assertEqual(self.map.get("Author"), "barra") query = self.map.getElevations("id", "OfficialMapElevation") self.assertEqual(len(query), 1) self.elevatio...
treverhines/ModEst
modest/pymls/init.py
Python
mit
7,780
0.002571
""" Created on Thu May 05 20:02:00 2011 @author: Tillsten """ import numpy as np from scipy.linalg import qr eps = np.finfo(float).eps def mls(B, v, umin, umax, Wv=None, Wu=None, ud=None, u=None, W=None, imax=100): """ mls - Control allocation using minimal least squares. [u,W,iter] = mls_alloc(...
urf(x, y, np.sqrt(((SN - b.T) ** 2).sum(-1)), 30, cmap=plt.cm.PuBu_r) plt.colorbar() #plt.axhline(ll[0]) #plt.axhline(ul
[0]) #plt.axvline(ll[1]) #plt.axvline(ul[1]) rect = np.vstack((ll, ul - ll)) patch = plt.Rectangle(ll, *(ul - ll), facecolor=(0.0, 0., 0., 0)) plt.gca().add_patch(patch) plt.annotate("Bounded Min", xy=x0, xycoords='data', xytext=(-5, 5), textcoords='data...
mitnk/letsencrypt
letsencrypt/renewal.py
Python
apache-2.0
15,711
0.000827
"""Functionality for autorenewal and associated juggling of configurations""" from __future__ import print_function import copy import glob import logging import os import traceback import six import zope.component import OpenSSL from letsencrypt import configuration from letsencrypt import cli from letsencrypt impo...
"] INT_CONFIG_ITEMS = ["rsa_key_size", "tls_sni_01_port", "http01_port"] def renewal_conf_files(config): """Return /path/to/*.conf in the renewal conf directory""" return glob.glob(os.path.join(config.renewal_conf
igs_dir, "*.conf")) def _reconstitute(config, full_path): """Try to instantiate a RenewableCert, updating config with relevant items. This is specifically for use in renewal and enforces several checks and policies to ensure that we can try to proceed with the renwal request. The config argument is m...
testmana2/test
Plugins/VcsPlugins/vcsMercurial/RebaseExtension/rebase.py
Python
gpl-3.0
4,473
0.00313
# -*- coding: utf-8 -*- # Copyright (c) 2011 - 2015 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing the rebase extension interface. """ from __future__ import unicode_literals import os from PyQt5.QtWidgets import QDialog from ..HgExtension import HgExtension from ..HgDialog import HgDialog ...
join(repodir, self.vcs.adminDir)): repodir = os.path.dirname(repodir) if os.path.splitdrive(repodir)[1] == os.sep: return False args = self.vcs.initComman
d("rebase") args.append("--abort") args.append("--verbose") dia = HgDialog(self.tr('Rebase Changesets (Abort)'), self.vcs) res = dia.startProcess(args, repodir) if res: dia.exec_() res = dia.hasAddOrDelete() self.vcs.checkVCSStatus() ...
aronsky/home-assistant
tests/components/tasmota/test_sensor.py
Python
apache-2.0
33,360
0.0006
"""The tests for the Tasmota sensor platform.""" import copy import datetime from datetime import timedelta import json from unittest.mock import Mock, patch import hatasmota from hatasmota.utils import ( get_topic_stat_status, get_topic_tele_sensor, get_topic_tele_will, ) import pytest from homeassistant...
SENSOR_CONFIG) mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), )
await hass.async_block_till_done() async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/sensors", json.dumps(sensor_config), ) await hass.async_block_till_done() state = hass.states.get("sensor.tasmota_energy_totaltariff_1") assert state.state == "unavailable" asse...
chriszs/redash
tests/test_authentication.py
Python
bsd-2-clause
13,446
0.002157
import os import time from six.moves import reload_module from flask import request from mock import patch from redash import models, settings from redash.authentication import (api_key_load_user_from_request, get_login_url, hmac_load_user_from_request, ...
te them properly... # def setUp(self): super(TestHMACAuthentication, self).setUp() self.api_key = '10' self.query = self.factory.create_query(api_key=self.api_key) models.db.session.flush() self.path = '/{}/api/queries/{}'.format(self.query.org.slug, self.query.id) ...
self.query.api_key, self.path, expires) def test_no_signature(self): with self.app.test_client() as c: rv = c.get(self.path) self.assertIsNone(hmac_load_user_from_request(request)) def test_wrong_signature(self): with self.app.test_client() as c: rv = c.get(...
the-zebulan/CodeWars
tests/kyu_7_tests/test_complementary_dna.py
Python
mit
364
0
import unittest from katas.kyu_7.complementary_dna import DNA_strand class DNAStrandTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(DNA_strand('AAAA'), 'TTTT') def test_equals_2(self): self.assertEqual(DNA_strand('ATTGC'), 'TAACG') def
test_equa
ls_3(self): self.assertEqual(DNA_strand('GTAT'), 'CATA')
pathway27/games-prac
python3/tictactoe.py
Python
mit
6,138
0.006028
# Tic Tac Toe # Tic Tac Toe import random def drawBoard(board): # This function prints out the board that it was passed. # "board" is a list of 10 strings representing the board (ignore index 0) print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') p...
list with the player's letter as the first item, and the computer's letter as the second. letter = '' while not (letter == 'X' or letter == 'O'): print('Do you want to be X or O?') letter = input().upper() # the first element in the tuple is the player's letter, the second is the computer's...
return ['X', 'O'] else: return ['O', 'X'] def whoGoesFirst(): # Randomly choose the player who goes first. if random.randint(0, 1) == 0: return 'computer' else: return 'player' def playAgain(): # This function returns True if the player wants to play again, otherwis...
blueyed/coveragepy
coverage/multiproc.py
Python
apache-2.0
3,478
0.00115
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt """Monkey-patching to add multiprocessing support for coverage.py""" import multiprocessing import multiprocessing.process import os from coverage import env from...
# objects into the data that gets pick
led and sent to the sub-process. When # the Stowaway is unpickled, it's __setstate__ method is called, which # re-applies the monkey-patch. # Windows only spawns, so this is needed to keep Windows working. try: from multiprocessing import spawn original_get_preparation_data = spawn.get_p...
dardevelin/rhythmbox-shuffle
plugins/context/ArtistTab.py
Python
gpl-2.0
13,087
0.015741
# -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*- # # Copyright (C) 2009 John Iacona # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your optio...
self.sp.get_playing_entry () if entry is None: print "Nothing playing" return None artist = entry.get_string (RB.RhythmDBPropType.ARTIST) if self.active and self.artist != artist: self.datasource.fetch_artist_data (artist) self.view.loading (artis...
__ (self, shell, plugin, webview, ds): GObject.GObject.__init__ (self) self.webview = webview self.ds = ds self.shell = shell self.plugin = plugin self.file = "" plugindir = plugin.plugin_info.get_data_dir() self.basepath = "file://" + urllib.pat...
kurtrr/open-numismat
OpenNumismat/Settings.py
Python
gpl-3.0
14,504
0.000622
# -*- coding: utf-8 -*- from PyQt5.QtCore import Qt, QLocale, QSettings, QMargins from PyQt5.QtWidgets import * import OpenNumismat from OpenNumismat.EditCoinDialog.FormItems import NumberEdit from OpenNumismat.Collection.CollectionFields import CollectionFieldsBase from OpenNumismat.Reports import Report from OpenNu...
QLineEdit(self) self.reference.setMinimumWidth(120) self.reference.setText(settings['reference']) icon = style.standardIcon(QStyle.SP_DialogOpenButton) self.referenceButton = QPushButton(icon
, '', self) self.referenceButton.clicked.connect(self.referenceButtonClicked) hLayout = QHBoxLayout() hLayout.addWidget(self.reference) hLayout.addWidget(self.referenceButton) hLayout.setContentsMargins(QMargins()) layout.addRow(self.tr("Reference"), hLayout) s...
Salamek/DwaPython
tests/AllTests.py
Python
gpl-3.0
973
0.00925
# Copyright (C) 2014 Adam Schubert <adam.schubert@sg1-game.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Th...
neral Public Li
cense for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. __author__="Adam Schubert <adam.schubert@sg1-game.net>" __date__ ="$12.10.2014 1:49:02$" from tests.UserTest import * from tests.ApiTest import * from t...
xlvector/yoyo-migrations
yoyo/tests/test_parse_uri.py
Python
bsd-3-clause
1,061
0.001885
from yoyo.connections import parse_uri, unparse_uri def _test_parse_uri(connection_string, expected_uri_tuple): uri_tuple = parse_uri(connection_string) assert isinstance(uri_tuple, tuple) assert (uri_tuple == expected_uri_tuple) def _test_unparse_uri(uri_tuple, expected_connection_string): connecti...
assert (connection_string == expected_connection_string) def test_uri_without_db_params(): connection_string = 'postgres://user:password@server:7777/database' uri_tuple = ('postgres', 'user', 'password', 'server', 7777, 'database', None) _test_parse_uri(connection_string, uri_tuple) _test_unparse_uri(...
_with_db_params(): connection_string = 'odbc://user:password@server:7777/database?DSN=dsn' uri_tuple = ('odbc', 'user', 'password', 'server', 7777, 'database', {'DSN': 'dsn'}) _test_parse_uri(connection_string, uri_tuple) _test_unparse_uri(uri_tuple, connection_string)
DigitalCampus/oppia-data-scripts-hews-2015
scripts/hews-quiz-progress-threshold.py
Python
gpl-3.0
5,647
0.022844
import argparse import json import datetime import os import sys from codecs import open def run(cohort_id, threshold, period, course_range): from django.contrib.auth.models import User from django.db.models import Sum, Max, Min, Avg from django.utils.html import strip_tags from oppia.mode...
pnc': courses = Course.objects.filter(coursecohort__cohort_id = cohort_id, shortname__in=['pnc-et']) elif course_range =='all': courses = Course.objects.filter(coursecohort__cohort_id = cohort_id) else: print "Invalid course range supplied" sys.exit() filename = 'hew-q...
rname(os.path.realpath(__file__)), '..', '_output', filename) out_file = open(output_file, 'w', 'utf-8') out_file.write("<html>") out_file.write("<head>") out_file.write('<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />') out_file.write("<style> td {text-align:center;} #foot...
monikagrabowska/osf.io
kinto/tests/core/resource/test_pagination.py
Python
apache-2.0
10,656
0
import random from base64 import b64encode, b64decode import mock from six.moves.urllib.parse import parse_qs, urlparse from pyramid.httpexceptions import HTTPBadRequest from kinto.core.utils import json from . import BaseTest class PaginationTest(BaseTest): def setUp(self): super(PaginationTest, self)...
by', 10)]): result = self.resource.collection_get() s
elf.assertEqual(len(result['data']), 10) def test_forced_limit_has_precedence_over_provided_limit(self): with mock.patch.dict(self.resource.request.registry.settings, [ ('paginate_by', 5)]): self.resource.request.GET = {'_limit': '10'} result = self.resource.collecti...
simsong/grr-insider
gui/views.py
Python
apache-2.0
7,359
0.009512
#!/usr/bin/env python """Main Django renderer.""" import os import pdb import time from django import http from django import shortcuts from django import template from django.views.decorators import csrf import logging from grr import gui from grr.gui import renderers from grr.gui import webauth from grr.lib impo...
tion is valid ["Layout", "RenderAjax", "Download", "Validate"].index(action) renderer = renderer_cls() result = http.HttpResponse(content_type="text/html") # Pass the request only from POST parameters. It is much more convenient to # deal with normal dicts than Django'
s Query objects so we convert here. if flags.FLAGS.debug: # Allow both POST and GET for debugging request.REQ = request.POST.dict() request.REQ.update(request.GET.dict()) else: # Only POST in production for CSRF protections. request.REQ = request.POST.dict() # Build the security token for thi...
jbowes/yselect
test/fakes/repository.py
Python
gpl-2.0
1,532
0.001305
# yselect - An RPM/Yum pa
ckage handling frontend. # Copyright (C) 2006 James Bowes <jbowes@redhat.com> # Copyright (C) 2006 Devan Goodwin <dg@fnordia.org> # # 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; eit...
istributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this...
eisen-dev/eisen_engine
core/mysql_config.py
Python
gpl-3.0
1,454
0.003439
# (c) 2015, Alice Ferrazzi <alice.ferrazzi@gmail.com> # # This file is part of Eisen # # Eisen is free softwa
re: y
ou 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. # # Eisen is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
elationfoundation/PyOrgMode
build/lib/PyOrgMode/test_clock.py
Python
gpl-3.0
593
0.003373
import PyOrgMode import time import unittest class TestClockElement
(unittest.TestCase): def test_duration_format(self): """Durations are formatted identically to org-mode""" for hour in '0', '1', '5', '10', '12', '13', '19', '23': for minute in '00', '01', '29', '40', '59': orig_str = '%s:%s' % (hour, minute) orgdate_ele...
r) if __name__ == '__main__': unittest.main()
nikste/visualizationDemo
zeppelin-web/node/npm/node_modules/node-gyp/gyp/pylib/gyp/win_tool.py
Python
apache-2.0
6,979
0.006018
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility functions for Windows builds. These functions are executed via gyp-win-tool when using the ninja generator. """ from ctypes imp...
idl # objidl.idl lines = out.splitlines() prefix = 'Processing ' processing = set(os.path.basename(x) for x in lines if x.startswith(prefix)) for line in lines: if not line.startswith(prefix) and line not in processing: print line return popen.returncode def ExecAsmWrapper(self,...
lter logo banner from invocations of asm.exe.""" env = self._GetEnv(arch) # MSVS doesn't assemble x64 asm files. if arch == 'environment.x64': return 0 popen = subprocess.Popen(args, shell=True, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = po...
south-coast-science/scs_dfe_eng
src/scs_dfe/interface/component/cat24c32.py
Python
mit
2,699
0.005187
""" Created on 5 Sep 2016 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) in /boot/config.txt # RPi... # Uncomment for i2c-0 & i2c-3 access (EEPROM programming) # dtparam=i2c_vc=on dtoverlay i2c-gpio i2c_gpio_sda=0 i2c_gpio_scl=1 """ import time from scs_core.sys.eeprom_image import EEPROMImage from s...
ries CAT24C32 32-Kb S
erial EEPROM """ SIZE = 0x1000 # 4096 bytes __BUFFER_SIZE = 32 __TWR = 0.005 # seconds # ---------------------------------------------------------------------------------------------------------------- @classmethod def __read_image(cls, addr, co...
NGSegovia/wsgi-intercept
wsgi_intercept/mechanize_intercept/wsgi_browser.py
Python
mit
1,068
0.005618
""" A mechanize browser that redirects specified HTTP connections to a WSGI object. """ from httplib import HTTP from mechanize import Browser as MechanizeBrowser from wsgi_intercept.urllib2_intercept import install_opener, uninstall_opener try: from mechanize import HTTPHandler except ImportError: # pre mecha...
install(self) MechanizeBrowser.__init__(se
lf, *args, **kwargs) def install(browser): install_opener()
xflows/textflows
mothra/wsgi.py
Python
mit
1,305
0.002299
""" WSGI config for mothra 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`` s...
ver, 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 HelloWorldApplication # application = HelloWorldApplicatio
n(application)
ljwolf/pysal
pysal/spreg/error_sp_hom.py
Python
bsd-3-clause
57,745
0.001039
''' Hom family of models based on: [Drukker2013]_ Following: [Anselin2011]_ ''' __author__ = "Luc Anselin luc.anselin@asu.edu, Daniel Arribas-Bel darribas@asu.edu" from scipy import sparse as SP import numpy as np from numpy import linalg as la import ols as OLS from pysal import lag_spatial from utils import power...
2a and 2b from Arraiz et al. Note: max_iter provides an additional stop condition. A1 : string If A1='het', then the matrix A1 is defined as in Arraiz et al. If A1='hom', then as in Anselin (2011) (default). If A1='hom_sc' (defau...
kx1 array of estimated coefficients u : array nx1 array of residuals e_filtered : array nx1 array of spatially filtered residuals predy : array nx1 array of predicted y values n : integer Number ...
sangwook236/general-development-and-testing
sw_dev/python/rnd/test/machine_learning/keras/keras_visualization.py
Python
gpl-2.0
3,637
0.02887
#!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import print_function import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # REF [site] >> https://machinelearningmastery.com/how-to-visualize-filters-and-feature-maps-in-convolutional-neural-networks/ def visualize_filters_in_CNN():...
# Prepare the image (e.g. scale pixel values for the vgg). img = tf.keras.applications.vgg16.preprocess_input(img) #-------------------- # Load the model. model = tf.keras.applications.vgg16.VGG16() # Redefine model to output right after the first hidden layer. model = tf.keras.models.Model(inputs=model.input...
e_maps = model.predict(img) # Plot all 64 maps in an 8x8 squares. square = 8 ix = 1 for _ in range(square): for _ in range(square): # Specify subplot and turn of axis. ax = plt.subplot(square, square, ix) ax.set_xticks([]) ax.set_yticks([]) # Plot filter channel in grayscale. plt.imshow(feature...
stkyle/libtaxii
docs/conf.py
Python
bsd-3-clause
945
0
import os import libtaxii project = u'libtaxi
i' copyright = u'2014, The MITRE Corporation' version = libtaxii.__version__ release = version extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.ifconfig', 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon', ] intersphinx_mapping = { 'python': ('...
ates'] source_suffix = '.rst' master_doc = 'index' rst_prolog = """ **Version**: {0} """.format(release) exclude_patterns = [ '_build', ] on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.g...
jcatw/scnn
scnn/graph_proportion_baseline_experiment.py
Python
mit
6,889
0.019016
__author__ = 'jatwood' import sys import numpy as np from sklearn.metrics import f1_score, accuracy_score from sklearn.linear_model import LogisticRegression import data import util import kernel import structured from baseline_graph_experiment import GraphDecompositionModel def graph_proportion_baseline_experiment...
'ds_name':'nci1',
'window_size':2, 'ngram_type':0, 'sampling_type':1, 'graphlet_size':0, 'sample_size':2 }, 'nci109': {'num_dimensions':5, 'kernel_type':1, 'feature_type':3, 'ds_name':'nci...
bcso/CS_234_Assignments
Assignment 2/Stock.py
Python
apache-2.0
3,006
0.024285
"""CS 234 Assignment 2 Question 1a - Testing assumptions: Stock.py """ class Stock: """ A data type representing a single stock Fields: name - str: the company name as a string symbol - str: a string uniquely identifying the stock price - non-negative float: last/current price ...
raise ValueError, "Price must be lower than high!" elif (low <= high) == False: raise ValueError, "Low must be lower than high!" elif (type(price) != type(0.0)) or (type(low) != type(0.0)) or (type(high) != type(0.0)): raise ValueError, "Price, low and high inputs must be float input...
= high self.volume = volume def __repr__(self): """ Postcondition: return a string representation of Stock """ return "Stock(%s, %s, %.2f, %.2f, %.2f, %d)" % \ (self.name, self.symbol, self.price, \ self.low, self.high, self.volume) def __eq__(se...
6809/MC6809
MC6809/core/memory_info.py
Python
gpl-3.0
1,835
0
#!/usr/bin/env python """ DragonPy - base memory info ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :created: 2013 by Jens Diemer - www.jensdiemer.de :copyleft: 2013 by the MC6809 team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ import sys class BaseMemoryInfo...
if not mem_info: self.out_func(f"{info} ${addr:x}: UNKNOWN") else: self.out_func(f"{info} ${addr:x}:") for start, end, txt in mem_info: if start == end: self.out_func(f" * ${
start:x} - {txt}") else: self.out_func(f" * ${start:x}-${end:x} - {txt}")
charleswhchan/huey
huey/api.py
Python
mit
16,245
0.000616
import datetime import json import pickle import re import time import traceback import uuid from functools import wraps from huey.backends.dummy import DummySchedule from huey.exceptions import DataStoreGetException from huey.exceptions import DataStorePutException from huey.exceptions import DataStoreTimeout from hu...
def _remove(self, msg): return self.queue.remove(msg) @_wrapped_operation(DataStoreGetException) def _get(self, key, peek=False): if peek: return self.result_store.peek(key) else: return self.result_store.get(key) @_wrapped_operation(DataStorePutException...
(self, key, value): return self.result_store.put(key, value) @_wrapped_operation(ScheduleAddException) def _add_schedule(self, data, ts): if self.schedule is None: raise AttributeError('Schedule not specified.') self.schedule.add(data, ts) @_wrapped_operation(ScheduleRe...
DOV-Vlaanderen/pydov
tests/test_error_path.py
Python
mit
12,376
0
import datetime import gzip import os import sys import tempfile import time from importlib import reload from subprocess import Popen import numpy as np import pytest from owslib.fes import PropertyIsEqualTo import pydov from pydov.search.boring import BoringSearch from pydov.search.grondwaterfilter import Grondwate...
from pydov.util.hooks import Hooks from tests.abstract import ServiceCheck from tests.test_util_hooks import HookCounter @pytest.fixture(scope="module", autouse=True) def dov_proxy_no_xdov(): """Fixture to start the DOV proxy and set PYDOV_BASE_URL to route traffic through it. The DOV proxy behaves as th...
rver would be unavailable. """ process = Popen([sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'stub', 'dov_proxy.py'), '--dov-base-url', build_dov_url('/'), '--no-xdov']) time.sleep(2...
Pysellus/streaming-api-test
api-reader/APIReaderSmartvel.py
Python
mit
381
0.005249
#!/usr/bin/env python3 from AbstractAPIReader imp
ort AbstractAPIReader from Smartvel import Smartvel from smartvel_auth import TOKEN class APIReaderSmartvel(AbstractAPIR
eader): def __init__(self, token=TOKEN, endpoint='events'): self._token = token self._endpoint = endpoint def get_iterable(self): return Smartvel(self._token, self._endpoint)
jonhadfield/fval
fval/plan.py
Python
mit
3,930
0.002036
# -*- coding: utf-8 -*- from __future__ import unicode_literals from os.path import splitext import yaml def build_plan(discovery_result, config=None): """ Extract content and determine which checks need to be run Checks are assigned in the following order: 1. <filename>.fval 2. <dir>.fval 3. d...
): if mapping.get('extension') == unit_ext[1:]: matching_templates = mapping.get('templates') # IF MATCHING TEMPLATES WERE FOUND, THEN EXTRACT THE CHECKS if matchi
ng_templates: extracted_checks = dict() for matching_template in matching_templates: if config.get('templates') and matching_template in config.get('templates'): matched_template = config.get('templates').get(matching_template) ...
agry/NGECore2
scripts/mobiles/yavin4/hooded_crystal_snake.py
Python
lgpl-3.0
1,650
0.026667
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate...
mobileTemplate.setScale(1) mobileTemplate.setMeatType("Carnivore Meat") mobileTemplate.setMeatAmount(5) mobileTempl
ate.setHideType("Scaley Hide") mobileTemplate.setHideAmount(2) mobileTemplate.setSocialGroup("crystal snake") mobileTemplate.setAssistRange(12) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/sh...
wxgeo/geophar
wxgeometrie/sympy/printing/tests/test_rcode.py
Python
gpl-2.0
14,177
0.003597
from sympy.core import (S, pi, oo, Symbol, symbols, Rational, Integer, GoldenRatio, EulerGamma, Catalan, Lambda, Dummy, Eq) from sympy.functions import (Piecewise, sin, cos, Abs, exp, ceiling, sqrt, gamma, sign, Max, Min, factorial, beta) from sympy.sets import Range...
ssert rcode((x & y) | z) == "z | x & y" assert rcode((x | y) & z) =
= "z & (x | y)" def test_rcode_Relational(): from sympy import Eq, Ne, Le, Lt, Gt, Ge assert rcode(Eq(x, y)) == "x == y" assert rcode(Ne(x, y)) == "x != y" assert rcode(Le(x, y)) == "x <= y" assert rcode(Lt(x, y)) == "x < y" assert rcode(Gt(x, y)) == "x > y" assert rcode(Ge(x, y)) == "x >= ...
usnistgov/corr
corr-cloud/cloud/views/admin_generation.py
Python
mit
3,973
0.004782
from corrdb.common.models import UserModel from corrdb.common.models import ProfileModel from corrdb.common import get_or_create import hashlib import datetime import simplejson as json import os import re def password_check(password): """ Verify the strength of 'password' Returns a dict indicating the wro...
{} # Loading admin user account information. # The instance admin shoul
d make sure to securely backup this file. if os.path.isfile("/home/corradmin/credentials/tmp_admin.json"): with open("/home/corradmin/credentials/tmp_admin.json", "r") as admin_stuff: content = json.loads(admin_stuff.read()) try: if not check_admin(content['admin-email']): print("Cre...
phillxnet/rockstor-core
src/rockstor/cli/iscsi_console.py
Python
gpl-3.0
1,794
0
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 la...
ense for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from base_console import BaseConsole from share_iscsi_console import ShareIscsiConsole from rest_util import
api_call class IscsiConsole(BaseConsole): def __init__(self, prompt): BaseConsole.__init__(self) self.prompt = prompt + " Iscsi>" self.url = BaseConsole.url + "sm/services/iscsi/" def do_status(self, args): iscsi_info = api_call(self.url) print(iscsi_info) def pu...
google/llvm-propeller
lldb/test/API/lang/cpp/alignas_base_class/TestAlignAsBaseClass.py
Python
apache-2.0
473
0.004228
import lldb from ll
dbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @no_debug_info_test def test(self): self.build() self.dbg.CreateTarget(self.getBuildArtifact("a.out")) # T...
dkelsey/payment-remittance-processor
scripts/verifyHeader.py
Python
apache-2.0
2,156
0.014842
#!/usr/bin/env python ''' headderTemplate: an immutale tuple listing, in order, the expected headders ''' headderTemplate = ( "Payee Name: ", "Payee ID: ", "Payee Site: ", "Payment Number: ", "Payment Date: ", ) ''' headderConverter
s: a dictionary key'd on the Headder title. the value is a lambda to f
ormat data values ''' headderConverters = { "Payee Name: " : (lambda x: x), "Payee ID: " : (lambda x: x), "Payee Site: " : (lambda x: x), "Payment Number: " : (lambda x: x), "Payment Date: " : (lambda x: x), } ''' Perform some preliminary validataion of the input file ''' csvfile = 'BC...
albertz/music-player
mac/pyobjc-framework-Cocoa/PyObjCTest/test_nsxmlnodeoptions.py
Python
bsd-2-clause
2,358
0.001272
from Foundation import * from PyObjCTools.TestSupport import * class TestNSXMLNodeOptions (TestCase): def testConstants(self): self.assertEqual(NSXMLNodeOptionsNone, 0) self.assertEqual(NSXMLNodeIsCDATA, 1 << 0) self.assertEqual(NSXMLNodeExpandEmptyElement, 1 << 1) self.assertEqual(...
ertEqual(NSXMLNodePreserveCDATA, 1 << 24) self.assertEqual(NSXMLNodePreserveWhitespace, 1 << 25) self.assertEqual(NSXMLNodePreserveDTD, 1 << 26) self.assertEqual(NSXMLNodeP
reserveCharacterReferences, 1 << 27) self.assertEqual(NSXMLNodePreserveEmptyElements, ( NSXMLNodeExpandEmptyElement | NSXMLNodeCompactEmptyElement)) self.assertEqual(NSXMLNodePreserveQuotes, (NSXMLNodeUseSingleQuotes | NSXMLNodeUseDoubleQuotes)) self.assertEqual(NSXMLNodePreserveAll ...
GovReady/readthedocs.org
readthedocs/rtd_tests/mocks/mock_api.py
Python
mit
2,893
0
from contextlib import contextmanager import json import mock # Mock tastypi API. class ProjectData(object): def get(self): return dict() def mock_version(repo): class MockVersion(object): def __init__(self, x=None): pass def put(self, x=None): return x ...
"built": false, "id": "12095", "identifier": "remotes/origin/zip_importing", "resource_uri": "/api/v1/version/12095/", "slug": "zip_importing",
"uploaded": false, "verbose_name": "zip_importing" }""") project = json.loads(""" { "absolute_url": "/projects/docs/", "analytics_code": "", "copyright": "", "...
Osmose/snippets-service-prototype
snippets/base/urls.py
Python
bsd-3-clause
836
0.001196
from django.conf.urls.defaults import patterns, url from snippets.base import views urlpatterns = patterns('', url(r'^$', views.index, name='base.index'), url(r'^(?P<startpage_version>[^/]+)/(?P<name>[^/]+)/(?P<version>[^/]+)/' '(?P<appbuildid>[^/]+)/(?P<build_target>[^/]+)/(?P<locale>[^/]+)/' ...
l>[^/]+)/(?P<
os_version>[^/]+)/(?P<distribution>[^/]+)/' '(?P<distribution_version>[^/]+)/$', views.fetch_snippets, name='view_snippets'), url(r'^admin/base/snippet/preview/', views.preview_empty, name='base.admin.preview_empty'), url(r'^admin/base/snippet/(\d+)/preview/', views.preview_snippet, ...
litex-hub/lxbe-tool
lxbe_tool/providers/tool/fpga/xilinx/vivado.py
Python
apache-2.0
844
0.004739
def check_vivado(args): vivado_path = get_command("vivado") if vivado_path == None: # Look for the default Vivado install directory if os.name == 'nt': base_dir = r"C:\Xilinx\Vivado" else: base_dir = "/opt/Xilinx/Vivado" if os.path.exists(base_dir): ...
n your PATH", "download it from https://www.xilinx.com/support/download.html") return (True
, "found at {}".format(vivado_path))
ric2b/Vivaldi-browser
chromium/build/android/pylib/output/local_output_manager_test.py
Python
bsd-3-clause
930
0.004301
#! /usr/bin/env vpython3 # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=protected-access import tempfile import shutil import unittest from pylib.base import output_manager from
pylib.base import output_manager_test_case from pylib.output import local_output_manager class LocalOutputManagerTest(output_manager_test_case.OutputManagerTestCase): def setUp(self): self._output_dir = tempfile.mkdtemp() self._output_manager = local_output_manager.LocalOutputManager( self._output...
rchivedFile( 'test_file', 'test_subdir', output_manager.Datatype.TEXT)) def tearDown(self): shutil.rmtree(self._output_dir) if __name__ == '__main__': unittest.main()
dennisobrien/bokeh
bokeh/models/layouts.py
Python
bsd-3-clause
6,846
0.003944
''' Various kinds of layout components. ''' from __future__ import absolute_import i
mport logging logger = logging.getLogger(__name__) from ..core.enums import SizingMode from ..core.has_props import abstract from ..core.properties import Bool, Enum, Int, Instance, List, Seq, String from ..core.validation import warning from ..core.validation.warnings import
BOTH_CHILD_AND_ROOT, EMPTY_LAYOUT from ..model import Model @abstract class LayoutDOM(Model): ''' An abstract base class for layout components. ''' width = Int(help=""" An optional width for the component (in pixels). """) height = Int(help=""" An optional height for the component (in p...
tdyas/pants
src/python/pants/backend/jvm/tasks/coverage/manager.py
Python
apache-2.0
6,621
0.002568
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import shutil from pants.backend.jvm.subsystems.scoverage_platform import ScoveragePlatform from pants.backend.jvm.tasks.coverage.cobertura import Cobertura from ...
ue, help="JVM flags to be added when running the coverage processor. For example: " "{flag}=-Xmx4g {flag}=-Xms2g".format(flag="--coverage-jvm-options"), ) register( "--coverage-force", advanced=True, type=bool, help="Attempt to run ...
" "(defaults to False, as otherwise the coverage results would be unreliable).", ) # register options for coverage engines # TODO(jtrobec): get rid of these calls when engines are dependent subsystems Cobertura.register_junit_options(register, register_jvm_tool) class I...
390910131/Misago
misago/users/avatars/dynamic.py
Python
gpl-2.0
2,147
0.000466
from importlib import import_module import math import os from PIL import Image, ImageDraw, ImageColor, ImageFont, ImageFilter from misago.conf import settings from misago.users.avatars import store def set_avatar(user): name_bits = settings.MISAGO_DYNAMIC_AVATAR_DRAWER.split('.') drawer_module = '.'.join...
path.dirname(__file__), 'font.ttf') def draw_avatar_flavour(user, image): string = user.username[0] image_size = image.size[0] size = int(image_size * 0.7) font = ImageFont.truetype(FONT_FILE, size=size) text_size = font.getsize(string) text_pos = ((image_size - text_
size[0]) / 2, (image_size - text_size[1]) / 2) writer = ImageDraw.Draw(image) writer.text(text_pos, string, font=font) return image """ Some utils for drawring avatar programmatically """ CHARS = 'qwertyuiopasdfghjklzxcvbnm1234567890' def string_to_int(string): value = 0 for p,...
skyoo/jumpserver
apps/common/thread_pools.py
Python
gpl-2.0
538
0
from concurrent.futures import ThreadPoolExecutor class SingletonThreadPoolExecutor(ThreadPoolExecutor): """ 该类不要直接实例化 """ def __new__(cls, max_workers=None, t
hread_name_prefix=None): if cls is SingletonThreadPoolExecutor: raise NotImplementedError i
f getattr(cls, '_object', None) is None: cls._object = ThreadPoolExecutor( max_workers=max_workers, thread_name_prefix=thread_name_prefix ) return cls._object
lucperkins/heron
heron/shell/src/python/handlers/pmaphandler.py
Python
apache-2.0
1,144
0.004371
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2016 Twitter. 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...
the License for the specific language governing permissions and # limitations under the License. ''' pmaphandler.py ''' import json import tornado.web from heron.shell.src.python import utils class PmapHandler(tornado.web.RequestHandler): """ Responsible for reporting memory map of a process given its pid. """...
ornado.web.asynchronous def get(self, pid): ''' get method ''' body = utils.str_cmd(['pmap', '-pXX', pid], None, None) self.content_type = 'application/json' self.write(json.dumps(body)) self.finish()
JPETTomography/j-pet-gate-tools
examples/python_scripts/plot_sf_and_necr.py
Python
apache-2.0
7,141
0.028567
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib.pyplot as plt2 from numpy import * from scipy import interpolate from matplotlib import rcParams, rcParamsDefault import argparse from nema_common import * outputformat = "" def plot_rates(geometry,float_activity,N_true,...
_ctr = tmp[:,4] T = tmp[:,5] S = tmp[:,6] N_true = tmp[:,7] N_dsca = tmp[:,8] N_psca = tmp[:,9] N_acci = tmp[:,10] time
= tmp[:,11] plot_rates(geometry,float_activity,N_true,N_dsca,N_psca,N_acci,time) new_label = "" if "1lay" in geometry: linestyle='o-' new_label += "1 layer" else: linestyle = 'o--' new_label += "2 layers" if "L020" in geometry: datacolor ...
thetomcraig/redwood
web/node_modules/hiredis/build/c4che/build.config.py
Python
isc
434
0.002304
vers
ion = 0x105016 tools = [{'tool': 'ar', 'tooldir': None, 'funs': None}, {'tool': 'cc', 'tooldir': None, 'funs': None}, {'tool': 'gcc', 'tooldir': None, 'funs': None}, {'tool': 'compiler_cc', 'tooldir': None, 'funs': None}, {'tool': 'cxx', 'tooldir': None, 'funs': None}, {'tool': 'gxx', 'tooldir': None, 'funs': None}, {'...
don', 'tooldir': None, 'funs': None}]
mushkevych/scheduler
synergy/mx/freerun_action_handler.py
Python
bsd-3-clause
4,312
0.001623
__author__ = 'Bohdan Mushkevych' import json from synergy.db.model.freerun_process_entry import FreerunProcessEntry from synergy.db.dao.freerun_process_dao import FreerunProcessDao from synergy.mx.base_request_handler import valid_action_request from synergy.mx.abstract_action_handler import AbstractActionHandler fro...
onHandler(AbstractActionHandler): def __init__(self, request, **values): super(FreerunActionHandler, self).__init__(request, **values) self.process_name = self.request_arguments.get('process_name') self.entry_name = self.request_arguments.get('entry_name') self.freerun_process_dao = ...
self.is_request_valid = True if self.process_name and self.entry_name else False if self.is_request_valid: self.process_name = self.process_name.strip() self.entry_name = self.entry_name.strip() self.is_requested_state_on = self.request_arguments.get('is_on') == 'on' ...
txtbits/daw-python
primeros ejercicios/Ejercicios entradasalida/ejercicio6.py
Python
mit
445
0.008989
#Calculen el área de un rectángulo (alineado con los ejes x e y) dad
as sus coordenadas x1,x2,y1,y2. from math import pi print 'Ejercicio 6' print '-'*60 x1 = float(raw_input('Introduce x1: ')) x2 = float(raw_input('Introduce x2: ')) y1 = float(raw_input('Introduce y1: ')) y2 = float(raw_input('Introduce y2: ')) base= x2-x1 altura= y2-y1 print 'El area
del rectangulo es: ', base * altura raw_input('Pulse la tecla enter para finalizar')
Wittlich/DAT210x-Python
Module6/assignment5.py
Python
mit
2,871
0.00418
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn import tree from subprocess import call # https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.names # # TODO: Load up the mushroom dataset into dataframe 'X' # Verify you did it
properly. # Indices shouldn't be doubled. # Header information is on the dataset's website at the UCI ML Repo # Check NA Encoding X = pd.read_csv('Datasets/agaricus-lepiota.data', names=['label', 'cap-shape', 'cap-surface', 'cap-color', 'bruises', 'odor', 'gill-a...
', 'gill-spacing', 'gill-size', 'gill-color', 'stalk-shape', 'stalk-root', 'stalk-surface-above-ring', ...
yephper/django
tests/m2m_through_regress/tests.py
Python
bsd-3-clause
10,746
0.00214
from __future__ import unicode_literals from django.contrib.auth.models import User from django.core import management from django.test import TestCase from django.utils.six import StringIO from .models import ( Car, CarDriver, Driver, Group, Membership, Person, UserMembership, ) class M2MThroughTes...
lf.assertQuerysetEqual( self.roll.members.all(), [ "<Person: Bob>", ] ) def test_cannot_use_setattr_on_reverse_m2m_with_intermediary_model(self): msg = ( "Cannot set values on a ManyToManyField which specifies an " "intermedia...
self.bob.group_set.set([]) def test_cannot_use_setattr_on_forward_m2m_with_intermediary_model(self): msg = ( "Cannot set values on a ManyToManyField which specifies an " "intermediary model. Use m2m_through_regress.Membership's Manager " "instead." ) ...
one-love/api
devel.py
Python
gpl-3.0
116
0
from config import configs from onelove import create_app config = configs['development'] app = create_app
(config)
corradomonti/fbvoting
fbvoting/__main__.py
Python
mit
5,860
0.008191
# -*- coding: utf-8 -*- import logging from flask import Flask, redirect, request, jsonify, render_template, session import requests import fbvoting.pagebuilders.buildhome import fbvoting.pagebuilders.buildoverview import fbvoting.pagebuilders.buildprofile import fbvoting.pagebuilders.buildfriends import fbvoting.pag...
musicbrainz/log/update') def musicbrainz_logger():
fbvoting.apis.musicbrainz.log_update() return "OK\n" @route('/ajax/musicbrainz/check/') def musicbrainz_check_if_exist(): return jsonify({'results': fbvoting.pagebuilders.buildvote.check_with_suggestion(request.form)}) @route('/ajax/musicbrainz/search/artist') def musicbrainz_search_artist(): query = ...
lucian1900/Webified
messenger.py
Python
gpl-2.0
5,665
0.005296
# # Copyright (C) 2007, One Laptop Per Child # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Thi...
elf.tube.get_object(member, PATH).sync_with_members( self.model.get_links_ids(), dbus_interface=IFACE, reply_handler=self.reply_sync, error_handler=lambda e:self.error_sync(e, 'transfering file')) ...
True def reply_sync(self, a_ids, sender): a_ids.pop() for link in self.model.data['shared_links']: if link['hash'] not in a_ids: self.tube.get_object(sender, PATH).send_link( link['hash'], link['url'], link['title'], link[...
darkstar007/GroundStation
src/ReceiverEvent.py
Python
gpl-3.0
1,854
0.002157
# # Copyright 2013/2015 Matthew Nottingham # # This file is part of GroundStation # # GroundStation 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, or (at your option) # any later version. # ...
e Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import ephem import GnuRadio2 class ReceiverEvent(): def __init__(self, time, duration, frequency, bandwidth): self.freq = frequency self.d
uration = 60.0 * duration # Lets keep it in seconds. self.bandwidth = bandwidth self.channels = [] self.timerInterval = (time - ephem.now()) * 24.0 * 60.0 * 60.0 * 1000 self.timer = QtCore.QTimer(self) self.timer.timeout.connect(self.startReceiving) self.timer.setSingle...
duke605/RunePy
commands/vorago.py
Python
mit
3,188
0.001882
from discord.ext import commands from math import floor from datetime import datetime from util.arguments import Arguments from shlex import split class Vorago: def __init__(self, bot): self.bot = bot @commands.command(aliases=['rago'], description='Shows the current rotation o...
lit', 'Purple Bomb') }, { 'type': 'The End', 'unlock': 'Gloves of Omens', 'p10': ('Purple Bomb', 'Bleeds'), 'p11': ('Purple Bomb', 'Vitalis') } ) ms = round(datetime.utcnow().timestamp() * 1000) ...
) - 6) % (7 * len(rotations)) % 7 next = current + 1 if current + 1 < len(rotations) else 0 m = '**Curent Rotation**: %s.\n' % rotations[current]['type'] m += '**Next Rotation**: %s in `%s` day%s.' % (rotations[next]['type'], days_until, 's...
isislovecruft/switzerland
switzerland/lib/shrunk_scapy/data.py
Python
gpl-3.0
5,617
0.016023
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license import re from dadict import DADict from error import log_load
ing ############ ## Consts ## ############ ETHER_ANY = "\x00"*6 ETHER_BROADCAST = "\xff"*6 ETH_P_ALL = 3 ETH_P_IP = 0x800 ETH_P_ARP = 0x806 ETH_P_IPV6 = 0x86dd # From
net/if_arp.h ARPHDR_ETHER = 1 ARPHDR_METRICOM = 23 ARPHDR_PPP = 512 ARPHDR_LOOPBACK = 772 ARPHDR_TUN = 65534 # From net/ipv6.h on Linux (+ Additions) IPV6_ADDR_UNICAST = 0x01 IPV6_ADDR_MULTICAST = 0x02 IPV6_ADDR_CAST_MASK = 0x0F IPV6_ADDR_LOOPBACK = 0x10 IPV6_ADDR_GLOBAL = 0x00 IPV6_ADDR_LINKLOCAL ...
jEschweiler/Urease
urease_software/cluster.py
Python
gpl-3.0
5,877
0.052408
import numpy as np import scipy.spatial.distance as dist from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import matplotlib.lines as mplines import scipy.cluster.hierarchy as clust import os def kabsch(coord, ref,app): C = np.dot(np.transpose(coord), ref) V, S, W = np.linalg.svd(C...
#print(r) #jm = j - np.mean(j, axis = 0
) #jk = j[np.array([2,7,12])] #jkm = jk - np.mean(jk, axis = 0) #k = kabsch(jkm, ikm, jm) #k = k - np.mean(k, axis =0) #r = rmsd(k[np.array([3,4,8,9,13,14])], im[np.array([3,4,8,9,13,14])]) #r2 = rmsd(k[np.array([2,7,12])], im[np.array([2,7,12])]) #print(i) #print(r, r2) #rmsdlist1.append(r...
timxx/gitc
qgitc/gitutils.py
Python
apache-2.0
14,220
0
# -*- coding: utf-8 -*- from collections import defaultdict import subprocess import os import bisect import re from .common import log_fmt class GitProcess(): GIT_BIN = None def __init__(self, repoDir, args, text=None): startupinfo = None if os.name == "nt": startupinfo = sub...
th: args.append("--") args.append(path) cwd = branchDir if branchDir else Git.REPO_DIR process = GitProcess(cwd, args) @staticmethod def conflictFiles(): args = ["diff", "--name-only", "--diff-filter=U", "-n
o-color"] data = Git.checkOutput(args) if not data: return None return data.rstrip(b'\n').decode("utf-8").split('\n') @staticmethod def gitDir(): args = ["rev-parse", "--git-dir"] data = Git.checkOutput(args) if not data: return None ...
google/pigweed
pw_protobuf/py/pw_protobuf/codegen_pwpb.py
Python
apache-2.0
25,350
0.000118
# Copyright 2020 The Pigweed 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
type.""" if self is self.STREAMING: return 'StreamEncoder' if self is self.MEMORY: return 'MemoryEncoder' raise ValueError('Unknown encoder type') def codegen_class_name(self) -> str: """Returns the base class used by this encoder type.""" if self i...
return 'MemoryEncoder' raise ValueError('Unknown encoder type') # protoc captures stdout, so we need to printf debug to stderr. def debug_print(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) class ProtoMethod(abc.ABC): """Base class for a C++ method for a field in a protobuf m...
wubr2000/googleads-python-lib
examples/adwords/v201502/campaign_management/set_criterion_bid_modifier.py
Python
apache-2.0
2,408
0.007475
#!/usr/bin/python # # Copyright 2015 Google 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 applicable law or agreed to in writing, software # dis
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. """This example sets a bid modifier for the mobile platform on given campaign....
Eficent/odoomrp-wip
mrp_project_link_mto/models/stock_move.py
Python
agpl-3.0
1,072
0
# -*- coding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the L...
Y WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## from openerp import mod...