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
Comunitea/CMNT_004_15
project-addons/external_salesperson_visit/models/__init__.py
Python
agpl-3.0
874
0.001144
############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your...
etails. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from .
import partner_visit
tripodwire/simple_maven_repo
mvn.run.py
Python
mit
13,573
0.001547
#! /usr/bin/env python import os import subprocess import click import re import posixpath import urllib import time import traceback import sys import glob import base64 import json import ssl from concurrent.futures import ThreadPoolExecutor from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleH...
def repository_index(cls): return os.path.join(cls.repository, ".index") @classmethod def add_auth(cls, auth): cls.basic_authorizations.append(auth) @classmethod def add_auth_from_clear(cls, username, password): cls.add_auth(base64.b64encode("%s:%s" % (username, password))) ...
.repository = repo if not cls.repository_name: cls.repository_name = os.path.basename(cls.repository) os.chdir(cls.repository) @classmethod def add_location(cls, location): if location and os.path.exists(location): cls.jar_locations.append(location) ...
apache/incubator-airflow
tests/models/test_param.py
Python
apache-2.0
8,248
0.000606
# 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 u...
lve() == 1.0 with pytest.raises(ValueError): p = Param('42', type='number') def test_list_param(self): p = Param([1, 2], type='array') assert p.resolve() == [1, 2] def test_dict_param(self): p = Param({'a': 1, 'b': 2}, type='object') assert p.resolve() == {...
(value=5.0) == 5.0 def test_param_with_description(self): p = Param(10, description='Sample description') assert p.description == 'Sample description' def test_suppress_exception(self): p = Param('abc', type='string', minLength=2, maxLength=4) assert p.resolve() == 'abc' ...
javiersanp/CatAtom2Osm
test/test_osmxml.py
Python
bsd-2-clause
8,449
0.006628
import unittest import random from cStringIO import StringIO import os os.environ['LANGUAGE'] = 'C' import setup import osm import osmxml from osmxml import etree class OsmxmlTest(unittest.TestCase): def test_serialize(self): data = osm.Osm() n = data.Node(4,0) n.tags['entrance'] = 'yes'...
gs['type'] = 'import' fo = StringIO()
osmxml.serialize(fo, data) result = fo.getvalue() root = etree.fromstring(result) self.assertEquals(root.find('note').text, 'foobar') self.assertEquals(root.find('meta').get('foo'), 'bar') for (xmltag, osmtag) in zip(root.findall('changeset/tag'), data.tags.items()): ...
taigaio/taiga-back
tests/integration/test_watch_tasks.py
Python
agpl-3.0
4,832
0.001035
# -*- coding: utf-8 -*- # Copyright (C) 2014-present Taiga Agile LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later ver...
ponse = client.get(url) assert response.status_code == 200 assert response.data[0]['id'] == user.id def test_get_task_watcher(client): user = f.UserFactory.create() task = f.TaskFactory(owner=user) f.MembershipFactory.create(project=task.project, user=user, is_admin=True) watch = f.WatchedFac...
t response.status_code == 200 assert response.data['id'] == watch.user.id def test_get_task_watchers(client): user = f.UserFactory.create() task = f.TaskFactory(owner=user) f.MembershipFactory.create(project=task.project, user=user, is_admin=True) url = reverse("tasks-detail", args=(task.id,)) ...
mradamcox/arc2arches
shp2arches.py
Python
mit
10,515
0.01398
import os import argparse import shapefile import json import subprocess import csv import sys import unicodecsv import itertools ## try to get the path to the authority docs with the settings ## otherwise, hardcode path to likely location try: from crip import settings auth_doc_directory = settings.CONCEPT_SC...
return def pr
ocessSHP(infile,relation_info): """ process the input shapefile """ outfile = os.path.splitext(infile)[0]+".arches" config = os.path.splitext(infile)[0]+".conflig" if not os.path.isfile(config): raise Exception("no conflig file") if os.path.isfile(outfile): os.remove(outfile) ...
Phrozyn/MozDef
tests/mozdef_util/test_plugins/plugin4.py
Python
mpl-2.0
567
0
# 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/. # Copyright (c) 2014 Mozilla Corporation class message(obj
ect): def __init__(self): ''' intended to be the fourth plugin that will run and signals to delete the messa
ge (returning None) ''' self.registration = ['pears'] self.priority = 20 def onMessage(self, message, metadata): return None, metadata
ssarangi/self_driving_cars
traffic_sign_classifier/classify.py
Python
apache-2.0
6,030
0.004809
# Load pickled data import pickle import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid import numpy as np import tensorflow as tf from tensorflow.contrib.layers import flatten from sklearn.utils import shuffle class Data: def __init__(self): training_file = 'data/train.p' ...
_hot(y, max_classified_id) rate = 0.001 logits = LeNet(x, max_classified_id) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y) loss_operation = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate=rate) trainin...
.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver(), training_operation, accuracy_operation return saver, training_operation, accuracy_operation, x, y def evaluate(x, y, X_data, y_data, accuracy_operation, BATCH_SIZE): num_example...
geekaia/edx-platform
common/lib/xmodule/xmodule/modulestore/tests/test_split_w_old_mongo.py
Python
agpl-3.0
5,708
0.002803
import unittest import mock import datetime import uuid import random from xmodule.modulestore.inheritance import InheritanceMixin from opaque_keys.edx.locator import CourseLocator, BlockUsageLocator from xmodule.modulestore.split_mongo.split import SplitMongoModuleStore from xmodule.modulestore.mongo import MongoModu...
est collections, close the db connection """ split_db = self.sp
lit_mongo.db split_db.drop_collection(split_db.course_index) split_db.drop_collection(split_db.structures) split_db.drop_collection(split_db.definitions) def tear_down_mongo(self): """ Remove the test collections, close the db connection """ split_db = self.s...
apruden/opal
opal-python-client/src/main/python/opal/import_idsmap.py
Python
gpl-3.0
1,394
0.005022
""" Import identifiers mapping """ import sys import opal.core def add_arguments(parser): """ Add import_idsmap command specific options """ pars
er.add
_argument('--type', '-t', required=True, help='Entity type (e.g. Participant).') parser.add_argument('--map', '-m', required=True, help='Mapping name.') parser.add_argument('--separator', '-s', required=False, help='Field separator (default is ,).') def do_command(args): """ Execute import command ...
nhsengland/publish-o-matic
datasets/nhse_stats/topics/winter.py
Python
mit
1,729
0.004049
import collections import calendar import datetime import re import urllib from lxml.html import fromstring, tostring import requests import slugify from publish.lib.helpers import to_markdown, anchor_to_resource, get_dom, hd ROOT = "http://www.england.nhs.uk/
statistics/statistical-work-areas/winter-daily-sitreps/" def
is_header(p): return p.tag == 'p' and len(p.cssselect('strong')) > 0 def scrape_page(url): page = fromstring(requests.get(url).content) links = [a for a in page.cssselect('a') if ('upload' in a.get('href')) or ('files' in a.get('href'))] h1 = page.cssselect('h1')[1] desc = [] p = h1.getparent(...
manpaz/python-escpos
src/escpos/printer.py
Python
gpl-3.0
12,101
0.00157
#!/usr/bin/python # -*- coding: utf-8 -*- """ This module contains the implementations of abstract base class :py:class:`Escpos`. :author: `Manuel F Martinez <manpaz@bashlinux.com>`_ and others :organization: Bashlinux and `python-escpos <https://github.com/python-escpos>`_ :copyright: Copyright (c) 2012-2017 Bashlin...
ass describes a printer that natively speaks USB. inheritance: .. inheritance-diagram:: escpos.printer.Usb :parts: 1 """ def __init__(self, idVendor, idProduct, usb_args=None, timeout=0, in_ep=0x82, out_ep=0x01, *args, **kwargs): # noqa: N803 """ :param idVe...
:param timeout: Is the time limit of the USB operation. Default without timeout. :param in_ep: Input end point :param out_ep: Output end point """ Escpos.__init__(self, *args, **kwargs) self.timeout = timeout self.in_ep = in_ep self.out_ep = out_ep u...
sileht/deb-openstack-nova
nova/db/sqlalchemy/migrate_repo/versions/065_add_index_to_instance_project_id.py
Python
apache-2.0
1,111
0
# Copyright 2011 OpenStack 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 agr...
meta.bind = migrate_engine instances = Table('instances', meta, autoload=Tru
e) index = Index('project_id', instances.c.project_id) index.drop(migrate_engine)
zenn1989/scoria-interlude
L2Jscoria-Game/data/scripts/quests/614_SlayTheEnemyCommander_Varka/__init__.py
Python
gpl-3.0
3,372
0.032325
#Made by Emperorc import sys from com.l2scoria import Config from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest from com.l2scoria.gameserver.util import Util qn = "614_SlayTheEnemy...
if st.getPlayer().isAlliedWithVarka() : if cond == 1: if st.getPlayer().getAllianceWithVarkaKetra() == -4 and st.getQuestItemsCount(Varka_Alliance_Four) : st.giveItems(Tayr_Head,1) st.set("cond","2") class Quest (JQuest) : def __ini...
r): JQuest.__init__(self,id,name,descr) def onEvent (self,event,st) : htmltext = event if event == "31377-04.htm" : if st.getPlayer().getAllianceWithVarkaKetra() == -4 and st.getQuestItemsCount(Varka_Alliance_Four) : if st.getPlayer().getLevel() >= 75 : st.set("cond","1") ...
OnRampOrg/onramp
server/src/webapp/onramppce.py
Python
bsd-3-clause
31,343
0.004818
"""Functionality to support interacting with an OnRamp PCE Exports: PCEAccess: Client-side interface to OnRamp PCE server. """ import json import os # import requests import time class PCEAccess(): """Client-side interface to OnRamp PCE server. Methods: get_modules_avail: Return the list of modu...
!= 200: self._logger.error('%s Error: %d from DELETE %s: %s' % (self._name, r.status_code, url, r.text)) return False else: response = r.json() if ((not response) or ('status_code' not in response.keys()) or (0 != re...
elf): """Return the list of modules that are available at the PCE but not currently installed. Returns: List of JSON-formatted module objects. Returns 'None' on error. """ response = self._pce_get("modules", state="Available") if (not response) or ("modules" ...
totem/cluster-deployer
tests/unit/services/test_security.py
Python
mit
2,094
0
from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import ( # noqa bytes, dict, int, list, object, range, str, ascii, chr, hex, input, next, oct, open, pow, round, super, filter, map, zip) from nose.tools import eq_, ok_ fro...
mock_fn('arg1', arg2='arg2') # Then: Function is called with no store set @patch.dict('deployer.services.security.ENCRYPTION', {}) @patch('deployer.services.security.decrypt_obj') def
test_decrypt_config(m_decrypt_obj): # When: I invoke decrypt config decrypt_config({'mockkey': 'mockvalue'}) # Then: decrypt_obj is called with expected parameters m_decrypt_obj.assert_called_once_with( {'mockkey': 'mockvalue'}, profile='default', store=None, passphrase=None)
amirajdhawan/eYSIP_2015_Depth_Mapping_Kinect
Resources/Examples/PycharmProjects/Python freenect examples/Codec.py
Python
cc0-1.0
826
0.021792
__author__ = 'aniket' import freenect import cv2 import numpy as np kernel = np.ones((5,5),np.uint8) def grayscale(): maske = np.zeros((480,640,3)) a =
freenect.sync_get_depth()[0] np.clip(a, 0, 2**10 - 1, a) a >>= 2 a = a.astype(np.uint8) median = cv2.medianBlur(a,5) ret,mask = cv2.threshold(median,254,255,cv2.THRESH_BINARY_INV) mask = mask/255 ab = freenect.sync_get_video()[0] ab = cv2.cvtColor(ab, cv2.COLOR_BGR2RGB) for i in ran...
[:,:] maske = maske/255 abc = np.multiply(ab,maske) #print abc return abc def colored(): a = freenect.sync_get_video()[0] return a while(True): cv2.imshow('gray',grayscale()) #cv2.imshow('color',colored()) if cv2.waitKey(10) == 27: break cv2.destroyAllWindows()
obi-two/Rebelion
data/scripts/templates/object/mobile/shared_kittle.py
Python
mit
426
0.049296
#### 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 = Creature() result.template = "object/mobile/shared_kittle.iff" result.attribute_template_id = 9 result.stfName("...
TIONS #### #### END MOD
IFICATIONS #### return result
marcosxddh/aula_script
backend/appengine/routes/servicos/home.py
Python
mit
682
0.007331
# -*- coding:
utf-8 -*- from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from tekton import router from gaecookie.decorator import no_csrf from gaepermission.decorator import login_not_required from servico_app import facade from routes.servicos import admin @login_no...
vico_public_dcts = [public_form.fill_with_model(servico) for servico in servicos] context = {'servicos': servico_public_dcts,'admin_path':router.to_path(admin)} return TemplateResponse(context)
etothemanders/GoingPostal
run.py
Python
mit
155
0
#!env/bin/python import os from app impo
rt app if __name__ == "__main__": app.ru
n(debug=True, port=int(os.environ.get("PORT", 5050)), host="0.0.0.0")
aplicatii-romanesti/allinclusive-kodi-pi
.kodi/addons/plugin.video.nasa/addon.py
Python
apache-2.0
3,915
0.000766
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2012 Tristan Fischer (sphere@dersphere.de) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
oddard.jpg', 'channel_id': 'UCAY-SMFNfynqz1bdoaV8BeQ', 'user': 'NASAexplorer', }, { 'name': 'NASA Jet Propulsion Laboratory', 'logo': 'jpl.jpg', 'channel_id': 'UCryGec9PdUCLjpJW2mgCuLw', 'user': 'JPLnews', }, {
'name': 'NASA Kennedy Space Center', 'logo': 'nasa.jpg', 'channel_id': 'UCjJtr2fFcUp6yljzJOzpHUg', 'user': 'NASAKennedy', }, { 'name': 'Hubble Space Telescope', 'logo': 'hubble.jpg', 'channel_id': 'UCqvjEkH_41m4DYaoNQwk4Bw', 'user': 'HubbleSiteChannel...
cmusatyalab/vmnetx
vmnetx/controller/remote.py
Python
gpl-2.0
12,065
0.000912
# # vmnetx.controller.remote - Remote execution of a VM # # Copyright (C) 2008-2015 Carnegie Mellon University # # This program is free software; you can redistribute it and/or modify it # under the terms of version 2 of the GNU General Public License as published # by the Free Software Foundation. A copy of the GNU G...
urlparse import urlsplit from . import Controller, MachineExecutionError from ..protocol import ClientEndpoint, EndpointStateError from ..util import Er
rorBuffer, BackoffTimer, socketpair _log = logging.getLogger(__name__) class _ViewerConnection(object): def __init__(self, sock, token, callback): self._callback = callback self._endp = ClientEndpoint(sock) self._endp.connect('auth-ok', self._auth_ok) self._endp.connect('auth-fail...
yosukesuzuki/let-me-notify
project/kay/management/app_template/views.py
Python
mit
690
0.002899
# -*- coding: utf-8 -*- """ %app_name%.views """ """ import logging from google.appengine.api import users from google.appengine.api import memcache from werkzeug import ( unescape, redirect, Response, ) from werkzeug.exceptions import ( NotFound, MethodNotAllowed, BadRequest ) from kay.utils i
mport ( render_to_response, reverse, get_by_k
ey_name_or_404, get_by_id_or_404, to_utc, to_local_timezone, url_for, raise_on_dev ) from kay.i18n import gettext as _ from kay.auth.decorators import login_required """ from kay.utils import render_to_response # Create your views here. def index(request): return render_to_response('%app_name%/index.html', {'m...
Caoimhinmg/PmagPy
SPD/test_instance.py
Python
bsd-3-clause
3,635
0.013205
#!/usr/bin/env python from __future__ import print_function from __future__ import absolute_import import os from . import spd # K temps: [0.0, 100.0, 150.0, 200.0, 225.0, 250.0, 275.0, 300.0, 325.0, 350.0, 375.0, 400.0, 425.0, 450.0, 475.0, 500.0, 525.0, 550.0] # C temps: [273, 373.0, 423.0, 473.0, 498.0, 523.0, 548....
spec.reqd_stats() print('---------') print(calculate) def many_specimens(calculate=calculate): from itertools import combinations c = combinations(calculate, 2) for combo in c: print('combo', combo) spec = spd.PintPars(gui.Data, '0238x6011044', 473., 623., 'magic', comb...
0, 400 SCAT_spec2 = spd.PintPars(gui.Data, '0238x6011044', 273., 698.) # 0, 425 SCAT_spec.York_Regression() SCAT_spec2.York_Regression() #new_spec = spd.PintPars(gui.Data, '0238x5721062', 100. + 273., 525. + 273.) #new_spec.calculate_all_statistics() #gui2 = tgs.Arai_GUI('/consistency_tests/Yamamoto_...
ModestoCabrera/is210-week-07-warmup
task_03.py
Python
mpl-2.0
167
0
#!/usr/bin/env python # -*- coding: utf
-8 -*- """Module copies data module Variable DIRECTIONS""" from d
ata import DIRECTIONS DIRECTIONS = DIRECTIONS[0:3]+('West',)
asyncee/django-application-template
forms.py
Python
mit
69
0
# coding: utf-8 fro
m django import fo
rms from . import models as m
thombashi/DataProperty
dataproperty/__init__.py
Python
mit
792
0.002525
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@g
mail.com> """ from .__version__ import __author__, __copyright__, __email__, __license__, __version__ from ._align import Align from ._align_getter import align_getter from ._column
import ColumnDataProperty from ._common import MAX_STRICT_LEVEL_MAP, MIN_STRICT_LEVEL_MAP, NOT_QUOTING_FLAGS, DefaultValue from ._container import MinMaxContainer from ._dataproperty import DataProperty from ._extractor import DataPropertyExtractor, MatrixFormatting from ._formatter import Format from ._function impor...
iwoca/django-deep-collector
runtests.py
Python
bsd-3-clause
281
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.env
iron.setdefault("DJANGO_SETTINGS_MODULE", "tests.test_settings") from django.core.management import execute_from_command_line execute_from_command_lin
e(sys.argv[:1] + ['test'] + sys.argv[1:])
DiMartinoX/plugin.video.kinopoisk.ru
script.myshows/notification_service.py
Python
gpl-3.0
14,005
0.008925
# -*- coding: utf-8 -*- """ Handles notifications from XBMC via its own thread and forwards them on to the scrobbler """ import sys, re import xbmc import xbmcaddon import xbmcgui if sys.version_info < (2, 7): import simplejson as json else: import json import globals from myshowsapi import myshowsAPI from u...
pass elif action == "settingsChanged": Debug("[Notification] Settings changed, reloading.") globals.myshowsapi.updateSettings() else: Debug("[Notification] '%s' unknown dispatch action!" % action) def run(self): Debug("[Notification] Starting") ...
self.Monitor = myshowsMonitor(action = self._dispatch) # init myshowsapi class globals.myshowsapi = myshowsAPI() # initalize scrobbler class self._scrobbler = Scrobbler(globals.myshowsapi) # start loop for events while (not xbmc.abortRequested): ...
GPMueller/intersim
core/pyintersim/state.py
Python
mit
743
0.012113
import pyintersim.corelib as corelib import ctypes ### Load Library _core = corelib.LoadCoreLibrary(
) ### State wrapper class to be used in 'with' statement class State: """Wrapper Class for the State""" def __init__(self): self.p_state = setup() def __enter__(self): return self.p_state def __exit__(self, exc_type, exc_value, traceback): delete(self.p_state) ### Setup Sta...
ne _State_Setup.restype = ctypes.c_void_p def setup(): return _State_Setup() ### Delete State _State_Delete = _core.State_Delete _State_Delete.argtypes = [ctypes.c_void_p] _State_Delete.restype = None def delete(p_state): return _State_Delete(p_state)
openpolis/open_municipio
open_municipio/locations/admin.py
Python
agpl-3.0
267
0.007491
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from open_municipio.locations.models import Location
class LocationAdmin(admin.ModelAdmin): list_display = ('name', 'count') admin.site.register(Location, LocationAdmin
)
sunlightlabs/python-sunlight
setup.py
Python
bsd-3-clause
1,178
0.03056
#!/usr/bin/env python # Copyright (c) Sunlight Labs, 2012 under the terms and conditions # of the LICENSE file. from sunlight import __appname__, __version__ from setuptools import setup long_description = open('README.rst').read() setup( name = __appname__, version = __version__, packages = [...
author = "Paul Tagliamonte", author_email = "paultag@sunlightfoundation.com", long_description = long_description, description = 'Unified Sunlight API bindings', license = "BSD",
url = "https://github.com/sunlightlabs/python-sunlight", platforms = ['any'], classifiers = ['Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Pro...
turbinenreiter/micropython
docs/conf.py
Python
mit
10,766
0.005666
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # MicroPython documentation build configuration file, created by # sphinx-quickstart on Sun Sep 21 11:42:03 2014. # # 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 ...
directory, # add these directories to sys.path here. If the directory is relative to the # documentation root,
use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('.')) # Work out the port to generate the docs for from collections import OrderedDict micropy_port = os.getenv('MICROPY_PORT') or 'pyboard' tags.add('port_' + micropy_port) ports = OrderedDict(( ('unix', 'unix'), ('p...
agry/NGECore2
scripts/loot/lootItems/collections/shattered_crystal_shard/unknown_shard_2.py
Python
lgpl-3.0
412
0.041262
def itemTemplate(): return ['object/tangible/loot/creature_loot/collections/shared_unkno
wn_shattered_shard_fragment.iff'] def STFparams(): return ['static_item_n','col_shattered_shard_unknown_02_02','static_item_d','col_shattered_shard_unknown_02_02'] def AddToCollection(): return 'col_shattered_shards_01' def Collect
ionItemName(): return 'col_shattered_shard_piece_02' def stackable(): return 1
erudit/eruditorg
eruditorg/erudit/migrations/0083_auto_20180308_0922.py
Python
gpl-3.0
494
0.002028
# -*- coding: utf-8 -*- # Generate
d by Django 1.10.8 on 2018-03-08 14:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("erudit", "0082_auto_20180208_1331"), ] operations = [ migrations.AlterField( model_name="issue", ...
ld=models.BooleanField(default=False, verbose_name="Est publié sur www"), ), ]
Sazzadmasud/Keystone_hash_token
keystone/tests/test_content_types.py
Python
apache-2.0
58,611
0
# Copyright 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 in...
def test_invalid_token_404(self): token = s
elf.get_scoped_token() self.admin_request( path='/v2.0/tokens/%(token_id)s' % { 'token_id': 'invalid', }, token=token, expected_status=404) def test_validate_token_service_role(self): self.md_foobar = self.assignment_api.add_role_to_us...
fabian4/trove
trove/tests/unittests/guestagent/test_vertica_manager.py
Python
apache-2.0
16,382
0
# Copyright [2015] Hewlett-Packard Development Company, L.P. # 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...
meDevice.format
self.origin_migrate_data = volume.VolumeDevice.migrate_data self.origin_mount = volume.VolumeDevice.mount self.origin_unmount = volume.VolumeDevice.unmount self.origin_mount_points = volume.VolumeDevice.mount_points self.origin_set_read = volume.VolumeDevice.set_readahead_size ...
marcelometal/holmes-api
tests/unit/facters/test_head.py
Python
mit
2,889
0.000692
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.html from mock import Mock from preggy import expect from holmes.config import Config from holmes.reviewer import Reviewer from holmes.facters.head import HeadFacter from tests.unit.base import FacterTestCase from tests.fixtures import PageFactory class TestHead...
uuid, page_url=page.url, page_score=0.0, config=Config(), facters=[] ) content = '<html><head><link rel="canonical" href="http://my-url.com?item=test" /></head></html>' result = { 'url': page.url, 'status': 200, ...
reviewer.save_review = Mock() response = Mock(status_code=200, text=content, headers={}) reviewer.content_loaded(page.url, response) facter = HeadFacter(reviewer) facter.add_fact = Mock() facter.get_facts() expect(facter.review.data).to_length(1) expe...
rschnapka/purchase-workflow
purchase_landed_costs/purchase.py
Python
agpl-3.0
27,418
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-2013 Camptocamp (<http://www.camptocamp.com>) # Authors: Ferdinand Gasauer, Joel Grand-Guillaume # # This program is free software: you can...
omain=[('landed_cost_type', '!=', False)]), 'account_id': fields.many2one( 'account.account', 'Fiscal Account', required=True,), 'partner_id': fields.many2one( 'res.partner', 'Partner', help="The supplier of this cost
component.", required=True), 'distribution_type_id': fields.many2one( 'landed.cost.distribution.type', 'Distribution Type', required=True, help="Defines if the amount is to be calculated for each quantity " "or an absolute value"), ...
deepmind/dm_control
dm_control/entities/manipulators/kinova/kinova_test.py
Python
apache-2.0
11,745
0.004513
# Copyright 2019 The dm_control Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
del.worldbody).subtreemass expected_mass = 4.4 self.assertAlmostEqual(mass, expected_mass) @parameterized.parameters([ dict(actuator_index=0, control_input=0, expected_ve
locity=0.), dict(actuator_index=0, control_input=jaco_arm._LARGE_JOINT_MAX_VELOCITY, expected_velocity=jaco_arm._LARGE_JOINT_MAX_VELOCITY), dict(actuator_index=4, control_input=jaco_arm._SMALL_JOINT_MAX_VELOCITY, expected_velocity=jaco_arm._SMALL_JOINT_MAX_VELOCIT...
brownharryb/erpnext
erpnext/quality_management/doctype/quality_review/quality_review_dashboard.py
Python
gpl-3.0
347
0.005764
from frappe import _ def get_data(): return { 'fieldname': 'review', 'transactions': [ {
'label': _('Action'), 'items': ['Quality Action']
}, { 'label': _('Meeting'), 'items': ['Quality Meeting'] } ], }
grengojbo/st2
st2actions/tests/unit/test_remote_runners.py
Python
apache-2.0
6,700
0.001791
# Licensed to the StackStorm, Inc ('StackStorm') 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 th...
self.assertEqual(mock_shell_env.call_count, 0)
task.run() self.assertEqual(mock_settings.call_count, 1) self.assertEqual(mock_shell_env.call_count, 1)
lorensen/VTKExamples
src/Python/GeometricObjects/CellTypeSource.py
Python
apache-2.0
6,235
0.002887
# !/usr/bin/env python # -*- coding: utf-8 -*- import vtk def main(): cellName = get_program_parameters() # Store the cell class names in a dictionary. cellMap = dict() cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(vtk.VTK_LINE)] = vtk.VTK_LINE cellMap[vtk.vtkCellTypes.GetClassNameFromTypeId(v...
.vtkRenderWindow() renderWindow.SetWindowName("Cell Type Source") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene. renderer.AddViewProp(textActor) renderer.AddActor...
) renderer.ResetCameraClippingRange() # Render and interact. renderWindow.SetSize(640, 480) renderWindow.Render() renderWindowInteractor.Start() def get_program_parameters(): import argparse description = 'Cell Type Source.' epilogue = ''' You can supply an optional argument consi...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_02_01/operations/_route_tables_operations.py
Python
mit
29,837
0.004692
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ormat_arguments) # Construct parameters
query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) ...
frdb194/ubuntu-tweak
ubuntutweak/network/utdata.py
Python
gpl-2.0
2,772
0.003968
import os import random import urllib import time import datetime from gettext import ngettext from urlparse import urljoin from ubuntutweak.common.consts import install_ngettext from ubuntutweak.utils.tar import TarFile install_ngettext() DEV_MODE = os.getenv('UT_DEV') DATA_MIRRORS = ( 'http://ubuntu-tweak.com...
ime('%Y-%m-%d %H:%M', time.localtime(float(timestamp))) else: return _('Never') def save_synced_timestamp(folder): synced = os.path.join(folder, 'synced') f = open(synced, 'w') f.write(str(int(time.time()))) f.close() def get_last_synced(folder): try: timestamp = open(os.path.j...
erence = n_delta - o_delta weeks, days = divmod(difference.days, 7) minutes, seconds = divmod(difference.seconds, 60) hours, minutes = divmod(minutes, 60) if weeks: return ngettext('%d week ago', '%d weeks ago', weeks) % weeks if days: return ngettext('...
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Lib/asyncio/base_events.py
Python
gpl-2.0
69,268
0.000144
"""Base implementation of event loop. The event loop can be broken up into a multiplexer (the part responsible for notifying us of I/O events) and the event loop proper, which wraps a multiplexer with functionality for scheduling callbacks, immediately or at a given time in the future. Whenever a public API takes a c...
C: afs = [socket.AF_INET] if _HAS_IPv6: afs.append(socket.AF_INET6) else: afs = [family] if isinstance(host, bytes): host = host.decode('idna') if '%' in host: # Linux's inet_pton doesn't accept an IPv6 zone index after host, # like '::1%lo0'. ...
for af in afs: try: socket.inet_pton(af, host) # The host has already been resolved. if _HAS_IPv6 and af == socket.AF_INET6: return af, type, proto, '', (host, port, 0, 0) else: return af, type, proto, '', (host, port) exc...
Awingu/open-ovf
py/ovf/OvfPlatform.py
Python
epl-1.0
2,476
0.001616
# vi: ts=4 expandtab syntax=python ############################################################################## # Copyright (c) 2008 IBM Corporation # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distr...
f virtTypeIsAvailable(virtType): return virtType return None def getPlatformDict(vs, virtPlatform=None): """ Get the platform information @type node: DOM node @param node: Virtual System node @type virtPlatform: String @param node: Virtual Platform type. If None, will be taken...
environment. """ retDict = {} if not virtPlatform: virtPlatform = getVsSystemType(vs) retDict['Kind'] = virtPlatform # We could possibly look up the version and vendor here # gather the details of the platform (langCode, encoding) = getlocale() if langCode == None: (la...
epage/telepathy-python
examples/account.py
Python
lgpl-2.1
1,551
0.004513
import telepathy from telepathy.interfaces import CONN_MGR_INTERFACE import dbus def parse_account(s): lines = s.splitlines() pairs = [] manager = None protocol = None for line in lines: if not line.strip(): continue k, v = line.split(':', 1) k = k.strip() ...
else: if k not in ("account", "password"): if v.lower() == "false":
v = False elif v.lower() == "true": v = True else: try: v = dbus.UInt32(int(v)) except: pass pairs.append((k, v)) assert manager assert protocol return ma...
keithhamilton/transposer
setup.py
Python
mit
1,307
0.002295
from setuptools import setup, find_packages from codecs import open import os def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='transposer', version='0.0.3', description='Transposes column...
:: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic ::
Office/Business' ], keywords='text, csv, tab-delimited, delimited, excel, sheet, spreadsheet', packages=find_packages(exclude=['contrib', 'docs', 'test*', 'bin', 'include', 'lib', '.idea']), install_requires=[], package_data={}, data_files=[], entry_points={ 'console_scripts': [ ...
aberlanas/senia-cdd
tools/rellenarFormularioFP.py
Python
gpl-3.0
3,975
0.027946
#!/usr/bin/python3 # Instalar : # * python3-pdfrw import os from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict,PdfObject INVOICE_TEMPLATE_PATH = 'templates/9_FP_GM_I_GS_AUTOBIS.pdf' # DOCUMENTO BASE INVOICE_OUTPUT_PATH = 'invoice.pdf' #DESTINO ANNOT_KEY = '/Annots' ANNOT_FIELD_KEY = '/T' ANN...
#Check Basico 'untitled24': 'false', #Check No superado 'untitled25': 'Punto 2.1', #Punto 2.1 'untitled26': '
Punto 2.2', #Punto 2.2 'untitled27': 'Punto 2.3', #Punto 2.3 'untitled28': 'Punto 2.4', #Punto 2.4 'untitled30': 'Paiporta', #Firma Valencia 'untitled31': '28', #Firma dia 'untitled32': 'Mayo' #Firma Mes } if __name__ == '__main__': write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data...
CZ-NIC/thug
src/Analysis/androguard/decompiler/dad/writer.py
Python
gpl-2.0
25,574
0.000352
# This file is part of Androguard. # # Copyright (c) 2012 Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # 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://...
()) self.write_ext(('METHOD_START', '\n%s{\n' % self.space())) self.inc_ind() self.visit_node(self.graph.entry) self.dec_ind() self.write('%s}\n' % self.space()) self.write_ext(('METHO
D_END', '%s}\n' % self.space())) def visit_node(self, node): if node in (self.if_follow[-1], self.switch_follow[-1], self.loop_follow[-1], self.latch_node[-1], self.try_follow[-1]): return if not node.type.is_return and node in self.visited_nodes:...
bwrsandman/openerp-hr
hr_employee_legacy_id/__openerp__.py
Python
agpl-3.0
1,524
0.001312
#-*- coding:utf-8 -*- # # # Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.com>. # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation,...
etails. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # { 'name': 'Legacy Employee ID', 'version': '1.0', 'category': 'Generic Modules/Human Resources', 'description': """ Employee Identificat...
from Previous System ==================================================== When switching from a legacy HR system to a new one. It may be necessary to have a record of the ID No. used in the previous system. """, 'author': 'Michael Telahun Makonnen <mmakonnen@gmail.com>', 'website': 'http://miketelahun.wor...
yuanpengX/SE-NE
djcode/IMS/change_student_personal_info.py
Python
mit
3,064
0.007616
# -*- coding: utf-8 -*- __author__ = 'xyh' #... from head import * from models import Student_user from student_forms import StudentInfoForm LEN_OF_STUDENT_ID = 10 LEN_OF_
FACULTY_ID = 6 LEN_OF_ADMIN_ID = 3 #Note: has not finished @csrf_exempt @login_required def changeStudentInfo(request): if request.method == 'GET': print("Change Student Info:") c = {} c.update(csrf(request)) user = User.objects.get(username=str(request.user))
if user is None or not user.is_active: return HttpResponseRedirect('../home/') else: # user exists and valid form = StudentInfoForm(request.GET) if form.is_valid(): info = form.cleaned_data print request.user userid = str...
glemaitre/scikit-learn
sklearn/utils/_estimator_html_repr.py
Python
bsd-3-clause
9,492
0
from contextlib import closing from contextlib import suppress from io import StringIO from string import Template import uuid import html from .. import config_context class _VisualBlock: """HTML Representation of Estimator Parameters ---------- kind : {'serial', 'parallel', 'single'} kind ...
__control:checked~label.sk-toggleable__label { background-color: #d4ebff; } #$id div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { background-color: #d4ebff; } #$id input.sk-hidden--visually { border: 0; clip: rect(1px 1px 1px 1px); clip: rect(1px, 1px, 1px, 1px); height: 1px; ...
n: 0.25em 0.25em; border: 1px dotted black; border-radius: 0.25em; box-sizing: border-box; } #$id div.sk-estimator:hover { background-color: #d4ebff; } #$id div.sk-parallel-item::after { content: ""; width: 100%; border-bottom: 1px solid gray; flex-grow: 1; } #$id div.sk-label:hover label.sk-toggleable_...
rlr/fjord
fjord/search/tests/test_index.py
Python
bsd-3-clause
1,052
0
from fjord.base.tests import eq_, TestCase from fjord.feedback.models import ResponseMappingType from fjord.feedback.tests import ResponseFactory from fjord.search.index import chunked from fjord.search.tests import ElasticTestCase class ChunkedTests(TestCase): def test_chunked(self): # chunking nothing y...
chunked([1], 10)), [(1,)]) # chunking a list where len(list) == n eq_(list(chunked([1, 2], 2)), [(1, 2)]) # chunking list where len(list) > n eq_(list(chunked([1, 2, 3, 4, 5], 2)), [(1, 2), (3, 4), (5,)]) class TestLiveIndexing(ElasticTestCase): def
test_live_indexing(self): S = ResponseMappingType.search count_pre = S().count() s = ResponseFactory(happy=True, description='Test live indexing.') self.refresh() eq_(count_pre + 1, S().count()) s.delete() self.refresh() eq_(count_pre, S().count())
mjg/Impressive-svn
src/control.py
Python
gpl-2.0
19,439
0.003447
##### CONTROL AND NAVIGATION ################################################### # update the applications' title bar def UpdateCaption(page=0, force=False): global CurrentCaption, CurrentOSDCaption, CurrentOSDPage, CurrentOSDStatus global CurrentOSDComment if (page == CurrentCaption) and not(force):...
if override is not None: BoxZoomDarkness = override * 0.01 BoxZoomDarknessBase = override * 0.01 # c
alled each time a page is entered, AFTER the transition, AFTER entering box-fade mode def PageEntered(update_time=True): global PageEnterTime, PageTimeout, MPlayerProcess, IsZoomed, WantStatus if update_time: PageEnterTime = Platform.GetTicks() - StartTime IsZoomed = 0 # no, we don't have a pr...
pydata/pandas-gbq
pandas_gbq/schema.py
Python
bsd-3-clause
5,518
0.000362
# Copyright (c) 2017 pandas-gbq Authors All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Helper methods for BigQuery schemas""" import copy # API may return data types as legacy SQL, so maintain a mapping of aliases # from standard SQL to ...
l : dict Schema for comparison. Each item of ``fields`` should have a 'name' and a 'type' Returns ------- bool Whether the passed schema is a subset """ fields_remote = _clean_schema_fields(schema_remote.get("fields", [])) fields_local = _clean_schema_fields(schema_local...
def generate_bq_schema(dataframe, default_type="STRING"): """Given a passed dataframe, generate the associated Google BigQuery schema. Arguments: dataframe (pandas.DataFrame): D default_type : string The default big query type in case the type of the column does not exist in the sch...
FeitengLab/EmotionMap
0All/CollectData/linux_file_to_win.py
Python
mit
2,591
0.005419
import subprocess import os from unzip_rename import unzip_rename # 此处需要填写服务器IP,端口,用户名和密码,因上传github,此处隐去这些隐私信息 ip = "xx.xx.xx.xx" user = "xx" port = 22 passwd = 'xx' def download(linux_path, method='.sha1'): win_path = os.path.basename(linux_path) # 下载服务器目标文件 print('Downloading file: ') child1 = subp...
nload(linux_path) # 注意此处为相对路径,也就是只有文件名 print('Download complete!') print('Calculate local file checksum') compare_sum(win_path) print('Task ended!') return win_path if __name__ == "__main__": p
ath_temp = '/tmp/flickr{}.zip' unzip_flag = False for i in [5, 22, 25]: path = path_temp.format(i) win_path = download_check(path) if unzip_flag: unzip_rename(win_path)
lijiabogithub/QUANTAXIS
QUANTAXIS/QASpider/QAS/QAS/spiders/QASifeng.py
Python
mit
219
0
# -*- coding: utf-8 -*- import scrapy class QasifengSpider(scrapy.Spider): name = "QASifeng" allowed_domains =
["ifeng.com"] start_urls = ['http://ifeng.com/'] def parse(self, response):
pass
trawick/edurepo
src/edurepo/resources/models.py
Python
apache-2.0
4,199
0.002382
from django.core.exceptions import ValidationError from django.db import models from django.contrib.auth.models import User from urlparse import urlparse from repo.models import LearningObjective def validate_resource_url(u): o = urlparse(u) if o.scheme not in ['http', 'https']: raise ValidationError(...
ators=[validate_resource_url]) notes = models.CharField(max_length=1000, blank=True) when_
added = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "Resource %d for %s: %s" % (self.id, self.objective.id, self.url) class Meta: unique_together = ('objective', 'url') class ResourceSubmission(models.Model): user = models.ForeignKey(User, on_delete=models.CASCA...
turdusmerula/kicad-plugins
pcbnew/python/plugins/sfm10_wizard.py
Python
gpl-3.0
6,078
0.003949
# 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 hope that it will be useful,...
_width = body[self.body_width_key] body_horz_offset = body[self.body_horz_offset_key]
body_length = body[self.body_length_key] body_x_margin = body[self.body_x_margin_key] body_y_margin = body[self.body_y_margin_key] body_clearance = body[self.body_clearance_key] body_minlength = body[self.body_minlength_key] #bottom row pin1Pos = pcbnew.wxPoint(0...
richo/hw_rand
setup.py
Python
mit
263
0.057034
from distutils.core import setup, Extension module1 = Extension('hw_ran
d', sources = ['hw_randmodule.c']) setup (name = 'HwRand', version = '1.0', description = 'Interface for poking at intel\'s RDRAND
', ext_modules = [module1])
dentaku65/plugin.video.sod
platformcode/xbmctools.py
Python
gpl-3.0
40,049
0.020993
# -*- coding: utf-8 -*- #------------------------------------------------------------ # streamondemand - XBMC Plugin # XBMC Tools # http://blog.tvalacarta.info/plugin-xbmc/streamondemand/ # Modificado por super_berny: inclusion de infoLabels #------------------------------------------------------------ import urllib, ...
contextCommands.append((config.get_localized_string( 30300 ),DeleteCommand)) if "4" in item.context: searchSubtitleCommand = "XBMC.RunPlugin(%s?%s)" % ( sys.argv[ 0 ] , item.clone(channel="subtitletools", action="searchSubtitle").tourl()) contextCommands.append(("XBMC Subtitle",searchSubtitleC...
if "5" in item.context: trailerCommand = "XBMC.Container.Update(%s?%s)" % ( sys.argv[ 0 ] , item.clone(channel="trailertools", action="buscartrailer").tourl()) contextCommands.append((config.get_localized_string(30162),trailerCommand)) if "6" in item.context:# Ver canal en vivo en justintv ...
jmvrbanac/barbican
functionaltests/api/v1/behaviors/base_behaviors.py
Python
apache-2.0
1,531
0
""" Copyright 2014 Rackspace 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 dist...
e id from reference. The id must be the last item in the href. :param href: The href containing the id. :returns the id portion of the href """ item_id = None if href and len(href) > 0:
base, item_id = os.path.split(href) return item_id
chrisspen/asklet
asklet/management/commands/asklet_estimate.py
Python
lgpl-3.0
1,688
0.008886
#!/usr/bin/python import random import datetime import os import sys import time from optparse import make_option from django.conf import settings from django.core.management.base import BaseCommand from django.db import connection, reset_queries from django.db.transaction import commit_on_success, rollback from djang...
ight(subject, predicate, object): # Check for an explicit weight. try: return models.TargetQuestionWeight.objects.get( target__slug=subject, question__conceptnet_predicate=predicate,
question__conceptnet_object=object ) except models.TargetQuestionWeight.DoesNotExist: pass # Otherwise, attempt inference. class Command(BaseCommand): help = 'Estimates an edge in a domain.' args = '' option_list = BaseCommand.option_list + ( make_option('-...
wikimedia/operations-debs-contenttranslation-hfst
python/doc/hfst/exceptions/__init__.py
Python
gpl-3.0
7,967
0.005021
## @package hfst.exceptions ## exceptions... ## Base class for HfstExceptions. Holds its own name and the file and line number where it was thrown. class HfstException: ## A message describing the error in more detail. def what(): pass ## Two or more HfstTransducers are not of the same type. Same as H...
sAreNotAutomataException(HfstExceptio
n): pass ## The state number argument is not valid. # # An example : # # \verbatim # tr = hfst.HfstBasicTransducer() # tr.add_state(1) # try: # w = tr.get_final_weight(2) # except hfst.exceptions.StateIndexOutOfBoundsException: # print('State number 2 does not exist') # \endverbatim class StateIndexOu...
ioguntol/NumTy
numty/congruences.py
Python
mit
3,551
0.012954
import primes as py def lcm(a, b): return a * b / gcd(a, b) def gcd(a, b): while b != 0: (a, b) = (b, a % b) return a # Returns two integers x, y such that gcd(a, b) = ax + by def egcd(a, b): if a == 0: return (0, 1) else: y, x = egcd(b % a, a) return (x - (b ...
(len(congruences)): m = congruences[j][2] if gcd(m, M/m) !
= 1: return None x += congruences[j][1] * modInverse(M/m, m) * M / m return x % M # Returns the incongruent solution to any system of linear congruences def linCongrSystem(congruences): newCongruences = [] for i in xrange(len(congruences)): ...
fzimmermann89/pyload
module/plugins/hoster/WuploadCom.py
Python
gpl-3.0
586
0.011945
# -*- coding: utf-8 -*- from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo class WuploadCom(DeadHoster): __na
me__ = "WuploadCom" __type__ = "hoster" __version__ = "0.25" __status__ = "stable" __pattern__ = r'http://(?:www\.)?wupload\..+?/file/((\w+/)?\d+)(/.*)?' __config__ = [] #@TODO: Remove in 0.4.10 __description__ = """Wupload.com hoster plugin""" __license__ = "GPLv
3" __authors__ = [("jeix", "jeix@hasnomail.de"), ("Paul King", None)] getInfo = create_getInfo(WuploadCom)
azumimuo/family-xbmc-addon
plugin.video.phstreams/resources/lib/resolvers/stream4free.py
Python
gpl-2.0
582
0.015464
from resources.lib.modules import client from resources.lib.modules import cloudflare import re,sys,urllib,urlparse,base6
4,urllib2 domains = ['stream4free.pro', 'stream4free.eu'] def resolve(url): try: result = cloudflare.request(url) items = client.parseDOM(result, 'video', attrs={'id': 'live_player'}) url = client.parseDOM(items, 'source', ret='src')[0] if ('http') in url: return url+'|User-Agen...
/537.36' except: return None
michalwiacek/simplegenerator
tests/regenerator_tests.py
Python
mit
6,967
0.000574
#!/usr/bin/env python # -*- coding: utf-8 -*- from pyparsing import ParseFatalException from simplegenerator import ReGenerator import unittest class ReGeneratorTest(unittest.TestCase): def setUp(self): self.alphanum_pattern = "[a-zA-Z0-9_]" self.alpha_pattern = "[a-zA-Z]" self.num_patter...
result = test_gen.gener
ate() self.assertEqual(len(result), 1) self.assertRegexpMatches(result, self.alphanum_pattern) self.assertRegexpMatches(result, self.alphanum_short_pattern) def short_num_character_without_repeatition_test(self): test_gen = ReGenerator(self.numbers_short_pattern) result = te...
rrahn/jst_bench
include/seqan/apps/seqcons2/tests/run_tests.py
Python
gpl-3.0
7,418
0.002292
#!/usr/bin/env python """Execute the tests for the seqcons2 program. The golden test outputs are generated by the script generate_outputs.sh. You have to give the root paths to the source and the binaries as arguments to the program. These are the paths to the directory that contains the 'projects' directory. Usage...
=========' # Compute and return return code. return failures != 0 if __name__ == '__main__': sys.exit(app
_tests.main(main))
dkopecek/amplify
third-party/quex-0.65.2/quex/engine/generator/state/transition_map/bisection.py
Python
gpl-2.0
753
0.003984
from quex.blackboard import Lng class Bisection(object): __slots__ = ("bisection_value", "low", "high") def __init__(self, BisectionValue, Low, High): """TM -- transition map MOAT -- Most Often Appearing Target """
self.bisection_value = BisectionValue self.low = Low self.high = High def implement(self): global Lng txt = [ Lng.IF_INPUT("<", self.bisection_value) ] txt.extend( self.low.implement() ) txt.append( ...
nd( "%s\n" % Lng.END_IF() ) return txt
AtmaMani/pyChakras
python_parallel_concurrency/part1_ex_files/CH03/03_04/end/mutual_exclusion.py
Python
mit
674
0.002967
#!/usr/bin/env python3 """ Two shoppers adding items to a shared notepad """ import threading import time garlic_count = 0 pencil = threading.
Lock() # create mutex obj def shopper(): global garlic_count for i in range(5): print(threading.current_thread().getName(), 'is thinking.') time.sleep(0.5) pencil.acquire() garlic_count += 1 pencil.release() if __name__ == '__main__': barron = threading...
barron.join() olivia.join() print('We should buy', garlic_count, 'garlic.')
asoliveira/NumShip
scripts/plot/beta-velo-cg-plt.py
Python
gpl-3.0
2,086
0.032274
#!/usr/bin/env python # -*- coding: utf-8 -*- #É adimensional? adi = False #É para salvar as figuras(True|False)? save = True #Caso seja para salvar, qual é o formato desejado? formato = 'jpg' #Caso seja para salvar, qual é o diretório que devo salvar? dircg = 'fig-sen' #Caso seja para salvar, qual é o nome do arquivo...
or = pc, linestyle = ps, linewidth = 1, label=ur'padrão') plt.plot(velohis2[:, 0], velohis2[:, 1], color = r1c,linestyle = r1s, linewidth = 2, label=ur'1.1beta') plt.scatter(somep(velohis3[:, 0], num = 200), somep(velohis3[:, 1], num = 200), color = r2c, marker = r2s, s = 8, label=ur'1.2beta')
plt.scatter(somep(velohis4[:, 0], num = 100), somep(velohis4[:, 1], num = 100), color = r3c, marker = r3s, s = 20, label=ur'1.3beta') plt.title(titulo) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.ylabel(ylabel) plt.xlabel(xvelolabel) plt.axis(axl) plt.grid(True) if save: if not os.path.exist...
latticelabs/Mitty
mitty/tests/benchmarking/perfectbam_test.py
Python
gpl-2.0
1,522
0.003942
import pysam from nose.tools import assert_raises def create_small_bam(bam_name): """Create a small bam file that has a correctly aligned read, a read with wrong chrom, a read with wrong pos and a read with wrong CIGAR. Make sure the analysis of this BAM is correct""" header = { 'HD': {'SO': 'coordinate',...
|0|1|4=|1|5|4=' r4.
query_sequence = 'ACTG' r4.flag = 0b000010010011 r4.reference_id = 1 r4.pos = 5 r4.cigar = '4M'
apllicationCOM/youtube-dl-api-server
youtube_dl_server/test/test_download.py
Python
unlicense
8,537
0.002577
#!/usr/bin/env python from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from test.helper import ( assertGreaterEqual, expect_warnings, get_params, gettestcases, expe...
alled) expected_minsize = tc.get('file_minsize', 10000) if expected_minsize is not None: if params.get('test'): expected_minsi
ze = max(expected_minsize, 10000) got_fsize = os.path.getsize(tc_filename) assertGreaterEqual( self, got_fsize, expected_minsize, 'Expected %s to be at least %s, but it\'s only %s ' % (tc_...
nuigroup/pymt-widgets
pymt/weakmethod.py
Python
lgpl-3.0
1,945
0.002571
''' WeakMethod: implementation of weakref for function and bounded method. This class is used in Clock class, to prevent the clock of taking memory if the object is deleted. Check examples/core/clock_method.py for more informations. This WeakMethod class is taken from the recipe http://code.activestate.com/recipes/81...
= weakref.ref(method.im_self) else: # unbound method self._obj = None self._func = method.im_func self._class = method.im_class except AttributeError: # not a method self._obj = None self._func = method ...
self._class = None def __call__(self): '''Return a new bound-method like the original, or the original function if refers just to a function or unbound method. Returns None if the original object doesn't exist ''' if self.is_dead(): return None if...
wscullin/spack
var/spack/repos/builtin/packages/xdm/package.py
Python
lgpl-2.1
1,876
0.000533
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
ms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ter...
ng with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Xdm(AutotoolsPackage): """X Display Manager / XDMCP server.""" homepage =...
jsurloppe/remix
remix/mixins/request.py
Python
bsd-3-clause
4,591
0.002614
import threading from copy import deepcopy from functools import reduce from requests import exceptions from remix import utils class RaiseForStatusMixin(object): def process_request(self, *args, **kwargs): response = super(RaiseForStatusMixin, self).process_request(*args, **kwargs) response.rai...
ache is None: raise utils.SettingsRequired def process_request(self, method, url, cache
_key=None, force_cache_regen=False, **kwargs): cache_key = self.get_cache_key(method, url, cache_key, **kwargs) self._tdata.prefer_cache_key = cache_key + self.prefer_cache_key_suffix if not force_cache_regen and self.hot_cache.get(self._tdata.prefer_cache_key): return self.cold_cac...
JohnCEarls/tcDirac
tcdirac/__init__.py
Python
gpl-2.0
143
0
import sys from t
cdirac import static __version__ = static.VE
RSION __author__ = "John C. Earls (john.c.earls@gmail.com)" __all__ = ["static"]
cdondrup/turtlebot_behaviours
turtlebot_prey_behaviour/setup.py
Python
mit
259
0
from distutils.core import setup from catkin_pkg.python_setup import gener
ate_distutils_setup # fetch values from package.xml setup_args = generate_distutils_setup( packa
ges=['turtlebot_prey_behaviour'], package_dir={'': 'src'}) setup(**setup_args)
schalkneethling/bedrock
bedrock/firefox/tests/test_views.py
Python
mpl-2.0
40,623
0.002043
# 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/. imp
ort json from urlparse import parse_qs from django.test import override_settings from django.test.client import RequestFactory import querystringsafe_base64 from mock import patch, Mock from nose.tools import eq_, ok_ from pyquery import PyQuery as pq from bedrock.firefox import views from bedrock.mozorg.tests impor...
s TestStubAttributionCode(TestCase): def _get_request(self, params): rf = RequestFactory() return rf.get('/', params, HTTP_X_REQUESTED_WITH='XMLHttpRequest', HTTP_ACCEPT='application/json') def test_not_ajax_request(self): req = RequestFactory...
ddico/odoo
addons/website_sale/wizard/payment_acquirer_onboarding_wizard.py
Python
agpl-3.0
539
0.001855
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class Payme
ntWizard(models.TransientModel): _inherit = 'payment.acquirer.onboarding.wizard' _name = 'website.sale.payment.acquirer.onboarding.wizard' _descrip
tion = 'Website Payment acquire onboarding wizard' def _set_payment_acquirer_onboarding_step_done(self): """ Override. """ self.env.company.sudo().set_onboarding_step_done('website_sale_onboarding_payment_acquirer_state')
typeinference/jigsaw-puzzle
src/measures.py
Python
mit
1,631
0.003066
# -*-coding: utf-8 -*- import math import numpy as np import relations def _avg_difference(npiece, side): if side == relations.LEFT: difference = npiece[:, 0] - npiece[:, 1] elif side == relations.RIGHT: difference = npiece[:, -1] - npiece[:, -2] elif side == relations.UP: differe...
else: di
fference = npiece[-1, :] - npiece[-2, :] return sum(difference)/float(len(difference)) def _gradient(pieces_difference, average_side_difference): grad = pieces_difference - average_side_difference grad_t = np.transpose(grad) cov = np.cov(grad_t) try: cov_inv = np.linalg.inv(cov) excep...
ellmetha/django-machina
tests/models.py
Python
bsd-3-clause
1,013
0.002962
from django.db import models from mach
ina.models.fields import ExtendedImageField, MarkupTextField RESIZED_IMAGE_WIDTH = 100 RESIZED_IMAGE_HEIGHT = 100 VALIDATED_IMAGE_MIN_WIDTH = 100 VALIDATED_IM
AGE_MAX_WIDTH = 120 VALIDATED_IMAGE_MIN_HEIGHT = 100 VALIDATED_IMAGE_MAX_HEIGHT = 120 VALIDATED_IMAGE_MAX_SIZE = 12000 class DummyModel(models.Model): """ This model will be used for testing purposes only. """ content = MarkupTextField(null=True, blank=True) resized_image = ExtendedImageField( ...
leb2dg/osf.io
api_tests/preprints/views/test_preprint_list.py
Python
apache-2.0
38,270
0.000366
import mock from nose.tools import * # flake8: noqa import pytest from addons.github.models import GithubFile from api.base.settings.defaults import API_BASE from api_tests import utils as test_utils from api_tests.preprints.filters.test_filters import PreprintsListFilteringMixin from api_tests.preprints.views.tes
t_preprint_list_mixin import ( PreprintIsPublishedListMixin, PreprintListMatchesPreprintDetailMixin, PreprintIsValidListMixin, ) from api_tests.reviews.mixins.filter_mixins import ReviewableFilterMixin from osf.models import PreprintService, Node from osf.utils.workflows import DefaultStates from osf_tes
ts.factories import ( ProjectFactory, PreprintFactory, AuthUserFactory, SubjectFactory, PreprintProviderFactory, ) from tests.base import ApiTestCase, capture_signals from website.project import signals as project_signals from website.util import permissions def build_preprint_create_payload( ...
Wollert/beer
test_run.py
Python
mit
1,166
0.000858
import RPi.GPIO as GPIO import time import utils GPIO.setmode(GPIO.BOARD) pwr = utils.PSU(13, 15) pwr.on() print "Power on" fan = utils.Fan(32) fan.setDC(90) print "Fan set at 90%" pump = utils.NMOS(11) pump.on() print "Pump on" relay = utils.NMOS(16) relay.on() print "Peltier on" t_amb = utils.Therm('28-000004...
mp() t_c_m.store_temp() t_c_t.store_temp() t_hs.store_temp() # print "Ambient temperature: " + str(t_amb.store_temp()) # print "Down temperature in cooler: " + str(t_c_b.store_temp()) # print "Middle temperature in cooler: " + str(t_c_m.store_te
mp()) # print "Up temperture in cooler: " + str(t_c_t.store_temp()) # print "Heatsink temperature: " + str(t_hs.store_temp()) except KeyboardInterrupt: print "Exiting gracefully" relay.off() print "Peltier off" pump.off() print "Pump off" pwr.off() print "Power off" GPIO.cleanup() print "Goodbye!...
gtoolframework/gtool
gtool/plugins/average.py
Python
gpl-3.0
881
0.00227
from gtool.core.types.core import Aggregator class Average(Aggregator): def __init__(self, config=None): super(Average, self).__init__(config=config) def compute(self): selectionDict = super(Average, self).compute() _selection = [v for v in selectionDict.values()][0] _name =...
values.extend(_values) else: values.append(selectedvalue) if len(va
lues) == 0: _result = None else: _result = sum(values)/len(values) return {'name':_name, 'result': _result} def load(): return Average
charany1/Bookie
bookie/tests/test_api/test_social_api.py
Python
agpl-3.0
1,628
0.000614
import json import transaction from mock import patch from bookie.tests import factory from bookie.tests import TestViewBase class TestSocialConnectionsApi(TestViewBase): """Check if SocialConnections API returns all the added accounts""" def testBaseApi(self): factory.make_twitter_connection() ...
tions']
[0]['username'], 'Username should be admin') def testSocialAuthentication(self): """Test to check that user login is required to do this api call""" res = self.app.get('/api/v1/admin/social_connections', status=403) self.assertEqual( ...
fulfilio/nereid-cms
tests/__init__.py
Python
bsd-3-clause
578
0
# -*- coding: utf-8 -*- """ __init__ Collect all tests here """ import unittest from .test_banner import TestBanner, TestGetHtml from .test_cms import TestCMS from .test_menuitem import TestMenuItem def suite(): test_suite = unittest.TestSuite() test_suite.addTests([ unittest.TestLoader().l...
omTestCase(TestGetHtml), unittest.TestLoader().loadTestsFromTestCase(TestCMS), unittest.TestLoader().lo
adTestsFromTestCase(TestMenuItem), ]) return test_suite
vinx13/WikiCrawler
HtmlParser.py
Python
mit
982
0.002037
import bs4 from Entry import Entry class HtmlParser(object): def __init__(self, html, url): self.html = html self.url = url def parse(self): soup = bs4.BeautifulSoup(self.html, "lxml") mainContent = soup.find(id='mw-content-text') catagoryContent = soup.find(id="mw-no...
soup.find(id='firstHeading').contents[0] children = filter(lambda url: url.startswith("/wiki") and ':' not in url, map(lambda tag: (tag['href']), mainContent.find_all('a'))) if catagoryContent: catagories = map(lambda aTag: aTag[
'title'].lstrip("Category:"), filter(lambda aTag: (aTag['href'].startswith('/wiki/Category:')), catagoryContent.find_all('a'))) if catagories is None: catagories = [] return Entry(self.url, title, children, catagories)
chenkianwee/envuo
py4design/pycitygml/write_gml.py
Python
gpl-3.0
37,271
0.01752
# ================================================================================================== # # Copyright (c) 2016, Chen Kian Wee (chenkianwee@gmail.com) # # This file is part of py4design # # py4design is free software: you can redistribute it and/or modify # it under the terms of the GNU General ...
espaces.gen + "}" +'doubleAttribute') gen_doubleAttribute.attrib['name'] = name gen_value = SubElement(gen_doubleAttribute, "{" + XMLNamespaces.gen + "}" +'value') gen_value.tex
t = str(attrib) if type(attrib) == str: gen_stringAttribute = SubElement(parent_node, "{" + XMLNamespaces.gen + "}" +'stringAttribute') gen_stringAttribute.attrib['name'] = name gen_value = SubElement(gen_stringAttribute, "{" + XMLNamespaces.gen + "}" +'value') ...
aquamatt/Peloton
src/tools/ptap/evtap.py
Python
bsd-3-clause
4,829
0.009526
#!/usr/bin/python # $Id$ # # Copyright (c) 2007-2008 ReThought Limited and Peloton Contributors # All Rights Reserved # See LICENSE for details """ Quick and dirty tool for tapping into the event bus and dumping events posted to a given exchange and key. Key may be specified as a pattern in AMQP format. """ from peloto...
nn.addEventHandler(options.key, options.exchange, eventReceived) def disconnected(): global disconnectedTime if disconnectedTime == 0: outputMessage("EVTAP DISCONNECTED -- attempting reconnect") disconnectedTime += 1 def main(): global tapConn, options, outputMessage usage = "usage: %p...
help="Host for PSC to contact [default %default]", default="localhost") parser.add_option("--key", "-k", help="""Message key - may include the wildcards # (match zero or more tokens) or * (match a single token) as defined in the AMQP specification [default %default]...
django-master/django-master
djangomaster/__init__.py
Python
mit
404
0.00495
import os from djangomaster.core import
autodiscover from djangomaster.sites import mastersite def get_version(): path = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(path, 'version.txt') return open(path).read().strip() __version__ = get_version() def get_urls(): autodiscover() return mastersite.urlpatterns, 'django
master', 'djangomaster' urls = get_urls()
mppmu/secdec
examples/easy_cuda/generate_easy.py
Python
gpl-3.0
197
0.081218
from pySecDec import make_package make_package( name = 'easy', integration_variables = ['x','y'], regulators =
['eps'],
requested_orders = [0], polynomials_to_decompose = ['(x+y)^(-2+eps)'], )
miumok98/weblate
weblate/billing/migrations/0001_initial.py
Python
gpl-3.0
1,726
0.001159
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('trans', '0045_auto_20150916_1007'), ]...
me', models.CharField(unique=True, max_length=100)), ('price', models.IntegerField()), ('limit_strings', models.IntegerField()), ('limit_languages', models.IntegerField()), ('limit_repositories', models.IntegerField()), ('limit_projects', m...
d( model_name='billing', name='plan', field=models.ForeignKey(to='billing.Plan'), ), migrations.AddField( model_name='billing', name='projects', field=models.ManyToManyField(to='trans.Project', blank=True), ), migrat...
soonsam123/Django_FKSC
filiados/views.py
Python
mit
1,253
0.010375
from .models import Academia, Atleta, Preta from django.shortcuts import ren
der def index(request): return render(request, 'inicial/index.html') def ordenar_num(lista): for
i in range(0,len(lista)): for j in range(i,len(lista)): if lista[i] >= lista[j]: lista[i], lista[j] = lista[j], lista[i] return lista def ordenar(todas_academias): lista = [] for academia in todas_academias: lista = lista + [academia.num_reg] num_organizados...
Ircam-Web/mezzanine-organization
organization/projects/migrations/0086_auto_20190619_2029.py
Python
agpl-3.0
1,124
0.001779
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-06-19 18:29 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('organization_projects', '0...
e his team's content")), 'verbose_name': 'project', 'verbose_name_plural': 'projects'}
, ), migrations.AlterField( model_name='project', name='user', field=models.ForeignKey(default=4, on_delete=django.db.models.deletion.CASCADE, related_name='projects', to=settings.AUTH_USER_MODEL, verbose_name='Author'), preserve_default=False, ), ...
JamieCressey/apt-s3
apts3/resources/lock.py
Python
apache-2.0
29
0
class
Lock(object): pa
ss
wolfhechel/alfred-code
finders/sublime/__init__.py
Python
mit
1,625
0.004923
from os import path import json from .._base import BaseFinder class SublimeTextFinder(BaseFinder): application_id = 'com.sublimetext.3' sublime_application_path = path.expanduser('~/Library/Application Support/Sublime Text 3/Local') def load_json_file(self, json_file): json_data = None ...
, strict=False) # Sublime doesn't properly encode their control characters return json_data def find_subl_path(self): import AppKit workspace = AppKit.NSWorkspace.sharedWorkspace() app_path = workspace.fullPathForApplication_(self.app_name) subl_path = path.join(app
_path, 'Contents', 'SharedSupport', 'bin', 'subl') return subl_path def open_command(self, project_path): return (self.find_subl_path(), '--project', project_path) def find_items(self): sublime_session_path = path.join(self.sublime_application_path, 'Session.sublime_session') ...