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
anhstudios/swganh
data/scripts/templates/object/tangible/wearables/armor/padded/shared_armor_padded_s01_gloves.py
Python
mit
487
0.045175
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy
.object import * def create(kernel): result = Tangible() result.template = "object/tangible/wearables/armor/padded/shared_armor_padded_s01_gloves.iff" result.attribute_template_i
d = 0 result.stfName("wearables_name","armor_padded_s01_gloves") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
benob/chainer
chainer/functions/array/cast.py
Python
mit
787
0
from chainer import function from chainer.utils import type_check class Cast(function.Function): """Cast function.""" def __init__(self, typ): self.type = typ def check_type_forward(self, in_types): type_check.expect(in_types.size() == 1) x_type = in_types[0]
type_check.expect(x_type.dtype.kind == 'f') def forward(self, x): return x[0].astype(self.type), def backward(self, x, g): return g[0].astype(x[0].dtype.type), def cast(x, typ): """Cast an input variable to a given type. Args: x (~chainer.Variable): Input variable.
typ (str of dtype): Typecode or data type to cast. Returns: ~chainer.Variable: Variable holding a casted array. """ return Cast(typ)(x)
adamcharnock/swiftwind
swiftwind/transactions/apps.py
Python
mit
99
0
from django.apps import
Ap
pConfig class TransactionsConfig(AppConfig): name = 'transactions'
AllMyChanges/allmychanges.com
allmychanges/models.py
Python
bsd-2-clause
55,463
0.001732
# -*- coding: utf-8 -*- import os import requests import time import math import datetime import random import envoy import jsonfield import logging import urllib from collections import defaultdict from magic_repr import make_repr from hashlib import md5, sha1 from django.db import models from django.db.models import...
url=
url, username=username, email=email)) return self._create_user(username, email, password, **extra_fields) def active_users(self, interval): """Outputs only users who was active in last `interval` days. """ after = timezone.now...
NECCSiPortal/NECCSPortal-dashboard
nec_portal/dashboards/admin/log_management/tables.py
Python
apache-2.0
731
0
# -*- coding: utf-8 -*- # 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 requir
ed by applicable 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. # from horizon...
dot-cat/dotcat_platform
dpl/core/things/thing_registry.py
Python
mit
2,876
0.003106
from dpl.core.things import Thing, ThingFactory class ThingRegistry(object): """ Класс (Singleton по задумке), который хранит список фабрик для всех импортированных соединений """ __reg = dict() # type: dict[str, dict[type, ThingFactory]] @classmethod def register_factory(cls, type_alias...
type_reg[con_type] = factory @classmethod def resolve_factory(cls, type_alias: str, con_type: type, default=None) -> ThingFactory: """ Получение объекта-фабрики по псевдониму типа вещи и типу соединения :param type_alias: псевдоним типа объекта, который используется в конфиг-файлах ...
= cls.__reg.get(type_alias) if type_reg is None: return default return type_reg.get(con_type, default) @classmethod def has_type(cls, type_alias: str) -> bool: """ Проверка на наличие зарегистрированного типа :param type_alias: псевдоним типа объекта ...
SpaceGroupUCL/qgisSpaceSyntaxToolkit
esstoolkit/external/networkx/algorithms/centrality/tests/test_closeness_centrality.py
Python
gpl-3.0
10,220
0.000489
""" Tests for closeness centrality. """ import pytest import networkx as nx from networkx.testing import almost_equal class TestClosenessCentrality: @classmethod def setup_class(cls): cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 ...
.P4, nx.path_graph([4, 5, 6])) c = nx.closeness_centrality(G) cwf = nx.closeness_centrality(G, wf_improved=False) res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222}
wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667} for n in G: assert almost_equal(c[n], res[n], places=3) assert almost_equal(cwf[n], wf_res[n], places=3) def test_digraph(self): G = nx.path_graph(3, create_using=nx.DiGraph()) c = nx.clos...
oneman/xmms2-oneman-old
wafadmin/Tools/perl.py
Python
lgpl-2.1
3,665
0.027012
#!/usr/bin/env python # encoding: utf-8 # andersg at 0x63.nu 2007 import os import Task, Options, Utils from Configure import conf from TaskGen import extension, taskgen, feature, before xsubpp_str = '${PERL} ${XSUBPP} -noprototypes -typemap ${EXTUTILS_TYPEMAP} ${SRC} > ${TGT}' EXT_XS = ['.xs'] @before('apply_incpat...
PERL']: return False perl = conf.env['PERL'] def read_out(cmd): return Utils.to_list(Utils.cmd_output(perl + cmd)) conf.env["LINKFLAGS_PERLEXT"] = read_out(" -MConfig -e'print $Config{lddlflags}'") conf.env["CPPPATH_PERLEXT"] = read_out(" -MConfig -e'print \"$Config{archlib}/CORE\"'") conf.env["CCFLAGS_PERL...
PP"] = read_out(" -MConfig -e'print \"$Config{privlib}/ExtUtils/xsubpp$Config{exe_ext}\"'") conf.env["EXTUTILS_TYPEMAP"] = read_out(" -MConfig -e'print \"$Config{privlib}/ExtUtils/typemap\"'") if not getattr(Options.options, 'perlarchdir', None): conf.env["ARCHDIR_PERL"] = Utils.cmd_output(perl + " -MConfig -e'pri...
agronholm/apscheduler
src/apscheduler/triggers/cron/fields.py
Python
mit
4,680
0.002564
"""Fields represent CronTrigger options which map to :class:`~datetime.datetime` fields.""" from __future__ import annotations import re from calendar import monthrange from datetime import datetime from typing import Any, ClassVar, Sequence from .expressions import ( WEEKDAYS, AllExpression, LastDayOfMonthExpres...
angeExpression, WeekdayPositionExpression, WeekdayRangeExpression, get_weekday_index) MIN_VALUES = {'year': 1970, 'month': 1, 'day': 1, 'week': 1, 'day_of_week': 0, 'hour': 0,
'minute': 0, 'second': 0} MAX_VALUES = {'year': 9999, 'month': 12, 'day': 31, 'week': 53, 'day_of_week': 7, 'hour': 23, 'minute': 59, 'second': 59} DEFAULT_VALUES = {'year': '*', 'month': 1, 'day': 1, 'week': '*', 'day_of_week': '*', 'hour': 0, 'minute': 0, 'second': 0} SEPAR...
crtarsorg/glasomer.rs-v2
app/mod_main/views.py
Python
cc0-1.0
17,233
0.010969
# coding=utf-8 from app import mongo_utils from bson import json_util from flask import Blueprint, render_template, request, Response,session import json import time from datetime import datetime from operator import itemgetter mod_main = Blueprint('main', __name__) @mod_main.route('/', methods=['GET']) def index(): ...
, count_questions=count_questions) return Response(response=json_util.dumps(result), status=200, mimetype='application/json') @mod_main.route('/getuseranswerresults', methods=['GET', "POST"]) def get_user_answers_results(): if request.method == 'POST': data = request.form.to_dict() user_id = d...
n.loads(json_util.dumps(project_enabled)): docs = mongo_utils.find_all(project['year']) project_year=project['year'] result = mongo_utils.find_user_session_answers(project_year,user_id) return Response(response=json_util.dumps(result), status=200, mimetype='application/json') @mod_mai...
GoogleCloudPlatform/professional-services
tools/ml-auto-eda/ml_eda/constants.py
Python
apache-2.0
2,235
0.000895
# Copyright 2019 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 ...
MERICAL_FEATURES = 'NumericalFeatures' c.schema.CATEGORICAL_FEATURES = 'CategoricalFeatures' c.ANALYSIS_RUN = 'ANALYSIS.RUN' c.analysis_run.CONTINGENCY_TABLE_RUN = 'CONTINGENCY_TABLE.Run' c.analysis_run.TABLE_DESCRIPTIVE_RUN = 'TABLE_DESCRIPTIVE.Run' c.analysis_run.PEARSON_CORRELATION_RUN = 'PEARSON_CORRELATION.Run'
c.analysis_run.INFORMATION_GAIN_RUN = 'INFORMATION_GAIN.Run' c.analysis_run.CHI_SQUARE_RUN = 'CHI_SQUARE.Run' c.analysis_run.ANOVA_RUN = 'ANOVA.Run' c.ANALYSIS_CONFIG = 'ANALYSIS.CONFIG' c.analysis_config.HISTOGRAM_BIN = 'HISTOGRAM.Bin' c.analysis_config.VALUE_COUNTS_LIMIT = 'VALUE_COUNTS.Limit' c.analysis_config.GEN...
fgmacedo/raspador
raspador/cache.py
Python
mit
566
0
# coding: utf-8 from collections import deque class Ca
che(object): def __init__(self, max_length=0): self.max_length = max_length self._items = deque() def __len__(self): return len(self._items) def append(self
, item): self._items.append(item) if self.max_length: while len(self._items) > self.max_length: self._items.popleft() @property def items(self): return self._items def consume(self): while self._items: yield self._items.popleft()
adamtheturtle/boggle-solver
boggle/tests/test_boggle.py
Python
mit
8,539
0
""" Tests for a Boggle solver. """ import unittest import io import os import json from tempfile import mkstemp from textwrap import dedent from boggle.boggle import Board, Boggle, Language, Word, Position class LanguageTests(unittest.TestCase): """ Tests for `Language`. """ def test_words(self): ...
# Second on left of first. position.touching(Position(column=0, row=1)), # Second above first. position.touching(Position(column=1, row=0)), # Second below first. position.touching(Position(column=1, row=2)), ], ...
oubiwann/openpix
openpix/command/base.py
Python
lgpl-2.1
5,056
0.000593
import inspect from zope.interface import implements from pyparsing import MatchFirst from openpix import interfaces from openpix import util from openpix.util import oneOfCaseless commandClasses = {} subcCommandClasses = {} def getModules(subpackage): """ Get all the modules in a given subpackage. "...
by subclasses. """ raise NotImplementedError def getCommandName(self): """ """ return self.__class__.__name__.replace('Command', '').lower() def getDesc(self): """ """ return self.__doc__.strip() def getUsage(se
lf): """ """ return self.usage.strip() % self.getCommandName() def printShortHelp(self): """ """ print "\n %s\n\n %s\n" % (self.getSummary(), self.getUsage()) def getSyntax(self): """ """ return self.syntax def getSummary(self):...
jabbalaci/jabbapylib
jabbapylib/mail/gmail_send.py
Python
gpl-3.0
3,426
0.003503
#!/usr/bin/env python """ Send an email via Gmail either as a text or as an HTML. # from jabbapylib.mail import gmail_send """ import os import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders def mail_text(send...
msg.attach(part) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(sender['gmail_user'], sender['gmail_pwd']) #mailServer.sendmail(gmail_user, to, msg.as_string()) # just e-mail address in the From: field mailSe
rver.sendmail(sender['gmail_name'], to, msg.as_string()) # name + e-mail address in the From: field mailServer.close() def mail_html(sender, to, subject, html, attach=None): """ Send an HTML mail via gmail. It can also send an attachment. "sender" is a dictionary with these keys: - gmail_us...
wmarshall484/streamsx.topology
com.ibm.streamsx.topology/opt/python/packages/streamsx/rest_primitives.py
Python
apache-2.0
66,776
0.004283
# coding=utf-8 # Licensed Materials - Property of IBM # Copyright IBM Corp. 2016,2017 """ Primitive objects for REST bindings. ******** Overview ******** Contains classes representing primitive Streams objects, such as :py:class:`Instance`, :py:class:`Job`, :py:class:`PE`, etc. """ from future.builtins import * im...
file.write(chunk) except IOError as e: logger.error("IOError({0}) writing application log files: {1}".format(e.errno,
e.strerror)) raise e except Exception as e: logger.error("Error while writing application log files") raise e return path def __str__(self): return pformat(self.__dict__) class _IAMStreamsRestClient(_StreamsRestClient): """Handles the session conn...
NERC-CEH/ecomaps
ecomaps/model/create_new_user_form.py
Python
gpl-2.0
639
0.00313
import formencode __author__ = 'Chirag Mistry (Tessella)' class UpdateUserForm(formencode.Schema): allow_extra_fields = True filter_extra_fields = False first_name = formencode.validators.String(not_empty=True, max=50) last_name = formencode.validators.String(not_empty=True, max=50) email = for...
e.validators.Bool() class CreateUserForm(UpdateUserForm): """Used to validate data from the Create New User page""" allow_extra_fields = False filter_extra_fields =
True user_name = formencode.validators.String(not_empty=True)
caglar10ur/func
func/minion/modules/nm/vservermanager.py
Python
gpl-2.0
3,354
0.00477
# This software may be freely redistributed under the terms of the GNU # general public license. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. import os import sys import v...
liceTag(slice, tag["tagname"], tag["value"]) bwlimit.set(bwlimit.get
_xid(slice)) self.__startSlice__(slice) else: return False return True def DeleteSliceFromNode(self, slice): logger.log_call(["/bin/bash", "-x", "/usr/sbin/vuserdel", slice]) return True
slswee/google_python_exercise
basic/helloworld.py
Python
apache-2.0
60
0.05
#
!/usr/bin/python2.7 -tt import sys
def Cat(filename):
atareao/calendar-indicator
src/loginoption.py
Python
gpl-3.0
3,654
0.006021
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Calendar-Indicator # # Copyright (C) 2011-2019 Lorenzo Carbonell Cerezo # lorenzo.carbonell.cerezo@gmail.com # # 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 Softw...
rmissions for Googl
e Calendar'), _('Enable read and write permissions for Google Calendar.'), self.switch1)) self.switch1.set_active(os.path.exists(comun.TOKEN_FILE)) def on_switch1_changed(self,widget,data): if self.switch1.get_active(): if os.path.exists(...
ellmetha/mtlmurals
tests/pytests/unit/common/test_text.py
Python
mit
180
0.005556
# -*- coding: utf-8 -*- from mt
lmurals.common.text import replace def test
_replace(): assert replace('this ; is a | test', (';', '-'), ('|', '--')) == 'this - is a -- test'
gdimitris/FleetManagerBackend
virtual_env/lib/python2.7/site-packages/flask_cache/__init__.py
Python
mit
24,578
0.00175
# -*- coding: utf-8 -*- """ flask.ext.cache ~~~~~~~~~~~~~~ Adds cache support to your application. :copyright: (c) 2010 by Thadeus Burgess. :license: BSD, see LICENSE for more details """ __version__ = '0.13.1' __versionfull__ = __version__ import base64 import functools import hashlib import in...
ngs.warn("Flask-Cache: CACHE_TYPE is set to null, " "caching is effectively disabled.") if self.with_jinja2_ext: from .jinja2ext import CacheExtension, JINJA_CACHE_ATTR_NAME setattr(app.jinja_env, JINJA_CACHE_ATTR_NAME, self) app.jinja_env.add_exte...
xtension) self._set_cache(app, config) def _set_cache(self, app, config): import_me = config['CACHE_TYPE'] if '.' not in import_me: from . import backends try: cache_obj = getattr(backends, import_me) except AttributeError: ...
stevearc/pypicloud
tests/test_admin.py
Python
mit
7,357
0.000544
""" Tests for admin endpoints """ from mock import MagicMock from pyramid.httpexceptions import HTTPBadRequest from pypicloud.views.admin import AdminEndpoints from . import MockServerTest class TestAdmin(MockServerTest): """Tests for admin endpoints""" def setUp(self): super(TestAdmin, self).setU...
self.assertEqual(ret, self.access.user_package_permissions()) def test_get_group(self): """Get a group's members and permissions""" self.request.named_subpaths = {"group": "a"} ret = AdminEndpoints(self.request).get_group() self.access.group_members.assert_called_with("a") ...
bers": self.access.group_members(), "packages": self.access.group_package_permissions(), }, ) def test_get_package_permissions(self): """Get user and group permissions for a package""" self.request.named_subpaths = {"package": "a"} self.access.user_permis...
barche/k3d
tests/bitmap/bitmap.modifier.BenchmarkComparison.py
Python
gpl-2.0
647
0.018547
#python import benchmarking # a test to compare the benchmark results for a number of bitmap plugins compare_list = ["BitmapAdd", "BitmapSubtract", "BitmapMultiply", "BitmapColorMonochrome", "BitmapGamma", "BitmapInvert",
"BitmapMatteColorDiff", "BitmapMatteInvert", "BitmapThreshold"] for run in compare_list: try: benchmarking.generate_comparis
on_image(run, (run, "CUDA"+run), plotLabels=('Number of Pixels', 'Time [s]'), calculate_speedup = True) except: print "Error with: " + run
icbat/happiness-meter
api/server_test.py
Python
mit
5,113
0.009779
import server from bson.json_util import loads def list_data_test_no_data(): response = server.list_data(MockDB()) assert response == "[]" def list_data_test_one_datum(): data = [ {"username" : "barney", "emotion" : "2"} ] response = server.list_data(MockDB(data)) response = loads(re...
ty(): result = server.count_data([])
assert result == {} def count_data_test_one_point(): result = server.count_data([1]) assert result == {1: 1} def count_data_test_multiple_instances_of_a_point(): result = server.count_data([1, 1]) assert result == {1: 2} def count_data_test_multiple_instances_of_a_point(): result = server.count...
huangkuan/hack
lib/gcloud/pubsub/test_client.py
Python
apache-2.0
8,655
0
# 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 a...
self.assertEqual(len(subscriptions), 1) self.assertIsInstance(subscriptions[0], Subscription) self.assertEqual(subscriptions[0].name, self.SUB_NAME) self.assertEqual(subscriptions[0].topic.name, self.TOPIC_NAME) self.assertEqual(subscriptions[0].ack_deadline, ACK_DEADLINE) ...
push_endpoint, PUSH_ENDPOINT) self.assertEqual(next_page_token, TOKEN2) self.assertEqual(api._listed_subscriptions, (self.PROJECT, SIZE, TOKEN1)) def test_list_subscriptions_w_missing_key(self): PROJECT = 'PROJECT' creds = _Credentials() client = s...
Jumpscale/jumpscale6_core
apps/gridportal/tests/jpackagesRest__test.py
Python
bsd-2-clause
1,238
0.023425
from JumpScale import j import unittest import JumpScale.portal descr = """ test jpackages over rest to portal (appserver) """ organization = "jumpscale" author = "kristof@incubaid.com" license = "bsd" version = "1.0" category = "appserver.jpackages.rest,portal" enable=True priority=5 class TEST(unittest.TestCase):...
.application.whoAmI.nid) print l1 l2=self.actor.getJPackages(j.application.whoAmI.nid,"jumpscale") print l2 def test_getJpackageInfo(self): jp=self.actor.getJPackageInfo(j.application.whoAmI.nid,"jumpscale","osis") print jp
def test_getJpackageFilesInfo(self): info=self.actor.getJPackageFilesInfo(j.application.whoAmI.nid,"jumpscale","osis") # print info def test_action(self): info=self.actor.action(j.application.whoAmI.nid,domain="jumpscale",pname="osis",action="start") print info #@to...
Laurawly/tvm-1
python/tvm/contrib/mkldnn.py
Python
apache-2.0
1,715
0.000583
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed w
ith 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 this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/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. """External function interface to BLAS libraries.""" import tvm from tvm import te def matmul(lhs, r...
jantman/python-obd
SpeedMeter.py
Python
gpl-3.0
81,844
0.006036
# -*- coding: iso-8859-1 -*- # --------------------------------------------------------------------------- # # SPEEDMETER Control wxPython IMPLEMENTATION # Python Code By: # # Andrea Gavana, @ 25 Sep 2005 # Latest Revision: 10 Oct 2005, 22.40 CET # # # TODO List/Caveats # # 1. Combination Of The Two Styles: # # SM_D...
----------- # Event Binding #--
-------------------------------------------------------------------- # SM_MOUSE_TRACK: The Mouse Left Click/Drag Allow You To Change The # SpeedMeter Value Interactively SM_MOUSE_TRACK = 1 LINE1 = 1 LINE2 = 2 LINE3 = 4 LINE4 = 8 LINE5 = 16 LINE6 = 32 LINE7 = 64 DECIMALSIGN = 128 DIGIT0 = LINE1 | LINE...
biotty/rmg
graphics/py/edseq.py
Python
bsd-2-clause
3,127
0.005117
#!/usr/bin/env python3 # # (c) Christian Sommerfeldt OEien # All rights reserved import itertools import sys, os def extrapatt(patt): if "%" in patt: return patt else: return patt + "%d.jpeg" class FileSeq: def __init__(self, patt): self.patt = extrapatt(patt) self.count = sel...
os.symlink(orig.path(i), target.newpath()) elif sys.argv[2] == "pad": orig = FileSeq(sys.argv[4])
startn, endn = sys.argv[3].split(",") for _ in range(int(startn)): os.symlink(orig.path(0), target.newpath()) for i in range(orig.count): os.symlink(orig.path(i), target.newpath()) for _ in range(int(endn)): os.symlink(orig.path(orig.count - 1), target.newpath()) elif sys.argv[2] ==...
COOLMASON/arrows
arrows/candidates.py
Python
mit
113
0
bs = u'Bernie
Sanders' hc = u'Hillary Clinton' jb = u'Jeb Bush' rp = u'Rand Paul' candidates =
[bs, hc, jb, rp]
wangshiphys/HamiltonianPy
HamiltonianPy/tests/unit/test_indextable.py
Python
gpl-3.0
1,978
0
""" A test script for the `indextable` module """ from random import randrange import pytest from HamiltonianPy.indextable import IndexTable class TestIndexTable: def test_init(self): match0 = r"unhashable type" match1 = r"The .* has different type from the previous ones" mat
ch2 = r"The .* object already exists" with pytest.raises(TypeError, match=match0): IndexTable([[0, 1], [2, 3]]) with pytest.raises(TypeError, match=match1): IndexTable([(0, 1), "ab
"]) with pytest.raises(ValueError, match=match2): IndexTable([(0, 1), (2, 3), (0, 1)]) def test_object_type(self): table = IndexTable((x, y) for x in range(4) for y in range(4)) assert table.object_type is tuple def test_str_and_iteration(self): separator = "*" * 80...
svidela/pyzcasp
setup.py
Python
gpl-3.0
2,214
0.004065
# Copyright (c) 2014, Santiago Videla # # This file is part of pyzcasp. # # caspo 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 lat
er version. # # caspo 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 have received a copy of the GNU General Public License #...
If not, see <http://www.gnu.org/licenses/>. # -*- coding: utf-8 -*- from setuptools import setup, find_packages import sys, os version = '1.0.2dev' long_desc = """ This package provides a framework to build on top of Answer Set Programming tools using the Zope Component Architecture. For more details on available f...
PanDAWMS/panda-harvester
pandaharvester/harvesterstager/yoda_rucio_rse_direct_stager.py
Python
apache-2.0
23,712
0.009025
import time import datetime import uuid import os import sys import stat import os.path import threading import tarfile import hashlib import string import shutil import errno from future.utils import iteritems from rucio.client import Client as RucioClient from rucio.common.exception import DataIdentifierNotFound, D...
ater' # loop over the Rucio rules for rucioRule in groups: if rucioRule is None: continue # lock have_db_lock = self.dbInterface.get_object_lock(rucioRule, lock_interval=120) if not have_db_lock: msgStr = '
escape since {0} is locked by another thread'.format(rucioRule) tmpLog.debug(msgStr) return None, msgStr # get transfer status groupStatus = self.dbInterface.get_file_group_status(rucioRule) tmpLog.debug('rucioRule - {0} - groupStatus - {1}'.format(ruc...
opsolutely/flask-nginx-starter
app/config.py
Python
gpl-3.0
1,274
0.003925
import os CSRF_ENABLED = True ENV = os.environ.get('ENVIRONMENT', 'dev') MODEL_HASH = os.environ.get('MODEL_HASH') PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) ROOT_PATH = BASE_DIR = os.path.join(os.path.dirname(__file__), '..') SECRET_KEY = os.environ.get('SECRET_KEY') STATIC_FOLDER
= os.path.join(ROOT_PATH, 'static') TEMPLATE_FOLDER = os.path.join(ROOT_PATH, 'templates') SQLALCHEMY_MIGRATE_REPO = os.path.join(ROOT_PATH, 'db_repository') if ENV == 'dev': PORT = 7070 APP_BASE_LINK = 'http://localhost:{}'.format(PORT) DEBUG = True SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/d...
resql://{}:{}@{}:{}/{}'.format(os.environ.get('POSTGRES_ENV_POSTGRES_USER'), os.environ.get('POSTGRES_ENV_POSTGRES_PASSWORD'), os.environ.get('POSTGRES_PORT_5432_TCP_ADDR'), ...
minghuascode/pyj
library/pyjslib.PyV8.py
Python
apache-2.0
10,519
0.001901
# pyv8_print_fn is actually in pyv8run.py and is added to the Globals def printFunc(objs, newline): JS(""" var s = ""; for(var i=0; i < @{{objs}}.length; i++) { if(s != "") s += " "; s += @{{objs}}[i]; } @{{pyv8_print_fn}}(s); """) # pyv8_import_modu...
module = pyv8_import_module(parent_name, module_name) module.__was_initialized__ = True JS("""$pyjs.modules_hash[@{{importName}}] = @{{module}}""") importName += '.' name = names[0] JS("""$pyjs.modules[@{{name}}] = $pyjs.modules_hash[@{{name}}];""") return None # FIX...
d_module and it's always "async" @noSourceTracking def load_module(path, parent_module, module_name, dynamic=1, async=False): """ """ JS(""" var cache_file; var module = $pyjs.modules_hash[@{{module_name}}]; if (typeof module == 'function') { return true; } ...
fujicoin/electrum-fjc
electrum/contacts.py
Python
mit
4,481
0.000893
# Electrum - Lightweight Fujicoin Client # Copyright (c) 2015 Thomas Voegtlin # # 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 ...
IED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CON...
HE # SOFTWARE. import re import dns from dns.exception import DNSException from . import bitcoin from . import dnssec from .util import export_meta, import_meta, to_string from .logging import Logger class Contacts(dict, Logger): def __init__(self, storage): Logger.__init__(self) self.storage =...
google/layered-scene-inference
lsi/nnutils/helpers.py
Python
apache-2.0
6,450
0.007442
#!/usr/bin/python # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
ars_all: optional list of the vari
able superset Returns: restorer: object on which we should call restore(sess, save_file) """ if vars_all is None: vars_all = tf.global_variables() reader = tf.train.NewCheckpointReader(save_file) saved_shapes = reader.get_variable_to_shape_map() var_names = sorted([(var.name, var.name.split(':')[0]...
JoaoFelipe/snowballing
snowballing/bibtex/database/__init__.py
Python
mit
23,508
0.005913
import os import textwrap from pathlib import Path from string import ascii_lowercase from copy import copy from selenium import webdriver from IPython.display import HTML from bibtexparser.customization import homogenize_latex_encoding from snowballing import config from snowballing.collection_helpers import define_...
words", "options", "ids", # Related "related", "relatedtype", "relatedstring", # Data "entryset", "crossref", "xref", "xdata", # Lang "langid", "langidopts", "gender", # Sorting "presort", "sortkey", "sortname", "sortshorthand", "shorttitle", "indexsorttitle", "sortyear", ] ## Igno...
div", "_pyref", "_work_type", "_ref", "_scholar", "_scholar_id", "_scholar_ok", "_cluster_id", "_citation_id", "_prefix", "_link", "_tyear", "_draw", # Custom "_note", "_due", "_url", # Approach "_display", "_approach_name", ] ### Transformation Rules ## Map BibTex to Info object config...
apache/aurora
src/test/python/apache/aurora/client/cli/test_cron.py
Python
apache-2.0
8,687
0.010821
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under ...
n_value
= self.create_simple_success_response() cmd = AuroraCommandLine() result = cmd.execute(['cron', 'start', 'west/bozo/test/hello']) assert result == EXIT_OK api.start_cronjob.assert_called_once_with(self.TEST_JOBKEY, config=None) def test_start_cron_open_browser(self): mock_context = FakeAu...
simphony/simphony-openfoam
foam_controlwrapper/examples/dahl_rel_vel.py
Python
gpl-2.0
6,807
0
"""Example to solve mixture model """ import foam_controlwrapper from simphony.core.cuba import CUBA from simphony.api import CUDS, Simulation from simphony.cuds.meta import api from simphony.engine import EngineInterface from mayavi.scripts import mayavi2 import dahl_mesh import tempfile case_name = 'dahl' mesh_na...
udge').uid cuds.add([mm]) # use Bingham plastic for sludge rheology model bp = api.BinghamPlasticModel(name='sludge_rheology') bp.linear_constant = (0.00023143, 0.0005966) bp.power_law_index = (179.26, 1050.8) bp.maximum_viscosity = 10.0 bp.material = cuds.get_by_name('sludge').uid # water is Newtonian so no need to ...
.MesoscopicRelativeVelocityModel(name='meso_rel_vel_model') cuds.add([rvm]) gm = api.GravityModel(name='gravitation') gm.acceleration = (0, -9.81, 0) cuds.add([gm]) vel_inlet = api.Dirichlet(water, name='vel_inlet') vel_inlet.data[CUBA.VARIABLE] = CUBA.VELOCITY vel_inlet.data[CUBA.VELOCITY] = (0.0191, 0, 0) pres_inle...
hvwaldow/inktex
inktex/ui.py
Python
mit
8,707
0.002297
import os import pygtk pygtk.require('2.0') import gtk from gtkcodebuffer import CodeBuffer, SyntaxLoader class Ui(object): """ The user interface. This dialog is the LaTeX input window and includes widgets to display compilation logs and a preview. It uses GTK2 which must be installed an importable...
pacings(8) self.settings_container.show() self.label_preamble = gtk.Label("Preamble") self.label_preamble.set_alignment(0, 0.5) self.label_preamble.show() self.preamble = gtk.FileChooserButton("...") if 'preamble' in self.settings and os.path.exists(self.settings['preamb...
f.settings['preamble']) self.preamble.set_action(gtk.FILE_CHOOSER_ACTION_OPEN) self.preamble.show() self.settings_container.attach(self.label_preamble, yoptions=gtk.SHRINK, left_attach=0, right_attach=1, top_attach=0, bottom_attach=1) self.settings_container.attach(self.pream...
refeed/coala-bears
bears/typescript/TSLintBear.py
Python
agpl-3.0
2,040
0
import json from coalib.bearlib.abstractions.Linter import linter from dependency_management.requirements.NpmRequirement import NpmRequirement from coalib.results.Result import Result from coalib.settings.Setting import path @linter(executable='tslint') class TSLintBear: """ Check TypeScript code for s
tyle violations and possible semantical problems. Read more about the capabilities at <https://github.com/palantir/tslint#core-rules>. """ LANGUAGES = {'TypeScript'} REQUIREMENTS = {NpmRequirement('tslint', '3'), NpmRequirement('typescript', '>=1.7.3')} AUTHORS = {'The ...
GPL-3.0' ASCIINEMA_URL = 'https://asciinema.org/a/9re9c4fv17lhn7rmvzueebb3b' CAN_DETECT = {'Syntax', 'Formatting', 'Smell'} @staticmethod def create_arguments(filename, file, config_file, tslint_config: path = '', rules_dir: path = '', ...
bqbn/addons-server
src/olympia/translations/tasks.py
Python
bsd-3-clause
504
0.001984
import olympia.core.logger from olympia.amo.celery import task from olympia
.amo.decorators import use_primary_db from olympia.translations.models import NoURLsTranslation log = olympia.core.logger.getLogger('z.task
') @task @use_primary_db def reclean_collection_descriptions(ids, **kw): log.info('Recleaning translation of ids %d-%d [%d].', ids[0], ids[-1], len(ids)) translations = NoURLsTranslation.objects.filter(pk__in=ids) for translation in translations: translation.save()
dhamaniasad/mythbox
resources/itest/test_livetv.py
Python
gpl-2.0
2,961
0.005404
# # MythBox for XBMC - http://mythbox.googlecode.com # Copyright (C) 2009 analogue@yahoo.com # # 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 you...
log.debug(self.brain.getLiveTVStatus()) log.debug('Stopping live tv...') self.brain.onPlayBackStopped() log.debug('all done') def xxxtest_stopAllTuners(self):
tuners = self.conn.getTuners() for t in tuners: if t.tunerId == 5: t.stopLiveTV() # ============================================================================= if __name__ == '__main__': import logging.config logging.config.fileConfig('mythbox_log.ini') unittest.ma...
catapult-project/catapult
tracing/tracing/mre/failure.py
Python
bsd-3-clause
1,876
0.004264
# Copyright 2015 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 tracing.mre import job as job_module class Failure(object): def __init__(self, job, function_handle_string, trace_canonical_url, fai...
nce(job, job_module.Job) self.job = job self.function_handle_string = function_handle_string self.trace_canonical_url = trace_canonical_url self.failure_type_name = failure_type_name self.description = description self.stack = stack def __str__(self): return ( 'Failure for job %s...
_handle_string, self.trace_canonical_url, self.failure_type_name, self.description, self.stack)) def AsDict(self): return { 'job_guid': str(self.job.guid), 'function_handle_string': self.function_handle_string, 'trace_canonical_url': self.trace_canonical_url, ...
alanwill/aws-tailor
sam/functions/talr-entsupport/handler.py
Python
gpl-3.0
4,302
0.000697
# coding: utf-8 from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import boto3 import os import sys import time # Path to modules needed to package local lambda function for upload currentdir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os...
(os.environ['TAILOR_TABLENAME_CBINFO']) incomingMessage = json.loads(event['Records'][0]['Sns']['Message']) accountEmailAddress = incomingMessa
ge['lambda']['accountEmailAddress'] getAccountInfo = accountInfo.get_item( Key={ 'accountEmailAddress': accountEmailAddress } ) laAccountId = getAccountInfo['Item']['accountId'] requestId = getAccountInfo['Item']['requestId'] accountCbAlias = getAccountInfo['Item']['acco...
alephu5/Soundbyte
environment/lib/python3.3/site-packages/IPython/kernel/zmq/tests/test_session.py
Python
gpl-3.0
12,636
0.005935
"""test building messages with streamsession""" #------------------------------------------------------------------------------- # Copyright (C) 2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #-...
Equal(new_msg['header'],msg['header']) self.assertEqual(new_msg['content'],msg['content']) self.assertEqual(new_msg['metadata'],msg['metadata']) self.assertEqual(new_msg['parent_header'],msg['parent_header']) self.assertEqual(new_msg['buffer
s'],[b'bar']) self.session.send(A, msg, ident=b'foo', buffers=[b'bar']) ident, new_msg = self.session.recv(B) self.assertEqual(ident[0], b'foo') self.assertEqual(new_msg['msg_id'],msg['msg_id']) self.assertEqual(new_msg['msg_type'],msg['msg_type']) self.assertEqual(new_m...
eternnoir/PyrserPTT
PyrserPTT/PttHtmlGraber.py
Python
gpl-2.0
1,773
0.003384
#! /usr/bin/env python # -*- coding: utf-8 -*- import cookielib import sys import urllib from BeautifulSoup import BeautifulSoup import mechanize class WebPttBot(object): def __init__(s
elf,board): self._board = board # Browser self._br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() self._br.set_cookiejar(cj) # Browser options self._br.set_handle_equiv(True) self._br.set_handle_redirect(True) self._br.s...
# Follows refresh 0 but not hangs on refresh > 0 self._br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # User-Agent (this is cheating, ok?) self._br.addheaders = [('User-agent', "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1)" ...
uwosh/UWOshMusicRecruiting
Extensions/import_visits.py
Python
gpl-2.0
3,594
0.012521
import csv, os from Products.CMFCore.utils import getToolByName def get_folder(self, type, name): folder_brains = self.queryCatalog({'portal_type':type, 'title':name})[0] return folder_brains.getObject() def cr
eate_object_in_directory(self, container, type): id = container.generateUniqueId(type) container.invokeFactory(id=id, type_name=type) return container[id] def get_type_or_create(self, type, folder, cmp, val): brains = self.queryCatalog({'portal_type':type, cmp:val}) if len(brains) > 0: retu...
].getObject() else: return create_object_in_directory(self, folder, type) def set_reference(self, object, visit): existing_visits = object.getVisits() if visit not in existing_visits: existing_visits.append(visit) object.setVisits(existing_visits) def import_visits(self): read...
DemocracyClub/Website
democracy_club/apps/report_2019/apps.py
Python
bsd-3-clause
96
0
from django.apps import AppConfig class Report2019Config(AppConfi
g):
name = "report_2019"
namespace-ee/django-rest-framework-sso
rest_framework_sso/views.py
Python
mit
4,556
0.001756
# coding: utf-8 from __future__ import absolute_import, unicode_literals from rest_framework import status from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_sso import claims from rest_framework_sso.models i...
st.user ) except SessionToken.DoesNotExist: return Response({"detail": "Invalid token."}, status=status.HTTP_401_UNAUTHORIZED) else: session_token = ( SessionToken.object
s.active().filter(user=request.user).with_user_agent(request=request).first() ) if session_token is None: session_token = SessionToken(user=request.user) session_token.update_attributes(request=request) session_token.save() payload = create_authorization_...
SamuraiT/extensionpy
cythonexample/setup.py
Python
gpl-2.0
447
0.01566
#! /usr/bin/env python #
coding: utf-8 """ Copyright 2
014 Tatsuro Yasukawa. Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext hello_modules = [Extension("hello", ["hello.pyx"])] setup( name = 'Hello cython module', ...
timothycrosley/hug
tests/test_directives.py
Python
mit
7,351
0.003537
"""tests/test_directives.py. Tests to ensure that directives interact in the anticipated manner Copyright (C) 2016 Timothy Edmund Crosley 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 ...
ers" in hug.directives.documentation(api=api) def test_api_version(): """Ensure that it's possible to get the current version of an API based on a directive""" @hug.get(versions=1) def version_tester(hug_api_version): return hug_api_version assert hug.test.get(api, "v1/version_tester").data ...
sure that it's possible to retrieve methods from the same version of the API""" @hug.get(versions=1) def first_method(): return "Success" @hug.get(versions=1) def version_call_tester(hug_current_api): return hug_current_api.first_method() assert hug.test.get(api, "v1/version_call_...
youdar/work
work/Clashes/Old work/submit_clashscore_compare_to_queue.py
Python
mit
2,675
0.029907
from __future__ import division from libtbx.command_line import easy_qsub from misc_scripts import helpers from misc_scripts.r_factor_calc import * from iotbx import pdb import cPickle as pickle import random import os,sys def run(): # convert the path to python format directory_path = '/net/cci/youval/Work/work...
cmd = 'qsub -q all.q@rebus', #qsub_cmd = 'qsub -q all.q@rebus', qsub_cmd = 'qsub -q all.q@morse', size_of_chunks= 300) # because jobs are quick def get_file_names(file_list): ''' returns the list of files that need to be processed ''' #os.chdir('/net/cci-filer2/raid1/home/youva
l/Work/work') results = [] for f in file_list: file_path = find_full_path(f) results.append([file_path,f]) return results def find_full_path(file_name): '''(str) -> str returns the full path a pdb file name in LBL PDB_MIRROR_PDB ''' # change file name to the form in the PDB_MIRROR_PDB f = 'pdb...
jittat/adm2
application/views/status.py
Python
agpl-3.0
21,058
0.00723
# -*- coding: utf-8
-*- from random import randint from datetime import timedelta from django.http import HttpResponseRedirect from django.shortcuts import render_to_response, redirect from django.core.urlresolvers import reverse from
django.conf import settings from commons.decorators import applicant_required from commons.decorators import submitted_applicant_required from commons.utils import submission_deadline_passed, supplement_submission_deadline_passed, admission_major_pref_deadline_passed, round2_confirmation_deadline_passed from commons....
sophilabs/pyconuy-site
pyconuy2012/main/urls.py
Python
mit
497
0.004024
from django.conf.urls import * urlpatterns = patterns('main.views', url(r"^$", 'index', na
me='index'), url(r"^proposal-add$", 'proposal_add', name='proposal_add'), url(r"^proposal-sent$", 'proposal_sent', name='proposal_sent'), url(r"^schedule$", 'schedule', name='schedule'), url(r"^sponsors", 'spons
ors', name='sponsors'), url(r"^speakers", 'speakers', name='speakers'), url(r"^proposals", 'proposals', name='proposals'), url(r"^talks", 'talks', name='talks'), )
mluo613/osf.io
addons/s3/migrations/0001_initial.py
Python
apache-2.0
2,638
0.003412
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-11-01 15:19 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import osf.models.base import osf.utils.datetime_aware_jsonfield class Migration(migrations.Migratio...
=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='addons_s3_user_settings', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='nodesettings', name='us...
True, null=True, on_delete=django.db.models.deletion.CASCADE, to='addons_s3.UserSettings'), ), ]
jimbelton/wikidata
lib/simplify.py
Python
gpl-3.0
1,426
0.008415
# See https://www.wikidata.org/wiki/Special:ListDatatypes for descriptions of the wikidata data types # Simplifies a wikidata time. The result is a either a date or a time (d
ate and time), depending on the precision. Leading + signs # are removed and dates lack the time component, but the types are o
therwise like wikidata times. The properties of the value object # are collapsed into the date or time object. # def time(wdTime): assert wdTime["type"] == "time" wdValue = wdTime["value"] simpleTime = {"type": "time", "value": wdValue["time"][1:] if wdValue["time"].startswith("+") else wdValue["time"]}...
igemsoftware/SYSU-Software2013
project/Python27_32/web/setup.py
Python
mit
232
0.056034
#!
/usr/bin/env python from distutils.core import se
tup, Extension module1 = Extension('graph', sources = ['graph.cpp']) setup (name = 'igem2013', version = '1.0', description = 'This is a demo package', ext_modules = [module1])
keen99/SickRage
sickbeard/clients/__init__.py
Python
gpl-3.0
3,669
0.000545
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
ng error status codes to official W3C names http_error_code = { 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Switch Proxy', 307: 'Temporary Redirect', 308: 'Permanent Redirect', 400: 'Bad Request',...
: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: ...
varoroyo/Alvaro-Roman
web.py
Python
apache-2.0
5,333
0.006378
# Copyright [2017] [name of copyright owner] # 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 ...
def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPENFDA_API_EVENT + '?search
=companynumb:'+com_num+'&limit=10') r1 = conn.getresponse() print(r1.status, r1.reason) data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) return events def get_event(self): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) ...
tuffery/Frog2
frowns/.happydoc.__init__.py
Python
gpl-3.0
660
0.101515
(S'39c672e88b52d0cc607701e2f9883dc3' p1 (ihappydoclib.parseinfo.moduleinfo ModuleInfo p2 (dp3 S'_namespaces' p4 ((dp5 (dp6 tp7 sS'_import_info' p8 (ihappydoclib.parseinfo.imports ImportInfo p9 (dp10 S'_named_imports' p11
(dp12 sS'_straight_imports' p13 (lp14 sbsS'_filename' p15 S'../python/frowns/__init__.py' p16 sS'_docstring' p17 S'' sS'_name' p18 S'__init__' p19 sS'_parent' p20 NsS'_comment_info' p21 (dp22 sS'_configuration_values' p23 (dp24 S'include_comments' p25
I1 sS'cacheFilePrefix' p26 S'.happydoc.' p27 sS'useCache' p28 I1 sS'docStringFormat' p29 S'StructuredText' p30 ssS'_class_info' p31 g5 sS'_function_info' p32 g6 sS'_comments' p33 S'' sbt.
rocky/python2-trepan
test/functional/test-sig.py
Python
gpl-3.0
2,976
0.001344
#!/usr/bin/env python import os, signal, unittest from fn_helper import strarray_setup, compare_output, get_lineno class TestSigHandler(unittest.TestCase): def test_handle(self): # FIXME! self.assertTrue(True) return # See that we handle a USR1 signal with a 'stop' action ...
kill_line)] compare_output(self, out, d, cmds) # Now define a signal handler and see that this i
s skill okay # "ignore" is the same as "nopass" # FIXME: add this common code to the helper. cmds = ['handle usr1 stop ignore', 'continue', 'where', 'continue'] d.intf[-1].output.output = [''] d.core.step_ignore = 0 d.intf[-1].input.input = cmds def signal_handle...
ttm/percolation
percolation/bootstrap.py
Python
gpl-3.0
2,675
0.000748
import percolation as P import rdflib as r import os import time from rdflib import ConjunctiveGraph TT = time.time() class PercolationServer: def __init__(self, percolationdir="~/.percolation/"): percolationdir = os.path.expanduser(percolationdir) if not os.path.isdir(percolationdir): ...
: if args and isinstance(args[0], str) \ and (len(args[0]) == args[0].count("\n")): print("{}{:.3f}".format(args[0], time.time()-TT), *args[1:]) TT = time.time() else: print("{:.3f}".format(time.time()-TT), *args)
TT = time.time() if args[0] == "prompt": input("ANY KEY TO CONTINUE") QUIET = False c = check if __name__ == "__main__": start() rdflibok = isinstance(P.percolation_graph, r.ConjunctiveGraph) ntriples = len(P.percolation_graph) c("rdflib in P.percolation_graph:", rdflibok, "nt...
zbqf109/goodo
openerp/addons/account/models/account_bank_statement.py
Python
gpl-3.0
46,649
0.004545
# -*- coding: utf-8 -*- from openerp import api, fields, models, _ from openerp.osv import expression from openerp.tools import float_is_zero from openerp.tools import float_compare, float_round from openerp.tools.misc import formatLang from openerp.exceptions import UserError, ValidationError import time import math...
e_ids.amount', 'balance_end_real') def _end_balance(self): self.total_entry_encoding = sum([line.amount for line in self.line_ids]) self.balance_end = self.balance_start + self.to
tal_entry_encoding self.difference = self.balance_end_real - self.balance_end @api.one @api.depends('journal_id') def _compute_currency(self): self.currency_id = self.journal_id.currency_id or self.env.user.company_id.currency_id @api.one @api.depends('line_ids.journal_entry_ids') ...
jmartinm/invenio
modules/websearch/lib/websearch_services_regression_tests.py
Python
gpl-2.0
15,343
0.00554
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 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 2 of t...
ices_loading_time_first_time)) # Load search services, hopefully from cache t1 = time.time() services = get_search_services() t2 = time.time() search_services_loading_time = t2 - t1 # We expect search services on the demo site to be loaded # under 1 second, i.e....
om_cache: self.fail("""Loading Search services from cache took too much time: %s seconds. Limit: %s second""" % (search_services_loading_time, max_seconds_services_loading_time_from_cache)) def test_search_services_loading(self): """websearch - loading default search serv...
mmartinortiz/pyePuck
examples/line_follower.py
Python
gpl-3.0
3,739
0.03344
#!/usr/bin/env python # -*- coding: utf-8 -*- # # line_follower.py # # Copyright 2011 Manuel Martín Ortiz <mmartinortiz@gmail.com> # # 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 # ...
Boston, # MA 02110-1301, USA. # -- Line Follower -- # # Program to follow a black line ober white floor # # Requisite: # * ePuck with Web
ots' firmware 1.4.2 # * ePuck.py Library (>= 0.9) # * Bluetooth device from ePuck import ePuck import time import sys import re # You can use this dictionary to asociate an ePuck ID with its MAC Address epucks = { '1797' : '10:00:E8:6C:A2:B6', '1903' : '10:00:E8:6C:A1:C7' } def log(text): """ Show @text in st...
ebnn/jass
examples/normal.py
Python
mit
563
0
"""This example samples from a simple bivariate normal distribution.""" import jass.mcmc as mcmc import jass.samplers as samplers import numpy as np i
mport scipy.stats as stats import triangle import matplotlib.pyplot as pl # Define the log-likelihood function to be a bivariate normal normal_rv = stats.multivariate_normal(cov=np.identity(2)) # Initialise the chain at the mean initial = [0.0, 0.0] sampler = samplers.ComponentWiseSlice() sa
mples = mcmc.run(sampler, normal_rv.logpdf, initial, 5000) # Plot the the samples triangle.corner(samples) pl.show()
toast38coza/FlashGiving
campaign/migrations/0006_auto_20160716_1641.py
Python
mit
895
0.001117
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-16 16:41 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('campaign', '0005_auto_201607
16_1624'), ] operations = [ migrations.AddField( model_name='charity', name='gateway', field=models.ManyToManyField(through='campaign.GatewayProperty', to='campaign.Gateway'), ), migrations.AlterField( model_name='campaign', na...
name='value', field=models.CharField(blank=True, max_length=255, null=True), ), ]
letsencrypt/letsencrypt
certbot-nginx/certbot_nginx/_internal/constants.py
Python
apache-2.0
2,987
0
"""nginx plugin constants.""" import platform from typing import Any from typing import Dict FREEBSD_DARWIN_SERVER_ROOT = "/usr/local/etc/nginx" LINUX_SERVER_ROOT = "/etc/nginx" PKGSRC_SERVER_ROOT = "/usr/pkg/etc/nginx" if platform.system() in ('FreeBSD', 'Darwin'): server_root_tmp = FREEBSD_DARWIN_SERVER_ROOT el...
53ffdcc0af54582452ca1e52f5f776f16', 'c052ffff0ad683f43bffe105f7c606b339536163490930e2632a335c8d191cc4', '0232
9eb19930af73c54b3632b3165d84571383b8c8c73361df940cb3894dd426', '63e2bddebb174a05c9d8a7cf2adf72f7af04349ba59a1a925fe447f73b2f1abf', '2901debc7ecbc10917edd9084c05464c9c5930b463677571eaf8c94bffd11ae2', '30baca73ed9a5b0e9a69ea40e30482241d8b1a7343aa79b49dc5d7db0bf53b6c', '02329eb19930af73c54b3632b3165d845713...
ravibhure/ansible
lib/ansible/modules/packaging/os/apk.py
Python
gpl-3.0
11,310
0.002299
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Kevin Brebanov <https://github.com/kbrebanov> # Based on pacman (Afterburn <http://github.com/afterburn>, Aaron Bull Schaefer <aaron@elasticdog.com>) # and apt (Matthew Williams <matthew@flowroute.com>) modules. # # GNU General Public License v3.0+ (see COPYING or ...
ry_latest(module, name): cmd = "%s version %s" % (APK_PATH, name) rc, stdout, stderr = module.run_command(cmd, check_rc=False) search_pattern = r"(%s)-[\d\.\w]+-[\d\w]+\s+(.)\s+[\d\.\w]+-[\
d\w]+\s+" % (re.escape(name)) match = re.search(search_pattern, stdout) if match and match.group(2) == "<": return False return True def query_virtual(module, name): cmd = "%s -v info --description %s" % (APK_PATH, name) rc, stdout, stderr = module.run_command(cmd, check_rc=False) sear...
rv816/serrano_night
serrano/resources/base.py
Python
bsd-2-clause
11,880
0
import functools from datetime import datetime from django.core.cache import cache from restlib2.params import Parametizer from restlib2.resources import Resource from avocado.models import DataContext, DataView, DataQuery from serrano.conf import settings from django.contrib.auth import authenticate, login from ..toke...
if request.method == 'POST': attrs = request.data.get(key) elif request.method == 'GET': attrs = request.GET.get(key) # If the `attrs` still could not be resolved, try to get the view or # context from the query data if it exists within the request. if attrs is None: ...
est_data = None # Try to read the query data from the request if request.method == 'POST': request_data = request.data.get('query') elif request.method == 'GET': request_data = request.GET.get('query') # If query data was found in the request, then attempt to cr...
schleichdi2/OPENNFR-6.3-CORE
bitbake/lib/bb/fetch2/local.py
Python
gpl-2.0
3,672
0.003268
""" BitBake 'Fetch' implementations Classes for obtaining upstream sources for the BitBake build tools. """ # Copyright (C) 2003, 2004 Chris Larson # # SPDX-License-Identifier: GPL-2.0-only # # Based on functions from the base bb module, Copyright 2003 Holger Schurig # import os import urllib.request, urllib.parse...
faulting to %s for %s" % (dldirfile, path)) bb.utils.mkdirhier(os.path.dirname(dldirfile)) searched.append(dldirfile) return searched
return searched def need_update(self, ud, d): if ud.url.find("*") != -1: return False if os.path.exists(ud.localpath): return False return True def download(self, urldata, d): """Fetch urls (no-op for Local method)""" # no need to fetch local fil...
EdinburghGenomics/clarity_scripts
tests/test_assign_workflow_kapa_qc.py
Python
mit
2,427
0.00412
from itertools import cycle from unittest.mock import Mock, patch from scripts.assign_workflow_kapa_qc import AssignWorkflow from tests.test_common import TestEPP, NamedMock, FakeEntitiesMaker class TestAssignNextStep(TestEPP): def setUp(self): self.protostep = NamedMock(real_name='SeqPlatePrepST', uri='...
a', 'SeqPlatePrepWF'] + ['-b', 'SeqPlatePr
epST'] + ['-c', 'RepeatWF'] + ['-x', 'RepeatST']) def test_assign_next_step_seq_plate_prep(self): # show that samples are assigned to Sequencing Plate Prep fem = FakeEntitiesMaker() self.epp.lims = fem.lims self.epp.process = fem.create_a_fake_process( ...
ODM2/ODM2ControlledVocabularies
src/odm2cvs/cvinterface/views/base_views.py
Python
bsd-3-clause
14,543
0.003026
import json from os import linesep from urllib2 import Request, urlopen from string import capwords from django.conf import settings from django.core.mail import send_mail from django.contrib.auth.decorators import login_required from django.contrib.messages.views import SuccessMessageMixin from django.utils import ti...
ct = self.model.objects.get(pk=kwargs['pk']) request.POST._mutable = True for field in self.read_only: request.POST[field] = unicode(object.__getattribute__(field)) return super(DefaultRequestUpdateView, self).post(request, *args, **kwargs) def form_valid(self, form): em...
.request.POST: email_message = ''.join([form.instance.submitter_name, ', your submission "', form.instance.name, '" for the ', self.vocabulary, ' vocabulary was accepted.', linesep, linesep, "To se...
bmoretz/Algorithms
Python/ch_01/reinforcement/r_1.9.py
Python
gpl-3.0
136
0.022059
# What parameters should be sent
to the range constructor, to produce a range with values 50, 60, 70, 80? [k for k
in range(50,90,10)]
pinterest/mysql_utils
zdict_gen/zdict_gen.py
Python
gpl-2.0
4,693
0
#!/usr/bin/python3.3 from __future__ import print_function import argparse import json ''' Zlib's implementation uses 262 bytes of overhead for pre-defined dictionary thus, the max zdict size is 32KB - 262B = 23506B ''' MAX_WINDOW_SIZE = 32506 # 32KB-262B, size of MAX_WBITS - zdict overhead MAX_LOOKAHEAD_BUFFER_SI...
3 # Number
of times of cores to use as batching size DEFAULT_ZDICT_SIZE = 32506 # Length of predefined dictionary to generate ''' TODO Implement a more optimal shortest common superstring solution. This would allow more relevant substrings to fit within the pre-defined dictionary window. In order to generalize it for compres...
SuperSuperSuperSuper5/everyweak-auto-punch
test/CYBL/module/send_mail.py
Python
gpl-3.0
1,395
0.004301
#!/usr/bin/env python #coding:utf-8 """ Send mail module """ import smtplib import time def return_message(): """ return the message dict """ message = { "addr": "", "subject": "", "status_code": "" } return message def _send_mail(to_addr, subject, text): """ ...
)) smtp = smtplib.SMTP() smtp.connect(server, '25') smtp.starttls() smtp.login('super_big_hero@163.com', 'wshmn12345') smtp.sendmail(from_
addr, [to_addr], body) smtp.quit() def send(message_dict): """ send mail demo dict: message_dict['addr'] message_dict['subject'] message_dict['status_code'] """ addr = message_dict['addr'] subject = message_dict['subject'] status_code = message_dict['status_code'] try...
gietal/Stocker
sandbox/udacity/1-9.py
Python
mit
472
0.021186
import utils import pandas as pd import numpy
as np import scipy.optimize as spo def get_data(): return utils.get_data(['SPY', 'MSFT', 'GOOG', 'AMD', 'TSLA', 'GLD'], pd.date_range('2011
-01-01', '2017-01-01')) def optimizer_error(allocs, data): return 0 def test(): data = get_data() normalized_data = utils.normalize_data(data) # unoptimized original_alloc = [0.33, 0.33, 0.33] if __name__ == "__main__": test()
pyblish/pyblish-win
pythonpath/pyblish/__init__.py
Python
lgpl-3.0
163
0.006135
import os import imp util
= imp
.load_source("__pyblish_util", os.path.join(__file__, "..", "..", "__pyblish_util.py")) util.wrap_module(__name__, "pyblish-base")
antoinecarme/pyaf
tests/model_control/detailed/transf_Logit/model_control_one_enabled_Logit_MovingAverage_Seasonal_WeekOfYear_MLP.py
Python
bsd-3-clause
162
0.049383
import tests.model_control.test_ozone_custom_models_enabled as test
mod testmod.build_model( ['Logit'] , ['MovingAverage'] , ['Seasonal_WeekOfYear'] , ['MLP']
);
tiborsimko/reana-job-controller
reana_job_controller/config.py
Python
mit
4,351
0.001149
# -*- coding: utf-8 -*- # # This file is part of REANA. # Copyright (C) 2017, 2018, 2019, 2020, 2021, 2022 CERN. # # REANA is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Flask application configuration.""" import os from reana_co...
_CACHE_FILENAME = "krb5_{}" """Name of the Kerberos token cache file.""" KRB5_CONFIGMAP_NAME = o
s.getenv( "REANA_KRB5_CONFIGMAP_NAME", f"{REANA_COMPONENT_PREFIX}-krb5-conf" ) """Kerberos configMap name.""" VOMSPROXY_CONTAINER_IMAGE = os.getenv( "VOMSPROXY_CONTAINER_IMAGE", "reanahub/reana-auth-vomsproxy:1.0.0" ) """Default docker image of VOMSPROXY sidecar container.""" VOMSPROXY_CONTAINER_NAME = "voms-...
gburd/dbsql
src/py/pydbsql/dbapi2.py
Python
gpl-3.0
3,459
0.002602
#-*- coding: ISO-8859-1 -*- # # DBSQL - A SQL database engine. # # Copyright (C) 2007-2008 The DBSQL Group, Inc. - All rights reserved. # # This library 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 ...
part, timepart = val.split(" ") year, month, day = map(int, datepart.split("-")) timepart_full = timepart.split(".") hours, minutes, seconds = map(int, timepart_full[0].split(":")) if len(timepart_full)
== 2: microseconds = int(timepart_full[1]) else: microseconds = 0 val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds) return val register_adapter(datetime.date, adapt_date) register_adapter(datetime.datetime, adapt_datetime) reg...
kickapoo/prometheus
prometheus/blueprints/auth/views.py
Python
gpl-3.0
1,737
0.002879
from prometheus import login_manager from . import auth from flask i
mport render_template, url_for, redirect, request, flash from flask.ext.login import login_user, logout_user, login_required from prometheus.models.auth import User, Role from .forms import LoginForm login_manager.login_view = 'auth.login'
@login_manager.user_loader def load_user(id): return User.query.get(int(id)) @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is None or not user.verify_password(fo...
Teekuningas/mne-python
examples/connectivity/plot_mne_inverse_envelope_correlation_volume.py
Python
bsd-3-clause
4,055
0
""" ==================================================== Compute envelope correlations in volume source space ==================================================== Compute envelope correlations of orthogonalized activity [1]_ [2]_ in source space using resting state CTF data in a volume source space. """ # Authors: Er...
th as op import mne from mne.beamformer import make_lcmv, apply_lcmv_epochs from mne.connectivity import envelope_correlation from mne.preprocessing import compute_proj_ecg, compute_proj_eog data_path = mne.datasets.brainstorm.
bst_resting.data_path() subjects_dir = op.join(data_path, 'subjects') subject = 'bst_resting' trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif') bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif') raw_fname = op.join(data_path, 'MEG', 'bst_resting', 'sub...
chrisdjscott/Atoman
atoman/lattice_gen/setup.py
Python
mit
1,398
0.005722
from __future__ import print_function from __future__ import absolute_import import os def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration # path to header files cwd = os.path.dirname(os.path.abspath(__file__)) incdir = os.path.abspath(os.pat...
include_dirs=[incdir], depends=arraydeps, libraries=["array_utils"]) config.add_extension("_lattice_gen_fcc", ["_lattice_gen_fcc.c"], include_dirs=[incdir], depends=...
config.add_extension("_lattice_gen_pu3ga", ["_lattice_gen_pu3ga.c"], include_dirs=[incdir], depends=arraydeps, libraries=["array_utils"]) return config if __name__ == "__main__": print("This is the ...
siosio/intellij-community
python/testData/inspections/PyUnresolvedReferencesInspection/ConditionalImports/a.py
Python
apache-2.0
245
0.040816
def f(c, x): if c > 2: from lib1 import f #pass
elif c > 1: from lib2 import f #pass else: <warning descr="Unused import stateme
nt 'from lib2 import g #fail'">from lib2 import g #fail</warning> return f(x)
Frencil/box-python-sdk
test/functional/test_file_upload_update_download.py
Python
apache-2.0
2,514
0.003182
# coding: utf-8 from __future__ import unicode_literals from mock import patch import six from test.util.streamable_mock_open import streamable_mock_open def test_upload_then_update(box_client, test_file_path, test_file_content,
update_file_content, file_name): with patch('boxsdk.object.folder.open', streamable_mock_open(read_data=test_file_content), create=True)
: file_object = box_client.folder('0').upload(test_file_path, file_name) assert file_object.name == file_name file_object_with_info = file_object.get() assert file_object_with_info.id == file_object.object_id assert file_object_with_info.name == file_name file_content = file_object.content()...
sburnett/seattle
network_semantics_tests/tests/stopcomm/stopcomm_duplicate2.py
Python
mit
387
0.046512
# if stopcomm is called twice on the same handle it # returns false. def echo(rip,rport,msg,h): sock.close() if callfunc ==
"initialize": ip = '127.0.0.1' waitport = 12345 # the waitfor conn we will connect to handle = recvmess(ip,waitport,echo) stopcomm(handle) stopped = stopcomm(handle) if stopped is
not False: print 'stopcomm did not return False'
vossman/ctfeval
appionlib/apCtf/leastsq.py
Python
apache-2.0
7,781
0.037784
#!/usr/bin/env python import sys import math import time import numpy from appionlib import apDisplay """ File of functions that solve least square problems in matrix notation: X * beta = Y which is equivalent to: beta[1] * X[1,1] + beta[2] * X[1,2] + ... = y[1] beta[1] * X[2,1] + beta[2] * X[2,2] + ... = y[...
eights of observations, de-emphasizing bad fitting points """ t0 = time.time() ### check the input if checkMatrixSizes(X, Y) i
s False: return None ### setup weights if necessary if W is None: #W = numpy.random.random((m)) # weights for the observations #W = W*float(M)/W.sum() W = numpy.ones(Y.shape) # even weights for the observations ### solve it err0 = None sys.stderr.write("running total least squares") for i in range(maxit...
endlessm/chromium-browser
third_party/blink/renderer/platform/PRESUBMIT.py
Python
bsd-3-clause
2,138
0.000935
# 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. """Presubmit script for changes affecting Source/platform. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about...
] def _Co
mmonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] results.extend(_CheckRuntimeEnabledFeaturesSorted(input_api, output_api)) return results def CheckChangeOnUpload(input_api, output_api): return _CommonChecks(input_api, output_api) def CheckChangeOnCom...
luamct/WebSci14
features/color/stats.py
Python
gpl-3.0
1,332
0.053303
''' Created on 13/08/2013 @author: Felipe Costa ''' from math import sqrt, atan2, pi import matplotlib.pyplot as pp import numpy as np import utils class Statistics : def __init__(self): self.table_name = "stats" def get_table_name(self): return self.table_name def process(self,rgb_img): #...
td(S) # Hue mean is calculated using circular statistics S /= 255.0 As = np.sum(np.cos(img[:,:,0])*S) Bs = np.sum(np.sin(img[:,:,0])*S) # Fix negatives values H_mean = atan2(Bs,As) if H_mean<0 : H_mean += 2*pi # Circular variance pixels = img.shape[0]*img.shape[1] H_std = 1.0 - (sqrt(As**2 + ...
td': H_std, 'Y_mean': Y_mean, 'Y_std': Y_std, 'S_mean': S_mean, 'S_std': S_std } def test(): from utils.image import rgb2ihls imgs = {'ihls' : rgb2ihls(pp.imread("../in/purple.jpg"))} # ihls = np.array([[np.pi/2,100,120], # [np.pi/2,100,120], # [3*np.pi/2,100,120], # ...
RevansChen/online-judge
Codefights/arcade/python-arcade/level-13/92.Weird-Encoding/Python/solution1.py
Python
mit
120
0.008333
# Python3 import base64 def weirdEncoding(encoding, message): return base64.b64decode(message, encoding).decode()
rubenk/cobbler
cobbler/codes.py
Python
gpl-2.0
2,451
0.013464
""" various codes and constants used by Cobbler Copyright 2006-2008, Red H
at, Inc Michael DeHaan <mdehaan@redhat.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the...
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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA...
iandees/all-the-places
locations/spiders/mcdonalds_il.py
Python
mit
3,804
0.003155
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsILSpider(scrapy.Spider): name = "mcdonalds_il" allowed_domains = ["www.mcdonalds.co.il"] start_urls = ( 'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D...
turn lat, lon def parse_phone(self, phone): phon
e = phone.xpath('//div[@class="padding_hf_v sp_padding_qt_v"]/a/text()').extract_first() if not phone: return "" return phone.strip() def parse_address(self, address): address = address.xpath('//h2/strong/text()').extract_first() return address.strip() def pa...
cgwalters/pykickstart
tests/commands/reqpart.py
Python
gpl-2.0
1,533
0.002609
# # Chris Lumens <clumens@redhat.com> # # Copyright 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be usef...
ntation are not # subject to the GNU General Public License and may only be used or replicated # with the express permission of Red Hat, Inc. # import unittest from tests.baseclass import CommandTest, CommandSequenceTest class F23_TestCase(CommandTest): command = "reqpart" def runTest(self): # pass ...
tCase(CommandSequenceTest): def runTest(self): # fail - can't use both autopart and reqpart self.assert_parse_error(""" autopart reqpart""") RHEL7_TestCase = F23_TestCase if __name__ == "__main__": unittest.main()
xuhcc/airy
airy/tests/test_user.py
Python
mit
1,289
0
import datetime import pytest from airy import settings from airy.exceptions import UserError from airy.units.user import User from airy.utils.date import tz_now, week_beginning from factories impor
t ( ClientFactory, TimeEntryFactory, ) @pytest.mark.usefixtures('db_class') class TestUser(): def test_login_error(self): session = {} with pytest.raises(UserError): User.login(session, {'password': 'wrong password'}) def test_serialization(self): user = User() ...
time_entries.append(TimeEntryFactory.create( task__project__client=client, added_at=week_beg + datetime.timedelta(days=day))) self.db.session.commit() result = user.serialize() assert result['name'] == settings.USER_NAME assert result['open_tasks']...
jettisonjoe/openhtf
test/output/callbacks/callbacks_test.py
Python
apache-2.0
6,095
0.005414
# Copyright 2016 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 agre...
e License. """Unit tests for the openhtf.output.callbacks module. This test currently only provides line coverage, checking that the Python code is sane. It might be worth expanding the tests to also check for things we actually care for. """ import io import sys import unittest import openhtf as htf from openhtf im...
om examples import all_the_things from openhtf.output.callbacks import console_summary from openhtf.output.callbacks import json_factory from openhtf.output.proto import mfg_event_converter from openhtf.output.proto import mfg_event_pb2 from openhtf.output.proto import test_runs_converter from openhtf.output.proto impo...
mahak/neutron
neutron/plugins/ml2/drivers/openvswitch/agent/common/constants.py
Python
apache-2.0
6,043
0
# Copyright (c) 2012 OpenStack Foundation. # # 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...
types to tables number TUN_TABLE = {p_const.TYPE_GRE: GRE_TUN_TO_LV, p_const.TYPE_VXLAN: VXLAN_TUN_TO_LV, p_const.TYPE_GENEVE: GENEVE_TUN_TO_LV} # The default respawn interval for the ovsdb monitor DEFAULT_OVSDBMON_RESPAWN = 30 # Represent invalid OF Port OFPORT_INVALID = -1 ARP_RESPONDER...
rc:%(mac)s,' 'load:0x2->NXM_OF_ARP_OP[],' 'move:NXM_NX_ARP_SHA[]->NXM_NX_ARP_THA[],' 'move:NXM_OF_ARP_SPA[]->NXM_OF_ARP_TPA[],' 'load:%(mac)#x->NXM_NX_ARP_SHA[],' 'load:%(ip)#x->NXM_OF_ARP_SPA[],...