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
geoenvo/opendims
opendims/automaticweathersystem/migrations/0001_initial.py
Python
gpl-3.0
2,669
0.005995
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-21 07:08 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True ...
('wind_speed', models.PositiveIntegerField(default=0, verbose_name='Wind Speed')), ('wind_direction', models.PositiveIntegerField(default=0, verbose_name='Wind Direction')), ('day_rain', models.PositiveIntegerField(default=0, verbose_name='Day Rain')), ('rai...
_index', models.PositiveIntegerField(default=0, verbose_name='UV Index')), ('solar_radiation', models.PositiveIntegerField(default=0, verbose_name='Solar Radiation')), ], options={ 'ordering': ['-updated', '-created'], 'get_latest_by': 'updated', ...
DiMartinoX/plugin.video.kinopoisk.ru
script.myshows/episode_sync.py
Python
gpl-3.0
16,581
0.024365
# -*- coding: utf-8 -*- import xbmc import xbmcgui import xbmcaddon from utilities import xbmcJsonRequest, Debug, notification, chunks, get_bool_setting __setting__ = xbmcaddon.Addon('script.myshows').getSetting __getstring__ = xbmcaddon.Addon('script.myshows').getLocalizedString add_episodes_to_myshows = get_bool...
yshowsapi.getShowLibrary() def AddTomyshows(self): Debug('[Episodes Sync] Checking for episodes missing from myshows.tv collection') if self.show_progress: progress.update(30, line1=__getstring__
(1435), line2=' ', line3=' ') add_to_myshows = [] myshows_imdb_index = {} myshows_tvdb_index = {} myshows_title_index = {} for i in range(len(self.myshows_shows['collection'])): if 'imdb_id' in self.myshows_shows['collection'][i]: myshows_imdb_index[self.myshows_shows['collection'][i]['imdb_id']] = i...
indictranstech/omnitech-frappe
setup.py
Python
mit
438
0.004566
from setuptools import setup, find_packages version = "6.3.0" with open("requirements.txt", "r") as f: install_requires = f.readlines() setup( name='frappe', version=version, description='Metadata driven, full-stack web f
ramework', author='Frappe Technologies', author_email='[email protected]', packages=find_packages(), zip_safe=False, include_package_data=True,
install_requires=install_requires )
thiagoferreiraw/mixapp
events/views/choose_image_view.py
Python
mit
1,771
0.003953
from django.shortcuts import render, redirect from django.http import Http404 from events.forms import Event from django.views.generic import View from events.services import PlacesService from events.forms import ImageUploadForm from django.contrib import messages
import uuid class ChooseImageView(View): template_name = "events/choose_image.html" form_action = "Edit" def __init__(self): self.places_service = PlacesService() def get(self, request, event_id): event = self.get_event_or_404(event_id, request.user.id) images = self.places...
id, "en") images += self.places_service.get_images_street_view(event.location_lat, event.location_lng) images = [{'idx': idx, 'url': image} for idx, image in enumerate(images)] if "image_idx" in request.GET: event.get_remote_image(images[int(request.GET['image_idx'])]['url']) ...
DrewMcCarthy/dartboard
game.py
Python
apache-2.0
3,208
0.037406
import player import pygame import menu import settings as s pygame.init() pygame.mixer.init() class Game: def __init__(self, numplayers=2, doublebull='ON', mpcalc='ROUND'): #GAME INFO self.mpcalc = mpcalc self.doublebull = doublebull self.numplayers = numplayers self.mainLoop = True self.cl...
_score() if self.total_darts_thrown % 3 == 0: pygame.event.post(self.end_turn_event) if self.forced_next_turn: self.next_turn_flag = False else: self.next_turn_flag = True self.players[self.ap].add_dart(self.roundNum, self.last_dart, self.valid_marks) self.check_winner() def on_ev...
nu.Menu()) if event.type == pygame.MOUSEMOTION: print(pygame.mouse.get_pos()) if event.type == self.ENDTURN: print('game on_event ENDTURN') self.update_turn() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.manager.go_to(menu.Menu()) def on_gpio(self, seg...
ragb/sudoaudio
sudoaudio/core.py
Python
gpl-3.0
2,629
0.002282
# Copyright (c) 2011 - Rui Batista <[email protected]> # # 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 vers...
ult(event) def on_quit_event(self): pygame.quit() sys.exit(0) def get_events(self): return pygame.event.get() def run_before(self): pass def run_after(self): pass
def on_run(self): pass def on_event_default(self, event): pass class VoiceDialog(PygameMainLoop): @key_event(pygame.K_ESCAPE) def escape(self, event): self.quit(None) def get_events(self): return [pygame.event.wait()]
rpiotti/Flask-AppBuilder
setup.py
Python
bsd-3-clause
1,758
0.003413
import os import sys import imp import multiprocessing from setuptools import setup, find_packages version = imp.load_source('version', os.path.join('flask_appbuilder', 'version.py')) def fpath(name): return os.path.join(os.path.dirname(__file__), name) def read(fname): return open(fpath(fname)).read() def...
n', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite=
'nose.collector' )
quarkslab/irma
probe/tests/modules/antivirus/test_avg.py
Python
apache-2.0
4,618
0
from .test_antivirus import AbstractTests import modules.antivirus.avg.avg as module import modules.antivirus.base as base from mock import patch from pathlib import Path class TestAvg(Abstr
actTests.TestAntivirus): name = "AVG AntiVirus Free (Linux)" scan_path = Path("/usr/bin/avgscan") scan_args = ('--heur', '--paranoid', '--arc', '--macrow', '--pwdw', '--pup') module = module.AVGAntiVirusFree scan_clean_stdout = """AVG command line Anti-Virus scanner Copyright (c) 2...
rus database release date: Mon, 21 May 2018 13:00:00 +0000 Files scanned : 1(1) Infections found : 0(0) PUPs found : 0 Files healed : 0 Warnings reported : 0 Errors reported : 0 """ scan_virus_retcode = 4 virusname = "EICAR_Test" scan_virus_stdout = """AVG command line Anti-V...
hftools/hftools
hftools/networks/tests/test_spar_functions.py
Python
bsd-3-clause
3,696
0.000812
#----------------------------------------------------------------------------- # Copyright (c) 2014, HFTools Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #--------------------------------------------------...
def make_array(a): dims = (aobj.DimSweep("f", len(a)), aobj.DimMatrix_i("i", 2), aobj.DimMatrix_j("j", 2)) return aobj.hfarray(a, dims=dims) class Test_cascade(TestCase): def setUp(self): self.a = make_array([[[0, 1], [1, 0j]]]) self.b = make_array([[[0, 2], [2, 0j]...
test_cascade_2(self): r = spfun.cascadeS(self.a, self.b) self.assertTrue(np.allclose(r, self.b)) def test_cascade_3(self): r = spfun.cascadeS(self.b, self.b) self.assertTrue(np.allclose(r, self.a * 4)) def test_cascade_4(self): r = spfun.cascadeS(self.a, self.c) ...
dasbruns/netzob
src/netzob/Common/Utils/NetzobRegex.py
Python
gpl-3.0
15,254
0.004132
#-*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols...
nstead we highly recommend the use of the static methods offered to build different types o
f regex. If still you want to use the constructor, don't specify the group since it will be automaticaly added. For example, if your regex is (.*), only specify .* and forget the () that will be added. In addition the constructor will also generate and add the group identifier. Your regex will therefor...
poojavade/Genomics_Docker
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/chebyshev.py
Python
apache-2.0
6,561
0.00381
#!/usr/bin/env python # Author : Pierre Schnizer """ This module describes routines for computing Chebyshev approximations to univariate functions. A Chebyshev approximation is a truncation of the series \M{f(x) = S{sum} c_n T_n(x)}, where the Chebyshev polynomials \M{T_n(x) = cos(n \arccos x)} provide an orthogonal ...
mode) # # def eval_mode_e(self, x, mode): # return self._eval(self._ptr, x, mode) def calc_deriv(self): """ This method computes the derivative of the series CS. It returns a new instance of the cheb_series class. """ tmp = cheb_series(self._size) self._cal...
calc_integ(self): """ This method computes the integral of the series CS. It returns a new instance of the cheb_series class. """ tmp = cheb_series(self._size) self._calc_integ(tmp._ptr, self._ptr) return tmp def get_coefficients(self): """ G...
mysociety/yournextrepresentative
candidates/tests/test_search.py
Python
agpl-3.0
4,466
0.000672
import re from django.core.management import call_command from django_webtest import WebTest from .auth import TestUserMixin from .settings import SettingsMixin from popolo.models import Person from .uk_examples import UK2015ExamplesMixin class TestSearchView(TestUserMixin,
SettingsMixin, UK2015Example
sMixin, WebTest): def setUp(self): super(TestSearchView, self).setUp() call_command('rebuild_index', verbosity=0, interactive=False) def test_search_page(self): # we have to create the candidate by submitting the form as otherwise # we're not making sure the index update hook f...
vapkarian/soccer-analyzer
src/versions/f4.py
Python
mit
3,131
0.000639
from collections import OrderedDict from src.models import FlashscoreMatch from src.settings import match_cache, Colors @match_cache def is_available(match: FlashscoreMatch) -> bool: return ( match.ah_0_1_current_odds is not None and match.ah_0_2_current_odds is not None and match.home_dr...
e def other(match: FlashscoreMatch) -> bool: return not(e1(match) or e2(match) or a1(match) or h2(match) or test(match)) @match_cache def bet(match: FlashscoreMatch) -> str: values = OrderedDict([ ('e1', e1(mat
ch)), ('e2', e2(match)), ('a1', a1(match)), ('h2', h2(match)), ('test', test(match))]) return ', '.join((key for key, value in values.items() if value)) @match_cache def ah_0_1_color(match: FlashscoreMatch) -> Colors: if e1(match) or a1(match): return Colors.GREEN r...
hydroffice/hyo_soundspeed
hyo2/soundspeed/atlas/regofsoffline.py
Python
lgpl-2.1
8,583
0.001748
from datetime import datetime as dt import os from enum import IntEnum import logging from typing import Optional from netCDF4 import Dataset, num2date from hyo2.soundspeed.base.geodesy import Geodesy from hyo2.soundspeed.profile.dicts import Dicts from hyo2.soundspeed.profile.profile import Profile from hyo2.soundspe...
# Gulf of Mexico NGOFS = 20 # RG = True # Format is GoMOFS TBOFS = 21 # RG = True # Format is GoMOFS # Great Lakes LEOFS = 30 # RG = True # Format is GoMOFS LHOFS = 31 # RG = False LMOFS = 32 # RG = False LOOFS = 33 # RG = F
alse LSOFS = 34 # RG = False # Pacific Coast CREOFS = 40 # RG = True # Format is GoMOFS SFBOFS = 41 # RG = True # Format is GoMOFS # noinspection DuplicatedCode regofs_model_descs = \ { Model.CBOFS: "Chesapeake Bay Operational Forecast System", ...
macobo/python-grader
tasks/MTAT.03.100/2013/Midterm_1_resit/KT2_J1_vahenda_tester.py
Python
mit
1,967
0.028659
""" Task description (in Estonian): 3. Maatriksi vähendamine (6p) Kirjuta funktsioon vähenda, mis võtab argumendiks arvumaatriksi, milles ridu ja veerge on paarisarv, ning tagastab uue maatriksi, milles on kaks korda vähem ridu ja kaks korda vähem veerge, ja kus iga element on esialgse maatriksi nelja elemendi keskmin...
, 6, 7, 8]], description="Mitte-ruudukujuline maatriks - {function}({args}) == {expected}") checker([[1,5,2,6,3,6], [1,3,2,7,3,3], [4,8,5,1,1,6], [4,4,9,5,6,1]]) checker([[1,5,2,6,3,6], [1,3,2,7,3,3], [4,8,5,1,1,6], [4,4,9,5,6,1]]) checker([], description="Erijuht, tühi maatriks- {function}({args}) == {expecte...
[0, 5, 1, 7]], [[4, 4], [0, 8], [4, 9], [3, 0], [3, 6], [8, 2]], [[9, 4, 6, 5, 4, 6], [3, 8, 7, 1, 2, 5], [8, 9, 8, 5, 0, 2], [2, 7, 2, 4, 3, 5], [2, 6, 8, 0, 2, 9], [7, 4, 6, 4, 8, 2]], [[-1, -3], [-6, 6], [5, -6], [1, 0]], [[-5, -10, 6, -1], [-8, -10, -5, 7], [-7, 9, -5, -5], ...
kylon/pacman-fakeroot
test/pacman/tests/upgrade055.py
Python
gpl-2.0
618
0.001618
self.description = "Upgrade a package that provides one of two imaginary packages" lp1 = pmpkg("pkg1") lp1.depends = ["imaginary", "imaginary2"] self.addpkg2db("local", lp1) lp2 = pmpkg("pkg2") l
p2.provides = ["imaginary"] self.addpkg2db("local", lp2) lp3 = pmpkg("pkg3") lp3.provides = ["imaginary2"] self.addpkg2db("local", lp3) p = pmpkg("pkg2", "1.0-2") p.provides = ["imaginary"] self.addpkg(p) self.args = "-U %s" % p.filename() self.addrule("PACMA
N_RETCODE=0") self.addrule("PKG_EXIST=pkg1") self.addrule("PKG_VERSION=pkg2|1.0-2") self.addrule("PKG_EXIST=pkg3") self.addrule("PKG_DEPENDS=pkg1|imaginary")
sokil/VotingEngine
models/voting_variant.py
Python
mit
361
0.00277
from app import db f
rom sqlalchemy import Column, String, Integer, ForeignKey class VotingVariant(db.Model): __tablename__ = 'voting_variants' id = Column(Integer, primary_key=True) voting_id = Column(Integer, ForeignKey('votings.id')) title = Column(String(255)) description = Column(String(1000)) voting =
db.relationship('Voting')
DarknessSwitch/django-tutorial
catalog/admin.py
Python
cc0-1.0
2,208
0.005888
from django.contrib import admin # Register your models here. from .models import Author, Genre, Book, BookInstance, Language """ # Minimal registration of Models. admin.site.register(Book) admin.site.register(Author) admin.site.register(BookInstance) admin.site.register(Genre) admin.site.register(Language) """ adm...
or) class AuthorAdmin(admin.ModelAdmin): """ Administration object for Author models. Defines:
- fields to be displayed in list view (list_display) - orders fields in detail view (fields), grouping the date fields horizontally - adds inline addition of books in author view (inlines) """ list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death') fields = ['first_name', 'l...
endlessm/chromium-browser
build/run_swarming_xcode_install.py
Python
bsd-3-clause
3,039
0.005923
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ This script runs swarming_xcode_install on the bots. It should be run when we need to upgrade all the swarming testers. It: 1) ...
rgs.isolate_server, '--priority', '20', '--batches', str(args.batches), '--tags', 'name:run_swarming_xcode_install', ] + dim_args + ['--name', 'run_swarming_xcode_install', '--', isolate_hash, 'pyt
hon', 'swarming_xcode_install.py', ] subprocess.check_call(cmd) print('All tasks completed.') finally: shutil.rmtree(tmp_dir) return 0 if __name__ == '__main__': sys.exit(main())
sebastic/QGIS
python/plugins/processing/algs/qgis/VariableDistanceBuffer.py
Python
gpl-2.0
3,079
0.001299
# -*- coding: utf-8 -*- """ *************************************************************************** VariableDistanceBuffer.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ****************...
jects.getObjectFromUri(self.getParameterValue(self.INPUT)) dissolve = self.getParameterValue(self.DISSOLVE) field = self.getParameterValue(self.FIELD) segments = int(self.getParameterValue(self.SEGMENTS)) writer = self.getOutputFromName(self.OUTPUT).getVectorWriter( layer.pe...
segments)
arubertoson/maya-mamprefs
mamprefs/markingmenus.py
Python
mit
11,879
0.000253
""" """ import sys import re import keyword import logging import traceback from functools import partial from PySide import QtCore from PySide.QtCore import QObject from maya import cmds from mampy.pyside.utils import get_qt_object from mamprefs import config from mamprefs.base import BaseManager,...
=lambda *args: self.reload_marking_menus()) if self.map: self.add_menu_items() else: cmds.menuItem(l='No Marking Menus', enable=False) cmds.menuItem(l='Clean Scene', c=lambda *args: self.clean_menu()) def parse_files(self): for file_name, f in self.fi...
e] = [ MarkingMenu(**menu) for menu in file_map # for name, item in menu.iteritems() ] def reload_marking_menus(self): """ Rebuild menus and re-parse files. Then rebuild the UI. """ self.reload() self.ini...
zstackio/zstack-woodpecker
integrationtest/vm/vm_password/test_chg_unexist_usr_passwd_u14.py
Python
apache-2.0
2,941
0.011561
''' test for changing unexisted user password @author: SyZhao ''' import apibinding.inventory as inventory import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.vm_operations as vm_ops im...
# normal_failed_string = "not exist" # if normal_failed_string
in str(e): # test_util.test_logger("unexisted user return correct, create a the user for it.") #else: # test_util.test_fail("user not exist in this OS, it should not raise exception, but return a failure.") test_stub.create_user_in_vm(vm.get_vm(), usr, pa...
dantebarba/docker-media-server
plex/Subliminal.bundle/Contents/Libraries/Shared/guessit/transfo/split_on_dash.py
Python
gpl-3.0
1,659
0.000603
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2013 Nicolas Wa
ck <[email protected]> # # 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 Software Foundation; either version 3 of the License, or # (at your option) any later version. # # GuessIt 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 th...
RivuletStudio/rivuletpy
tests/testssm.py
Python
bsd-3-clause
624
0.001603
from filtering.morphology import ssm from rivuletpy.utils.io import * import matplotlib.pyplot as plt import skfmm ITER = 30 img = loadimg('/home/siqi/ncidata/rivuletpy/tests/data/test-crop.tif') bimg = (img > 0).astype('int') dt = skfmm.distance(bimg, dx=1) sdt = ssm(dt, anisotro
pic=True, iterations=ITER) try: from skimage import filters except ImportError: from skimage import filter as filters s_seg = s > filters.threshold_otsu(s) plt.figure() plt.title('DT') plt.imshow(dt.max(-1)) plt.figure() plt
.title('img > 0') plt.imshow((img > 0).max(-1)) plt.figure() plt.title('SSM-DT') plt.imshow(sdt.max(-1))
yavalvas/yav_com
build/matplotlib/lib/matplotlib/tight_bbox.py
Python
mit
2,604
0
""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixe...
gBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): ...
xes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout ...
rohitsinha54/Learning-Python
algorithms/stack.py
Python
mit
716
0
#!/usr/bin/env python """stack.py: Stack implementation""" __author__ = 'Rohit Sinha' class Stack:
def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[le
n(self.items) - 1] def size(self): return len(self.items) def __str__(self): return str(self.items).strip('[]') if __name__ == '__main__': s = Stack() print(s.isEmpty()) s.push(5) s.push('Hello') print(s.peek()) s.push(True) print(s.peek()) print(s.size()) ...
fruce-ki/utility_scripts
chromosome_surgery.py
Python
mit
3,387
0.006791
#!/usr/bin/env python3 import sys from Bio import SeqIO from argparse import ArgumentParser, RawDescriptionHelpFormatter usage = "Chromosome surgery: Splice something into and/or out of a chromosome." # Main Parsers parser = ArgumentParser(description=usage, formatter_class=RawDescriptionHelpFormatter) parser.add_arg...
inates. if args.excision_start > args.incision and args.excision_end > args.incision: excision_start = args.excision_start + len(splice_in) excision_end = args.excision_end + len(splice_in) elif args.excision_start < incision and args.excision_end < incision: pass
# The incision will be applied first, no need to adjust it. The excision is unaffected by the incision anyway. else: sys.stderr.write('Error: Cannot apply the specified coordinates. Excision end must be after excision start, and the incision cannot be inside the excision.') # Parse and apply edit wit...
SteveDiamond/cvxpy
examples/extensions/sudoku_admm.py
Python
gpl-3.0
2,414
0.018641
""" Copyright 2013 Ste
ven Diamond Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the...
ng permissions and limitations under the License. """ from cvxpy import * from mixed_integer import * import cvxopt import numpy as np n = 9 # 9x9 sudoku grid numbers = Variable(n,n) # TODO: 9*[Boolean(9,9)] doesn't work.... solution = cvxopt.matrix([ [0, 5, 2, 3, 7, 1, 8, 6, 4], [6, 3, 7, 8, 0, 4, 5, 2, 1]...
Hoshiyo/fabric_navitia
integration_tests/test_tyr/test_setup.py
Python
agpl-3.0
5,824
0.00206
# encoding: utf-8 from ..docker import docker_exec from ..utils import filter_column, python_requirements_compare from ..test_common import skipifdev # @skipifdev def test_update_tyr_config_file(distributed_undeployed): platform, fabric = distributed_undeployed # create empty directory for task under test ...
/srv/tyr/settings.py') assert platform.path_exists('/srv/tyr/se
ttings.wsgi') env = fabric.get_object('env') env.tyr_broker_username = 'toto' value, exception, stdout, stderr = fabric.execute_forked('update_tyr_config_file') assert exception is None assert stderr.count("Warning: run() received nonzero return code 1 while executing " "'di...
jgmanzanas/CMNT_004_15
project-addons/purchase_picking/purchase.py
Python
agpl-3.0
5,513
0.000908
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved # $Jesús Ventosinos Mayor <[email protected]>$ # # This program is free software: you can redistribute it and/or modify # it under the ...
are done''' for purchase in self: for line in purchase.order_line: for move in line.move_ids: if move.state != 'done': return False return True def is_picking_created(self): self.picking_created = self.picking_ids ...
, picking_id, group_id, context=None): """ prepare the stock move data from the PO line. This function returns a list of dictionary ready to be used in stock.move's create() """ purchase_line_obj = self.pool['purchase.order.lin...
slozier/ironpython2
Src/StdLib/Lib/clrtype.py
Python
apache-2.0
27,760
0.006484
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. __all__ = ["ClrClass", "ClrInterface", "accepts", "returns", "attribute", "propagate_attributes"] import clr c...
il the generated
type # gets explicitly published as the underlying CLR type is_typed = is_typed or (hasattr(t, "__metaclass__") and t.__metaclass__ in [ClrInterface, ClrClass]) if not is_typed: raise Exception, "Invalid CLR type %s" % str(t) if not var_signature: if clr_type.IsBy...
tjwei/HackNTU_Data_2017
Week09/q_posts_friends.py
Python
mit
367
0.00545
from collections import Counter from pprint import pprint count = Counter() posts = gra
ph.get_object('me', fields=['posts.limit(100)'])['posts']['data'] for i, p in enumerate(posts): likes = get_all_data(graph, p['id']+"/likes") print(i, p['id'], len(
likes)) for x in likes: name = x['name'] count[name] += 1 pprint(count.most_common(15))
obulpathi/cdn1
cdn/transport/pecan/controllers/__init__.py
Python
apache-2.0
879
0
# Copyright (c) 2014 Rackspace, Inc. # # Licensed und
er the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is di...
ssions and # limitations under the License. """Pecan Controllers""" from cdn.transport.pecan.controllers import root from cdn.transport.pecan.controllers import services from cdn.transport.pecan.controllers import v1 # Hoist into package namespace Root = root.RootController Services = services.ServicesController V1...
citrix-openstack-build/tempest
tempest/services/compute/xml/interfaces_client.py
Python
apache-2.0
4,377
0
# Copyright 2013 IBM Corp. # 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 app...
auth
_url, tenant_name) self.service = self.config.compute.catalog_type def _process_xml_interface(self, node): iface = xml_to_json(node) # NOTE(danms): if multiple addresses per interface is ever required, # xml_to_json will need to be fixed or replaced in this case iface['fixed...
googleads/google-ads-python
google/ads/googleads/v9/services/services/product_bidding_category_constant_service/transports/__init__.py
Python
apache-2.0
1,165
0.000858
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
License. # from collections import OrderedDict from typing import Dict, Type from .base import ProductBiddingCategoryConstantS
erviceTransport from .grpc import ProductBiddingCategoryConstantServiceGrpcTransport # Compile a registry of transports. _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[ProductBiddingCategoryConstantServiceTransport]] _transport_registry["grpc"] = ProductBiddingCategoryConstantServiceGrpcTransport...
ara-ta3/jupyter-gauche
jupyter_gauche/install.py
Python
mit
1,024
0.006836
import json import os import sys from jupyter_client.kernelspec import install_kernel_spec from IPython.utils.tempdir import TemporaryDirectory kernel_json = { "display_name": "Gauche", "language": "gauche", "argv": [sys.executable, "-m", "jupyter_gauche", "-f", "{connection_file}"], "codemirror_mode"...
Starts off as 700, not user readable with open(os.path.join(td, 'kernel.json'), 'w') as f: json.dump(kernel_json, f, sort_keys=True) print('Installing IPython kernel spec') install_kernel_spec(td, 'gauche', user=user, replace=True) def _is_root(): try: return os.geteuid...
main(argv=[]): user = '--user' in argv or not _is_root() install_gauche_kernel_spec(user=user) if __name__ == '__main__': main(argv=sys.argv)
darren-rogan/CouchPotatoServer
couchpotato/core/providers/base.py
Python
gpl-3.0
2,933
0.004773
from couchpotato.core.event import addEvent from couchpotato.core.helpers.variable import tryFloat from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from urlparse import urlparse import re import time log = CPLog(__name__) class Provid...
ize * 1024 for s in self.sizeMb: if s in sizeRaw: return size for s in self.sizeKb: if s in sizeRaw: return size / 1024 return 0 def getCatId(self, identifier): for cats in self.ca
t_ids: ids, qualities = cats if identifier in qualities: return ids return [self.cat_backup_id] def found(self, new): log.info('Found: score(%(score)s) on %(provider)s: %(name)s', new)
Levis0045/MetaLex
metalex/xmlised/makeBalise.py
Python
agpl-3.0
26,115
0.01425
#! usr/bin/env python # coding: utf8 from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals """metalex is general tool for lexicographic and metalexicographic activities Copyright (C) 2017 by Elvis MBONING This program is free software: you can redistri...
ild HTML editor file of the all articles :return file: metalexViewerEditor.html """ print('\n --- %s %s \n\n' %(colored('Part 4: Generate Output formats', attrs=['bold']), '--'*25)) metalex.plugins instanceHtml = BaliseHTML() filepath = metalex.html_template metalex.utils.crea...
souphtl = instanceHtml.html_inject('CopymetalexTemplate.html') if save: metalex.utils.go_to_dicresult() name = metalex.currentOcr+'_metalexViewerEditor.html' with codecs.open(name, 'w') as htmlresult: htmlresult.write(souphtl) metalex.utils.creat...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/internet/iocpreactor/tcp.py
Python
gpl-3.0
68
0.014706
../../../
../../../share/pyshared/twisted/
internet/iocpreactor/tcp.py
rcosnita/fantastico
fantastico/middleware/tests/test_routing_middleware.py
Python
mit
4,545
0.011441
''' Copyright 2013 Cosnita Radu Viorel 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...
oked = True router = Mock() router_cls = Mock(return_value=router) router.get_loaders = lambda: get_loaders() router.register_routes = lambda: register_routes() RoutingMiddleware(Mock(), router_cls)
self.assertTrue(self.get_loaders_invoked) self.assertTrue(self.register_routes_invoked) class SimpleController(object): '''Class used to simulate a controller that can handle certain requests.''' pass
jeffery-do/Vizdoombot
doom/lib/python3.5/site-packages/dask/dataframe/tests/test_utils_dataframe.py
Python
mit
7,032
0
import numpy as np import pandas as pd import pandas.util.testing as tm import dask.dataframe as dd from dask.dataframe.utils import (shard_df_on_index, meta_nonempty, make_meta, raise_on_meta_error) import pytest def test_shard_df_on_index(): df = pd.DataFrame({'x': [1, 2, 3, 4...
ame == idx.name idx = pd.Int64Index([1], name='foo') res = meta_nonempty(idx) assert type(res) is pd.Int64Index assert res.name == idx.name idx = pd.Index(['a'], name='foo') res = meta_nonempty(idx) assert type(res) is pd.Index assert res.name == idx.name idx = pd.DatetimeIndex(['...
) is pd.DatetimeIndex assert res.tz == idx.tz assert res.freq == idx.freq assert res.name == idx.name idx = pd.PeriodIndex(['1970-01-01'], freq='d', name='foo') res = meta_nonempty(idx) assert type(res) is pd.PeriodIndex assert res.freq == idx.freq assert res.name == idx.name idx =...
houseurmusic/my-swift
swift/obj/updater.py
Python
apache-2.0
9,252
0.001405
# Copyright (c) 2010-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 agreed to ...
async_pending = os.path.join(device, ASYNCDIR) if not os.path.isdir(async_pending): return for prefix in os.listdir(async_pending): prefix_path = os.path.join(async_pending, prefix) if not os.path.isdir(prefix_path): continue last_obj_ha...
e_path = os.path.join(prefix_path, update) if not os.path.isfile(update_path): continue try: obj_hash, timestamp = update.split('-') except ValueError: self.logger.error( _('ERROR async pe...
shakamunyi/fig
tests/integration/project_test.py
Python
apache-2.0
55,924
0.00059
from __future__ import absolute_import from __future__ import unicode_literals import os.path import random import py import pytest from docker.errors import APIError from docker.errors import NotFound from .. import mock from ..helpers import build_config as load_config from ..helpers import create_host_file from ....
f.client, ) project.up() web = project.get_service('web') net = project.get_service('net') self.assertEqual(web.network_mode.mode, 'container:' + net.containers()[0].id) @no_cluster('container networks not supported in Swarm') def test_net_from_container_v1(self): ...
st', config_data=load_config({ 'web': { 'image': 'busybox:latest', 'net': 'con
smarrazzo/pyava
consts.py
Python
mit
1,919
0.039083
USER_ID_LEN = 64; NR_WAVELEN_POL_COEF = 5; NR_NONLIN_POL_COEF = 8; NR_DEFECTIVE_PIXELS = 30; MAX_NR_PIXELS = 4096; MEAS_DEAD_PIX = 13;# 18 MEAS_PIXELS = 3648; SIZE_PREFIX = 6; NR_TEMP_POL_COEF = 5; MAX_TEMP_SENSORS = 3; ROOT_NAME_LEN ...
C_POL_COEF = 2; TIMEOUT = 1000000; ADR_WRITE = 0x02; ADR_READ = 0x86; ID_VENDOR = 0x1992; ID_PRODUCT = 0x0
667; ERR_CODE = [ 'CODE 0x00 : UNKNOW', 'CODE 0x01 : INVALID PARAMETER', 'CODE 0x02 : INVALID PASSWORD', 'CODE 0x03 : INVALID COMMAND', 'CODE 0x04 : INVALID SIZE', 'CODE 0x05 : MEASUREMENT PENDING', 'CODE 0x06 : INVALID PIXEL RANGE', ...
maxdrib/Trump-Twitter
keywords/parse_companies.py
Python
mit
633
0.004739
import re useless_words = ['Inc', 'Corporation', 'Company', 'Corp', 'Co', 'Energy', '&', 'The', '.com', "Inc.", "Corp.", "Co.", "of", "Ltd.", "Ltd"] with open('companie
s.txt', 'r') as f: companies = f.readlines() new_companies = [] for company in companies: company = company[:-1] company_words = company.split() new_company = [word for word in company_words if word not in useless_words] new_companies.append([word.lower() for word in new_company if len(word)>1]) ...
: f.write(' '.join(company)+'\n')
mpascu/SmartThermostatServer
server.py
Python
mit
6,963
0.012638
from flask import Flask, request, json import RPi.GPIO as GPIO import threading import time import socket import ast import Adafruit_DHT GPIO.setmode(GPIO.BCM) USE_TEST_TEMPERATURES = False app = Flask(__name__) class sensorReader(threading.Thread): def __init__(self): threading.Thread.__init__(self) ...
,file,indent=4) file.close() return "All thermostates deleted successfully" else: return "Not a valid method" def main(): global data file=open('testData.json','r') data = json.load(file) file.close() mySensorReader = sensorReader() mySensorReader.start() myActu...
() myActuatorTrigger.join() except KeyboardInterrupt: mySensorReader.exitapp = True myActuatorTrigger.exitapp = True GPIO.cleanup() if __name__ == "__main__": main()
Canpio/Paddle
python/paddle/fluid/tests/unittests/test_im2sequence_op.py
Python
apache-2.0
5,232
0.004014
# Copyright (c) 2018 PaddlePaddle 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 applicabl...
2 self.img_height = 3 self.img_wi
dth = 3 self.attrs = { 'kernels': [2, 2], 'strides': [1, 1], 'paddings': [0, 0, 0, 0] } if __name__ == '__main__': unittest.main()
naikymen/QB9
uniprot_parser/uniprot_parser_v01.py
Python
gpl-3.0
14,072
0.004417
__author__ = 'nicolas' # coding=utf-8 from os.path import expanduser from ordereddict import OrderedDict from Bio import SwissProt import time import MySQLdb as mdb """ Fuck! from ordereddict import OrderedDict import MySQLdb as mdb dicc = {} dictdebug_empty = OrderedDict() dictdebug = dictdebug_empty dictdebug['hol...
ity"] # Y "Experimental" # Las categorías están en un diccionario con su type de mysql todo volar categories = OrderedDict() categories['AC'] = "varchar(30) NOT NULL" # accesion number categories['FT'] = "varchar(30) NOT NULL" categories['STATUS'] = "varchar(30) NOT NULL" categories['PTM'] = "varchar(100) NOT NULL" ...
implementar el target directamente!!!! =D categories['TO_AA'] = "varchar(10) NOT NULL" categories['SQ'] = "text(45000) NOT NULL" # SQ SEQUENCE XXXX AA; XXXXX MW; XXXXXXXXXXXXXXXX CRC64; categories['LENGTH'] = "varchar(200) NOT NULL" # SQ SEQUENCE XXXX AA; XXXXX MW; XXXXXXXXXXXXXXXX CRC64; categories['ORG'] = "t...
mitsei/dlkit
dlkit/json_/relationship/searches.py
Python
mit
11,651
0.001717
"""JSON implementations of relationship searches.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowe...
raise: NullArgument - ``relationship_search_record_type`` is ``null`` raise: OperationFailed - unable to complete requ
est raise: PermissionDenied - authorization failure occurred raise: Unsupported - ``has_record_type(relationship_search_record_type)`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ raise errors.Unimplemented() cl...
liyu1990/tensorflow
tensorflow/python/platform/default/_app.py
Python
apache-2.0
214
0
"""Generic entry point
script.""" import sys from tensorflow.python.platform import flags def run(): f = flags.FLAGS f._parse_flags() main = sys.modules[
'__main__'].main sys.exit(main(sys.argv))
Elchi3/kuma
kuma/users/signup.py
Python
mpl-2.0
1,747
0.001145
from allauth.socialaccount.forms import SignupForm as BaseSignupForm from django import forms from django.core import validators from django.utils.translation import gettext_lazy as _ USERNAME_REQUIRED = _("Username is requ
ired.") USERNAME_SHORT = _( "Username is too short (%(show_value)s characters). " "It must be at least %(limit_value)s characters." ) USERNAME_LONG = _( "Username is too long (%(show_value)s characters). " "It must be %(limit_value)s characters or less." ) TERMS_REQUIRED = _("You must agree to the term...
form field with our own strings. The heavy lifting happens in the view. """ terms = forms.BooleanField( label=_("I agree"), required=True, error_messages={"required": TERMS_REQUIRED} ) is_github_url_public = forms.BooleanField( label=_("I would like to make my GitHub profile U...
yiwen-luo/LeetCode
Python/search-in-rotated-sorted-array-ii.py
Python
mit
1,138
0.006151
# Time: O(logn) # Space: O(1) # # Follow up for "Search in Rotated Sorted Array": # What if duplicate
s are allowed? # # Would thi
s affect the run-time complexity? How and why? # # Write a function to determine if a given target is in the array. # class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ left, right = 0, len(nums) - 1 ...
ProgramRepair/experiments-infrastructure
awsscripts-defects4j/fullrepairtesting.py
Python
gpl-2.0
8,390
0.019547
from time import sleep import boto.ec2 import sys import subprocess import argparse import os # specify AWS keys auth = {"aws_access_key_id": "<aws key>", "aws_secret_access_key": "<value>"} # create the connection object conn = boto.ec2.connect_to_region("us-east-1", **auth) # status of vms instancefree={} # statu...
print "system status is: ",status[0].system_status.status, status[0].instance_status.status sleep(10) print "instance started = ", i.id, " ip address is ", i.ip_address instancefree[i.ip_address]=True # launch experiment on instance
if i.ip_address != None and i.id!="i-10fa21c8": print "copying launch-repair script to ", i.ip_address do_scp(i.ip_address,"~/", vm_key) print "set permissions of script on ", i.ip_address set_permissions(i.ip_address, vm_key) if not projects['Chart']: # launch chart defects startdefecti...
AlexMog/IRCPokemonBot
commands/classes/Battle.py
Python
mit
1,766
0.003964
#!/usr/bin/env python2 import time import random class Battle: def __init__(self, user1, user2): self.user1 = user1 self.user2 = user2 self.turn = user1 self.notTurn = user2 self.accepted = False self.finished = False self.auto = False self.turnCount...
attacker.gainExp(defender) if attacker.level != old:
message += attacker.name + " passe niveau " + str(attacker.level) + "!" self.finished = True self.turn, self.notTurn = self.notTurn, self.turn self.turnCount += 1 return message def itemUsed(self): self.turn, self.notTurn = self.notTurn, self.turn def nextSte...
RevansChen/online-judge
Codefights/arcade/python-arcade/level-13/90.Url-Similarity/Python/test.py
Python
mit
1,205
0.00249
# Python3 from solution1 import urlSimilarity as f qa = [ ('https://codesignal.com/home/test?param1=42&param3=testing&login=admin', 'https://codesignal.com/home/secret/test?param3=fish&param1=42&password=admin', 19),
('https://codesignal.com/home/test?param1=42&param3=testing&login=admin', 'http://codesignal.org/about?42=param1&tesing=param3&admin=login', 0), ('https://www.google.com/search?q=codesignal', 'http://www.google.com/search?q=codesignal',
13), ('ftp://www.example.com/query?varName=value', 'http://example.com/query?varName=value', 3), ('ftp://www', 'http://anotherexample.com/www?ftp=http', 0), ('https://codesignal.com/home/test?param1=42&param3=testing&login=admin&param4=abc&param5=codesignal', 'https://codesigna...
eevee/cocos2d-mirror
test/test_moveby.py
Python
bsd-3-clause
867
0.026528
# This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) # testinfo = "s, t 3, s, t 6.1, s, q" tags = "MoveBy" import cocos from cocos.director import director from cocos.actions import MoveBy from cocos.sprite imp...
( self.sprite, name='sprite' ) self.sprite.do( MoveBy( (x/2,y/2), 6 ) ) def main(): director.init() test_layer = TestLayer () main_scene = cocos.scene.Scene() main_scene.add(test_layer, name='test_layer') director.run (main_scene) if __name__ == '__main__': mai
n()
ovresko/erpnext
erpnext/accounts/doctype/cash_flow_mapper/cash_flow_mapper.py
Python
gpl-3.0
267
0.003745
# -*- coding: utf-
8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals from frappe.model.document import Document class CashFlowMapper(Doc
ument): pass
deltaburnt/LameBot
api/loader.py
Python
gpl-2.0
1,994
0.037111
import os, importlib, inspect import api.plugin, util.logger_factory class Loader(): def __init__(self, scheduler, bot, sql_conn): filenames = os.listdir(os.path.abspath(__file__+'/../../ext')) self.ext_names = [x[:-3] for x in filenames if x[-3:] == '.py' and x != '__init__.py'] self.scheduler = scheduler ...
_get_class(self, module): for info in inspect.getmembers(module): if issubclass(info[1], api.plugin.Plugin) and info[1] is not api.plugin.Plugin: return info def _install_plugins(self): for plugin in self.plugins: self.sql.execute('SELECT * FROM `__plugins` WHERE name = ?', (plugin['name'],)) if...
values (?)', (plugin['name'],)) def _start_plugins(self): for plugin in self.plugins: plugin['object']._start_()
Gab-km/papylon
setup.py
Python
mit
1,466
0
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages root = os.path.abspath(os.path.dirname(__file__)) try: with open(os.path.join(root, 'README.rst')) as f: README = f.read() with open(os.path.join(root, 'CHANGES.rst')) as f: CHANGES = f.read() except IOError: REA...
+ CHANGES, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", ...
g", "Topic :: Utilities" ], keywords='papylon quickcheck random test', author='Kazuhiro Matsushima', author_email='[email protected]', license='The MIT License (MIT)', url='https://github.com/Gab-km/papylon', packages=find_packages(), include_package_da...
catapult-project/catapult
third_party/gsutil/gslib/tests/test_notification.py
Python
bsd-3-clause
4,981
0.002409
# -*- coding: utf-8 -*- # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
is fixed. return unittest.skip('Functionality has been disabled due to b/132277269') bucket_uri = self.CreateBucket() # Set up an OCN (object change notification) on the newly created bucket. self.RunGsUtil( ['notific
ation', 'watchbucket', NOTIFICATION_URL, suri(bucket_uri)], return_stderr=False) # The OCN listing in the service is eventually consistent. In initial # tests, it almost never was ready immediately after calling WatchBucket # above, so we A) sleep for a few seconds before the first OCN list...
apagac/robottelo
tests/foreman/api/test_discovery.py
Python
gpl-3.0
7,489
0
# -*- encoding: utf-8 -*- """API Tests for foreman discovery feature""" from robottelo.common.decorators import stubbed from robottelo.test import APITestCase class Discovery(APITestCase): """Implements tests for foreman discovery feature""" @stubbed() def test_list_all_discovered_host(self): """...
@Status: Manual """ @stubbed() def test_auto_provision_host(self): """@Test: Auto provision a host by executing discovery rules @Feature: Foreman Discovery @Setup: Provisioning should be configured and a host should be disco
vered @Steps: 1. POST /api/v2/discovered_hosts/:id/auto_provision @Assert: Selected Host should be auto-provisioned successfully @Status: Manual """ @stubbed() def test_auto_provision_all_host(self): """@Test: Auto provision all host by executing discovery r...
google/citest
tests/json_contract/observation_verifier_test.py
Python
apache-2.0
14,132
0.004033
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
s], verifier.dnf_verifiers) expect = _makeObservationVerifyResult( False, bad_results=[pred_results[0]]) global _called_verifiers _called_verifiers = [] got = verifier(context, jc.Observation()) self.assertEqual(expect, got) self.assertEqual(verifiers[:1], _called_verifiers) def te...
vation_verifier_disjunction_success_aborts_early(self): context = ExecutionContext() builder = jc.ObservationVerifierBuilder(title='Test') verifiers = [] results = [] pred_results = [jp.PredicateResult(False, comment='Result %d' % i) for i in range(2)] for ...
pkgw/pwkit
pwkit/environments/ciao/analysis.py
Python
mit
6,635
0.008747
# -*- mode: python; coding: utf-8 -*- # Copyright 2016-2017 Peter Williams <[email protected]> and collaborators # Licensed under the MIT License """Various helpers for X-ray analysis that rely on CIAO tools. """ from __future__ import absolute_import, division, print_function, unicode_literals __all__ = str(''' get_r...
all counts in the source region are due to background events. src_sigma The confidence of source detection in sigma inferred from log_prob_bkg. The proba
bility of backgrounditude is computed as: b^s * exp (-b) / s! where `b` is `nbkg_scaled` and `s` is `nsrc`. The confidence of source detection is computed as: sqrt(2) * erfcinv (prob_bkg) where `erfcinv` is the inverse complementary error function. """ import numpy as np import ...
Etharr/plugin.video.youtube
resources/lib/youtube_plugin/youtube/helper/yt_context_menu.py
Python
gpl-2.0
9,739
0.009241
__author__ = 'bromix' from ... import kodion def append_more_for_video(context_menu, provider, context, video_id, is_logged_in=False, refresh_container=False): _is_logged_in = '0' if is_logged_in: _is_logged_in = '1' _refresh_container = '0' if refresh_container: _refresh_container =...
'action
': 'remove'}))) def append_add_my_subscriptions_filter(context_menu, provider, context, channel_name): context_menu.append((context.localize(provider.LOCAL_MAP['youtube.add.my_subscriptions.filter']), 'RunPlugin(%s)' % context.create_uri(['my_subscriptions', 'filter'], ...
mbauskar/helpdesk-erpnext
erpnext/accounts/report/profit_and_loss_statement/profit_and_loss_statement.py
Python
agpl-3.0
1,352
0.022189
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from erpnext.accounts.report.financial_statements import (get_peri
od_list, get_columns, get_data) def execute(filters=None): period_list = get_period_list(filters.fiscal_year, filters.periodicity) income = get_data(filters.company, "Income", "Credit", period_list, ignore_closing_entries=True) expense = get_data(filters.company, "Expense", "Debit", period_list, ignore_closing_en...
t_loss = get_net_profit_loss(income, expense, period_list, filters.company) data = [] data.extend(income or []) data.extend(expense or []) if net_profit_loss: data.append(net_profit_loss) columns = get_columns(period_list, filters.company) return columns, data def get_net_profit_loss(income, expense, period...
dbrattli/RxPY
tests/test_observable/test_forin.py
Python
apache-2.0
1,468
0.004768
import unittest from rx import Observable from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable from rx.disposables import Disposable, SerialDisposable on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe sub...
next(x * 100 + 30, x * 10 + 3), on_completed(x * 100 + 40)) return Observable.for_in([1, 2, 3], selector) results = scheduler.start(create=create) results.messages.assert_equal(on_next(310, 11), on_next(320, 12), on_next(330, 13), on_next(550, 21), on_next(560, 22), on_next(...
0, 23), on_next(890, 31), on_next(900, 32), on_next(910, 33), on_completed(920)) def test_for_throws(self): ex = 'ex' scheduler = TestScheduler() def create(): def selector(x): raise Exception(ex) return Observable.for_in([1, 2, 3], selector)...
yujikato/DIRAC
src/DIRAC/ResourceStatusSystem/Agent/ElementInspectorAgent.py
Python
gpl-3.0
9,113
0.008449
""" ElementInspectorAgent This agent inspect Resources (or maybe Nodes), and evaluates policies that apply. The following options can be set for the ElementInspectorAgent. .. literalinclude:: ../ConfigTemplate.cfg :start-after: ##BEGIN ElementInspectorAgent :end-before: ##END :dedent: 2 :caption: ElementI...
is already on the queue or not. It may # be there, but in any case, it is not a big problem. lowerElementDict = {'element': self.elementType} for key, value in elemDict.items(): if len(key) >= 2: # VO ! lowerElementDict[key[0].lower() + key[1:]] = value
# We add lowerElementDict to the queue toBeChecked.put(lowerElementDict) self.log.verbose('%s # "%s" # "%s" # %s # %s' % (elemDict['Name'], elemDict['ElementType'], elemDict['StatusType'], ...
kd0aij/matrixpilot_old
Tools/MAVLink/MAVProxy/modules/lib/mp_tile.py
Python
gpl-3.0
18,202
0.028843
#!/usr/bin/env python ''' access satellite map tile database some functions are based on code from mapUtils.py in gmapcatcher Andrew Tridgell May 2012 released under GNU GPL v3 or later ''' import math, cv, sys, os, mp_util, httplib2, threading, time, collections, string, hashlib, errno, tempfile class...
lf.zoom) def refresh_time(self): '''reset the request time''' self.request_time = time.time() def coord(self, offset=(0,0)): '''return lat,lon within a tile given (offsetx,offsety)''' (tilex, tiley) = self.tile (o
ffsetx, offsety) = offset world_tiles = 1<<self.zoom x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1 y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1 lon = x * 180.0 y = math.exp(-y*2*math.pi) e = (y-1)/(y+1) lat = 180.0/math.pi * math.asin(e) return (lat, lon) d...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/interfaces/interface/subinterfaces/subinterface/ipv4/addresses/address/__init__.py
Python
apache-2.0
15,915
0.00132
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
s, register_paths=True, is_keyval=True, namespace="http://openconfig.net/yang/interfaces/ip", defining_module="openconfig-if-ip", yang_type="leafre
f", is_config=True, ) def _get_config(self): """ Getter method for config, mapped from YANG variable /interfaces/interface/subinterfaces/subinterface/ipv4/addresses/address/config (container) YANG Description: Configuration data for each configured IPv4 address on the interface...
supriyagarg/pydatalab
datalab/bigquery/_view.py
Python
apache-2.0
11,620
0.007831
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
uiltins import str from builtins import object import datalab.context from . import _query from . import _tabl
e # Query import is at end to avoid issues with circular dependencies. class View(object): """ An implementation of a BigQuery View. """ # Views in BigQuery are virtual tables, but it is useful to have a mixture of both Table and # Query semantics; our version thus internally has a BaseTable and a Query (for ...
akissa/baruwa2
baruwa/tasks/status.py
Python
gpl-3.0
13,729
0.003933
# -*- coding: utf-8 -*- # Baruwa - Web 2.0 MailScanner front-end. # Copyright (C) 2010-2015 Andrew Colin Kissa <[email protected]> # vim: ai ts=4 sts=4 et sw=4 "status tasks" import os import datetime import psutil from StringIO import StringIO from pylons import config from celery.task import task from sqlalc...
review-queued-msg") def preview_queued_msg(msgid, direction, attachid=None, imgid=None): "Preview a queued message" try: logger = preview_queued_msg.get_logger()
header = search_queue(msgid, int(direction)) convertor = Exim2Mbox(header) mbox = convertor() msgfile = StringIO(mbox) previewer = PreviewMessage(msgfile) if attachid: logger.info("Download attachment: %(attachid)s of " "message: %(id)s", ...
robotarium/robotarium-python-simulator
examples/barrierCertificates.py
Python
mit
2,240
0
import numpy as np from robotarium import Robotarium, transformations, controllers
# Get Robotarium object used to communicate with the robots/simulator. r = Robotarium() # Get the number of available agents from the Robotarium. We don't need a # specific value from this algorithm. n = r.get_available_agents() # Number of iterations. iterations = 20000 # Initialize the Robotarium object with the...
# Initialize velocity vector for agents. Each agent expects a 2x1 velocity # vector containing the linear and angular velocity, respectively. dx = np.zeros((2, n)) xy_bound = np.array([-0.5, 0.5, -0.3, 0.3]) p_theta = (np.arange(1, 2*n, 2)) / (2 * n) * 2 * np.pi p_circ = np.vstack( [np.hstack([xy_bound[1] * np.cos...
rdoh/pixelated-user-agent
service/pixelated/config/services.py
Python
agpl-3.0
2,909
0.002063
from pixelated.adapter.mailstore.searchable_mailstore import SearchableMailStore from pixelated.adapter.services.mail_service import MailService from pixelated.adapter.model.mail import InputMail from pixelated.adapter.services.mail_sender import MailSender from pixelated.adapter.search import SearchEngine from pixelat...
tore(self, leap_session): leap_session.ma
il_store = SearchableMailStore(leap_session.mail_store, self.search_engine) @defer.inlineCallbacks def index_all_mails(self): all_mails = yield self.mail_service.all_mails() self.search_engine.index_mails(all_mails) @defer.inlineCallbacks def setup_search_engine(self, leap_home, search...
diego0020/PySurfer
examples/save_movie.py
Python
bsd-3-clause
1,110
0
""" Create movie from MEG inverse solution ======================================= Data were computed using mne-python (http://martinos.org/mne) """ import os
import numpy as np from surfer import Brain from surfer.io import read_stc print(__doc__) """ create Brain object for visualization """ brain = Brain('fsaverage', 'split', 'inflated', size=(800, 400)) """ read and display MNE dSPM inverse solution """ stc_fname = os.path.join('example_data', 'meg_source_estimate-%...
tc['data'] times = np.arange(data.shape[1]) * stc['tstep'] + stc['tmin'] brain.add_data(data, colormap='hot', vertices=stc['vertices'], smoothing_steps=10, time=times, hemi=hemi, time_label=lambda t: '%s ms' % int(round(t * 1e3))) """ scale colormap """ brain.scale_data_co...
jcchoiling/learningPython
books/learn-python-the-hard-way/ex17_More_Files.py
Python
gpl-3.0
645
0.009302
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Janice Cheng # ex17_inFile.txt # ex17_outFile.txt from sys import argv from os.path import exists script,from_file,to_file = argv print("Copying from {} to {}".format(from_file,to_file)) # we could do these two on one line too, how? in_file = open(from_file) ...
ytes long".format(len(indata))) print("Does the output file exists? %r" %exists(to_file)) print("Ready, hit RETURN to continue, CTRL-C to abort.") i
nput() out_file = open(to_file,'w') out_file.write(indata) print("Alright, all done.") out_file.close() in_file.close()
corcra/UMLS
parse_metamap.py
Python
mit
8,989
0.00534
#!/bin/python # The purpose of this script is to take the *machine-readable* output of UMLS # MetaMap and convert it to something that looks like a sentence of UMLS CUIs, # if possible. Ideally there would be an option in MetaMap to do this, assuming # it is sensible. import re import sys #INTERACTIVE = True INTERA...
lif line == '': # EOF I guess... return phrases elif not EOU_re.match(line): print'ERROR: utterance not followed
by EOU line, followed by:' print line sys.exit('ERROR: missing EOU') line = metamap_output.readline() return phrases def parse_negline(neg_line): """ Parse the THIRD line of the .mmo file, where the negations are stored. Why does it not do this per-phrase? Mystery. W...
lixiangning888/whole_project
modules/signatures_merge_tmp/ek_silverlight.py
Python
lgpl-3.0
1,071
0.009794
# -*- coding: utf-8 -*- try: import re2 as re except ImportError: import re from lib.cuckoo.common.abstracts import Signature class Silverlight_JS(Signature): name = "silverlight_js" description = "执行伪装过的包含一个Silverlight对象的JavaScript,可能被用于漏洞攻击尝试" weight = 3 severity = 3 categories = ["explo...
(["browser"]) # backward compat filter_apinames = set(["JsEval", "COleScript_Compile", "COleScript_ParseScriptText"]) def on_call(self, call, process): if call["api"] == "JsEval": buf = self.g
et_argument(call, "Javascript") else: buf = self.get_argument(call, "Script") if re.search("application\/x\-silverlight.*?\<param name[ \t\n]*=.*?value[ \t\n]*=.*?\<\/object\>.*", buf, re.IGNORECASE|re.DOTALL): return True
anhstudios/swganh
data/scripts/templates/object/tangible/lair/base/shared_poi_all_lair_insecthill_large_fog_gray.py
Python
mit
469
0.046908
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/lair/base/shared_poi_all_lair_insecthill_large_fog_gray
.iff" result.attribute_template_id = -1 result.stfName("lair_n","insecthill") #### BEGIN MODIFICATIONS #### #### END MODIFICATI
ONS #### return result
lu-ci/apex-sigma-plugins
core_functions/stats/ev_mention.py
Python
gpl-3.0
572
0
async def ev_mention(ev, message):
def_stat_data = { 'event': 'mention', 'count': 0 } collection = 'EventStats' database = ev.bot.cfg.db.database
check = ev.db[database][collection].find_one({"event": 'mention'}) if not check: ev.db[database][collection].insert_one(def_stat_data) ev_count = 0 else: ev_count = check['count'] ev_count += 1 update_target = {"event": 'mention'} update_data = {"$set": {'count': ev_count}}...
nawawi/poedit
deps/boost/tools/build/test/lib_source_property.py
Python
mit
917
0
#!/usr/bin/python # Copyright (C) Vladimir Prus 2006. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # Regression test: if a library had no explicit sources, but only <source> # properties, it was built as if it ...
*/a.obj") t.rm("bin") # N
ow try with <conditional>. t.write("jamroot.jam", """ rule test ( properties * ) { return <source>a.cpp ; } lib a : : <conditional>@test ; """) t.run_build_system() t.expect_addition("bin/$toolset/debug*/a.obj") t.cleanup()
slackhq/python-slackclient
slack_sdk/rtm_v2/__init__.py
Python
mit
16,519
0.001574
"""
A Pyth
on module for interacting with Slack's RTM API.""" import inspect import json import logging import time from concurrent.futures.thread import ThreadPoolExecutor from logging import Logger from queue import Queue, Empty from ssl import SSLContext from threading import Lock, Event from typing import Optional, Callable, ...
noironetworks/neutron
neutron/tests/functional/agent/linux/helpers.py
Python
apache-2.0
2,881
0
# Copyright (c) 2014 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
directory] delete_cmd = ['rm', '-r', self.directory] utils.execute(create_cmd, run_as_root=True) self.addCleanup(utils.execute, delete_cmd, run_as_root=True) class SleepyProcessFixture(fixtures.Fixture): """Process fixture to perform time.sleep for a given numbe
r of seconds.""" def __init__(self, timeout=60): super(SleepyProcessFixture, self).__init__() self.timeout = timeout @staticmethod def yawn(seconds): time.sleep(seconds) def _setUp(self): self.process = multiprocessing.Process(target=self.yawn, ...
dbinetti/barberscore-django
project/apps/bhs/config.py
Python
bsd-2-clause
898
0
# Django from django.apps import AppConfig class BhsConfig(AppConfig): name = 'apps.bhs' verbose_name = 'Base' def ready(self): import algoliasearch_django as algoliasearch from .indexes import AwardIndex Award = self.get_model('award') algoliasearch.register(Award, Awar...
Group = self.get_model('group') algoliasearch.register(Group, GroupIndex) from .indexes import PersonIndex
Person = self.get_model('person') algoliasearch.register(Person, PersonIndex) from .indexes import ConventionIndex Convention = self.get_model('convention') algoliasearch.register(Convention, ConventionIndex) return
mweb/python
exercises/circular-buffer/circular_buffer_test.py
Python
mit
3,083
0
import unittest from circular_buffer import ( CircularBuffer, BufferFullException, BufferEmptyException ) class CircularBufferTest(unittest.TestCase): def test_read_empty_buffer(self): buf
= CircularBuffer(1) with self.assertRaises(BufferEmptyException): buf.read() def test_write_and_read_back_one_item(self): buf = CircularBuffer(1) buf.write('1') self.assertEqual('1', buf.read())
with self.assertRaises(BufferEmptyException): buf.read() def test_write_and_read_back_multiple_items(self): buf = CircularBuffer(2) buf.write('1') buf.write('2') self.assertEqual(buf.read(), '1') self.assertEqual(buf.read(), '2') with self.assertRaises(B...
varunarya10/ironic
ironic/api/config.py
Python
apache-2.0
1,302
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
readthedocs.org/en/latest/integrate.html#configuration wsme = { 'debug':
cfg.CONF.debug, }
lich-uct/molpher-lib
src/python/molpher/algorithms/pathfinders.py
Python
gpl-3.0
1,908
0.003145
from molpher.algorithms.functions import find_path from molpher.core import ExplorationTree as ETree class BasicPathfinder: """ :param settings: settings to use in the search :type settings: `Settings` A very basic pathfinder class that can be used to run exploration with any combination of opera...
settings """a settings class (should be a subclass of `Settings`)""" self.tree = ETree.create(source=self.settings.source, target=self.settings.target) """:class:`~molpher.core.ExplorationTree.ExplorationTree` used in the search""" if self.settings.tree_params:
self.tree.params = self.settings.tree_params self.tree.thread_count = self.settings.max_threads self._iteration = operations self.path = None """a list of SMILES strings if a path was found, `None` otherwise""" def __call__(self): """ Executes the searc...
girasquid/cab
cab/models.py
Python
bsd-3-clause
7,952
0.006916
""" Models for code snippets and related data. Most of these models also have custom managers defined which add convenient shortcuts for repetitive or common bits of logic; see ``managers.py`` in this directory. """ import datetime, re from django.db import connection, models from django.template.defaultfilters impo...
k=True, help_text="Optional. Fill this in if this Snippet is based on another.") objects = managers.SnippetsManager() class Meta: ordering = ('-pub_date',) def save(self, *args, **kwargs): if not self.id: self.pub_date = datetime.da...
self.description_html = self.sanitize(self.description) # Use safe_mode in Markdown to prevent arbitrary tags. # self.description_html = markdown(self.description, safe_mode=True) self.highlighted_code = self.highlight() self.tag_list = self.tag_list.lower() # Normali...
shajoezhu/server
tests/unit/test_simulated_stack.py
Python
apache-2.0
6,031
0
""" End-to-end tests for the simulator configuration. Sets up a server with the backend, sends some basic queries to that server and verifies results are as expected. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import ga4gh.frontend...
he correct type and range for callSet in responseData.callSets: self.assertIs(type(callSet.info), dict) self.assertIs(type(callSet.
variantSetIds), list) splits = callSet.id.split(".") variantSetId = '.'.join(splits[:2]) callSetName = splits[-1] self.assertIn(variantSetId, callSet.variantSetIds) self.assertEqual(callSetName, callSet.name) self.assertEqual(callSetName, callSet.s...
samklr/spark-gce
setup.py
Python
apache-2.0
1,354
0.00517
# Copyright 2015 Michael Broxton # # 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 writi...
create a Spark cluster on Google Compute Engine.', author='Michael Broxton', author_email='[email protected]', url='https://github.com/broxtronix/spark-gce', download_url = 'https://github.com/broxtronix/spark-gce/tarball/1.0.6', scripts = ['bin/spark-gce'], package_data =
{'spark_gce': support_files}, install_requires=['boto'] )
hockeybuggy/bigcommerce-api-python
bigcommerce/__init__.py
Python
mit
225
0.004444
# from bigcommer
ce.connection import Connection, OAuthConnection, HttpException, ClientRequestException, \ # EmptyResponseWarning, RedirectionException, ServerException import bigcommerce.resources im
port bigcommerce.api
wagoodman/bridgy
bridgy/inventory/source.py
Python
mit
6,467
0.003402
import re import abc import warnings import collections from functools import partial from bridgy.error import MissingBastionHost with warnings.catch_warnings(): # Thiw warns about using the slow implementation of SequenceMatcher # instead of the python-Levenshtein module, which requires compilation. # I'...
nstances(self, stub=True, filter_sour
ces=tuple()): instances = [] for inventory in self.inventories: if len(filter_sources) == 0 or (len(filter_sources) > 0 and inventory.source in filter_sources): instances.extend(inventory.instances()) return instances def search(self, targets, partial=True, fuz...
bigown/SOpt
Python/Algorithm/Payroll.py
Python
mit
159
0.006289
salario
= 1000 ano = 1996 while ano <= 2020: salario *= 1.015
ano += 1 print("{0:.2f}".format(salario, 2)) #https://pt.stackoverflow.com/q/432854/101
nkremerh/cctools
work_queue/src/bindings/python2/work_queue_futures.py
Python
gpl-2.0
15,412
0.003634
## @package work_queue_futures # Python Work Queue bindings. # # This is a library on top of work_queue which replaces q.wait with the concept # of futures. # # This is experimental. # # - @ref work_queue_futures::WorkQueue # - @ref work_queue::Task import work_queue import multiprocessing import os import subprocess ...
t.set_exception(FutureTaskError(t, err)) self._tasks_to_submit.task_done()
except ThreadQueue.Empty: pass while not self._tasks_before_callbacks.empty(): try: t = self._tasks_before_callbacks.get(False) t.set_exception(FutureTaskError(t, err)) ...
maxis1314/pyutils
web/views/base.py
Python
apache-2.0
1,087
0.014719
# coding: utf-8 from flask import Flask, session, redirect, url_for, request,abort import config config = config.rec() def on_finish(): None def currentUserGet(): if 'user' in session: user = session['user'] return user['username'] else: return None def currentUserSet(username):...
session['user'] = dict({'username':username}) else: session.pop('user',None) def replyerSet(name, email, website): if name: session['replyer'] = dict({'name': name, 'email': email,'website': webs
ite}) else: session.pop('replyer',None) def replyerGet(): if 'replyer' in session: reply = session['replyer'] name = reply['name'] return name else: return None def userAuth(username, password): return username == config.admin_username and password == con...
nlgcoin/guldencoin-official
test/functional/p2p_disconnect_ban.py
Python
mit
5,333
0.003375
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node disconnect and ban behavior""" import time from test_framework.test_framework import GuldenT...
odes[1].setmocktime(old_time) self.nodes[1].setban("192.168.0.1", "add", 1) # ban for 1 seconds self.nodes[1].setban("2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/19", "add", 1000) # ba
n for 1000 seconds listBeforeShutdown = self.nodes[1].listbanned() assert_equal("192.168.0.1/32", listBeforeShutdown[2]['address']) # Move time forward by 3 seconds so the third ban has expired self.nodes[1].setmocktime(old_time + 3) assert_equal(len(self.nodes[1].listbanned()), ...
PNNutkung/Coursing-Field
coursing_field/wsgi.py
Python
apache-2.0
406
0
""" WSGI config for coursing_field project.
It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MO
DULE", "coursing_field.settings") application = get_wsgi_application()
abramhindle/UnnaturalCodeFork
python/testdata/launchpad/lib/lp/app/widgets/tests/test_widget_doctests.py
Python
agpl-3.0
498
0
# Copyright 2009-2011 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). __metaclass__
= type import doctest import unittest from lp.testing.layers import DatabaseFunctionalLayer def test_suite(): suite = unittest.TestSuite() suite.layer = DatabaseFunctionalLayer
suite.addTest(doctest.DocTestSuite('lp.app.widgets.textwidgets')) suite.addTest(doctest.DocTestSuite('lp.app.widgets.date')) return suite
GreatLakesEnergy/sesh-dash-beta
seshdash/api/forecast.py
Python
mit
1,952
0.019467
import forecastio class ForecastAPI: _API_KEY = "8eefab4d187a39b993ca9c875fe
f6159" _LAZY = False _LAT = 0 _LNG = 0 _forecast = () def __init__(self,key,lat,lng,lazy=False)
: self._LAT = lat self._LNG = lng self._API_KEY = key self._LAZY = lazy self._forecast = forecastio.load_forecast(self._API_KEY,self._LAT,self._LNG,lazy=lazy) def get_7day_forecast_detailed(self): return self._forecast.daily().data """ Help getting cloud...
becm/meson
mesonbuild/mconf.py
Python
apache-2.0
12,095
0.002232
# Copyright 2014-2016 The Meson development team # 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 agree...
self.default_values_only = False elif os.path.isfile(os.path.join(self.build_dir, environment.build_filename)): # Make sure that log entries in other parts of meson
don't interfere with the JSON output mlog.disable() self.source_dir = os.path.abspath(os.path.realpath(self.build_dir)) intr = mintro.IntrospectionInterpreter(self.source_dir, '', 'ninja', visitors = [AstIDGenerator()]) intr.analyze() # Re-enable logging just ...
FluidityStokes/fluidity
tests/lagrangian_detectors_3d_1e2/get_RK_traj.py
Python
lgpl-2.1
640
0.029688
from scipy import * from pylab import * num_detectors = 100 x = 0.5+0.25*arange(0,float(num_detectors))/float(num_detectors) y = zeros(num_detectors) + 0.5 t = 0. n_cycles = 1 dt = 0.1/n_cycles tmax = 8 def vel(x,y): return [-(y-0.5),x-0.5] while(t<tmax): t = t +
dt [k1_x,k1_y] = vel(x,y) [k2_x,k2_y] = vel(x+0.5*dt*k1_x,y+0.5*dt*k1_y) [k3_x,k3_y] = vel(x+0.5*dt*k2_x,y+0.5*dt*k2_y) [k4_x,k4_y
] = vel(x+dt*k3_x,y+dt*k3_y) x = x + dt*(k1_x/6.+k2_x/3. + k3_x/3. + k4_x/6.) y = y + dt*(k1_y/6.+k2_y/3. + k3_y/3. + k4_y/6.) plot(x,y,'.') #show() x.tofile('Xvals.txt',sep=' ') y.tofile('Yvals.txt',sep=' ')