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
kwadrat/ipij_vim
rdzen_vim.py
Python
isc
6,361
0.005823
#!/usr/bin/python # -*- coding: UTF-8 -*- import time import re import unittest zncz_pocz = 'godz_pocz' zncz_kon = 'godz_kon' etkt_pocz = 'BEGIN:' etkt_kon = 'END:' znak_daty_pocz = 7 znak_daty_kon = 32 rozmiar_daty = 19 wzorcowa_data_pocz = 'BEGIN: 2012.12.29_13.01.23 END: 0000.00.00_00.00.00' sama_wzorcowa_data =...
templi_czasowych(rodzaj, vim) else: wstaw_date_z_dzis(vim) format_linii = r''' BEGIN: \s # Spacja po słowie BEGIN \d{4} # Rok \. # Kropka \d{2} # Miesiąc \. # K
ropka \d{2} # Dzień _ # Oddzielenie dnia od godziny \d{2} # Godzina \. # Kropka \d{2} # Minuta \. # Kropka \d{2} # Sekunda \s # Spacja po dacie początkowej END: \s # Spacja po słowie END \d{4} # Rok \. # Kropka \d{2} # Miesiąc \. # Kropka \d{2} # Dzień _ # Oddzielenie dnia od godziny \d{2} # G...
dotKom/onlineweb4
apps/splash/api/views.py
Python
mit
665
0
from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ReadOnlyModelVi
ewSet from apps.splash.api.serializers import SplashEventSerializer from apps.splash.filters import SplashEventFilter from apps.splash.models import SplashEvent class HundredItemsPaginator(PageNumberPagination): page_size = 100 class SplashEventViewSet(ReadOnlyModelViewSet): queryset = SplashEvent.objects....
shEventSerializer pagination_class = HundredItemsPaginator filter_class = SplashEventFilter filter_fields = ('start_time', 'end_time') ordering_fields = ('id', 'start_time', 'end_time')
xwzy/triplet-deep-hash-pytorch
triplet-deep-hash-pytorch/src/extract_feature/convert_weights/convert_weights_to_keras.py
Python
apache-2.0
1,736
0.035138
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.insert(0,'..') import tensorflow as tf import numpy as np import itertools import pickle import os import re import inception_v4 os.environ['CUDA_VISIBLE_DEVICES'] = '' def atoi(text): ...
t_prep + [[fn]] return out if __name__ == "__main__": model = inception_v4.create_model() with open('weights.p', 'rb') as fp: weights = pickle.load(fp) # Get layers to set layers = get_layers(model) layers = list(itertools.chain.from_iterable(layers)) # Set the layer weights
setWeights(layers, weights) # Save model weights in h5 format model.save_weights("../weights/inception-v4_weights_tf_dim_ordering_tf_kernels_notop.h5") print("Finished saving weights in h5 format")
ericawright/bedrock
tests/pages/contact.py
Python
mpl-2.0
2,012
0.001988
# 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 selenium.webdriver.common.by import By from pages.base import BasePage, BaseRegion class ContactPage(BasePage): ...
layed(self): return self.is_element_displayed(*self._mobile_menu_toggle_locator) class Tab(BaseRegion): @property def is_selected(self): return 'current' in self.root.g
et_attribute('class') class SpacesPage(ContactPage): URL_TEMPLATE = '/{locale}/contact/spaces/{slug}' _map_locator = (By.ID, 'map') _nav_locator = (By.CSS_SELECTOR, '#nav-spaces li h4') @property def is_nav_displayed(self): return self.is_element_displayed(*self._nav_locator) @prop...
airbnb/kafka
tests/kafkatest/tests/produce_consume_validate.py
Python
apache-2.0
8,828
0.003285
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
sg = self.annotate_missing_msgs(missing, acked, consumed, msg) success = False #Did we miss anything due to data loss? to_validate = list(missing)[0:1000 if len(missing) > 1000 else len(missing)] data_lost = self.kafk
a.search_data_files(self.topic, to_validate) msg = self.annotate_data_lost(data_lost, msg, len(to_validate)) if self.enable_idempotence: self.logger.info("Ran a test with idempotence enabled. We expect no duplicates") else: self.logger.info("Ran a te
SarahBA/b2share
b2share/modules/communities/views.py
Python
gpl-2.0
10,646
0.00047
# -*- coding: utf-8 -*- # # This file is part of EUDAT B2Share. # Copyright (C) 2016 University of Tuebingen, CERN. # Copyright (C) 2015 University of Tuebingen. # # B2Share 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...
ols import wraps from flask import Blueprint, abort, current_app, make_response, request, \ jsonify, url_for from invenio_db import db from invenio_rest import ContentNeg
otiatedMethodView from invenio_rest.decorators import require_content_types from jsonpatch import InvalidJsonPatch, JsonPatchConflict, JsonPatchException from werkzeug.exceptions import HTTPException from werkzeug.local import LocalProxy from .api import Community from .errors import CommunityDeletedError, CommunityDo...
pudo/morphium
morphium/archive.py
Python
mit
2,477
0
import os import logging import boto3 import mimetypes from datetime import datetime from morphium.util import env, TAG_LATEST log = logging.getLogger(__name__) config = {} class Archive(object): """A scraper archive on S3. This is called when a scraper has generated a file which needs to be backed up to a ...
copy_source = {'Key': key_name, 'Bucket': self.bucket} self.client.copy(copy_source, self.bucket, copy_nam
e, ExtraArgs=args) return 'http://%s/%s' % (self.bucket, key_name)
abilian/abilian-sbe
src/abilian/sbe/apps/wiki/forms.py
Python
lgpl-2.1
1,942
0.00103
"""Forms for the Wiki module.""" from __future__ import annotations from typing import Any from wtforms import HiddenField, StringField, TextAreaField, ValidationError from wtforms.validators import data_required from abilian.i18n import _, _l from abilian.web.forms import Form from abilian.web.forms.filters import ...
if title != field.object_data and page_exists(title): raise ValidationError( _("A page with this name already exists. Please use another name.") ) def validate_last_revision_id(self, field: HiddenField): val = field.data current = field
.object_data if val is None or current is None: return if val != current: raise ValidationError(_("this page has been edited since")) # Not used yet class CommentForm(Form): message = TextAreaField(label=_l("Message"), validators=[data_required()]) page_id = HiddenFie...
elyezer/robottelo
tests/foreman/api/test_usergroup.py
Python
gpl-3.0
10,650
0
"""Unit tests for the ``usergroups`` paths. Each ``APITestCase`` subclass tests a single URL. A full list of URLs to be tested can be found here: http://theforeman.org/api/1.11/apidoc/v2/usergroups.html :Requirement: Usergroup :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: API :TestType: Functi...
.login, user_group.user[0].read().login) @tier2 def test_positive_update_with_existing_user(self): """Update user that assigned to user group with another one
:id: 71b78f64-867d-4bf5-9b1e-02698a17fb38 :expectedresults: User group is updated successfully. :CaseLevel: Integration """ users = [entities.User().create() for _ in range(2)] user_group = entities.UserGroup(user=[users[0]]).create() user_group.user[0] = users...
ilendl2/wagtail-cookiecutter-foundation
{{cookiecutter.project_slug}}/pages/wagtail_hooks.py
Python
mit
1,721
0
from django.urls import reverse from django.utils.html import format_html, format_html_join from django
.utils.translation import ugettext_lazy as _ from django.conf import settings from wagtail.core import hooks from wagtail.admin.menu import MenuItem from wagtail.core.whitelist import attribute_rule, check_url @hooks.register('register_settings_menu_item') def register_django_admin_menu_item(): return MenuItem(_(...
truct_whitelister_element_rules') def whitelister_element_rules(): # Whitelist custom elements to the hallo.js editor return { 'a': attribute_rule({'href': check_url, 'target': True}), 'blockquote': attribute_rule({'class': True}) } @hooks.register('insert_editor_js') def editor_js(): ...
ziiin/onjCodes
codejam/2014/B-cookie-clicker.py
Python
mit
294
0.05102
import sys import mat
h def getNextEle (X, C, F, i): res = 0
residue = 0 for j in range(1,i): t = int ( math.ceil ( (C-residue) / (x+ j*F))) residue = t * # cosider residue cookies because of integral time seconds res += X / (x + i*F); def main():
madmax983/h2o-3
h2o-py/tests/testdir_algos/glm/pyunit_DEPRECATED_link_functions_binomialGLM.py
Python
apache-2.0
1,473
0.033944
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils import pandas as pd import zipfile import statsmodels.api as sm def link_functions_binomial(): print("Read in prostate data.") h2o_data = h2o.import_file(path=pyun
it_utils.locate("smalldata/prostate/prostate_complete.csv.zip")) h2o_data.head() sm_data = pd.read_csv(zipfile.ZipFile(pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip")).open("prostate_complete.csv")).as_matrix() sm_data_response = sm_data[:,2] sm_data_features = sm_data[:,[1,3,4,5,6,7,8,9]] ...
ID","AGE","RACE","GLEASON","DCAPS","PSA","VOL","DPROS"] print("Create models with canonical link: LOGIT") h2o_model = h2o.glm(x=h2o_data[myX], y=h2o_data[myY].asfactor(), family="binomial", link="logit",alpha=[0.5], Lambda=[0]) sm_model = sm.GLM(endog=sm_data_response, exog=sm_data_features, family=sm.families.B...
pcdummy/socketrpc
socketrpc/gevent_srpc.py
Python
bsd-3-clause
10,766
0.002415
# -*- coding: utf-8 -*- # vim: set et sts=4 sw=4 encoding=utf-8: ############################################################################### # # This file is part of socketrpc. # # Copyright (C) 2011 Rene Jochum <[email protected]> # ############################################################################### from ...
nt < message_length: chunk = self.rec
v(min(message_length - bytes_count, 32768)) part_count = len(chunk) if part_count < 1: return None bytes_count += part_count sock_buf.write(chunk) return sock_buf.getvalue() def _sendsized(self, data): data = STRUCT_INT.pack(len(data)) + data self.sendall(dat...
kobotoolbox/kobocat
onadata/apps/logger/migrations/0012_add_asset_uid_to_xform.py
Python
bsd-2-clause
390
0
#
coding: utf-8 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('logger', '0011_add-index-to-instance-uuid_and_xform_uuid'), ] operations = [ migrations.AddField( model_name='xform', name='kpi_
asset_uid', field=models.CharField(max_length=32, null=True), ), ]
leschzinerlab/AWS
aws/list_all.py
Python
mit
8,823
0.030488
#!/usr/bin/env python import subprocess import os import sys onlyinstances=False if len(sys.argv) ==1: print '\nUsage: awsls_admin [region]\n' print '\nSpecify region (NOT availability zone) that will be displayed for all users\n' sys.exit() region=sys.argv[1] if sys.argv[-1] == '-i': ...
nce-id %s --region %s --query "Reservations[0].Instances[*].State" | grep Name' %(instanceID,region),shell=True, stdout=subprocess.PIPE).stdout.read().strip().split()[-1].split('"')[1] if status == 'running': PublicIP=subprocess.Popen('aws ec2 describe-instances --region %s --instance-id %s --query "Reservation...
cess.PIPE).stdout.read().strip().split()[-1].split('"')[1] status='%s\t'%(status) print '%s\t\t%s\t%s\t%s\t\t%s\t%s\t%s\t$%1.3f' %(instanceType,availZone,spotID,spotStatus,instanceID,status,PublicIP,float(spotPrice)) counter=counter+1 if onlyinstances is True: sys.exit() #Get number of insta...
alexgorin/txcaching
examples/cache_render_get_example.py
Python
mit
3,675
0.003265
# -*- coding: utf-8 -*- import time from twisted.internet import defer, reactor from twisted.web import server from twisted.web.resource import Resource from txcaching import cache, keyregistry cache.load_config(**{"disable": False, "ip": "127.0.0.1", "port": 11212}) header = """ <html> <head> <style> b...
quest): if not path: return self if path == "set": return EmailSetter() if
path == "get": return Getter() def render_GET(self, request): return main_html % "\n".join( '<li><a href="/get/%s">%s</a>' % (username, username) for username in DB.data.keys() ) cache.flushAll() reactor.listenTCP(8888, server.Site(MainResource())) reactor.run()
lifanov/cobbler
cobbler/utils.py
Python
gpl-2.0
65,236
0.001211
""" Misc heavy lifting functions for cobbler Copyright 2006-2009, Red Hat, Inc and Others Michael DeHaan <michael.dehaan AT gmail> 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...
there a formatting error in a Cheetah directive? # (3) Should dollar signs ($) be escaped that are not being escaped? # # Try fixing the problem and then investigate to see if this message goes # away or changes. # """ # From http://code.activestate.com/recipes/303342/ class Translator: allchars = string.maketran...
if keep is None: self.delete = delete else: self.delete = self.allchars.translate(self.allchars, keep.translate(self.allchars, delete)) def __call__(self, s): return s.translate(self.trans, self.delete) # placeholder for translation def _(foo): return foo MODUL...
JohnTroony/nikola
nikola/plugins/command/github_deploy.py
Python
mit
4,476
0.000895
# -*- coding: utf-8 -*- # Copyright © 2014-2015 Puneeth Chaganti and others. # 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...
POSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS # OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import pri
nt_function from datetime import datetime import io import os import subprocess import sys from textwrap import dedent from nikola.plugin_categories import Command from nikola.plugins.command.check import real_scan_files from nikola.utils import get_logger, req_missing, makedirs, unicode_str from nikola.__main__ impor...
culots/meld
setup_win32.py
Python
gpl-2.0
4,346
0.002531
#!/usr/bin/env python import glob import os import site from cx_Freeze import setup, Executable import meld.build_helpers import meld.conf site_dir = site.getsitepackages()[1] include_dll_path = os.path.join(site_dir, "gnome") missing_dll = [ 'libgtk-3-0.dll', 'libgdk-3-0.dll', 'libatk-1.0-0.dll', ...
l_path, path), path) for path in missing_dll + gtk_libs] build_exe_options = { "compressed": False, "icon": "data/icons/meld
.ico", "includes": ["gi"], "packages": ["gi", "weakref"], "include_files": include_files, } # Create our registry key, and fill with install directory and exe registry_table = [ ('MeldKLM', 2, 'SOFTWARE\Meld', '*', None, 'TARGETDIR'), ('MeldInstallDir', 2, 'SOFTWARE\Meld', 'InstallDir', '[TARGETDI...
joel-wright/DDRPi
experiments/python/drawingarea.py
Python
mit
6,432
0.007774
#!/usr/bin/env python # example drawingarea.py import pygtk pygtk.require('2.0') import gtk import operator import time import string class DrawingAreaExample: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("Drawing Area Example") window.connect("destroy", l...
(210, 10) s
elf.draw_lines(310, 10) self.draw_segments(10, 100) self.draw_rectangles(110, 100) self.draw_arcs(210, 100) # self.draw_pixmap(310, 100) self.draw_polygon(10, 200) # self.draw_rgb_image(110, 200) return True def draw_point(self, x, y): self.area.window...
odoousers2014/odoo
addons/account_analytic_analysis/sale_order.py
Python
agpl-3.0
1,018
0.000982
# -*- coding: utf-8 -*- from openerp import models, api class sale_order_line(models.Model): _inherit = "sale.order.line" @api.one def button_confirm(self): if self.product_id.recurring_invoice and self.order_id.project_id: invoice_line_ids = [((0, 0, { 'product_id': ...
ids} if not self.order_id.project_id.partner_id: analytic_values['partner_id'] = self.order_id.partner_id.id self.order_id.project_id.write(analytic_values) return super(sale_order_line, sel
f).button_confirm()
contactgsuraj/ICHack2017
RBP/test_client.py
Python
mit
390
0.017949
#A client for testing the bluetooth server running on the pi import socket serverMACAddress = 'b8:27:eb
:f1:bb:a6' port = 3 s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) s.connect((serverMACAddress,port)) s.send("Hello") while 1: #client, address == s.accept() #data = s.recv(1024) data = "
Hello" s.send(data) #print(data) s.close()
gph82/PyEMMA
pyemma/thermo/util/__init__.py
Python
lgpl-3.0
790
0.001266
# This file is part of PyEMMA. # # Copyright (c) 2016 Computational Molecular Biology Group, Fre
ie Universitaet Berlin (GER) # # PyEMMA is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the h...
ied 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 Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from .util import *
dabura667/electrum
plugins/digitalbitbox/cmdline.py
Python
mit
415
0.004819
from electrum.util import print_msg from .digitalbitbox import DigitalBitboxPlugin class Di
gitalBitboxCmdLineHandler: def stop(self): pass def show_message(self, msg): print_msg(msg) def get_passphrase(self, msg, confirm): import getpass print_msg(msg) return getpass.getpass('') class Plugin(DigitalBitboxPlugin): handle
r = DigitalBitboxCmdLineHandler()
mdwhatcott/pyspecs
setup.py
Python
mit
1,353
0
""" Because I always forget, here's how to submit to PyPI: # python setup.py register sdist upload """ from distutils.core import setup import pyspecs setup( name='pyspecs', version=pyspecs.__version__, packages=['pyspecs'], scripts=['scripts/run_pyspecs.py'], url='https://github.com/mdwhatcott...
'tests/specs.', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI App
roved :: GNU General Public License (GPL)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Environment :: Console', 'Programming Language :: Python', 'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Libraries :: Py...
nomuna/codility
Lesson_06/max_prod_three.py
Python
mit
390
0.048718
# correc
tness: 100%, performance: 0% def solution(a): l = len(a) if l < 3: return reduce(lambda x, y: x * y, a) products = [] for i in xrange(0, l): for j in xrange(i+1, l): for
k in xrange (j+1, l): products.append(a[i] * a[j] * a[k]) return max(products) if __name__ == '__main__': array = [ -3 , 1 , 2 , -2 , 5 , 6] print "result: ", solution(array)
pysmt/pysmt
pysmt/solvers/z3.py
Python
apache-2.0
40,275
0.003501
# # This file is part of pySMT. # # Copyright 2014 Andrea Micheli and Marco Gario # # 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 ...
DO: IF unsat_cores_mode is all, then we add this fresh variable. # Otherwise, we should track this only if
it is named. key = self.mgr.FreshSymbol(template="_assertion_%d") tkey = self.converter.convert(key) self.z3.assert_and_track(term, tkey) return (key, named, formula) else: self.z3.add(term) return formula def get_model(self): ...
nbari/zunzuncito
my_api/default/v0/zun_tld/tldextract/tldextract.py
Python
bsd-3-clause
14,203
0.004224
# -*- coding: utf-8 -*- """`tldextract` accurately separates the gTLD or ccTLD (generic or country code top-level domain) from the registered domain and subdomains of a URL. >>> import tldextract >>> tldextract.extract('http://forums.news.cnn.com/') ExtractResult(subdomain='forums.news', domain='cnn', suff...
inside `tldextract`'s directory. """ @classmethod def resource_stream(cls, package, res
ource_name): moddir = os.path.dirname(__file__) f = os.path.join(moddir, resource_name) return open(f) import re import socket try: string_types = basestring except NameError: string_types = str try: # pragma: no cover # Python 2 from urllib2 import urlopen fro...
mondhs/heroku_test
transcriber_re_mg14.py
Python
gpl-3.0
7,933
0.023621
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @author: Mindaugas Greibus trancriber mg1.4 ''' import sys, re import collections class TranscriberRegexp: # http://cmusphinx.sourceforge.net/wiki/tutorialam # Do not use case-sensitive variants like “e” and “E”. Instead, all your phones must be different even in c...
='Input text file one word per line, \'-\' for standard input', metavar='in-file', type=argparse.FileType('rt')) args = parser.parse_args() if args.verbose: print args sphinx_dictionary = {} if args.input_file: sphinx_dictionary = processFile(args.input_file) elif args.input_words...
iakopūstaudavome") if args.output_file: writeToFile(sphinx_dictionary, args.output_file) else: writeToConsole(sphinx_dictionary) if __name__ == "__main__": main()
fjorba/invenio
modules/websearch/lib/search_engine_query_parser.py
Python
gpl-2.0
54,879
0.007507
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2008, 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 2 of the ## License, or (a...
p = re.sub('\&', '+', p) return p # pylint: enable=C0103 def parse_query(self, query): """Make query into something suitable for search_engine. This is the main entry point of the class. Given an expression of the form:
"expr1 or expr2 (expr3 not (expr4 or expr5))" produces annoted list output suitable for consumption by search_engine, of the form: ['+', 'expr1', '|', 'expr2', '+', 'expr3 - expr4 | expr5'] parse_query() is a wrapper for self.tokenize() and self.parse(). """ tokli...
stephanie-wang/ray
rllib/utils/policy_server.py
Python
apache-2.0
3,404
0
import pickle import traceback from http.server import SimpleHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn from ray.rllib.utils.annotations import PublicAPI from ray.rllib.utils.policy_client import PolicyClient @PublicAPI class PolicyServer(ThreadingMixIn, HTTPServer): """REST server t...
TPRequestHandler): def do_POST(self): content_len = int(self.headers.get("Content-Length"), 0) raw_body = self.rfile.read(content_len) parsed_input = pickle.loads(raw_body) try: response = self.execute_command(parsed_input) self.sen...
format_exc()) def execute_command(self, args): command = args["command"] response = {} if command == PolicyClient.START_EPISODE: response["episode_id"] = external_env.start_episode( args["episode_id"], args["training_enabled"]) ...
openhatch/oh-missions-oppia-beta
core/storage/base_model/gae_models.py
Python
apache-2.0
15,533
0.000193
# Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
entity. strict: bool. Whether to fail noisily if no entity with the given id exists in the datastore. Returns: None, if strict == False and no undeleted entity with the given id
exists in the datastore. Otherwise, the entity instance that corresponds to the given id. Raises: - base_models.BaseModel.EntityNotFoundError: if strict == True and no undeleted entity with the given id exists in the datastore. """ entity = cls.get_by_id(e...
wldcordeiro/servo
etc/ci/performance/test_runner.py
Python
mpl-2.0
14,471
0.002073
#!/usr/bin/env python3 # 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/. import runner import pytest def test_log_parser(): mock_log = b''' [PERF] perf block start...
oadEventEnd": None, "redirectStart": None, "redirectEnd": None, "fetchStart": None, "domainLookupStart": None, "domainLookupEn
d": None, "connectStart": None, "connectEnd": None, "secureConnectionStart": None, "requestStart": None, "responseStart": None, "responseEnd": None, "domLoading": 1460358376000, "domInteractive": 1460358388000, "domContentLoadedEventStart": 1460358...
s20121035/rk3288_android5.1_repo
cts/apps/CameraITS/pymodules/its/error.py
Python
gpl-3.0
791
0.005057
# Copyright 2013 The Android Open Source Project # # 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 a...
he License for the specific language governing permissions and # limitations under the License. import unittest class Error(Exception): pass class __UnitTest(unittest.TestCase): """Run a suite of unit
tests on this module. """ if __name__ == '__main__': unittest.main()
wadobo/papersplease
papersplease/papers/admin.py
Python
agpl-3.0
1,742
0.000574
from __future__ import print_function from __future__ import unicode_literals from django.contrib import admin fr
om .models import Conference from .models import Paper from .models import Author from .models import Attachment from .actions import paper_actions class AttachInline(admin.TabularInline): model = Attachment class ConferenceAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} list_display...
', 'place') date_hierarchy = 'date' class PaperAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} list_display = ('title', 'conference', 'status', 'pauthors', 'hasattach') list_filter = ('status', 'conference') search_fields = ('title', 'conference__name', 'co...
shinriyo/workalendar
workalendar/core.py
Python
mit
17,530
0.000057
"""Working day tools """ import warnings import ephem import pytz from calendar import monthrange from datetime import date, timedelta, datetime from ma
th import pi from dateutil import easter from lunardate import LunarDate from calverter import Calverter MON, TUE, WED, THU, FRI, SAT, SUN = range(7) class Calendar(object): FIXED_HOLIDAYS = () def __init__(self): self._holidays = {} def get_fixed_holidays(self, year): """Return the f...
r, month, day), label)) return days def get_variable_days(self, year): return [] def get_calendar_holidays(self, year): """Get calendar holidays. If you want to override this, please make sure that it **must** return a list of tuples (date, holiday_name).""" ret...
zrax/pycdc
tests/input/test_extendedPrint.py
Python
gpl-3.0
122
0
import sys print >>sys.stdout, 'Hello World' prin
t >>sys.stdout, 1, 2, 3 print >>sys.stdout, 1,
2, 3, print >>sys.stdout
HyperloopTeam/Hyperloop
src/hyperloop/geometry/pod.py
Python
apache-2.0
4,408
0.0152
from os.path import dirname, join from openmdao.main.api import Assembly #from openmdao.lib.components.api import GeomComponent from openmdao.lib.datatypes.api import Float, Int #hyperloop sizing calculations from inlet import InletGeom from battery import Battery from passenger_capsule import PassengerCapsule from ...
self.connect('capsule.area_cross_section','battery.area_cross_section')
#Inlet -> Aero self.connect('inlet.area_frontal','aero.area_capsule') #Boundary Output Connections #Capsule -> Pod self.connect('capsule.area_cross_section','area_cross_section') #Tube->Pod self.connect('tube.radius_outer','radius_tube_outer') #Inlet->Pod ...
emanueldima/b2share
b2share/modules/files/__init__.py
Python
gpl-2.0
908
0
# -*- coding: utf-8 -*- # # This file is part of EUDAT B2Share. # Copyright (C) 2016 CERN. # # B2Share 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...
ful, 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 B2Share; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """B2SHARE""" from __future__ import absolute_import, print_function fro...
enaut/Minecraft-Overviewer
overviewer.py
Python
gpl-3.0
29,543
0.003283
#!/usr/bin/env python3 # This file is part of the Minecraft Overviewer. # # Minecraft Overviewer 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 o...
sys.exit(1) import os import os.path import re import subprocess import multiprocessing import t
ime import logging from argparse import ArgumentParser from collections import OrderedDict from overviewer_core import util from overviewer_core import logger from overviewer_core import textures from overviewer_core import optimizeimages, world from overviewer_core import config_parser, tileset, assetmanager, dispatc...
dans-er/resync
resync/client_utils.py
Python
apache-2.0
4,699
0.008725
"""Client Utilities Factor out code shared by both the resync and resync-explorer clients. Copyright 2012,2013 Simeon Warner 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:/...
mport UTCFormatter def init_logging(to_file=False, logfile=None, default_logfile='/tmp/resync.log', human=True, verbose=False, eval_mode=False, default_logger='client', extra_loggers=None): """Initialize logging Use of log levels: DEBUG - very verbose, for evaluation
of output (-e) INFO - verbose, only seen by users if they ask for it (-v) WARNING - messages output messages to console Logging to a file: If to_file is True then output will be written to a file. This will be logfile if set, else default_logfile (which may also be overridden). """ fm...
kandluis/machine-learning
prac4/practical4-code/modelbased.py
Python
mit
3,542
0.00734
from tdlearner import TDLearner from collections import defaultdict import numpy as np # finds Euclidean norm distance between two lists a, b def find_dist(a,b): cumsum = 0.0 for i in xrange(len(a)): cumsum += (a[i]-b[i])**2 return np.sqrt(cumsum/float(len(a))) class ModelBased(TDLearner): ''...
_state) # print "Last state {}".format(self.last_state)
# increase iteration count and maximize chose action to maximize expected reward self.iter_num += 1 # we need update our Q for the last state and action if (self.last_state is not None and self.last_action is not None and self.last_reward is not None): ...
easies/dentist
dentist/main.py
Python
mit
2,740
0
#!/usr/bin/env python from . import dentist from .watchers import LogNotify, Notifier, Poller import logging import os import sys def parse(): from optparse import OptionParser parser = OptionParser() parser.add_option('-d', '--daemonize', dest='daemonize', action='store_true', defa...
logs if options.output_dir: dentist.LogReader.set_output_directory(options.output_dir) poller = Poller() # Setup the log readers # Add the customized prefixes clr = dentist
.CombinedLogReader clr.add_prefix(*options.prefixes) # Set the root of the home directories elr = dentist.ErrorLogReader elr.configure(homedir_root=options.parent_user_dir) notifier = Notifier() # Create the list of files and log the set of their directories. directories = set() for f ...
Andrei-Stepanov/avocado-vt
virttest/utils_misc.py
Python
gpl-2.0
116,705
0.000548
""" Virtualization test utility functions. :copyright: 2008-2009 Red Hat Inc. """ import time import string import random import socket import os import stat import signal import re import logging import commands import fcntl import sys import inspect import tarfile import shutil import getpass import ctypes import t...
self._target = target self._args = args self._kwargs = kwargs def run(self): """ Ru
n target (passed to the constructor). No point in calling this function directly. Call start() to make this function run in a new thread. """ self._e = None self._retval = None try: try: self._retval = self._target(*self._args, **self._kwargs...
plxaye/chromium
src/chrome/common/extensions/docs/server2/test_file_system_test.py
Python
apache-2.0
6,461
0.002476
#!/usr/bin/env python # Copyright (c) 2012 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. from copy import deepcopy from file_system import FileNotFoundError, StatInfo from test_file_system import TestFileSystem import un...
.Stat('404.html') fs.Stat('apps/') self.assertFalse(
fs.CheckAndReset(stat_count=42)) self.assertFalse(fs.CheckAndReset(stat_count=42)) self.assertTrue(fs.CheckAndReset()) fs.ReadSingle('404.html') fs.Stat('404.html') fs.Stat('apps/') self.assertTrue(fs.CheckAndReset(read_count=1, stat_count=2)) self.assertTrue(fs.CheckAndReset()) def test...
Architektor/PySnip
venv/lib/python2.7/site-packages/twisted/python/compat.py
Python
gpl-3.0
19,303
0.001813
# -*- test-case-name: twisted.test.test_compat -*- # # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Compatibility module to provide backwards compatibility for useful Python features. This is mainly for use of internal Twisted code. We encourage you to use the latest version of Python di...
a stack-level argument. Restore that functionality from Python 2 so we don't have to re-implement the C{f_back}-walking loop in places where it's called. @param n: The number of stack levels above the caller to walk. @type n: L{int} @return: a frame, n
levels up the stack from the caller. @rtype: L{types.FrameType} """ f = inspect.currentframe() for x in range(n + 1): f = f.f_back return f def inet_pton(af, addr): if af == socket.AF_INET: return socket.inet_aton(addr) elif af == getattr(socket, 'AF_INET6', 'AF_INET6'): ...
natetrue/ReplicatorG
skein_engines/skeinforge-0006/skeinforge_tools/comb.py
Python
gpl-2.0
26,905
0.043895
""" Comb is a script to comb the extrusion hair of a gcode file. The default 'Activate Comb' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called. Comb bends the extruder travel paths around holes in the carve, to avoid stringers. It moves the extr...
) self.fileNameInput = preferences.Filename().getFromFilename( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File to be Combed', '' ) self.archive.append( self.fileNa
meInput ) #Create the archive, title of the execute button, title of the dialog & preferences fileName. self.executeTitle = 'Comb' self.saveTitle = 'Save Preferences' preferences.setHelpPreferencesFileNameTitleWindowPosition( self, 'skeinforge_tools.comb.html' ) def execute( self ): "Comb button has been cl...
jiemakel/omorfi
test/conllu-compare.py
Python
gpl-3.0
7,037
0.001279
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Compare two conllu files for matches on each field. """ from argparse import ArgumentParser, FileType from sys import stderr def main(): a = ArgumentParser() a.add_argument('-H', '--hypothesis', metavar="HYPFILE", type=open, required=True, ...
le", help="analysis results") a.add_argument('-r', '--reference', metavar="REFFILE", type=open, required=True, dest="reffile", help="reference data") a.add_argument('-l', '--log', metavar="LOGFILE", required=True, type=FileType('w'), de...
help="Allow fuzzy matches if tokenisation differs") a.add_argument('-v', '--verbose', action="store_true", default=False, help="Print verbosely while processing") a.add_argument('-t', '--thresholds', metavar='THOLDS', default=99, type=int, help="require THOLD % for lem...
varses/awsch
lantz/drivers/andor/ccd.py
Python
bsd-3-clause
74,992
0.00028
# -*- coding: utf-8 -*- # pylint: disable=E265 """ lantz.drivers.andor.ccd ~~~~~~~~~~~~~~~~~~~~~~~ Low level driver wrapping library for CCD and Intensified CCD cameras. Only functions for iXon EMCCD cameras were tested. Only tested in Windows OS. The driver was written for the single-camera ...
_ERROR_BUFFSIZE', 20121: 'DRV_ERROR_NOHANDLE', 20130: 'DRV_GATING_NOT_AVAILABLE', 20131: 'DRV_FPGA_VOLTAGE_ERROR', 20100: 'DRV_INVALID_AMPLIFIER', 20101: 'DRV_INVALID_COUNTCONVERT_MODE' } class CCD(LibraryDriver): LIBRARY_NAME = 'atmcd64d.dll' def __init__(self, *args, **kwargs): ...
= [ct.pointer(ct.c_uint)] internal.Filter_SetAveragingFactor.argtypes = [ct.c_int] internal.Filter_SetThreshold.argtypes = ct.c_float internal.Filter_GetThreshold.argtypes = ct.c_float def _return_handler(self, func_name, ret_value): excl_func = ['GetTemperatureF', 'IsCountConvertM...
kk6/poco
tests/test_utils.py
Python
mit
1,427
0.000701
# -*- coding: utf-8 -*- from datetime import datetime, timezone, timedelta import pytest class TestStr2Datetime(object): @pytest.fixture def target_func(self): from poco.utils import str2datetime return str2datetime @pytest.mark.parametrize( 's,expected', [ ('...
om poco.utils import force_int return force_int @pytest.mark.parametrize( 's,expecte
d', [ ('100', 100), (100, 100), (2.5, 2), ('', None), (True, 1), (False, 0), ], ) def test_call(self, target_func, s, expected): assert target_func(s) == expected @pytest.mark.parametrize('non_str_value', [None,...
maxamillion/atomic-reactor
tests/test_rpm_util.py
Python
bsd-3-clause
2,380
0.00042
""" Copyright (c) 2017 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import absolute_import, print_function import pytest from atomic_reactor.rpm_util import rpm_qf_args, parse_rpm_output FAK...
, None, r"-qa --qf '%{NAME};%{VERSION};%{RELEASE};%{ARCH};%{EPOCH};%{SIZE};%{SIGMD5};%{BUILDTIME};%{SIGPGP:pgpsig};%{SIGGPG:pgpsig}\n'"), # noqa (['NAME', 'VERSION'], "|", r"-qa --qf '%{NAME}|%{VERSION}\n'"), ]) def test_rpm_qf_args(tags, separator, expected): kwargs = {} if tags is not None: ...
arse_rpm_output(): res = parse_rpm_output([ "name1;1.0;1;x86_64;0;2000;" + FAKE_SIGMD5.decode() + ";23000;" + FAKE_SIGNATURE + ";(none)", "name2;2.0;1;x86_64;0;3000;" + FAKE_SIGMD5.decode() + ";24000;" + "(none);" + FAKE_SIGNATURE, "gpg-pubkey;64dab85d;57d33e22;(none);(none);...
HenryCorse/Project_Southstar
CharacterApp/creator/apps.py
Python
mit
89
0
from django.apps
impo
rt AppConfig class CreatorConfig(AppConfig): name = 'creator'
hanleilei/note
python/vir_manager/utils/libvirt_utils.py
Python
cc0-1.0
3,602
0.000943
import hashlib import libvirt from django.forms.models import model_to_dict from utils.common import gen_passwd from utils.common import gen_user_passwd from backstage.models import LibvirtPass from utils.salt_utils import SaltApiHandler def get_host_passwd(host): """ * desc 获取机器的用户名和密码 * input 主机ip ...
t): ""
" * desc 生成libvirt的用户名和密码 * input 主机ip * output libvirt用户名和libvirt密码 """ hash_md5 = hashlib.md5() hash_md5.update(bytes(host.strip(), encoding='utf-8')) user = hash_md5.hexdigest() password = gen_passwd() return user, password def set_libvirt_passwd(handler, host, user, password...
marchon/poker
setup.py
Python
mit
1,020
0.025515
# -*- coding: utf-8 -*- from setuptools import setup, find_packages install_requires = [ 'pytz', 'requests', 'lxml', 'python-dateutil', 'parsedatetime', 'cached-pro
perty', 'click', 'enum34', # backported versions from Pyth
on3 'pathlib', 'configparser', ] console_scripts = [ 'poker = poker.commands:poker', ] classifiers = [ "Intended Audience :: Developers", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", ] setup( name = 'poker', v...
jevinw/rec_utilities
babel_util/recommenders/ef2.py
Python
agpl-3.0
1,698
0.004122
#!/usr/bin/env python import itertools from operator import attrgetter, itemgetter class ClusterRecommendation(object): __slots__ = ("cluster_id", "papers") def __init__(self, cluster_id, papers): self.cluster_id = cluster_id self.papers = [(p.pid, p.score) for p in papers] def __str__(s...
: leaf_stream = itertools.groupby(stream, lambda e: e.local) for (cluster_id, stream) in leaf_stream: papers = [e for e in stream]
papers = sorted(papers, key=attrgetter('score'), reverse=True) yield ClusterRecommendation(cluster_id, papers[:rec_limit]) def parse_tree(stream, rec_limit=10): mstream = make_leaf_rec(stream, rec_limit) child_stream = itertools.groupby(mstream, lambda e: get_parent(e.cluster_id)) for (parent_...
lreis2415/PyGeoC
examples/ex06_model_performace_index.py
Python
mit
874
0.002288
# -*- coding: utf-8 -*- # Exercise 6: Calculate model performance indexes with PyGeoC from pygeoc.utils import MathClass def cal_model_performance(obsl, siml): """Calculate model performance indexes.""" nse = MathClass.nashcoef(obsl, siml) r2 = MathClass.rsquare(obsl, siml) rmse = MathClass.r...
2f' % (nse, r2, pbias, rm
se, rsr)) if __name__ == "__main__": obs_list = [2.92, 2.75, 2.01, 1.09, 2.87, 1.43, 1.96, 4.00, 2.24, 17.00, 5.88, 0.86, 13.21, 10.00, 11.00, 6.60] sim_list = [0.40, 4.88, 1.92, 0.49, 0.28, 5.36, 1.89, 4.08, 1.50, 10.00, 7.02, 0.33, 8.40, 7.8, 12, 3.8] cal_model_pe...
havard024/prego
venv/lib/python2.7/site-packages/PIL/MspImagePlugin.py
Python
mit
2,173
0.004602
# # The Python Imaging Library. # $Id$ # # MSP file handling # # This is the format used by the Paint program in Windows 1 and 2. # # History: # 95-09-05 fl Created # 97-01-03 fl Read/write MSP images # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1995-97. # # See the README fi...
), i16(b"nM") # version 1 header[2], header[3] = im.size header[4], header[5] = 1, 1 header[6], header[7] = 1, 1 header[8], header[9] = im.size sum = 0 for h in header: sum = sum ^ h header[12] = sum # FIXME: is this the right field?
# header for h in header: fp.write(o16(h)) # image body ImageFile._save(im, fp, [("raw", (0,0)+im.size, 32, ("1", 0, 1))]) # # registry Image.register_open("MSP", MspImageFile, _accept) Image.register_save("MSP", _save) Image.register_extension("MSP", ".msp")
Dehyrf/python_gates
window.py
Python
gpl-3.0
3,800
0.002632
from gi.repository import Gtk, Gdk, GdkPixbuf (TARGET_ENTRY_TEXT, TARGET_ENTRY_PIXBUF) = range(2) (COLUMN_TEXT, COLUMN_PIXBUF) = range(2) DRAG_ACTION = Gdk.DragAction.COPY class DragDropWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Drag and Drop") vbox = Gtk.Box(orien...
() class DragSourceIconView(Gtk.IconView): def __init__(self): Gtk.IconView.__init__(self) self.set_text_column(COLUMN_TEXT) self.set_pixbuf_column(COLUMN_PIXBUF) model = Gtk.ListStore(str, GdkPixbuf.Pixbuf) self.set_model(model) self.add_item("Item 1", "image-miss...
DRAG_ACTION) self.connect("drag-data-get", self.on_drag_data_get) def on_drag_data_get(self, widget, drag_context, data, info, time): selected_path = self.get_selected_items()[0] selected_iter = self.get_model().get_iter(selected_path) if info == TARGET_ENTRY_TEXT: ...
glenngillen/dotfiles
.vscode/extensions/ms-python.python-2021.5.842923320/pythonFiles/lib/jedilsp/pydantic/json.py
Python
mit
3,365
0.001189
import datetime import re import sys from collections import deque from decimal import Decimal from enum import Enum from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network from pathlib import Path from types import GeneratorType from typing import Any, Callable, Dict, Typ...
str, Path: str, Pattern: lambda o: o.pattern, SecretBytes: str, SecretStr: str, set: list, UUID: str, } def pydantic_encoder(obj: Any) -> Any: from dataclasses import asdict, is_dataclass from .main import BaseModel if isinstance(obj, BaseModel): return obj.dict() el...
encoder = ENCODERS_BY_TYPE[base] except KeyError: continue return encoder(obj) else: # We have exited the for loop without finding a suitable encoder raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") def custom_pydantic_encoder(type_encod...
urashima9616/Leetcode_Python
Leet154_FindMinRotatedArrayII.py
Python
gpl-3.0
1,397
0.012169
""" Duplicate entries allowed this raises the complexity from log n to n/2 log n key idea: if mid equal to two ends, there must be constant on one side and min on the other. if left end < mid < right: no rotation if mid less than both ends => min on your left if min greater than both ends => min on your right """ ...
else: mid = length/2 right = 0 if nums[mid] == nums[0] and nums[mid] == nums[-1]:#Need to search both direction prev = nums[mid] for i in xrange(mid,len(nums)): if prev != nums[i]: right = 1 ...
:mid+1]) elif nums[mid]>= nums[0] and nums[mid]<=nums[-1]: # no rotation return nums[0] elif nums[mid] >= nums[0] and nums[mid] >= nums[-1]:# on the right hand side return self.findMin(nums[mid:]) elif nums[mid] <= nums[0] and nums[mid] <= nums[-1]: # ...
julienmalard/Tikon
pruebas/test_central/rcrs/modelo_valid.py
Python
agpl-3.0
1,156
0.000877
import numpy as np import pandas as pd import xarray as xr from tikon.central import Módulo, SimulMódulo, Modelo, Exper, Parcela from tikon.central.res import Resultado from tikon.datos import Obs from tikon.utils import EJE_TIEMPO, EJE_PARC f_inic = '2000-01-01' crds = {'eje 1': ['a', 'b'], 'eje 2': ['x', 'y', 'z']}...
[EJE_TIEMPO]
).expand_dims({EJE_PARC: ['parcela'], **crds}) ) exper = Exper('exper', Parcela('parcela'), obs=obs) modelo = Modelo(MóduloValid)
asljivo1/802.11ah-ns3
ns-3/.waf-1.8.12-f00e5b53f6bbeab1384a38c9cc5d51f7/waflib/Tools/fc_scan.py
Python
gpl-2.0
1,859
0.069392
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file import re from waflib import Utils,Task,TaskGen,Logs from waflib.TaskGen import feature,before_method,after_method,extension from waflib.Configure import conf INC_REGEX="""(?:^|['">]\s*;)\s*(?:|#\s*)...
DULE(?!\s*PROCEDURE)(?:\s+|(?:(?:\s*,\s*(?:NON_
)?INTRINSIC)?\s*::))\s*(\w+)""" re_inc=re.compile(INC_REGEX,re.I) re_use=re.compile(USE_REGEX,re.I) re_mod=re.compile(MOD_REGEX,re.I) class fortran_parser(object): def __init__(self,incpaths): self.seen=[] self.nodes=[] self.names=[] self.incpaths=incpaths def find_deps(self,node): txt=node.read() incs=[]...
Domatix/stock-logistics-workflow
stock_pack_operation_auto_fill/models/stock_move.py
Python
agpl-3.0
1,537
0
# Copyright 2017 Pedro M. Baeza <[email protected]> # Copyright 2018 David Vidal <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models class StockMove(models.Model): _inherit = 'stock.move' def _create_extra_move(self): """ ...
ra stock move with the difference a
nd it is posible to create an extra stock move line with qty_done = 0 which will be deleted in _action_done method. This method set a context variable to prevent set qty_done for these cases. """ my_self = self if self.picking_id.auto_fill_operation: m...
rst2pdf/rst2pdf
rst2pdf/tests/input/sphinx-issue252/conf.py
Python
mit
1,417
0.002117
# -*- coding: utf-8 -*- # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.imgmath', 'rst2pdf.pdfbuilder'] # The ma...
ting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # #
The short X.Y version. version = 'test' # The full version, including alpha/beta/rc tags. release = 'test' # -- Options for PDF output ---------------------------------------------------- # Grouping the document tree into PDF files. List of tuples # (source start file, target name, title, author). pdf_documents = [(...
vicenteneto/python-cartolafc
examples/examples.py
Python
mit
1,020
0.00098
import cartolafc api = cartolafc.Api(email='[email protected]', password='s3nh4', attempts=5, redis_url='redis://localhost:6379/0') print(api.amigos()) print(api.clubes()) print(a
pi.liga(nome='Virtus Premier League')) print(api.liga(nome='Nacional', page=2)) print(api.liga(nome='Nacional', page=3, order_by=cartolafc.RODADA)) print(api.liga(slug='virtus-premier-league')) print(api.ligas(query='Virtus')) print(api.ligas_patrocinadores()) print(api.mercado()) print
(api.mercado_atletas()) print(api.parciais()) print(api.partidas(1)) print(api.pontuacao_atleta(81682)) print(api.pos_rodada_destaques()) print(api.time(id=2706236)) print(api.time(id=2706236, as_json=True)) print(api.time(nome='ALCAFLA FC')) print(api.time(nome='ALCAFLA FC', as_json=True)) print(api.time(slug='alcafla...
YunoHost/moulinette
test/src/authenticators/dummy.py
Python
agpl-3.0
2,129
0.001409
# -*- coding: utf-8 -*- import logging from moulinette.utils.text import random_ascii from moulinette.core import MoulinetteError, MoulinetteAuthenticationError from moulinette.authentication import BaseAuthenticator logger = logging.getLogger("moulinette.authenticator.yoloswag") # Dummy authenticator implementation...
ssion_cookie(raise_if_no_session_exists=False) new_infos = {"id": current_infos["id"]} new_infos.update(infos) response.set_cookie(
"moulitest", new_infos, secure=True, secret=session_secret, httponly=True, # samesite="strict", # Bottle 0.12 doesn't support samesite, to be added in next versions ) def get_session_cookie(self, raise_if_no_session_exists=True): ...
avoorhis/vamps-node.js
public/scripts/node_process_scripts/vamps_script_create_json_dataset_files.py
Python
mit
17,471
0.022208
#!/usr/bin/env python """ create_counts_lookup.py """ print('3)-->files') import sys,os import argparse import pymysql as MySQLdb import json import configparser as ConfigParser """ SELECT sum(seq_count), dataset_id, domain_id,domain FROM sequence_pdr_info JOIN sequence_uniq_info USING(sequence_id) JOIN silva_t...
yB}, {"rank": "klass", "queryA": class_queryA, "queryB": class_queryB}, {"rank": "order", "queryA": order_queryA, "queryB": order_queryB}, {"rank": "family", "queryA": family_queryA, "queryB": family_queryB}, {"rank": "genus", "queryA": genus_queryA, "queryB": genus_queryB}, ...
lobals CONFIG_ITEMS = {} DATASET_ID_BY_NAME = {} # # # class Dict2Obj(object): """ Turns a dictionary into a class """ #---------------------------------------------------------------------- def __init__(self, dictionary): """Constructor""" for key in dictionary: setattr...
sagarsane/abetterportfolio
github/GitTag.py
Python
apache-2.0
3,535
0.04017
# Copyright 2012 Vincent Jacques # [email protected] # This file is part of PyGithub. http://vincent-jacques.net/PyGithub # PyGithub is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either vers...
or isinstance( attributes[ "sha" ], ( str, unicode ) ), attributes[ "sha" ] self._sha = attributes[ "sha" ] if "tag" in attributes: # pragma no branch assert attributes[ "tag" ] is None or isinstance( attributes[ "tag" ], ( str, unicode ) ), attributes[ "tag" ] self._tag = at...
o branch assert attributes[ "tagger" ] is None or isinstance( attributes[ "tagger" ], dict ), attributes[ "tagger" ] self._tagger = None if attributes[ "tagger" ] is None else GitAuthor.GitAuthor( self._requester, attributes[ "tagger" ], completed = False ) if "url" in attributes: # prag...
jor-/simulation
simulation/util/args.py
Python
agpl-3.0
12,072
0.00439
import numpy as np import measurements.all.data import simulation.model.options import simulation.model.cache import simulation.optimization.constants import simulation.accuracy.linearized def init_model_options(model_name, time_step=1, concentrations=None, concentrations_index=None, paramete...
s_index is not None: model = simulation.model.cache.Model(model_options=model_options) # set initia
l concentration if concentrations is not None: c = np.array(concentrations) elif concentrations_index is not None: c = model._constant_concentrations_db.get_value(concentrations_index) if concentrations is not None or concentrations_index is not None: model_options.initial_concentrat...
pauron/ShaniXBMCWork
script.video.F4mProxy/lib/f4mDownloader.py
Python
gpl-2.0
39,022
0.016478
import xml.etree.ElementTree as etree import base64 from struct import unpack, pack import sys import io import os import time import itertools import xbmcaddon import xbmc import urllib2,urllib import traceback import urlparse import posixpath import re import hmac import hashlib import binascii imp...
header_end = 8 if size == 1: real_size = self.read_unsigned_long_long() header_end = 16 return real_size, box_type, self.read(real_size-header_end) def read_asrt(self, debug=False): version = self.read_unsigned_char() self.read(3) # flags ...
y_entry_count): quality_modifier = self.read_string() quality_modifiers.append(quality_modifier) segment_run_count = self.read_unsigned_int() segments = [] #print 'segment_run_count',segment_run_count for i in range(segment_run_count): first_seg...
maaku/django-reuse
templates/apps/basic/myapp/urls.py
Python
agpl-3.0
886
0
#!/usr/bin/env python # -*- coding: utf-8 -*- ## # myapp.urls ## ## # Copyright (C) $YEAR$, $AUTHOR_NAME$ <$AUTHOR_EMAIL$> # # This program is free software: you can redistrib
ute it and/or modify it # under the terms of version 3 of the GNU Affero General Public License as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MER
CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this source code; if not, see <http://www.gnu.org/licenses/>, # or write to # # Free Software Foundation, Inc. #...
kslundberg/pants
src/python/pants/backend/jvm/tasks/junit_run.py
Python
apache-2.0
37,903
0.00802
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import copy import f...
ompute_complete_classpath(): return self._task_exports.classpath(targets, cp=bootstrapped_cp) self._context.releas
e_lock() self.instrument(targets, tests_and_targets.keys(), compute_complete_classpath) def _do_report(exception=None): self.report(targets, tests_and_targets.keys(), tests_failed_exception=exception) try: self.run(tests_and_targets) _do_report(exception=None) except TaskError as e: ...
nagyistoce/devide
modules/viewers/MaskComBinar.py
Python
bsd-3-clause
62,014
0.006305
from wxPython._controls import wxLIST_MASK_STATE from wxPython._controls import wxLIST_STATE_SELECTED import os.path # Modified by Francois Malan, LUMC / TU Delft # December 2009 # # based on the SkeletonAUIViewer: # skeleton of an AUI-based viewer module # Copyright (c) Charl P. Botha, TU Delft. # set to False for 3D...
.4) self.slice_viewer = OverlaySliceViewer(self._view_frame.rwi2d, self.ren2d) self._view_frame.rwi2d.GetRenderWindow().AddRenderer(self.ren2d) self.slice_viewer.add_overlay('a', [0, 0, 1, 1]) #Blue for selection A self.slice_viewer.add_overlay('b', [1, 0, 0, 1]) #Red for selection B ...
dow(self): # create the necessary VTK objects for the 3D window: we only need a renderer, # the RenderWindowInteractor in the view_frame has the rest. self.ren3d = vtk.vtkRenderer() self.ren3d.SetBackground(0.6,0.6,0.6) self._view_frame.rwi3d.GetRenderWindow().AddRenderer(self.re...
thedod/boilerplate-peewee-flask
application/sitepack/babel_by_url.py
Python
gpl-3.0
3,249
0.004617
import flask_babel from flask import request, url_for, current_app, g, session from flask_nav.elements import View class LanguageCodeFromPathMiddleware(object): def __init__(self, app, babel_by_url): self.app = app self.babel_by_url = babel_by_url def __call__(self, environ, start_response): ...
iron['PATH_INFO'] language_code = self.babel_by_url.language_code_from_path(path) if language_code: environ['PATH_INFO'] = path[1+len(language_code):] environ['LANGUAGE_CODE_FROM_URL'] =
language_code return self.app(environ, start_response) class BabelByUrl(object): app = None babel = None default_locale = None locales = [] locale_map = {} def __init__(self, app=None, *args, **kwargs): if app is not None: self.init_app(app) def get_language_co...
zalf-lsa/carbiocial-project
monica/monica-cluster-mpi/run_carbiocial_simulation.py
Python
mpl-2.0
9,103
0.018455
#!/usr/bin/python # -*- coding: ISO-8859-15-*- import sys sys.path.append('.') # path to monica.py import mpi_helper import monica import os import datetime import numpy import analyse_monica_outputs import shutil import time import csv from mpi4py import MPI # MPI related initialisations comm = MPI.COMM_WORLD r...
ar2openFile.iteritems(): line = " ".join([str(ys) for ys in year2currentColYields[year]]) + "\n" f.write(line) year2currentCol
Yields[year] = [] #write the averaged column values to the file avgLine = " ".join([str(ys) for ys in currentColAvgYields]) + "\n" outputAvgGridFile.write(avgLine) currentColAvgYields = [] for year, f in year2openFile.iteritems(): f.close() outputAvgGridFile.close() def splitAs...
OA-DeepGreen/sphinx-doc
conf.py
Python
apache-2.0
4,810
0.000416
# -*- coding: utf-8 -*- # # DeepGreen documentation build configuration file, created by # sphinx-quickstart on Mon Dec 12 18:24:23 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
e shown here. # # import os # import sys # sys.path.insert(0, os.path.a
bspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or you...
bnoordhuis/mongrel2
examples/configs/multi_conf.py
Python
bsd-3-clause
1,384
0.007225
from mongrel2.config import * main = Server( uuid="f400bf85-4538-4f7a-8908-67e313d515c2", access_log="/logs/access.log", error_log="/logs/error.log", chroot="./", default_host="localhost", name="test", pid_file="/run/mongrel2.pid", port=6767, hosts = [ Host(name="localhost"...
default_ctype='text/plain') }) ] ) foo = Server( uuid="2355e656-fac6-41c8-9cba-4977b937cb94", access_log="/logs/access.log", error_log="/logs/error.log", chroot="./", default_h
ost="foo", name="sub", pid_file="/run/mongrel2.pid", port=6767, hosts = [ Host(name="foo", routes={ r'/dev/null/(.*)': Dir(base='tests/', index_file='index.html', default_ctype='text/plain') }) ] ) commit([main, foo, sub])
zetaops/pyoko
tests/test_model_to_solr_schema.py
Python
gpl-3.0
1,268
0.002366
# -*- coding: utf-8 -*- """ """ # Copyright (C) 2015 ZetaOps Inc. # # This file is licensed under the GNU General Public License v3 # (GPLv3). See LICENSE.txt for details. from pyoko.conf import settings from pyoko.db.schema_update import SchemaUpdater from tests.data.solr_schema import test_data_so
lr_fields_debug_zero, test_data_solr_fields_debug_not_zero,\ test_data_solr_s
chema_debug_zero, test_data_solr_schema_debug_not_zero from tests.models import Student def test_collect_index_fields(): st = Student() result = st._collect_index_fields() sorted_result = sorted(result, key=lambda x: x[0]) if not settings.SOLR['store']: sorted_data = sorted(test_data_solr_fiel...
kowey/attelo
attelo/decoding/greedy.py
Python
gpl-3.0
5,290
0
''' Implementation of the locally greedy approach similar with DuVerle & Predinger (2009, 2010) (but adapted for SDRT, where the notion of adjacency includes embedded segments) July 2012 @author: stergos ''' from __future__ import print_function import sys from .interface import Decoder from .util import (convert_p...
one.id != two.id:
if are_strictly_adjacent(one, two, edus): if two.id not in one_neighbours_ids: one_neighbours_ids.add(two.id) one_neighbours.append(two) if is_embedded(one, two) or is_embedded(two, one): if two.id not in one_neig...
DiegoGuidaF/telegram-raspy
modules.py
Python
mit
358
0.011173
# -*- coding: utf-8 -*- """ Created on Tue Mar 14 02:17:11 2017 @author: guida """ import json import requests def get_url(url): response = requests.get(url) content = response.content.d
ecode("utf8")
return content #Json parser def get_json_from_url(url): content = get_url(url) js = json.loads(content) return js
whiskerlabs/mmringbuffer
mmringbuffer/constants.py
Python
mit
292
0.013699
#
Constant indices within mmap buffers. _POS_VALUE_LEN = 8 _READ_POS_IDX = 0 _WRITE_POS_IDX = _POS_VALUE_LEN _HEADER_LEN = _POS_VALUE_LEN * 2 # Item size constants. _ITEM_SIZE_LEN = 4 # struct.[un]pack format string for length fields _POS_VALUE_FORMAT = "q" _ITEM_SIZE_FORMA
T = "i"
Moonshile/fast12306
src/core/settings.py
Python
apache-2.0
2,707
0.002277
#coding=utf-8 import os # Basic settings # requests settings TIMEOUT = 5 VERIFY = False # directories might be used LOCATIONS = { 'log': 'log', 'data': 'data', } # stderr is redirected to this file ERR_LOG_FILE = os.path.join(LOCATIONS['log'], 'err.log') # log in this file LOGGING_FILE = os.path.join(LOCAT...
': URL_BASE + 'otn/confirmPassenger/initDc', 'order_
check': URL_BASE + 'otn/confirmPassenger/checkOrderInfo', } # 3rd party tools settings # Setup for settings import socket if socket.gethostname() in ['duankq-ThinkPad-X201', ]: DEBUG = True else: DEBUG = False import os for loc in LOCATIONS.values(): if not os.path.isdir(loc): os.mkdir(loc) f...
polyaxon/polyaxon
core/polyaxon/vendor/shell_pty.py
Python
apache-2.0
6,910
0.001013
# This code is based on logic from # http://sqizit.bartletts.id.au/2011/02/14/pseudo-terminals-in-python/ # Licensed under the MIT license: # Copyright (c) 2011 Joshua D. Bartlett # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ...
. """ self._set_pty_size() def _set_pty_size(self): """ Sets the window size of the child pty based on the window size of our own controlling terminal. """ packed = fcntl.ioctl( pty.STDOUT_FILENO, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0...
L, json.dumps({"Height": rows, "Width": cols}) ) def _loop(self): """ Main select loop. Passes all data to self.master_read() or self.stdin_read(). """ assert self.client_shell is not None client_shell = self.client_shell while 1: try: ...
Azure/azure-sdk-for-python
sdk/identity/azure-identity/azure/identity/aio/_credentials/certificate.py
Python
mit
3,645
0.003841
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from typing import TYPE_CHECKING import msal from .._internal import AadClient, AsyncContextManager from .._internal.get_token_mixin import GetTokenMixin from ..._cred...
Directory documentation <https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-microsoft-identity-platform>`_ for more information on configuring certificate authentication. :param str tenant_id: ID of the service principal's tenan...
l's client ID :param str certificate_path: path to a PEM-encoded certificate file including the private key. If not provided, `certificate_data` is required. :keyword str authority: Authority of an Azure Active Directory endpoint, for example 'login.microsoftonline.com', the authority for A...
uw-it-aca/bridge-sis-provisioner
sis_provisioner/csv/writer.py
Python
apache-2.0
1,345
0
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 import logging import traceback from sis_provisioner.dao.uw_account import get_all_uw_accounts from sis_provisioner.csv import get_filepath from sis_provisioner.csv.user_writer import make_import_user_csv_files from sis_provisioner....
e = make_import_user_csv_files( self.fetch_users(), self.filepath) logger.info("Total {0:d} users wrote into {1}\n".format( number_users_wrote, self.filepath)) return number_users_wrote
except Exception: log_exception( logger, "Failed to make user csv file in {0}".format(self.filepath), traceback.format_exc())
our-city-app/oca-backend
src/rogerthat/bizz/features.py
Python
apache-2.0
3,441
0.001453
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
t returns, arguments from mcfw.utils import Enum from rogerthat.dal.mobile import get_mobile_settings_cached from rogerthat.rpc.models import Mobile @total_ordering # @total_ordering uses __lt__ and __eq__ to create __gt__, __ge__, __le__ and __ne__ class Version(object): major = long_property('1') # actually m...
major=MISSING, minor=MISSING): if major is not MISSING: self.major = major if minor is not MISSING: self.minor = minor def __eq__(self, other): return (self.major, self.minor) == (other.major, other.minor) def __lt__(self, other): return (self.major, se...
serbinsh/UniSpec_Processing
src/BasicProcessing/Main.py
Python
gpl-2.0
2,919
0.015416
''' Created on Aug 4, 2015 @author: amcmahon ''' from BasicProcessing import UnispecProcessing from BasicProcessing import consts import os.path import sys def main(): """ Main function for generating CSV files from a directory of Unispec data. Input/Output paths, white plate identifier string and h...
ount): if (WP_count[run] == 0) or (stop_count[run] == 0):
continue WP_data = [[[None], [None]] for item in range(0,WP_count[run])] Stop_data = [[[None], [None]] for item in range(0,stop_count[run])] sat = [[None], [None]] #When getting data from these, they are formatted as: # var[file index][header/dat...
ktaneishi/deepchem
deepchem/feat/tests/test_mol_graphs.py
Python
mit
6,110
0.0018
""" Tests for Molecular Graph data structures. """ from __future__ import division from __future__ import unicode_literals __author__ = "Han Altae-Tran and Bharath Ramsundar" __copyright__ = "Copyright 2016, Stanford University" __license__ = "MIT" import unittest import os import sys import numpy as np from deepche...
y_equal(deg_adj_lists[4], np.zeros([0, 4]))
# 0 atoms of degree 5 assert np.array_equal(deg_adj_lists[5], np.zeros([0, 5])) def test_null_conv_mol(self): """Running Null AggrMol Test. Only works when max_deg=6 and min_deg=0""" num_feat = 4 min_deg = 0 null_mol = ConvMol.get_null_mol(num_feat) deg_adj_lists = null_mol.get_deg_adjace...
andrzejgorski/whylog
whylog/constraints/verifier.py
Python
bsd-3-clause
8,521
0.003286
import itertools from whylog.config.investigation_plan import Clue from whylog.constraints.exceptions import TooManyConstraintsToNegate from whylog.front.utils import FrontInput class Verifier(object): UNMATCHED = Clue(None, None, None, None) @classmethod def _create_investigation_result(cls, clues_comb...
ues_lists = cls._construct_proper_clues_lists(clues_lists) causes = [] for combination in cls._clues_combinations(clues_lists): if all( cls._verify_constraint(combination, effect, idx, constraint, c
onstraint_manager) for idx, constraint in enumerate(constraints) ): causes.append( cls._create_investigation_result( combination, constraints, InvestigationResult.AND ) ) return causes ...
xray/xray
xarray/backends/api.py
Python
apache-2.0
50,534
0.000772
import os.path import warnings from glob import glob from io import BytesIO from numbers import Number from pathlib import Path from typing import ( TYPE_CHECKING, Callable, Dict, Hashable, Iterable, Mapping, Tuple, Union, ) import numpy as np from .. import backends, coding, conventio...
"netCDF4-python or scipy installed" ) return engine def _get_engine_from_magic_number(filename_or_obj): # check byte header to determine file type if isinstance(filename_or_obj, bytes): magic_number = filename_or_obj[:8] el
se: if filename_or_obj.tell() != 0: raise ValueError( "file-like object read/write pointer not at zero " "please close and reopen, or use a context " "manager" ) magic_number = filename_or_obj.read(8) filename_or_obj.seek(0)...
bcoca/ansible
test/lib/ansible_test/_util/controller/sanity/yamllint/yamllinter.py
Python
gpl-3.0
8,386
0.002146
"""Wrapper around yamllint that supports YAML embedded in Ansible modules.""" from __future__ import annotations import ast import json import os import re import sys import typing as t import yaml from yaml.resolver import Resolver from yaml.constructor import SafeConstructor from yaml.error import MarkedYAMLError f...
if not module_ast: return {} is_plugin = path.startswith('lib/ansible/modules/') or path.startswith('lib/ansible/plugins/') or path.startswith('plugins/') is_doc_fragment = path.startswith('lib/ansible/plugins/doc_fragments/') or path.startswith('plugins/do
c_fragments/') if is_plugin and not is_doc_fragment: for body_statement in module_ast.body: if isinstance(body_statement, ast.Assign): check_assignment(body_statement, module_doc_types) elif is_doc_fragment: for body_statement in module_ast.bo...
edouard-lopez/django-learner
django_learner/settings/local.py
Python
bsd-3-clause
279
0
from .base import * # noqa DEBUG = True # Databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'd
jango_learner', 'USER': 'django_learner', 'PASSWORD': 'admin', 'HOST': 'localhost' } }
borni-dhifi/vatnumber
vatnumber/__init__.py
Python
gpl-3.0
8,864
0.000451
#This file is part of vatnumber. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' Check the VAT number depending of the country based on formula from http://sima-pc.com/nif.php (dead link, was http://web.archive.org/web/20120118023804/http://sima-pc.com...
''' Check Germany VAT number. ''' import stdnum.de
.vat return stdnum.de.vat.is_valid(vat) def check_vat_dk(vat): ''' Check Denmark VAT number. ''' import stdnum.dk.cvr return stdnum.dk.cvr.is_valid(vat) def check_vat_ee(vat): ''' Check Estonia VAT number. ''' import stdnum.ee.kmkr return stdnum.ee.kmkr.is_valid(vat) de...
akrherz/iem
htdocs/plotting/auto/scripts200/p215.py
Python
mit
7,271
0
"""KDE of Temps.""" import calendar from datetime import date, datetime import pandas as pd from pyiem.plot.util import fitbox from pyiem.plot import figure from pyiem.util import get_autoplot_context, get_sqlalchemy_conn from pyiem.exceptions import NoDataFound from matplotlib.ticker import MaxNLocator from scipy.sta...
("dec", "December"), ] ) def get_description(): """Return a dict d
escribing how to call this plotter""" desc = {} desc["cache"] = 3600 desc["data"] = True desc[ "description" ] = """This autoplot generates some metrics on the distribution of temps over a given period of years. The plotted distribution in the upper panel is using a guassian kernel ...
peterseymour/django-storages-1.1.8
storages/tests/s3boto.py
Python
bsd-3-clause
8,692
0.001266
import os import mock from uuid import uuid4 from urllib.request import urlopen import datetime from django.test import TestCase from django.core.files.base import ContentFile from django.conf import settings from django.core.files.storage import FileSystemStorage from boto.s3.key import Key from storag...
filename, files)) def test_storage_listdir_subdir(self): file_names = ["some/path/1.txt", "some/2.txt"] self.storage.bucket.list.return_value = [] for p in file_names:
key = mock.MagicMock(spec=Key) key.name = p self.storage.bucket.list.return_value.append(key) dirs, files = self.storage.listdir("some/") self.assertEqual(len(dirs), 1) self.assertTrue('path' in dirs, """ "path" not in director...
shimpe/pyvectortween
examples/example_pointandcoloranimation.py
Python
mit
3,258
0.003069
if __name__ == "__main__": import gizeh import moviepy.editor as mpy from vectortween.TimeConversion import TimeConversion from vectortween.PointAnimation import PointAnimation from vectortween.ColorAnimation import ColorAnimation W, H = 250, 250 # width, height, in pixels duration = 10 ...
(0 + 75, 100 + 75), tween=['easeOutElastic', 0.1, 0.5]) p3 = PointAnimation((100 + 75 + 10, 0 + 75 + 10), (0 + 75 + 10, 100 + 75 + 10), tween=['easeOutCubic']) c = ColorAnimation((1, 0, 0), ...
0.3, 0.6, 0.2), tween=['easeOutElastic', 0.1, 0.1]) surface = gizeh.Surface(W, H) f = p.make_frame(frame=tc.sec2frame(t, fps), birthframe=None, startframe=tc.sec2frame(0.2, fps), stopframe=tc.sec2frame...
mpreisler/openscap
release_tools/query-milestones.py
Python
lgpl-2.1
1,404
0
#!/usr/bin/python3 import argparse as ap import shared ACTIONS = dict() def action(key): def wrapper(function): ACTIONS[key] = function return function return wrapper def get_closed_issues(repo, milestone): issues_and_prs = repo.get_issues(milestone=milestone, state="closed") iss...
: issues_and_prs = repo.get_issues(milestone=milestone, state="closed") prs_only = [i for i in issues_and_prs if i.pull_request is not None] return prs_only @action("issues-closed") def print_closed_issues(repo, milestone): for issue in get_closed_issues(repo, milestone): print(issue.title) ...
ne): for pr in get_closed_prs(repo, milestone): print(pr.title) def create_parser(): parser = ap.ArgumentParser() parser.add_argument("version", type=shared.version_type) parser.add_argument("what", choices=(ACTIONS.keys())) shared.update_parser_with_common_stuff(parser) return parser ...
msbeta/apollo
scripts/record_map_data.py
Python
apache-2.0
6,330
0.001106
#!/usr/bin/env python3 ############################################################################### # Copyright 2018 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
se, action="store_true", help='Start recorder. It is the default ' 'action if no other actions are triggered. In ' 'that case, the False value is ignored.') self.parser.add_argument('--stop', default=False, action...
rue", help='Stop recorder.') self.parser.add_argument('--split_duration', default="1m", help='Duration to split bags, will be applied ' 'as parameter to "rosbag record --duration".') self._args = None ...
mibanescu/pulp
server/test/unit/server/db/test_model.py
Python
gpl-2.0
22,379
0.00219
# -*- coding: utf-8 -*- """ Tests for the pulp.server.db.model module. """ from mock import patch, Mock from mongoengine import ValidationError, DateTimeField, DictField, Document, IntField, StringField from pulp.common import error_codes, dateutils from pulp.common.compat import unittest from pulp.server.exception...
ass ContentUnitHelper(model.ContentUnit): apple = StringField() pear = StringField() unit_key_fields = ('apple', 'pear') unit_type_id = StringField(default='bar') my_unit = ContentUnitHelper(apple='apple', pear='pear') ret = my_unit.to_id_dic
t() expected_dict = {'unit_key': {'pear': u'pear', 'apple': u'apple'}, 'type_id': 'bar'} self.assertEqual(ret, expected_dict) def test_type_id(self): class ContentUnitHelper(model.ContentUnit): unit_type_id = StringField() my_unit = ContentUnitHelper(unit_type_id='apple'...
pmisik/buildbot
master/buildbot/test/util/querylog.py
Python
gpl-2.0
3,257
0.000614
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
og.msg(f"{record.name}:{record.threadName}:result: {record.getMessage()}") else: log.msg(f"{record.name}:{record.threadName}:query: {record.getMessage()}") def start_log_queries(log_query_result=False, record_mode=False): handler = _QueryToTwistedHandler( log_query_result=log_query_re...
ging.getLogger('sqlalchemy.engine') # TODO: this is not documented field of logger, so it's probably private. handler.prev_level = logger.level logger.setLevel(logging.DEBUG) logger.addHandler(handler) # Do not propagate SQL echoing into ancestor handlers handler.prev_propagate = logger.propa...