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
MichaelGrupp/evo
test/test_filters.py
Python
gpl-3.0
6,476
0
#!/usr/bin/env python """ unit test for filters module author: Michael Grupp This file is part of evo (github.com/MichaelGrupp/evo). evo 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 Li...
th.pi tol = 0.001 expected_result = [(0, 3), (0, 4)] # Result should be unaffected by global transformation. for poses in (POSES_6, POSES_6_TRANSFORMED): id_pairs = filters.filter_pairs_by_angle(poses, target_angle, tol, al...
unittest.main(verbosity=2)
kevin-zhaoshuai/zun
zun/db/sqlalchemy/alembic/versions/9fe371393a24_create_table_container.py
Python
apache-2.0
1,820
0.001648
# 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 # d...
D: 9fe371393a24 Revises: a9a92eebd9a8 Create Date: 2016-06-12 16:09:35.686539 """ # revision identifiers, used by Alembic. revision =
'9fe371393a24' down_revision = 'a9a92eebd9a8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa import zun def upgrade(): op.create_table( 'container', sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nulla...
dwillis/socialcongress
tracker/utils.py
Python
unlicense
6,562
0.006248
import datetime from tracker.models import Member, Report from django.template.defaultfilters import slugify import csv import urllib import simplejson as json from dateutil.parser import * import time def update_twitter(branch='house', official=True, batch=1): if official: screen_names = [x.official_twit...
= 2: screen_names = screen_names[100:200] elif batch == 3:
screen_names = screen_names[200:300] elif batch == 4: screen_names = screen_names[300:400] elif batch == 5: screen_names = screen_names[400:] url = "http://api.twitter.com/1/users/lookup.json?screen_name=%s" % ",".join(screen_names) response = urllib.urlopen(url).read() results = jso...
autocorr/besl
besl/clump_match.py
Python
gpl-3.0
37,622
0.000983
""" =============== Clump Match All =============== Merge catalogs based on clump label masks """ import os import numpy as _np import pandas as _pd import catalog from .image import sample_bgps_img def clump_match_water(bgps=[], out_filen='bgps_maser', verbose=False): """ Match maser catalog observations ...
Name of output catalog, comma seperated verbose : boolean, default False Print clump and number of matches Returns ------- bgps : pd.DataFrame """ # read in catalogs corn = catalog.read_cornish(exten='hii')
if len(bgps) == 0: bgps = catalog.read_bgps() # add new columns new_cols = ['corn_n'] for col in new_cols: bgps[col] = _np.nan # make haystacks corn_hs = corn[['glon', 'glat']].values # galactic # loop through clumps for cnum in bgps['cnum']: cnum_select = bgps.cnum ...
emonty/pyos
pyos/clouddatabases.py
Python
apache-2.0
30,566
0.003991
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c)2012 Rackspace US, 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.a...
turn body def create_backup(self, instance, name, description=None): """ Creates a backup of the specified instance, giving it the specified name along with an optional description. """ body = {"backup": { "instance": utils.get_id(instance), ...
}} if description is not None: body["backup"]["description"] = description uri = "/backups" resp, resp_body = self.api.method_post(uri, body=body) mgr = self.api._backup_manager return CloudDatabaseBackup(mgr, body.get("backup")) def restore_backu...
binoculars/osf.io
osf/models/mixins.py
Python
apache-2.0
26,369
0.002237
import pytz from django.apps import apps from django.contrib.auth.models import Group from django.core.exceptions import ObjectDoesNotExist from django.db import models, transaction from django.utils import timezone from django.utils.functional import cached_property from guardian.shortcuts import assign_perm from gua...
nstance def remove_tag(self, *args, **kwargs): raise NotImplementedError('Removing tags requires that remove_tag is implemented') def add_system_tag(self, tag, save=True): if isinstance(tag, Tag) and not tag.system: raise ValueError('Non-system tag passed to add_sy
stem_tag') return self.add_tag(tag=tag, auth=None, save=save, log=False, system=True) def add_tag_log(self, *args, **kwargs): raise NotImplementedError('Logging requires that add_tag_log method is implemented') def on_tag_added(self, tag): pass class Meta: abstract = True ...
hglkrijger/WALinuxAgent
tests/common/osutil/test_default.py
Python
apache-2.0
36,933
0.002626
# Copyright 2018 Microsoft Corporation # # 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...
osutil.DefaultOSUtil().read_route_table() self.assertEqual(len(raw_route_list), 6) self.assertEqual(textutil.hash_strings(raw_route_list), known_sha1_hash) route_list = osutil.DefaultOSUtil().get_list_of_routes(raw_route_list) self.assertEqual(len(route_list), 5) self.assertEq...
(route_list[1].mask_quad(), '255.255.255.192') self.assertEqual(route_list[2].destination_quad(), '168.63.129.16') self.assertEqual(route_list[1].flags, 1) self.assertEqual(route_list[2].flags, 15) self.assertEqual(route_list[3].flags, 7) self.assertEqual(route_list[3].metric, 0)...
stephenfin/patchwork
patchwork/api/index.py
Python
gpl-2.0
942
0
# Patchwork - automated patch tracking system # Copyright (C) 2016 Linaro Corporation # # SPDX-License-Identifier: GPL-2.0-or-later from rest_framewo
rk.response import Response from rest_framework.reverse import reverse from rest_framework.views import APIView class IndexView(APIView): def get(self, request, *args, **kwargs): """List API resources.""" return Response({ 'projects': reverse('api-project-l
ist', request=request), 'users': reverse('api-user-list', request=request), 'people': reverse('api-person-list', request=request), 'patches': reverse('api-patch-list', request=request), 'covers': reverse('api-cover-list', request=request), 'series': reverse('a...
jordillull/unit-tests-uib-2015
code_sample/python/mock_finished.py
Python
mit
1,336
0.005988
import unittest from unittest.mock import Mock class Mailer: def send_email(self, email, message): raise NotImplementedError("Not implemented yet") class DB: def insert_user(self, user): raise NotImplementedError("Not implemented yet") class User: def __init__(self, email, name): ...
testRegisterUser(self): mock_db = Mock(DB) mock_mailer = Mock(Mailer) user = registerUser(self.TEST_EMAIL, self.TEST_NAME, mock_db, mock_mailer) mock_db.insert_user.assert_called_once_with(user) mock_mailer.send_email.assert_called_once_with(self.TEST_EMAIL, "Welcome") ...
self.TEST_EMAIL) self.assertEqual(user.name, self.TEST_NAME) def testRegisterUserThrowsNotImplemented(self): with self.assertRaises(NotImplementedError): user = registerUser(self.TEST_EMAIL, self.TEST_NAME, DB(), Mailer()) if __name__ == '__main__': unittest.main()
repotvsupertuga/repo
plugin.program.jogosEmuladores/service.py
Python
gpl-2.0
20,151
0.033199
import xbmc, xbmcaddon, xbmcgui, xbmcplugin,os,base64,sys,xbmcvfs import urllib2,urllib import zipfile import extract import downloader import re import time import common as Common import wipe import plugintools from random import randint USERDATA = xbmc.translatePath(os.path.join('special://home/userdata','')) ...
n currversion: if vernumber > 0: req = urllib2.Request(checkurl) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') try: response = urllib2.urlopen(req) except: sys.exit(1)
link=response.read() response.close() match = re.compile('<build>'+build+'</build><version>(.+?)</version><fresh>(.+?)</fresh>').findall(link) for newversion,fresh in match: if fresh =='false': # TRUE if newversion > vernumber: updateurl = KryptonOne req =...
mferenca/HMS-ecommerce
ecommerce/extensions/checkout/apps.py
Python
agpl-3.0
349
0.002865
from django.apps import AppConfig class CheckoutAppConfig(AppConfig): name = 'ecommerce.extensions.checkout' verbose_name = 'Checkout' def ready(self): super(CheckoutAppConfig, self).ready() # noinspection PyUnresolvedReferences
import ecommerce.ext
ensions.checkout.signals # pylint: disable=unused-variable
peoplepower/botengine
com.ppc.Bot/utilities/dailyreport.py
Python
apache-2.0
1,792
0.004464
""" Created on November 20, 2019 This file is subject to the terms and conditions defined in the file 'LICENSE.txt', which is part of this source code package. @author: David Moss """ # Section ID's SECTION_ID
_ALERTS = "alerts" SECTION_ID_NOTES = "notes" SECTION_ID_TASKS = "tasks" SECTION_ID_SLEEP = "sleep" SECTION_ID_ACTIVITIES = "activities" SECTION_ID_MEALS = "meals" SECTION_ID_MEDICATION = "medication" SECTION_ID_BATHROOM = "bathroom" SECTION_ID_SOCIAL = "social" SECTION_ID_MEMORIES = "memories" SECTION_ID_SYSTEM = "sys...
comment=None, subtitle=None, identifier=None, include_timestamp=False, timestamp_override_ms=None): """ Add a section and bullet point the current daily report :param botengine: BotEngine environment :param location_object: Location object :param section_id: Section ID like dailyreport.SECTION_ID_A...
access-missouri/am-django-project
am/finance/models/managers/__init__.py
Python
bsd-2-clause
159
0.006289
# -*- coding: utf-8 -*- """ Custom model managers for finance. """ from .entity
_manager import FinanceEntityManager __all__ = (
'FinanceEntityManager', )
mirestrepo/voxels-at-lems
super3d/boxm2_create_scene.py
Python
bsd-2-clause
1,566
0.030013
#THIS IS /helicopter_providence/middletown_3_29_11/site1_planes/boxm2_site1_1/boxm2_create_scene.py from boxm2WriteSceneXML import * import optparse from xml.etree.ElementTree import ElementTree import os, sys #Parse inputs parser = optparse.OptionParser(description='Create BOXM2 xml file'); parser.add_opt...
tree.parse(scene_info); #find scene dimensions bbox_elm = tree.getroot().find('bbox'); if bbox_elm is None: print "Invalid info file: No bbox" sys.exit(-1); minx = float(bbox_elm.get('minx')); miny = float(bbox_elm.get('miny')); minz = float(bbox_elm.get('minz')); maxx = float(bbox_elm.get('maxx...
solution'); if res_elm is None: print "Invalid info file: No resolution" sys.exit(-1); resolution = float(res_elm.get('val')); print ("Resolution: " + str(resolution)); #PARAMETERS ntrees=32 max_num_lvls=4 min_pt = [minx, miny, minz] max_pt = [maxx, maxy, maxz] writeSceneFromBox(boxm2_dir,r...
ivelum/django-debug-toolbar
debug_toolbar/panels/sql/views.py
Python
bsd-3-clause
3,971
0.001259
from __future__ import absolute_import, unicode_literals from django.http import HttpResponseBadRequest from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from debug_toolbar.panels.sql.forms import SQLSelectForm @csrf_exempt def sql_select(request): """Returns the output of...
# SQLite's EXPLAIN dumps the low-level opcodes generated for a query; # EXPLAIN QUERY PLAN dumps a more human-readable summary # See http://www.sqlite.org/lang_explain.html for details cursor.execute("EXPLAIN QUERY PLAN %s" % (sql,), params) elif vendor == 'postgresql':...
), params) else: cursor.execute("EXPLAIN %s" % (sql,), params) headers = [d[0] for d in cursor.description] result = cursor.fetchall() cursor.close() context = { 'result': result, 'sql': form.reformat_sql(), 'duration': form.cleane...
darioizzo/d-CGP
doc/examples/getting_started.py
Python
gpl-3.0
1,313
0.020564
from dcgpy import expression_gdual_double as expression from dcgpy import kernel_set_gdual_double as kernel_set from pyaudi import gdual_doubl
e as gdual # 1- Instantiate a random expression using the 4 basic arithmetic operations ks = kernel_set(["sum", "diff", "div", "mul"]) ex = expression(inputs = 1, outputs = 1, rows = 1,
cols = 6, levels_back = 6, arity = 2, kernels = ks(), n_eph = 0, seed = 4232123212) # 2 - Define the symbol set to be used in visualizing the expression # (in our case, 1 input variable named "x") and visualize the exp...
plotly/python-api
packages/python/plotly/plotly/validators/histogram2dcontour/colorbar/_borderwidth.py
Python
mit
555
0
import _plotly_utils.basevalidators class Bord
erwidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="borderwidth", parent_name="histogram2dcontour.colorbar", **kwargs ): super(BorderwidthValidator, self).__init__( plotly_name=plotly_name, parent_name=p...
kwargs )
falkTX/Cadence
src/systray.py
Python
gpl-2.0
23,718
0.008812
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # KDE, App-Indicator or Qt Systray # Copyright (C) 2011-2018 Filipe Coelho <falktx@falktx.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; e...
#from PyKDE5.k
deui import KAction, KIcon, KMenu, KStatusNotifierItem #TrayEngine = "KDE" else: TrayEngine = "Qt" except: TrayEngine = "Qt" print("Using Tray Engine '%s'" % TrayEngine) iActNameId = 0 iActWidget = 1 iActParentMenuId = 2 iActFunc = 3 iSepNameId = 0 iSepWidget = 1 iSepParentMenuId = 2 iMen...
JoaoRodrigues/pdb-tools
pdbtools/pdb_keepcoord.py
Python
apache-2.0
3,212
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2018 João Pedro Rodrigues # # 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 # # Unl...
ECT. Usage: python pdb_keepcoord.py <pdb file> Example: python pdb_keepcoord.py 1CTF.pdb This program is part of the `pdb-tools` suite of utilities and should not be distributed isolatedly. The `pdb-tools` were created to quickly manipulate PDB files using the terminal, and can be used sequentially, with one...
os import sys __author__ = "Joao Rodrigues" __email__ = "j.p.g.l.m.rodrigues@gmail.com" def check_input(args): """Checks whether to read from stdin/file and validates user input/options. """ # Defaults fh = sys.stdin # file handle if not len(args): # Reading from pipe with default opt...
spatialhast/clickfu
osm.py
Python
gpl-3.0
1,309
0.02139
from clickFuUtils import cfAction class osmViewMap(cfAction): def __init__(self,iface): cfAction.__init__(self,self.name(),iface) return None def name(self): return "View OSM map" def desc(self): return "Goto Location on OpenStreetMap" def createURL(self,lat,long): ...
nd start editing with iD" def createURL(self,lat,long): url = "http://www.openstreetmap.org/edit?editor=id#map=17/%s/%s" % (lat,long) return url class osmEditMapJOSM(cfAction): def __init__(self,iface): cfAction.__init__(self,self.name(),iface) return None def name(self): ...
OSM" def createURL(self,lat,long): url = "http://127.0.0.1:8111/load_and_zoom?left=%s&top=%s&right=%s&bottom=%s" % (long-0.005,lat+0.005,long+0.005,lat-0.005) return url
kevindias/django-chalk
chalk/compat.py
Python
bsd-3-clause
358
0
from django.conf import setti
ngs # Safe User import for Djang
o < 1.5 try: from django.contrib.auth import get_user_model except ImportError: from django.contrib.auth.models import User else: User = get_user_model() # Safe version of settings.AUTH_USER_MODEL for Django < 1.5 auth_user_model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
OpusVL/odoo-trading-as
trading_as/__openerp__.py
Python
agpl-3.0
1,741
0.001723
# -*- coding: utf-8 -*- ############################################################################## # # Trading As Brands # Copyright (C) 2015 OpusVL (<http://opusvl.com/>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pub...
eneral Public License for more details. # # 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': 'Trading As Brands', 'version': '0.1', 'author': 'OpusVL', 'website': 'http://opusvl.com/', 'summary': 'A...
solus-project/package-management
pisi/actionsapi/shelltools.py
Python
gpl-2.0
9,041
0.008185
#-*- coding: utf-8 -*- # # Copyright (C) 2005-2010 TUBITAK/UEKAE # # 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. # # P...
il import join_path def can_access_file(filePath
): '''test the existence of file''' return os.access(filePath, os.F_OK) def can_access_directory(destinationDirectory): '''test readability, writability and executablility of directory''' return os.access(destinationDirectory, os.R_OK | os.W_OK | os.X_OK) def makedirs(destinationDirectory): '''rec...
jcolekaplan/WNCYC
src/main/api/decEncoder.py
Python
mit
441
0.004535
"""Workaround for forma
tting issue Source: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html """ import decimal import json class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, dec
imal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o)
msonnabaum/thrift
test/crossrunner/run.py
Python
apache-2.0
9,516
0.010824
# # 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...
self.expired = False def _expire(self): self._log.info('Timeout') self.expired = True self.kill() def kill(self): self._log.debug('Killing process : %d' % self.proc.pid) if platform.system() != 'Windows': try: os.killpg(
self.proc.pid, signal.SIGKILL) except Exception as err: self._log.info('Failed to kill process group : %s' % str(err)) try: self.proc.kill() except Exception as err: self._log.info('Failed to kill process : %s' % str(err)) self.report.killed() def _popen_args(self): args = {...
uber-common/opentracing-python-instrumentation
tests/opentracing_instrumentation/test_mysqldb.py
Python
mit
2,279
0.000878
import sys import pytest from opentracing.ext import tags from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks from opentracing_instrumentation.request_context import span_in_context from .sql_common import metadata...
import MySQLdb with MySQLdb.connect(host='127.0.0.1', user='root'): pass return True except: return False def assert_span(span, operation, parent=None): assert span.operation_name == 'MySQLdb:' + operation assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_C...
assert span.parent_id is None @pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION) @pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3) def test_db(tracer, session): root_span = tracer.start_span('root-span') # span recording works for regular operations within ...
garyjs/Newfiesautodialer
newfies/api/api_playgrounds/campaign_delete_cascade_playground.py
Python
mpl-2.0
1,138
0.001757
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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) 2011-2013 Star2Billing S.L. # # The Initia...
Original Code is # Arezqui Belaid <info@star2billing.com> # from django.utils.translation import gettext as _ from apiplayground import APIPlayground class CampaignDelCascadeAPIPlayground(APIPlayground): schema = { "title": _("campaign delete cascade"), "base_url": "http://localhost/api/v1/", ...
": _("this resource allows you to delete campaign."), "endpoints": [ { "method": "DELETE", "url": "/api/v1/campaign_delete_cascade/{campaign-id}/", "description": _("delete campaign"), } ...
lmascare/utils
python/tutorials/oop6a.py
Python
artistic-2.0
811
0.008631
#!/usr/bin/env python3 class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self,first,last): self.first = first self.last = last self.email = first + '.' + last + '@kellynoah.com' def fullname(self): return '{} {}'.format(self.first,self.last) def ...
= int(self.pay * self.raise_amount) def __repr__(self): return "Employee('{}', '{}', '{}')".format(self.first, self.last, self.pay) def __str__(self): return '{} - {}'.format(self.fullname(), self.email) def __add__(self, other): return self.pay
+ other.pay def __len__(self): return len(self.fullname()) emp_1 = Employee('John', 'Smith') print(emp_1.first) print(emp_1.email) print(emp_1.fullname())
Tiger-C/python
python教程/第四集.py
Python
mit
3,007
0.006783
#第四集(包含部分文件3.py和部分第二集) # courses=['History','Math','Physics','Compsci']#此行代码在Mutable之前都要打开 # print(courses) # courses.append('Art')#在最后添加一个元素 # courses.insert(0,'English')#在0的位置添加一个元素 # courses_2=['Chinese','Education'] # courses.insert(1,courses_2)#看看这条代码与下面两条代码有什么不同 # courses.append(courses_2) # courses.extend(cour...
(括号内无数字则默认最后一个) # print(popped)#输出被删除的元素 # courses.reverse()#将元素倒叙 # courses.sort()#排序 按开头字母的顺序 数字排在字母前 # print(courses) # courses.sort(reverse=True)#按顺序倒叙(若=False则无效) # print(courses) # sorted_courses=sorted(courses) # print(sorted_courses) # alphabet=['DA1','SA2','AD3','3AD'] # alphabet.sort() # print(alphabet) #...
最小数 # print(max(nums))#输出最大数 # print(sum(nums))#输出总和 # #中文不知道是什么规则 # Chinese=['啊了','吧即','啦'] # Chinese.sort() # print(Chinese) # print(courses.index('Math'))#查找某元素在列表中的位置 # print('Art' in courses)#True则表示该元素存在于列表,False则是不存在 #for和in语言 # for item in courses: #将courses中的元素一个一个输出 # print(item) # #输出元素位置和元素 # for co...
MichaelDoyle/Diamond
src/collectors/elb/test/testelb.py
Python
mit
8,325
0.00024
#!/usr/bin/python # coding=utf-8 import datetime import mock from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import patch from test import run_only from mock import Mock from diamond.collector import Collector from elb import ElbCollector def run_only_if...
unt'}], [{u'Timestamp': ts, u'Sum': 14.0, u'Unit': u'Count'}], ] cloudwatch.connect_to_region = Mock() cloudwatch.connect_to_region.return_value = cw_conn collector = ElbCollector(config, handlers=[]) target = ts + datetime.timedelta(minutes=1) with mock.pa...
) as patched: patched.utcnow.return_value = target collector.collect() self.assertPublishedMetricMany( publish_metric, { 'us-west-1a.elb1.HealthyHostCount': 1, 'us-west-1a.elb1.UnHealthyHostCount': 2, 'us-west-1a.el...
auduno/gensim
gensim/corpora/bleicorpus.py
Python
gpl-3.0
3,768
0.00345
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Blei's LDA-C format. """ from __future__ import with_statement import logging from gensim import interfaces, utils from gensim.c...
ger.info("saving vocabulary of %i words to %s" % (num_terms, fname_vocab)) with ope
n(fname_vocab, 'w') as fout: for featureid in xrange(num_terms): fout.write("%s\n" % utils.to_utf8(id2word.get(featureid, '---'))) return offsets def docbyoffset(self, offset): """ Return the document stored at file position `offset`. """ with op...
lmazuel/azure-sdk-for-python
azure-eventgrid/azure/eventgrid/models/resource_write_failure_data.py
Python
mit
3,203
0.000312
# 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 ...
rmed. :type operation_name: str :param status: The status of the operation. :type status: str :param authorization: The requested authorization for the operation. :type authorization: str :param claims: The properties of the claims. :type claims: str :param correlation_id: An operation I...
correlation_id: str :param http_request: The details of the operation. :type http_request: str """ _attribute_map = { 'tenant_id': {'key': 'tenantId', 'type': 'str'}, 'subscription_id': {'key': 'subscriptionId', 'type': 'str'}, 'resource_group': {'key': 'resourceGroup', 'type': ...
notapresent/rutracker_rss
feeds.py
Python
apache-2.0
2,363
0
"""(Re)builds feeds for categories""" import os import datetime import jinja2 from google.appengine.api import app_identity import dao import util def build_and_save_for_category(cat, store, prefix): """Build and save feeds for category""" feed = build_feed(cat) save_feeds(store, feed, prefix, cat.key.id...
lass Feed(object): """Represents feed wi
th torrent entries""" def __init__(self, title, link, ttl=60, description=None): self.title = title self.link = link self.description = description or title self.ttl = ttl self.items = [] self.lastBuildDate = None self.latest_item_dt = datetime.datetime.utcfr...
SummerLW/Perf-Insight-Report
devil/devil/android/ports.py
Python
bsd-3-clause
6,336
0.007418
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Functions that deal with local and device ports.""" import contextlib import fcntl import httplib import logging import os import socket import trace...
ports_tried.append(port) while not IsHostPortAvailable(port): port += 1 ports_tried.append(port) if (port > _TEST_SERVER_PORT_LAST or port < _TEST_SERVER_PORT_FIRST): port = 0 else: fp.seek(0, os.SEEK_SET) fp.write('%d' % (port + 1)) except Except...
d-except logging.exception('ERror while allocating port') finally: if fp_lock: fcntl.flock(fp_lock, fcntl.LOCK_UN) fp_lock.close() if port: logging.info('Allocate port %d for test server.', port) else: logging.error('Could not allocate port for test server. ' 'List of...
xtuyaowu/jtyd_python_spider
celery_tasks/weibo/search.py
Python
mit
2,317
0.003021
# coding:utf-8 from urllib import parse as url_parse from logger.log import crawler from apps.celery_init import celery from page_get.basic import get_page from config.conf import get_max_search_page from page_parse import search as parse_search from db.search_words import get_search_keywords from db.keywords_wbdata im...
this turn'.format(keyword)) return @celery.task(ignore_result=True) def excute_search_task(): keywords = get_search_keywords() for each in keywords: celery.send_task('celery_tasks.weibo.search.search_keyword', args=(each[0], each[1]), queue='search_crawler', routi...
h_info')
sykora/django-ripwrap
setup.py
Python
gpl-3.0
712
0.025281
from distutils.core import setup from ripwrap import __VERSION__ setup( name = 'ripwrap', version = __VERSION__, description = 'A wrapper for ReSTinPeace, for Django applications.', long_description = open('README').read() author = 'P.C. Shyamshankar', packages = ['ripwrap'], url = 'http...
sykora/django-ripwrap
/', license = 'GNU General Public License v3.0', classifiers = ( 'Development Status :: 1 - Planning', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Prog...
simongibbons/numpy
numpy/core/tests/test_casting_unittests.py
Python
bsd-3-clause
29,168
0.000583
""" The tests exercise the casting machinery in a more low-level manner. The reason is mostly to test a new implementation of the casting machinery. Unlike most tests in NumPy, these are closer to unit-tests rather than integration tests. """ import pytest import textwrap import enum import itertools import random i...
ed_stringlength(dtype): """Returns the string length when casting the basic dtypes to strings. """
if dtype == np.bool_: return 5 if dtype.kind in "iu": if dtype.itemsize == 1: length = 3 elif dtype.itemsize == 2: length = 5 elif dtype.itemsize == 4: length = 10 elif dtype.itemsize == 8: length = 20 else: ...
QualiSystems/vCenterShell
package/cloudshell/tests/test_network/vlan/test_factory.py
Python
apache-2.0
324
0
from unittest import TestCase from cloudshell.cp.vcenter.network.vlan.factory im
port VlanSpecFactory class TestVlanSpecFactory(TestCase):
def test_get_vlan_spec(self): vlan_spec_factory = VlanSpecFactory() vlan_spec = vlan_spec_factory.get_vlan_spec('Access') self.assertIsNotNone(vlan_spec)
timtim17/IntroToGameProg
Labs/Paycheck.py
Python
gpl-2.0
746
0.002681
# Austin Jenchi # 1/30/2015 # 8th Period # Paycheck print "Welcome to How to Job" print wage_per_hour = raw_input("How much is your hourly wage? ==> $") if not wage_per_hour == "": try: wage_per_hour = float(wage_per_hour) except: wage_per_hour = 12.00 else: wage_per_hour = 12.00 pri
nt "Your pay is $%2.2f per hour." % wage_per_hour print print "You've worked 26 hours. (in one 24-hour day! remarkable!)" print total_wage = wage_per_hour * 26
print "Your Pay Before Taxes is $%2.2f" % total_wage print print "After taxes of 23%%, your total pay is $%2.2f." % (total_wage * .23) print print "After paying your union fees, you recieved a measly $%2.2f of your previous $%2.2f." % ((total_wage * .23) - 25, total_wage)
ifduyue/sentry
src/sentry/web/frontend/generic.py
Python
bsd-3-clause
3,640
0.001099
""" sentry.web.frontend.generic ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import os import posixpath from django.conf import settings from django.http import HttpRespo...
st-revalidate' def dev_favicon(request): document_root, path = resolve('sentry/images/favicon_dev.png') return static.serve(request, path, document_root=document_root) def resolve(path): # Mostly yanked from Dja
ngo core and changed to return the path: # See: https://github.com/django/django/blob/1.6.11/django/contrib/staticfiles/views.py normalized_path = posixpath.normpath(unquote(path)).lstrip('/') try: absolute_path = finders.find(normalized_path) except Exception: # trying to access bad pat...
rahulunair/nova
nova/db/sqlalchemy/api_migrations/migrate_repo/versions/016_resource_providers.py
Python
apache-2.0
4,495
0.000222
# 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 # d...
e_class_id_idx', 'resource_class_id'), I
ndex('allocations_consumer_id_idx', 'consumer_id'), mysql_engine='InnoDB', mysql_charset='latin1' ) resource_provider_aggregates = Table( 'resource_provider_aggregates', meta, Column('created_at', DateTime), Column('updated_at', DateTime), Column('resource_provid...
isovic/marginAlign
src/margin/marginAlign.py
Python
mit
4,995
0.015816
#!/usr/bin/env python import os import sys from optparse import OptionParser from jobTree.src.bioio import logger, setLoggingFromOptions from jobTree.scriptTree.stack import Stack from margin.mappers.last import Last, LastChain, LastRealign from margin.mappers.bwa import Bwa, BwaChain, BwaRealign from margin.mappers.gr...
.graphmapanchor): mapper = GraphMapAnchor; else: # i.e. --noRealign # mapper = BwaChain if options.bwa else LastChain mapper = LastChain; if (options.bwa): mapper = BwaChain; if (options.graphmap): mapper = GraphMapC...
er = BwaRealign if options.bwa else LastRealign mapper = LastRealign; if (options.bwa): mapper = BwaRealign; if (options.graphmap): mapper = GraphMapRealign; if (options.graphmapanchor): mapper = GraphMapAnchorRealign; #This line invokes jobTr...
ray-project/ray
rllib/examples/recsim_with_slateq.py
Python
apache-2.0
227
0
fr
om ray.rllib.utils.deprecation import deprecation_warning deprecation_warning( old="ray/rllib/examples/recsim_with_slateq.py", new="ray/rllib/examples/recommender_system_with_recsim_and_slateq.py", error=Tr
ue, )
aleSuglia/YAIEP
yaiep/graph/SearchGraph.py
Python
mit
1,169
0.001714
import networkx from yaiep.graph.Node import Node ## # Classe che rappresenta l'intero spazio di ricerca che viene # generato via via che il metodo di ricerca ispeziona nuovi nodi # class SearchGraph(networkx.DiGraph): ## # Crea il grafo di ricerca come un grafo direzionato # il quale ha come nodo inizial...
self._init_state = Node(init_state.copy(), None) # inserisci lo stato iniziale a partire dal quale ispezionare lo spazio di ricerca self.add_node(self._init_state) ## # Restituisce il riferimento allo stato iniziale dal # quale è iniziata la ricerca # def get_init_state(self): ...
for node in self: res += '{0} -> '.format(str(node.wm)) for adj in self.neighbors(node): res += str(adj.wm) + '\n' return res
brocade/pysdn
docs/source/conf.py
Python
bsd-3-clause
9,179
0.005992
# -*- coding: utf-8 -*- # # pysdn documentation build configuration file, created by # sphinx-quickstart on Wed Aug 5 08:56:12 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
d prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = Fa
lse # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Them...
songzhw/Hello-kotlin
Python101/src/math/PrimeSieve.py
Python
apache-2.0
1,333
0.007048
import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size):...
# num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i...
ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''
yu-peng/cdru
graph_theory/tests.py
Python
gpl-3.0
1,214
0.014003
import unittest from graph_the
ory.spfa import spfa class GraphTheoryTests(unittest.TestCase): def setUp(self): source = 0 num_nodes = 5 neighbour_list = [[1], # 0 [2], # 1 [3], # 2 [4, 1], # 3
[1], # 4 ] weights = {(0,1): 20, (1,2) : 1, (2,3) : 2, (3,4) : -2, (4, 1): -1, (3, 1): -4, } self.example_graph = (source, num_nodes, weight...
jxta/cc
vendor/boto/boto/manage/volume.py
Python
apache-2.0
16,328
0.002511
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
_name='EC2 Zone') mount_point = StringProperty(verbose_name='Mount Point') device = StringProperty(verbose_name="Device Name", default='/dev/sdp') volume_id = StringProperty(required=True) past_volume_ids = ListProperty(item_type=str) server = ReferenceProperty(Server, collection_name='volumes', ...
calculated_type=str, use_method=True) attachment_state = CalculatedProperty(verbose_name="Attachment State", calculated_type=str, use_method=True) size = CalculatedProperty(verbose_name="Size (GB)", calculated_type=int, use_method=True) ...
cmjatai/cmj
sapl/sessao/migrations/0002_sessaoplenaria_interativa.py
Python
gpl-3.0
518
0.001938
# -*- coding: utf-8 -*- #
Generated by Django 1.9.11 on 2017-05-10 15:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sessao', '0001_initial'), ] operations = [ migrations.AddField( model_name='sessaoplenar...
choices=[(True, 'Sim'), (False, 'Não')], verbose_name='Sessão interativa'), ), ]
ping/instagram_private_api_extensions
instagram_private_api_extensions/__init__.py
Python
mit
159
0
# Copyright (c)
2017 https://github.com/ping # # This software is released under the MIT License. # https://opensource.org/licenses/MIT __version__
= '0.3.9'
Azure/azure-sdk-for-python
sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2022_01_01/operations/_agent_pools_operations.py
Python
mit
40,397
0.004505
# 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 ...
**kwargs: Any ) -> HttpRequest: api_version = "2022-01-01" accept = "application/json" # Construct URL url = kwargs.pop("t
emplate_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/agentPools') path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), "resourceGroupName": _SERIALIZER....
Microvellum/Fluid-Designer
win64-vc/2.78/scripts/startup/fluid_operators/fd_api_doc.py
Python
gpl-3.0
10,496
0.0121
''' Created on Jan 27, 2017 @author: montes ''' import bpy from inspect import * import mv import os import math from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import legal,inch,cm from reportlab.platypus import Image from reportlab.platypus import Paragraph,Table,TableStyle from reportlab.platypus ...
tput_path, cls[0] + ".md") file = open(filepath, "w") fw = file.write fw("# class {}{}{}{}\n\n".format(cls[1].__module__, ".", cls[0], "():")) if getdoc(cls[1]): fw(self.esc_uscores(getdoc(cls[1])) + "\n\n") for func in getmembers(cls[1], p...
args_str = ', '.join(item for item in args if item != 'self') fw("## {}{}{}{}\n\n".format(self.esc_uscores(func[0]), "(", self.esc_uscores(args_str) if args_str else " ", ...
rocky/python2-trepan
trepan/processor/command/edit.py
Python
gpl-3.0
2,860
0.003846
# -*- coding: utf-8 -*- # Copyright (C) 2009, 2013-2015 Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ve...
filename = curframe.f_code.co_filename lineno = curframe
.f_lineno elif len(args) == 2: (modfunc, filename, lineno) = self.proc.parse_position(args[1]) if inspect.ismodule(modfunc) and lineno is None and len(args) > 2: val = self.proc.get_an_int(args[1], 'Line number expected, got %s.'...
whiteclover/Choco
choco/ui.py
Python
mit
3,191
0
# choco/ui.py # Copyright (C) 2006-2016 the Choco authors and contributors <see AUTHORS file> # # This module is part of Choco and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import re import os import posixpath from choco import errors from choco import util from choco.ru...
ult_template self.initialize()
def initialize(self): pass def get(self, key, default=None): """get parent context local data by key""" return self.context.get(key, default) def _execute(self, *args, **kw): """execute the template""" data = self.render(*args, **kw) t = self.get_template() ...
ThomasTheSpaceFox/furry-text-escape-2
TE2.py
Python
gpl-3.0
2,244
0.043226
#!/usr/bin/env python # coding=utf-8 # Furry Text Escape 2 main sc
ript gamevers = ('v1.0') n = ('null') tprint1 = ('1') tprint2 = ('1') while
n.strip()!="4": if tprint1==('1'): t = open('./art/title1.TCR', 'r') tcr_contents = t.read() print (chr(27) + "[2J" + chr(27) + "[H" + tcr_contents) t.close() tprint1=('0') print ( '''Furry Text Escape II (c) 2015-2016 Thomas Leathers ''' ) print ( '''Choose number: 1: Watch Intro 2: begin game...
jerbob92/CouchPotatoServer
libs/guessit/language.py
Python
gpl-3.0
13,849
0.003251
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2011 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
ng_fr_name_to_lng3 = dict((fr_name.lower(), l[0]) for l in language_matrix if l[4] for fr_name in l[4].split('; ')) # contains a list of exceptions: strings that shou
ld be parsed as a language # but which are not in an ISO form lng_exceptions = { 'unknown': ('und', None), 'inconnu': ('und', None), 'unk': ('und', None), 'un': ('und', None), 'gr': ('gre', None), 'greek': ('gre', None), ...
tsdmgz/ansible
lib/ansible/plugins/action/ironware_config.py
Python
gpl-3.0
4,167
0.00072
# # (c) 2017, Red Hat, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is...
cwd = self._ta
sk._role._role_path return cwd def _write_backup(self, host, contents): backup_path = self._get_working_path() + '/backup' if not os.path.exists(backup_path): os.mkdir(backup_path) for fn in glob.glob('%s/%s*' % (backup_path, host)): os.remove(fn) tst...
julienmalard/Tikon
tikon/móds/rae/orgs/ecs/repr/triang.py
Python
agpl-3.0
857
0
import scipy.stats as estad from tikon.ecs.aprioris import APrio
riDist from tikon.ecs.árb_mód import Parám from tikon.móds.rae.orgs.ecs.repr._plntll_ec import EcuaciónReprCoh class N(Parám): no
mbre = 'n' líms = (0, None) unids = None apriori = APrioriDist(estad.expon(scale=500)) class A(Parám): nombre = 'a' líms = (0, None) unids = None apriori = APrioriDist(estad.expon(scale=100)) class B(Parám): nombre = 'b' líms = (0, None) unids = None apriori = APrioriDist...
shayan72/Courseware
Courseware/wsgi.py
Python
mit
395
0.002532
""" WSGI config for Courseware project. It expose
s the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Courseware.settings") from django.core.wsgi imp
ort get_wsgi_application application = get_wsgi_application()
plotly/python-api
packages/python/plotly/plotly/validators/mesh3d/colorbar/_tickvals.py
Python
mit
460
0.002174
import _plotly_utils.basevalidators class TickvalsValidator(_plotly_utils.basevalidators.DataArrayVa
lidator): def __init__(self, plotly_name="tickvals", parent_name="mesh3d.colorbar", **kwargs): super(TickvalsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), role=kwargs.pop("role", "d...
**kwargs )
s20121035/rk3288_android5.1_repo
bionic/libc/tools/zoneinfo/update-tzdata.py
Python
gpl-3.0
8,075
0.016966
#!/usr/bin/python """Updates the timezone data held in bionic and ICU.""" import ftplib import glob import httplib import os import re import shutil import subprocess import sys import tarfile import tempfile regions = ['africa', 'antarctica', 'asia', 'australasia', 'etcetera', 'europe', 'northamerica', '...
/zoneinfo') CheckDirExists(bionic_libc_tools_zoneinfo_dir, 'bionic/libc/tools/zoneinfo') print 'Found bionic in %s ...' % bionic_dir # Find the icu4c directory. icu_dir = os.path.realpath('%s/../external/icu/icu4c/source' % bionic_dir) CheckDirExists(icu_dir, 'external/icu/icu
4c/source') print 'Found icu in %s ...' % icu_dir def GetCurrentTzDataVersion(): return open('%s/tzdata' % bionic_libc_zoneinfo_dir).read().split('\x00', 1)[0] def WriteSetupFile(): """Writes the list of zones that ZoneCompactor should process.""" links = [] zones = [] for region in regions: for line ...
ActiveState/code
recipes/Python/496684_Splicing_of_lists/recipe-496684.py
Python
mit
1,158
0.025043
def splice(alists, recycle = True): """ Accepts a list of nonempty lists or indexable objects in argument alists (each element list
may not be of the same length) and a keyword argument recycle which if true will reuse elements i
n lists of shorter length. Any error will result in an empty list to be returned. """ try: nlists = len(alists) lens = [len(alist) for alist in alists] if not recycle: totlen = sum(lens) else: totlen = max(lens) * nlists pos =...
tekton/DocuCanvas
socialplatform/migrations/0005_auto__add_field_facebookprofile_polls.py
Python
gpl-3.0
7,753
0.007868
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'FacebookProfile.polls' db.add_column(u'socialplatform_facebookprofile', 'polls', ...
: "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.m
odels.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'socialplatform.dmall': { 'Meta': {'object_name': 'DMAll'}, ...
apache/airflow
airflow/migrations/versions/952da73b5eff_add_dag_code_table.py
Python
apache-2.0
2,906
0.001376
# # 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...
class SerializedDagModel(Base): __tablename__ = 'serialized_dag' # There are other columns here, but these are the only ones we need for the SELECT/UPDATE we are doing da
g_id = sa.Column(sa.String(250), primary_key=True) fileloc = sa.Column(sa.String(2000), nullable=False) fileloc_hash = sa.Column(sa.BigInteger, nullable=False) """Apply add source code table""" op.create_table( 'dag_code', sa.Column('fileloc_hash', sa.BigInteger(), nullable=Fals...
honeynet/beeswarm
beeswarm/drones/client/baits/pop3.py
Python
gpl-3.0
3,174
0.001575
# Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This p...
er = logging.getLogger(__name__) class Pop3(ClientBase): def __init__(self, options): """ Initializes common values. :param options: A dict containing all options """
super(Pop3, self).__init__(options) def start(self): """ Launches a new POP3 client session on the server. """ username = self.options['username'] password = self.options['password'] server_host = self.options['server'] server_port = self.options['por...
horance-liu/tensorflow
tensorflow/python/keras/_impl/keras/utils/generic_utils.py
Python
apache-2.0
12,658
0.0079
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
but the function accepts a `**kwargs` argument. Returns: bool, whether `fn` accepts a `name` keyword argument. """ arg_spec = tf_inspect.getargspec
(fn) if accept_all and arg_spec.keywords is not None: return True return name in arg_spec.args class Progbar(object): """Displays a progress bar. Arguments: target: Total number of steps expected, None if unknown. interval: Minimum visual progre
cwisecarver/osf.io
tests/test_conferences.py
Python
apache-2.0
25,084
0.000518
# -*- coding: utf-8 -*- import mock from nose.tools import * # noqa (PEP8 asserts) import hmac import hashlib from StringIO import StringIO from django.db import IntegrityError import furl from modularodm import Q from modularodm.exceptions import ValidationError from framework.auth import get_or_create_user from ...
xists()) assert_not_in('spam', self.node.system_tags) def test_provision_private(self): self.conference.public_projects = False self.conference.save() with self.make_context(): msg = me
ssage.ConferenceMessage() utils.provision_node(self.conference, msg, self.node, self.user) assert_false(self.node.is_public) assert_in(self.conference.admins.first(), self.node.contributors) assert_in('emailed', self.node.system_tags) assert_not_in('spam', self.node.system_ta...
CTSRD-SOAAP/chromium-42.0.2311.135
tools/profile_chrome/perf_controller.py
Python
bsd-3-clause
6,890
0.00566
# Copyright 2014 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. import logging import os import signal import subprocess import sys import tempfile from profile_chrome import controllers from profile_chrome import ui fr...
for lib in required_libs: lib = os.path.join(symfs_dir, lib[1:]) if not os.path.exists(lib): continue objdump_path = android_profiling_helper.GetToolchainBinaryPath( lib, 'objdump') if objdump_path:
cmd += ' --objdump %s' % os.path.relpath(objdump_path, '.') break return cmd def PullTrace(self): symfs_dir = os.path.join(tempfile.gettempdir(), os.path.expandvars('$USER-perf-symfs')) if not os.path.exists(symfs_dir): os.makedirs(symfs_dir) required...
wincent/ultisnips
test/vim_interface.py
Python
gpl-3.0
6,882
0.000436
# encoding: utf-8 import os import re import shutil import subprocess import tempfile import textwrap import time from test.constant import (ARR_D, ARR_L, ARR_R, ARR_U, BS, ESC, PYTHON3, SEQUENCES) def wait_until_file_exists(file_path, times=None, interval=0.01): while times is None o...
`+Space = "` ". I work around this, by sending the host # ` as `+_+BS. Awkward, but the only way I found to get this working. ('`', '`_{BS}'), ('´', '´_{BS}'), ('{^}', '{^}_{BS}'), ] def __init__(self): # import window
s specific modules import win32com.client import win32gui self.win32gui = win32gui self.shell = win32com.client.Dispatch('WScript.Shell') def is_focused(self, title=None): cur_title = self.win32gui.GetWindowText( self.win32gui.GetForegroundWindow()) if (t...
ypid/series60-remote
pc/ui/ui_calendar_edit.py
Python
gpl-2.0
14,073
0.003837
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/src/calendar_edit.ui' # # Created: Wed Nov 17 12:05:53 2010 # by: PyQt4 UI code generator 4.7.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_CalendarEntryEdit(object): def se...
self.reminderUnitBox.setObjectName("reminderUnitBox") self.horizontalLayout.addWidget(self.reminderUnitBox) self.reminde
rStack.addWidget(self.basicReminderWidget) self.advancedReminderWidget = QtGui.QWidget() self.advancedReminderWidget.setObjectName("advancedReminderWidget") self.horizontalLayout_2 = QtGui.QHBoxLayout(self.advancedReminderWidget) self.horizontalLayout_2.setSpacing(0) self.horizon...
benjyw/pants
src/python/pants/backend/awslambda/python/register.py
Python
apache-2.0
577
0.001733
# Copyright 2019 Pants project contributors (see CONTRIBUTORS
.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """Create AWS Lambdas from Python code. See https://www.pantsbuild.org/docs/awslambda-python. """ from pants.backend.awslambda.python import rules as python_rules from pants.backend.awslambda.python.target_types import PythonAWSLambda from pants.b...
[PythonAWSLambda]
bouhlelma/smt
smt/sampling_methods/full_factorial.py
Python
bsd-3-clause
1,806
0.000554
""" Author: Dr. John T. Hwang <hwangjt@umich.edu> This package is distributed under New BSD license. Full-factorial sampling. """ import numpy as np from smt.sampling_methods.sampling_method import SamplingMethod class FullFactorial(SamplingMethod): def _initialize(self): self.options.declare( ...
least_1d(self.options["weights"]) weights /= np.sum(weights) num_list = np.ones(nx, int) while np.prod(num_list) < nt: ind = np.argmax(weights - num_list / np.sum(num_list)) num_list[ind] += 1 lins_list = [np.linspace(0.0, 1.0, num_list[kx]) for kx in range(...
p.zeros((nt, nx)) for kx in range(nx): x[:, kx] = x_list[kx].reshape(np.prod(num_list))[:nt] return x
jameshensman/pythonGPLVM
PCA_EM.py
Python
gpl-3.0
6,841
0.05087
# -*- coding: utf-8 -*- # Copyright 2009 James Hensman # Licensed under the Gnu General Public license, see COPYING #from numpy import matlib as ml import numpy as np from scipy import linalg class PCA_EM_matrix: def __init__(self,data,target_dim): """Maximum likelihood PCA by the EM algorithm""" self.X = ml.matr...
*missing_pc/100) observed2 = observed.copy() missingi = np.argsort(np.random.rand(N))[:Nmissing] missingj = np.random.randint(0,d-q,Nmissing)#last q columns will be complete observed2[missingi,missingj] = np.NaN b = PCA_E
M_missing(observed2,q) b.learn(niters) from hinton import hinton import pylab colours = np.arange(N)# to colour the dots with hinton(linalg.qr(trueW.T)[1].T) pylab.title('true transformation') pylab.figure() hinton(linalg.qr(a.W.T)[1].T) pylab.title('reconstructed transformation') pylab.figure() hinton(l...
mnunberg/couchbase-python-client
txcouchbase/iops.py
Python
apache-2.0
3,633
0.001376
from twisted.internet import error as TxErrors import couchbase._libcouchbase as LCB from couchbase._libcouchbase import ( Event, TimerEvent, IOEvent, LCB_READ_EVENT, LCB_WRITE_EVENT, LCB_RW_EVENT, PYCBC_EVSTATE_ACTIVE, PYCBC_EVACTION_WATCH, PYCBC_EVACTION_UNWATCH, PYCBC_EVACTION_CLEANUP ) cla...
self.ready_w()
def connectionLost(self, reason): if self.state == PYCBC_EVSTATE_ACTIVE: self.ready_w() def logPrefix(self): return "Couchbase IOEvent" class TxTimer(TimerEvent): __slots__ = ['_txev', 'lcb_active'] def __init__(self): super(TxTimer, self).__init__() self.lc...
eduNEXT/edunext-platform
import_shims/lms/certificates/apps.py
Python
agpl-3.0
374
0.008021
""
"Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('certificates.apps', 'lms.djangoapps.certificates.app...
crs4/ProMort
promort/reviews_manager/management/commands/build_prediction_reviews_worklist.py
Python
mit
5,988
0.00501
# Copyright (c) 2021, CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribu...
self, prediction_type): return Prediction.objects.filter(type=prediction_type, review_required=True).all() def _check_duplicated(self, prediction, reviewer): annotation_objs = PredictionReview.objects.filter(prediction=prediction, reviewe
r=reviewer) if annotation_objs.count() > 0: logger.info('There are already %d reviews for prediction %s assigned to user %s', annotation_objs.count(), prediction.label, reviewer.username) return True else: return False def _create_predicti...
moodpulse/l2
integration_framework/views.py
Python
mit
76,926
0.002275
import base64 import os from django.test import Client as TC import datetime import logging import pytz from django.utils.module_loading import import_string from api.directions.sql_func import direction_by_card, get_lab_podr, get_confirm_direction_patient_year, get_type_confirm_direction from api.stationar.stationa...
omPk": from_pk, "afterDate": after_date}) @api_view() def get_dir_amd(request): next_n = int(request.GET.get("nextN", 5))
dirs = sql_if.direction_resend_amd(next_n) result = {"ok": False, "next": []} if dirs: result = {"ok": True, "next": [i[0] for i in dirs]} return Response(result) @api_view() def get_dir_n3(request): next_n = int(request.GET.get("nextN", 5)) dirs = sql_if.direction_resend_n3(next_n) ...
yngcan/patentprocessor
test/test_alchemy.py
Python
bsd-2-clause
14,826
0.000742
import unittest import os import sys import shutil sys.path.append('../lib/') sys.path.append(os.path.dirname(os.path.realpath(__file__))) import alchemy from alchemy.schema import * class TestAlchemy(unittest.TestCase): def setUp(self): # this basically resets our testing database path = config....
self.assertEqual(19, len(law[1].lawyer.rawlawyers)) self.assertEqual(14, len(law[1].lawyer.patents)) def test_assigneematch(self): # blindly assume first 10 are the same asg0 = session.query(RawAssignee).limit(10) asg1 = session.query(RawAssignee).limit(1
0).offset(10) asgs = session.query(Assignee) alchemy.match(asg0, session) alchemy.match(asg1, session) # create two items self.assertEqual(10, len(asg0[0].assignee.rawassignees)) self.assertEqual(10, len(asg1[0].assignee.rawassignees)) self.assertEqual(10, len(a...
Venturi/cms
env/lib/python2.7/site-packages/cms/tests/test_plugins.py
Python
gpl-2.0
79,253
0.002801
# -*- coding: utf-8 -*- from __future__ import with_statement import base64 import datetime import json import os from django import http from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.core import urlresolvers from django.core.cache import cache from djan...
Registered, DontUsePageAttributeWarning from cms.models import Page, Placeholder from cms.models.pluginmodel import CMSPlugin from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from cms.sitemaps.cms_sitemap import CMSSitemap from cms.test_utils.project.pluginapp.plugins.manytomany_rel.mod...
rgetModel) from cms.test_utils.project.pluginapp.plugins.meta.cms_plugins import ( TestPlugin, TestPlugin2, TestPlugin3, TestPlugin4, TestPlugin5) from cms.test_utils.project.pluginapp.plugins.validation.cms_plugins import ( NonExisitngRenderTemplate, NoRender, NoRenderButChildren, DynTemplate) from cms.test_ut...
ESOedX/edx-platform
openedx/core/djangoapps/embargo/tests/test_forms.py
Python
agpl-3.0
5,361
0.002425
# -*- coding: utf-8 -*- """ Unit tests for embargo app admin forms. """ from __future__ import absolute_import import six # Explicitly import the cache from ConfigurationModel so we can reset it after each test from config_models.models import cache from django.test import TestCase from opaque_keys.edx.locator import...
t adding valid ip addresses # should be able to do both ipv4 and ipv6 # spacing sho
uld not matter form_data = { 'whitelist': u'127.0.0.1, 2003:dead:beef:4dad:23:46:bb:101, 1.1.0.1/32, 1.0.0.0/24', 'blacklist': u' 18.244.1.5 , 2002:c0a8:101::42, 18.36.22.1, 1.0.0.0/16' } form = IPFilterForm(data=form_data) self.assertTrue(form.is_valid()) ...
Morgan-Stanley/treadmill
lib/python/treadmill/api/nodeinfo.py
Python
apache-2.0
1,004
0
"""Implementation of allocation API. """ from __future__ import absolute_import from __future__ import division from __future_
_ import print_function from __future__ import unicode_literals import logging from treadmill import discovery from treadmill import context _LO
GGER = logging.getLogger(__name__) class API: """Treadmill Local REST api.""" def __init__(self): def _get(hostname): """Get hostname nodeinfo endpoint info.""" _LOGGER.info('Redirect: %s', hostname) discovery_iter = discovery.iterator( context.GLO...
CommonClimate/teaching_notebooks
GEOL351/CoursewareModules/setpath.py
Python
mit
5,073
0.013996
#---------------------------------------------------------------------- #This utility sets up the python configuration files so as to #allow Python to find files in a specified directory, regardless #of what directory the user is working from. This is typically #used to create a directory where the user will put resou...
her ipython or python) will find # the shared files. This feature will not work on # Windows operating systems, so Windows users should start # either start up python by clicking on the Canopy app, or # by starting ipython from the command line. It is possible # to set the PYTHONPATH environment variabl...
s) in a given script # by executing the lines: # # import sys # sys.path.append('home/MyModules') # # where you would replace '/home/MyModules') with the # actual full path to the directory you want on your own # system #---------------------------------------------------------------------- import os...
teamclairvoyant/airflow-scheduler-failover-controller
scheduler_failover_controller/command_runner/command_runner.py
Python
apache-2.0
2,797
0.002503
import subprocess import os class CommandRunner: HOST_LIST_TO_RUN_LOCAL = ["l
ocalhost", "127.0.0.1"] def __init__(self, local_hostname, logger): logger.debug("Creating CommandRunner with Args - local_hostname: {local_hostname}, logger: {logger}".format(**locals())) self.local_hostname = local_hostname self.logger = logger # returns: is_successful, output de...
t, base_command): self.logger.debug("Running Command: " + str(base_command)) if host == self.local_hostname or host in self.HOST_LIST_TO_RUN_LOCAL: return self._run_local_command(base_command) else: return self._run_ssh_command(host, base_command) # This will start t...
IBM-Security/ibmsecurity
ibmsecurity/isam/base/network/felb/services/advanced_tuning.py
Python
apache-2.0
6,046
0.004135
import logging import ibmsecurity.utilities.tools logger = logging.getLogger(__name__) module_uri = "/isam/felb/configuration/services/" requires_modules = None requires_versions = None requires_model = "Appliance" def add(isamAppliance, service_name, name, value, check_mode=False, force=False): """ Creates...
deletes a service level attribute """ check_value, warnings = _check(isamAppliance, service_name,
attribute_name) if force is True or check_value is True: if check_mode is True: return isamAppliance.create_return_object(changed=True, warnings=warnings) else: return isamAppliance.invoke_delete("Deleting a service attribute", ...
WindCanDie/spark
python/pyspark/tests/test_util.py
Python
apache-2.0
3,052
0.001311
# # 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 us...
a.set(x=1, other=b, other_x=2) self.assertEqual(a._x, 1) self.assertEqual(b._x, 2) class UtilTests(PySparkTestCase): def test_py4j_exception_message(self): from pyspark.util import _exception_message with self.assertRaises(Py4JJavaError) as context: # This attempts jav...
xt.exception)) def test_parsing_version_string(self): from pyspark.util import VersionUtils self.assertRaises(ValueError, lambda: VersionUtils.majorMinorVersion("abced")) if __name__ == "__main__": from pyspark.tests.test_util import * try: import xmlrunner testRunner = x...
llgoncalves/harpia
harpia/model/diagrammodel.py
Python
gpl-2.0
854
0.001171
# -*- coding: utf-8 -*- from harpia.model.connectionmodel import ConnectionModel as ConnectionModel from harpia.system import System as System class DiagramModel(object): # ---------------------------------------------------------------------- def __init__(self): self.last_id = 1 # first block is n1...
---------------------------------------------------------------------- @property def patch_name(self): return self.file_name.split
("/").pop() # ----------------------------------------------------------------------
lino-framework/xl
lino_xl/lib/orders/choicelists.py
Python
bsd-2-clause
992
0.006048
# -*- coding: UTF-8 -*- # Copyright 2019-2020 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from django.db import models from lino_xl.lib.ledger.choicelists import VoucherStates from lino.api import dd, _ class OrderStates(VoucherStates): pass add = OrderStates....
elled"), 'cancelled') OrderStates.draft.add_transition(required_states="active urgent registered cancelled") OrderStates.active.add_transition(required_states="draft urgent registered cancelled") OrderStates.urgent.add_transition(required_states="draft active registered cancelled") OrderStates.registered.add_transitio...
equired_states="draft active urgent registered")
hfp/tensorflow-xsmm
tensorflow/contrib/distribute/python/minimize_loss_test.py
Python
apache-2.0
20,274
0.007695
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
press or implied. # See the License for the specific language
governing permissions and # limitations under the License. # ============================================================================== """Tests for running legacy optimizer code with DistributionStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_functi...
matthiask/django-admin-sso
admin_sso/default_settings.py
Python
bsd-3-clause
1,071
0.001867
from django.conf import settings from django.utils.translation import gettext_lazy as _ ASSIGNMENT_ANY = 0 ASSIGNMENT_MATCH = 1 ASSIGNMENT_EXCEPT = 2 ASSIGNMENT_CHOICES = ( (ASSIGNMENT_ANY, _("any")), (ASSIGNMENT_MATCH, _("matches")), (ASSIGNMENT_EXCEPT, _("don't match")), ) DJANGO_ADMIN_SSO_ADD_LOGIN_BU...
_MODEL", "auth.User") DJANGO_ADMIN_SSO_OAUTH_CLIENT_ID = getattr( settings, "DJANGO_ADMIN_SSO_OAUTH_CLIENT_ID", None ) DJANGO_ADMIN_SSO_OAUTH_CLIENT_SECRET = getattr( settings, "DJANGO_ADMIN_SSO_OAUTH_CLIENT_SECRET", Non
e ) DJANGO_ADMIN_SSO_AUTH_URI = getattr( settings, "DJANGO_ADMIN_SSO_AUTH_URI", "https://accounts.google.com/o/oauth2/auth" ) DJANGO_ADMIN_SSO_TOKEN_URI = getattr( settings, "DJANGO_ADMIN_SSO_TOKEN_URI", "https://accounts.google.com/o/oauth2/token" ) DJANGO_ADMIN_SSO_REVOKE_URI = getattr( settings, "DJ...
GREO/GNU-Radio
gr-audio-alsa/src/qa_alsa.py
Python
gpl-3.0
1,240
0.010484
#!/usr/bin/env python # # Copyright 2005,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your opt...
lf): """Just see if we can import the module... They may not have ALSA drivers, etc. Don't try to run anything""" pass if __name__ == '__main__': gr_unittest.main ()
levythu/swift-layerC
inapi/httpd.py
Python
gpl-2.0
287
0
# coding=utf-8 from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOL
oop from app import app if __name__ == "__main__": http_server = HTTPServer(WSGIContainer(app)) http_server.listen(5000)
IOLoop.instance().start()
timm/timmnix
pypy3-v5.5.0-linux64/lib-python/3/distutils/command/sdist.py
Python
mit
17,891
0.000391
"""distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" import os import string import sys from types import * from glob import glob from warnings import warn from distutils.core import Command from distutils import dir_util, dep_util, file_util, archive_util from distu...
self.formats = [self.default_format[os.name]] except KeyError: raise DistutilsPlatformError( "don't know how to create source distributions " "on platform %s" % os.name) bad_format = archive_util.check_archive_formats(self.formats) ...
s'" % bad_format) if self.dist_dir is None: self.dist_dir = "dist" def run(self): # 'filelist' contains the list of files that will make up the # manifest self.filelist = FileList() # Run sub commands for cmd_name in self.get_sub_commands(): ...
RickMohr/nyc-trees
src/nyc_trees/nyc_trees/middleware.py
Python
apache-2.0
846
0
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division import re import waffle from django.conf import settings from django.shortcuts import redirect class SoftLaunchMiddleware(object): def __init__(self): self.redirect_url =...
_LAUNCH_REGEXES', []) self.regexes = [re.compile(r) for r in regexes] def process_view(self, request, view_func, view_args, view_kwargs): if waffle.flag_is_active(request, 'full_access'): return None allowed = ((request.path == self.redirect_url) or any(r.mat...
redirect(self.redirect_url)
dirkmoors/drf-tus
rest_framework_tus/storage.py
Python
mit
1,346
0.000743
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta, abstractmethod from django.core.files import File from six import with_metaclass from django.utils.module_loading import import_string from rest_framework_tus import signals from .settings import TUS_SAVE_HANDLER_CLASS class ...
pass def run(self): # Trigger state change self.upload.start_saving() self.upload.save() # Initialize saving self.handle_save() def finish(self): # Trigger signal signals.saved.send(sender=self.__class__, instance=self) # Finish self.up...
aultSaveHandler(AbstractUploadSaveHandler): destination_file_field = 'uploaded_file' def handle_save(self): # Save temporary field to file field file_field = getattr(self.upload, self.destination_file_field) file_field.save(self.upload.filename, File(open(self.upload.temporary_file_path...
Phonemetra/TurboCoin
test/functional/rpc_scantxoutset.py
Python
mit
12,820
0.008892
#!/usr/bin/env python3 # Copyright (c) 2018-2019 TurboCoin # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the scantxoutset rpc call.""" from test_framework.test_framework import TurbocoinTestFramework from test_framework.u...
prv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0'/0'/1h)"])['total_amount'], Decimal("0.016")) assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRv...
start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0h/0)"])['total_amount'], Decimal("0.064")) assert_equal(self.nodes[0].scantxoutset("start", [ "combo(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5...
eramirem/astroML
book_figures/chapter10/fig_wavelets.py
Python
bsd-2-clause
2,201
0.001363
""" Examples of Wavelets -------------------- Figure 10.9 Wavelets for several values of wavelet parameters Q and f0. Solid lines show the real part and dashed lines show the imaginary part (see eq. 10.16). """ # Author: Jake VanderPlas # License: BSD # The figure produced by this code is published in the textbook #...
------- # Set up the wavelets t0 = 0 t = np.linspace(-0.4, 0.4, 10000) f0 = np.array([5, 5, 10, 10]) Q = np.array([1, 0.5, 1, 0.5]) # compute wavelets all at once W = sinegauss(t, t0, f0[:, None], Q[:, None]) #------------------------------------------------------------ # Plot the wavelets fig = plt.figure(figsize=(5...
ange(4): ax = fig.add_subplot(221 + i) ax.plot(t, W[i].real, '-k') ax.plot(t, W[i].imag, '--k') ax.text(0.04, 0.95, "$f_0 = %i$\n$Q = %.1f$" % (f0[i], Q[i]), ha='left', va='top', transform=ax.transAxes) ax.set_ylim(-1.2, 1.2) ax.set_xlim(-0.35, 0.35) ax.xaxis.set_major_locator...
jgrizou/explauto
explauto/sensorimotor_model/inverse/__init__.py
Python
gpl-3.0
284
0.014085
fro
m .inverse import RandomInverseModel from .sciopt import BFGSInverseModel, COBYLAInverseModel from .nn import NNInverseModel from .wnn import WeightedNNInverseModel, ESWNNInverseModel from .cmamodel import CMAESInverseModel from .jacobian import JacobianInverseMod
el
kwailamchan/programming-languages
python/django/artdepot/artdepot/depot/migrations/0003_auto_20140930_2137.py
Python
mit
942
0.002123
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('depot', '0002_lineitem'), ] operations = [ migrations.CreateModel( name='Order', fie...
extField()), ('email', models.EmailField(max_length=75)), ], options={ },
bases=(models.Model,), ), migrations.AddField( model_name='lineitem', name='order', field=models.ForeignKey(default=datetime.date(2014, 9, 30), to='depot.Order'), preserve_default=False, ), ]
pswaminathan/python_efficiency_tweaks
plots/plot_string_subst_bar.py
Python
gpl-3.0
686
0.008746
# Plotting performance of string_subst_.py scripts # bar chart of relative comparison with variances as error bars import numpy as np import matplotlib.pyplot as plt performance = [10.3882388499416,1,10.3212
281215746] variance = [0.790435196936213,0,0.827207394592818] scripts = ['string_subst_1.py', 'string_subst_2.py', 'string_subst_3.py'] x_pos = np.arange(len(scripts)) plt.bar(x_pos, performance, yerr=variance, align='center', alpha=0.5) plt.xticks(x_pos, scripts) plt.axhline(y=1, linestyle='--', color='black') plt.y...
titution - Speed improvements') #plt.show() plt.savefig('PNGs/string_subst_bar.png')
andymckay/addons-server
src/olympia/amo/tests/test_decorators.py
Python
bsd-3-clause
5,822
0
from datetime import datetime, timedelta from django import http from django.conf import settings from django.core.exceptions import PermissionDenied import mock import pytest from olympia.amo.tests import BaseTestCase, TestCase from olympia.amo import decorators, get_user, set_user from olympia.amo.urlresolvers imp...
w_status(): def func(request): return {'x': 1} response = decorators.json_view(func, status_code=202)(mock.Mock()) assert response.status_code == 202 def test_json_view_response_status(): response = decorators.json_response({'msg': 'error'}, status_code=202) assert response.content == '{"...
sponse.status_code == 202 class TestTaskUser(TestCase): fixtures = ['base/users'] def test_set_task_user(self): @decorators.set_task_user def some_func(): return get_user() set_user(UserProfile.objects.get(username='regularuser')) assert get_user().pk == 999 ...