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
ChameleonCloud/horizon
horizon/tables/__init__.py
Python
apache-2.0
1,788
0
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this fi
le 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 distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Convenience imports for public API...
tehmaze/natural
setup.py
Python
mit
1,143
0.011374
#!/usr/bin/env python try: from setuptools import setup except: from distutils.core import setup setup(name='natural', version='0.2.0', description='Convert data to their natural (human-readable) format', long_description=''' Example Usage ============= Basic usage:: >>> from natural.file im...
ak your language (with `your support`_):: >>> import locale >>> locale.setlocale(locale.LC_MESSAGES, 'nl_NL') >>> print accessed(__file__) zojuist Bugs/Features ============= You can issue a ticket in GitHub: https://github.com/tehmaze/natural/issues Documentation ============= The project document...
hedocs.org/en/latest/locales.html ''', author='Wijnand Modderman-Lenstra', author_email='maze@pyth0n.org', license='MIT', keywords='natural data date file number size', url='https://github.com/tehmaze/natural', packages=['natural'], package_data={'natural': ['locale/*/LC_MESSAGES/*.mo']}, ...
corpnewt/CorpBot.py
Cogs/Monitor.py
Python
mit
2,040
0.036275
import asyncio import discord from discord.ext import commands def setup(bot): # Disabled for now return # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(Monitor(bot, settings)) # This is the Monitor module. It keeps track of how many messages fail class Monitor(commands.Cog)...
pass # Once we're here - we add our new command # Save the command to a list with t
he message newCommand = { 'Message': ctx.message, 'Success': False } self.commands.append(newCommand) while len(self.commands) > self.commandCount: # Remove the first item in the array until we're at our limit self.commands.pop(0) async def oncommandcompletion(self, command, ctx): for c...
laenderoliveira/exerclivropy
exercicios_resolvidos/capitulo 05/exercicio-05-17.py
Python
mit
695
0.002941
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2014 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Primeira reimpressão - Outubro/2011 # Segunda reimpressão - ...
pressão - Agosto/2013 # Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3 # Site: http://python.nilo.pro.br/ # # Arquivo: exercicios_resolvidos\capitulo 05\exercicio-05-17.py #######################################
####################################### # O programa pára logo após imprimir a quantidade de cédulas de R$50,00
loggerhead/dianping_crawler
dianping_crawler/spiders/base_spider.py
Python
mit
1,618
0
# -*- coding: utf-8 -*- import scrapy import logging from datetime import datetime try: from urlparse import urljoin except ImportError: from urllib.parse import urljoin from .delta_helper import DeltaHelper class BaseSpider(scrapy.Spider): # need overwrite
in subclass logger = logging.getLogger(__name__) def init(self): self.delta = DeltaHelper(self) self.delta.connect_db() def extract_int(self, text): i = -1 for i in range(len(text)):
if text[i].isdigit(): break j = len(text) if i >= 0 else -1 for j in range(i + 1, len(text)): if not text[j].isdigit(): break try: return int(text[i:j]) except ValueError: self.logger.warning('cannot extract integ...
WangYihang/Webshell-Sniper
core/utils/string_utils/random_string.py
Python
gpl-3.0
211
0.009479
#!/usr/bin/env python # encoding: utf-8 fro
m random import choice def random_string(length, random_range): result = "" for i in range(length): result += choic
e(random_range) return result
williechen/DailyApp
18/py201501/sample/sample.py
Python
lgpl-3.0
1,423
0.015544
''' Created on 2015年1月19日 @author: Guan-yu Willie Chen ''' # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.support.select import Select from selenium.webdriver.common.keys import Keys import time #browser = webdriver.Firefox() #browser = webdriver.Ie() browser = ...
_by_xpath("//input[@id='gotoPageNo']").send_keys(Keys.BACKSPACE) browser.find_element_by_xpath("//input[@id='gotoPageNo']").send_keys("3") browser.find_element_by_xpath("//div[
@id='turnpage']/table/tbody/tr/td/input[@value='跳至']").click()
stephenmcd/ratemyflight
ratemyflight/scripts/create_project.py
Python
bsd-2-clause
1,581
0.003163
#!/usr/bin/env python import os import shutil import sys import ratemyflight class ProjectException(Exception): pass def create_project(): """ Copies the contents of the project_template directory to a new directory specified as an argument to the command line. """ # Ensure a directory na...
" "Python module and cannot be used as a project name. Please try " "another name." % project_name) ratemyflight_path = os.path.dirname(os.path.abspath(ratemyflight.__file__)) from_path = os.path.join(ratemyflight_path, "project_template") to_path = o
s.path.join(os.getcwd(), project_name) shutil.copytree(from_path, to_path) shutil.move(os.path.join(to_path, "local_settings.py.template"), os.path.join(to_path, "local_settings.py")) if __name__ == "__main__": try: create_project() except ProjectException, e: print pri...
MostlyOpen/odoo_addons
myo_survey/__openerp__.py
Python
agpl-3.0
1,729
0
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published
by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Th
is program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public Licens...
arthepsy/ssh-audit
test/test_output.py
Python
mit
4,631
0.038221
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import pytest # pylint: disable=attribute-defined-outside-init class TestOutput(object): @pytest.fixture(autouse=True) def init(self, ssh_audit): self.Output = ssh_audit.Output self.OutputBuffer = ssh_audit.OutputBuffer def t...
rs out.colors = True output_spy.begin() out.info('info color') assert output_spy.flush() == [u'info color'] output_spy.begin() out.head('head color') assert output_spy.flush() == [u'\x1b[0;36mhead color\x1b[0m'] output_spy.begin() out.good('good color') assert output_spy.flush() == [u'\x1b[0;32mgood...
[u'\x1b[0;33mwarn color\x1b[0m'] output_spy.begin() out.fail('fail color') assert output_spy.flush() == [u'\x1b[0;31mfail color\x1b[0m'] def test_output_sep(self, output_spy): out = self.Output() output_spy.begin() out.sep() out.sep() out.sep() assert output_spy.flush() == [u'', u'', u''] def t...
TheAlgorithms/Python
graphs/minimum_spanning_tree_kruskal2.py
Python
mit
4,095
0.000488
from __future__ import annotations from typing import Generic, TypeVar T = TypeVar("T") class DisjointSetTreeNode(Generic[T]): # Disjoint Set Node to store the parent and rank def __init__(self, data: T) -> None: self.data = data self.parent = self self.rank = 0 class DisjointSetTr...
om the node to the neighbouring nodes (with weights) self.conne
ctions: dict[T, dict[T, int]] = {} def add_node(self, node: T) -> None: # add a node ONLY if its not present in the graph if node not in self.connections: self.connections[node] = {} def add_edge(self, node1: T, node2: T, weight: int) -> None: # add an edge with the given w...
litecoin-project/litecoin
test/functional/rpc_getchaintips.py
Python
mit
2,291
0.011349
#!/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 the getchaintips RPC. - introduce a network split - work on chains of different lengths - join th...
aintips () assert_equal (len (tips), 1) shortTip = tips[0] assert_equal (shortTip['branchlen'], 0) assert_equal (shortTip['height'], 210) assert_equal (tips[0]['status'], 'active')
tips = self.nodes[3].getchaintips () assert_equal (len (tips), 1) longTip = tips[0] assert_equal (longTip['branchlen'], 0) assert_equal (longTip['height'], 220) assert_equal (tips[0]['status'], 'active') # Join the network halves and check that we now have two tips ...
mozilla/zamboni
mkt/webapps/migrations/0009_remove_webapp_hosted_url.py
Python
bsd-3-clause
356
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependen
cies = [ ('webapps', '0008_remove_china_queue'), ] operations = [ migrations.RemoveField( model_name='webapp', name='hosted_url',
), ]
robertpyke/PyThesis
thesis/tests/gridded_mappable_point.py
Python
mit
6,740
0.003709
import unittest import transaction import os import csv from pyramid import testing from thesis.models import DBSession from sqlalchemy import create_engine from thesis.models import ( Base, GriddedMappablePoint, Layer ) class TestGriddedMappableItem(unittest.TestCase): def setUp(self): s...
result3[0].cluster_size
, 2) self.assertEqual(result3[1].cluster_size, 1) def test_get_cluster_centroids_as_geo_json(self): test_layer_1 = DBSession.query(Layer).filter_by(name='TestLayer1').one() test_layer_2 = DBSession.query(Layer).filter_by(name='TestLayer2').one() q = GriddedMappablePoint.get_points_...
MiniSEC/GRR_clone
lib/aff4.py
Python
apache-2.0
74,406
0.007701
#!/usr/bin/env python """AFF4 interface implementation. This contains an AFF4 data model implementation. """ import __builtin__ import abc import StringIO import time import zlib import logging from grr.lib import access_control from grr.lib import config_lib from grr.lib import data_store from grr.lib import lexe...
replace=True, sync=False) except access_control.UnauthorizedAccess: pass def _ExpandURNComponents(self, urn, unique_urns): """This expands URNs. This met
hod breaks the urn into all the urns from its path components and adds them to the set unique_urns. Args: urn: An RDFURN. unique_urns: A set to add the components of the urn to. """ x = ROOT_URN for component in rdfvalue.RDFURN(urn).Path().split("/"): if component: x = x....
vecnet/simulation-manager
sim_manager/tests/test_submit_group.py
Python
mpl-2.0
7,814
0.003583
# This file is part of the Simulation Manager project for VecNet. # For copyright and lic
ensing information about this project, see the # NOTICE.txt and LICENSE.md files in its top-level directory; they are # available at https://github.com/vecnet/simulation-manager # # This Source Code Form is subject to the terms of the Mozill
a Public # License (MPL), version 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/. """ Tests for the submit_group.py script. """ import random import sys from crc_nd.utils.test_io import WritesOutputFiles from django.test import LiveServerTestCase fro...
flosch/simpleapi
tests/settings.py
Python
mit
18
0.055556
SE
CRET_KEY = "foo
"
OSMNames/OSMNames
osmnames/logger.py
Python
gpl-2.0
788
0.001269
from subprocess import check_call import logging import datetime def setup(name): formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(messag
e)s') logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) timestamp = datetime.datetime.now().strftime('%Y_%m_%d-%H%M') file_handler = logging.FileHandler("data/l...
ogged_check_call(parameters): log.info("run {command}".format(command=' '.join(parameters))) check_call(parameters) log.info("finished")
stscieisenhamer/ginga
ginga/cvw/CvHelp.py
Python
bsd-3-clause
4,985
0.002207
# # CvHelp.
py -- help classes for the Cv drawing # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. import math import n
umpy import cv2 from ginga import colors class Pen(object): def __init__(self, color='black', linewidth=1, alpha=1.0): self.color = color self.linewidth = linewidth self.alpha = alpha class Brush(object): def __init__(self, color='black', fill=False, alpha=1.0): self.color = ...
simone-campagna/petra
petra/net.py
Python
apache-2.0
7,080
0.00339
__all__ = ( 'Net', ) import builtins import collections import itertools from .errors import InternalError, NodeError from .marking import Marking from .net_element import NamedNetElement from .node import Node from .place import Place from .transition import Transition class Net(NamedNetElement): __dict_f...
ory__ = collections.OrderedDict __defaultdict_factory__ = collections.defaultdict __globals__ = {attr_name: getattr(builtins, attr_name) for attr_name in dir(builtins)} def __init__(self, name=None, globals_d=None): super().__init__(name=name, net=self) self._places = self.__dict_factory__...
__.copy() self._globals_d = globals_d ### declare names: def declare(self, name, value): self._globals_d[name] = value @property def globals_d(self): return self._globals_d ### add engine: def add_engine(self, engine): self._engines.append(engine) def engi...
dichen001/Go4Jobs
JackChen/minimax/375. Guess Number Higher or Lower II.py
Python
gpl-3.0
1,292
0.004651
""" We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game w...
higher. You pay $7. Third round: You guess 9, I tell you that it's lower. You pay $9. Game over. 8 is the number I picked. You end up paying $5 + $7 + $9 = $21. Given a particular n ≥ 1, find out how much money you need to have to guarantee a win. """ class Solution(object): def getMoneyAmount(self, n): ...
self.dp = [[0] * (n + 1) for _ in range(n + 1)] return self.helper(1, n) def helper(self, s, e): if s >= e: return 0 if self.dp[s][e] != 0: return self.dp[s][e] res = float('inf') for i in range(s, e + 1): res = min(res, i + max(s...
ScreamingUdder/mantid
scripts/Diffraction/isis_powder/pearl.py
Python
gpl-3.0
9,681
0.005991
from __future__ import (absolute_import, division, print_function) import mantid.simpleapi as mantid from isis_powder.routines import common, instrument_settings from isis_powder.abstract_inst import AbstractInst from isis_powder.pearl_routines import pearl_advanced_config, pearl_algs, pearl_calibration_algs, pearl_o...
ile_path, calibration_dir=self._inst_settings.calibration_dir,
rebin_1_params=self._inst_settings.cal_rebin_1, rebin_2_params=self._inst_settings.cal_rebin_2, cross_correlate_params=cross_correlate_params, ...
wmayner/pyphi
pyphi/compute/__init__.py
Python
gpl-3.0
1,545
0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # compute/__init__.py """ See |compute.subsystem|, |compute.network|, |compute.distance|, and |compute.parallel| for documentation. Attributes: all_complexes: Alias for :func:`pyphi.compute.network.all_complexes`. ces: Alias for :func:`pyphi.compute.subsystem.ces...
phi.compute.network.complexes`. concept_distance: Alias for :func:`pyphi.compute.distance.concept_distance`. conceptual_info: Alias for :
func:`pyphi.compute.subsystem.conceptual_info`. condensed: Alias for :func:`pyphi.compute.network.condensed`. evaluate_cut: Alias for :func:`pyphi.compute.subsystem.evaluate_cut`. major_complex: Alias for :func:`pyphi.compute.network.major_complex`. phi: Alias for :func:`pyphi.compute.subsystem.phi`. ...
mgedmin/zest.releaser
zest/releaser/lasttagdiff.py
Python
gpl-2.0
903
0
# GPL, (c) Reinout van Rees # # Script to show the diff with the last relevant tag. import logging import sys import zest.releaser.choose from zest.releaser.utils import system from zest.releaser import utils logger = logging.getLogger(__name__) def main(): logging.basicConfig(level=utils.loglevel(), ...
differences from the last commit against tag %s", full_tag) diff_
command = vcs.cmd_diff_last_commit_against_tag(found) print diff_command print system(diff_command)
meisamhe/GPLshared
Programming/MPI — AMath 483 583, Spring 2013 1.0 documentation_files/matrix_rotation_constant.py
Python
gpl-3.0
1,490
0
import copy import sys import random import itertools def rotate_matrix(A): for i in range(len(A) // 2): for j in range(i, len(A) - i - 1): temp = A[i][j] A[i][j] = A[-1 - j][i] A[-1 - j][i] = A[-1 - i][-1 - j] A[-1 - i][-1 - j] = A[j][-1 - i] A[...
e(len(A)): for j in range(len(
A)): assert rA.read_entry(i, j) == B[i][j] def main(): if len(sys.argv) == 2: n = int(sys.argv[1]) k = itertools.count(1) A = [] for _ in range(1 << n): A.append([next(k) for _ in range(1 << n)]) B = copy.deepcopy(A) rotate_matrix(B) ...
our-city-app/oca-backend
src/solutions/common/to/pharmacy/order.py
Python
apache-2.0
1,626
0
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a co
py 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 distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specifi...
permissions and # limitations under the License. # # @@license_version:1.7@@ from mcfw.properties import unicode_property, long_property class SolutionPharmacyOrderTO(object): key = unicode_property('1') description = unicode_property('2') status = long_property('3') sender_name = unicode_property('4...
ph1l/halo_radio
HaloRadio/PlaylistListMaker.py
Python
gpl-2.0
1,038
0.012524
# # # Copyright (C) 2004 Philip J Freeman # # This file is part of halo_radio # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
PARTICULAR PURP
OSE. See the # GNU Affero General 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 <https://www.gnu.org/licenses/>. import HaloRadio.TopListMaker as TopListMaker class PlaylistListMaker(TopListMaker.TopListM...
rcbops/python-novaclient-buildpackage
tests/v1_1/utils.py
Python
apache-2.0
814
0
from nose.tools import ok_
def fail(msg): raise AssertionError(msg) def assert_in(thing, seq, msg=None): msg = msg or "'%s' not found in %s" % (thing, seq) ok_(thing in seq, msg) def assert_not_in(thing, seq, msg=Non
e): msg = msg or "unexpected '%s' found in %s" % (thing, seq) ok_(thing not in seq, msg) def assert_has_keys(dict, required=[], optional=[]): keys = dict.keys() for k in required: assert_in(k, keys, "required key %s missing from %s" % (k, dict)) allowed_keys = set(required) | set(optional)...
johntellsall/shotglass
shotglass/app/tests/test_render.py
Python
mit
881
0
import pytest # TODO: re-enable # from app import render # from app.models import SourceLine class AttrDict(dict): __getattr
__ = dict.__getitem__ # http://stackoverflow.com/a/11924754/143880 def is_subset(d1, obj): d2 = var
s(obj) return set(d1.items()).issubset(set(d2.items())) @pytest.mark.skip("OLD: uses SourceLine") @pytest.mark.django_db def test_make_skeleton(): symbols = [ SourceLine(path="a.py", length=3), SourceLine(path="a.py", length=3), SourceLine(path="b.py", length=3), ] for sym in s...
bringsvor/bc_korps
utils/parse_members.py
Python
agpl-3.0
2,410
0.048608
#!/usr/bin/env python #-.- encoding: utf-8 -.- import csv,re #medlemsfil = 'medlemmer_20032014.csv' #medlemsfil = 'Medlemsliste 08.03.2015.csv' medlemsfil = 'Medlemsliste 03.09.2015.csv' def parse(): f = open(medlemsfil) r = csv.reader(f) index = 0 headings = None members = None category = None for row in r: ...
.split('/') print "TLF", d['Telefon'], tlf, d['Telefon'].split('/') oerp['mobile'] = tlf[0] if len(tlf)>1: oerp['mobile2'] = tlf[1] print "D_CATEG", d['category_id'] oerp['c
ategory_id'] = d['category_id'] # Startår joined = d['Startår'] print "STARTÅR", joined oerp['join_date'] = '01-01-%s' % joined # Kl oerp['birthdate'] = klasse_til_dato[d['Kl']] oerp['instrument'] = d['Instrument'] #print "OERP", oerp yield oerp if __name__=='__main__': headings, members = parse...
justinjfu/doodad
testing/remote/test_gcp.py
Python
gpl-3.0
1,085
0.003687
"""
Instructions: 1) Set up testing/config.py (copy from config.py.example and fill in the fields) 2) Run this script 3) Look inside your GCP_BUCKET under test_doodad and you should see
results in secret.txt """ import os import doodad from doodad.utils import TESTING_DIR from testing.config import GCP_PROJECT, GCP_BUCKET, GCP_IMAGE def run(): gcp_mount = doodad.MountGCP( gcp_path='secret_output', mount_point='/output' ) local_mount = doodad.MountLocal( local_dir=...
vechnoe/products
src/urls.py
Python
mit
476
0
from django.c
onf.urls import include, url from django.contrib import admin from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('products.urls', namespace='products')), url(r'^', include('users.urls',...
, ]
stvstnfrd/edx-platform
cms/djangoapps/contentstore/views/tests/test_certificates.py
Python
agpl-3.0
31,931
0.001848
#-*- coding: utf-8 -*- """ Certificates Tests. """ import itertools import json import ddt import mock import six from django.conf import settings from django.test.utils import override_settings from opaque_keys.edx.keys import AssetKey from six.moves import range from cms.djangoapps.contentstore.tests.utils impor...
e this method to clean up response when creating new certificate. """ certificate_id = content.pop("id") return certificate_id def test_required_fields_are_absent(self): """ Test required fields are absent. """ bad_jsons = [ # must have name of th...
CHEMA_VERSION }, # an empty json {}, ] for bad_json in bad_jsons: response = self.client.post( self._url(), data=json.dumps(bad_json), content_type="application/json", HTTP_ACCEPT="applicati...
nikitos/npui
netprofile_access/netprofile_access/models.py
Python
agpl-3.0
23,665
0.046146
#!/usr/bin/env python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*- # # NetProfile: Access module - Models # © Copyright 2013-2015 Alex 'Unik' Unigovsky # # This file is part of NetProfile. # NetProfile is free software: you can redistribute it and/or # modify it under the terms of the GNU Affero General P...
ld' } ) stash_id = Column( 'stashid', UInt32(), ForeignKey('stashes_def.stashid', name='entities_access_fk_stashid', onupdate='CASCADE'), Comment('Used stash ID'), nullable=False, inf
o={ 'header_string' : _('Stash'), 'column_flex' : 3 } ) rate_id = Column( 'rateid', UInt32(), ForeignKey('rates_def.rateid', name='entities_access_fk_rateid', onupdate='CASCADE'), Comment('Used rate ID'), nullable=False, info={ 'header_string' : _('Rate'), 'column_flex' : 2 } ) alias...
hackerspace/memberportal
payments/common.py
Python
gpl-2.0
1,647
0.004857
from datetime import date class YearInfo(object): def __init__(self, year, months_ok, months_na): self.year = year self.months = set(range(1, 13)) self.months_ok = set(months_ok) self.months_na = set(months_na) self.months_er = self.months - (self.months_ok | self.month
s_na) today = date.today() if self.year == today.year: self.months_er -= set(range(today.month, 13)) def __unicode__(self): return u'%s' % self.year def missing(self): return len(self.months_er) != 0 def payments
_by_month(payments_list): monthly_data = set() if not payments_list: return [] for payment in payments_list: for m in payment.formonths(): monthly_data.add(m) since_year = payment.user.date_joined.year since_month = payment.user.date_joined.month years = set(range(s...
viktorki/Discrete-Distributions
manage.py
Python
gpl-3.0
264
0.003788
#!/usr/bin/env python import os import sys if __name__ == "__m
ain__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DiscreteDistributions.settings")
from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
uclmr/inferbeddings
inferbeddings/models/base.py
Python
mit
7,187
0.005148
# -*- coding: utf-8 -*- import abc import tensorflow as tf from inferbeddi
ngs.models import embeddings import sys class BaseModel(metaclass=abc.ABCMeta): def __init__(self, entity_embeddings=None, predicate_embeddings=
None, similarity_function=None, reuse_variables=False, *args, **kwargs): """ Abstract class inherited by all models. :param entity_embeddings: (batch_size, 2, entity_embedding_size) Tensor. :param predicate_embeddings: (batch_size, walk_size, predicate_embedding_size) T...
pythonpro-dev/pp-testing
tests/unit/test_sample.py
Python
bsd-3-clause
415
0
# $HeadUR
L$ import sys def test_import(): """ Test to make sure the project imports OK. """ import pp.testing def test_app(): """ Test the command-line app runs OK. """ from pp.testing.sc
ripts import app sys.argv = [] app.main() if __name__ == '__main__': # Run this tet file through py.test if executed on the cmdline import pytest pytest.main(args=[sys.argv[0]])
ryfeus/lambda-packs
pytorch/source/torch/optim/sparse_adam.py
Python
mit
4,595
0.001741
import math import torch from .optimizer import Optimizer class SparseAdam(Optimizer): r"""Implements lazy version of Adam algorithm suitable for sparse tensors. In this variant, only moments that show up in the gradient get updated, and only those portions of the gradient get applied to the parameters. ...
# old <- b * old + (1 - b) * new # <==> old += (1 - b) * (new - old) old_exp_avg_values = exp_avg.sparse_mask(grad)._values() exp_avg_u
pdate_values = grad_values.sub(old_exp_avg_values).mul_(1 - beta1) exp_avg.add_(make_sparse(exp_avg_update_values)) old_exp_avg_sq_values = exp_avg_sq.sparse_mask(grad)._values() exp_avg_sq_update_values = grad_values.pow(2).sub_(old_exp_avg_sq_values).mul_(1 - beta2) ...
springer-math/Mathematics-of-Epidemics-on-Networks
docs/examples/fig4p11.py
Python
mit
2,565
0.015595
import EoN import networkx as nx import matplotlib.pyplot as plt import scipy import random print(r"Warning, book says \tau=2\gamma/<K>, but it's really 1.5\gamma/<K>") print(r"Warning - for the power law graph the text says k_{max}=110, but I believe it is 118.") N=1000 gamma = 1. iterations = 200 rho = 0.05 tmax = ...
gamma, symbol) #bimodal symbol='x' graph_function = lambda: nx.configuration_model([5,35]*int(N/2+0.01)) simulate_process(graph_function, i
terations, tmax, tcount, rho, kave, tau, gamma, symbol) #erdos-renyi symbol = 's' graph_function = lambda : nx.fast_gnp_random_graph(N, kave/(N-1.)) simulate_process(graph_function, iterations, tmax, tcount, rho, kave, tau, gamma, symbol) symbol = 'd' pl_kmax = 118 pl_kmin = 7 pl_alpha = 2. Pk={} for k in range(pl_km...
UdK-VPT/Open_eQuarter
mole/stat_corr/window_wall_ratio_east_SDH_by_building_age_lookup.py
Python
gpl-2.0
1,995
0.175527
# coding: utf8 # OeQ autogenerated lookup function for 'Window/Wall Ratio East in correlation to year of construction, based on the source data of the survey for the "German Building Typology developed by the
"Institut für Wohnen und Umwelt", Darmstadt/Germany, 2011-2013' import math import numpy as np import oeqLookuptable as oeq def get(*xin): l_lookup = oeq.lookuptable( [ 1849,0, 1850,0, 1851,0, 1852,0, 1853,0, 1854,0, 1855,0, 1856,0, 1857,0, 1858,0, 1859,0, 1860,0, 1861,0, 1862,0, 1863,0, 1864,0, 1865,0, 1866,0,...
1884,0, 1885,0, 1886,0, 1887,0, 1888,0, 1889,0, 1890,0, 1891,0, 1892,0, 1893,0, 1894,0, 1895,0, 1896,0, 1897,0, 1898,0, 1899,0, 1900,0, 1901,0, 1902,0, 1903,0, 1904,0, 1905,0, 1906,0, 1907,0, 1908,0, 1909,0, 1910,0, 1911,0, 1912,0, 1913,0, 1914,0, 1915,0, 1916,0, 1917,0, 1918,0, 1919,0, 1920,0, 1921,0, 1922,0, 1923,0, ...
google-research/google-research
f_net/models_test.py
Python
apache-2.0
13,843
0.00354
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
bridAttentionLayout.BOTTOM, num_attention_layers=0, expected_attention_layers=[]), dict(
attention_layout=HybridAttentionLayout.MIDDLE, num_attention_layers=2, expected_attention_layers=[1, 2]), dict( attention_layout=HybridAttentionLayout.MIXED, num_attention_layers=2, expected_attention_layers=[0, 2]), dict( attention_layout=HybridA...
Laisky/laisky-blog
gargantua/apis/__init__.py
Python
apache-2.0
130
0
# import ipdb; ipdb.set_trace() from .posts
import PostAPIHandler, PostCategoriesAPI
Handler from .tweets import TweetsAPIHandler
kubeflow/kfp-tekton-backend
sdk/python/kfp/notebook/__init__.py
Python
apache-2.0
598
0
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0
(the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, #...
cense. from . import _magic
nikhilponnuru/codeCrumbs
code/create_file.py
Python
mit
4,006
0.01972
#!/usr/bin/env python #to create a file in codesnippets folder import pyperclip import os import re import subprocess def get_extension(file_name): if file_name.find('.')!=-1: ext = file_name.split('.') return (ext[1]) else: return 'txt' def cut(str, len1): return str[len1 + ...
sage): subprocess.Popen(['notify-send', message]) return while True: str = pyperclip.paste() if (str==" "): continue str_low = str.lower() str_lower=str_low.split("\n") #this is to ensure that only create a file if "add to code snippets" line is first line since if this line is pres...
a given text so "add to code snippets " must be definitely first line if(str_lower[0]=="stop -safe"): sendmessage("Stopped the background process for code snippet management...byebye") os.exit() if (str_lower[0].find("add") != -1 and str_lower[0].find("code")!=-1 and str_lower[0]...
Nimmard/james-olson.com
main/migrations/0001_initial.py
Python
gpl-2.0
1,003
0.018943
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.Ch...
max_length=255),), ('email', models.EmailField(max_length=75),), ('message', models.TextField(),), ('date', models.DateField(auto_now=True),)], bases = (models.Model,), options = {}, name = 'Contact', ), migrations.CreateModel(
fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('date', models.DateTimeField(),), ('title', models.CharField(max_length=255),), ('code', models.CharField(max_length=255),), ('summary', models.TextField(),)], bases = (models.Model,), ...
msabramo/django-netezza
netezza/pyodbc/introspection.py
Python
bsd-3-clause
4,001
0.002999
from django.db.backends import BaseDatabaseIntrospection import pyodbc as Database import types import datetime import decimal class DatabaseIntrospection(BaseDatabaseIntrospection): # Map type codes to Django Field types. data_types_reverse = { types.StringType: 'TextField', type...
tetime: 'DateTimeField', datetime.date: 'DateField', datetime.time: 'TimeField', decimal.Decimal: 'DecimalField', } de
f get_table_list(self, cursor): """ Returns a list of table names in the current database. """ # db = cursor.db.alias # if db == 'default': db = 'public' cursor.execute(""" SELECT distinct objname FROM _v_obj_relation WHERE objcla...
jogral/tigris-python-sdk
tigrissdk/auth/permission.py
Python
apache-2.0
3,756
0
# coding: utf-8 from __future__ import unicode_literals, absolute_import from ..exception import TigrisException import urllib.parse class Permission(object): """ Tigris Permission object """ BASE_ENDPOINT = 'permissions' def __init__(self, permission_obj, session): """ :param permissi...
populate(self, permission_obj): try: self._id = permission_obj['id'] except KeyError: self._id = False try: self.name = permission_obj['name'] except KeyError: self.name = None try: self.description = permission_obj['des...
except KeyError: self.description = None try: self.is_active = permission_obj['is_active'] except KeyError: self.is_active = None def activate(self): """ Changes `is_active` to `True` """ if not self._id: raise TigrisEx...
ionrock/json_url_rewriter
json_url_rewriter/middleware.py
Python
bsd-3-clause
2,398
0.000417
import json from json_url_rewriter import config from json_url_rewriter.rewrite import URLRewriter class HeaderToPathPrefixRewriter(object): """ A rewriter to take the value of a header and prefix any path. """ def __init__(self, keys, base, header_name): self.keys = keys self.base =...
return 'HTTP_' + self.header_name.upper().replace('-', '_') def __call__(self, doc, environ): key = self.header() if not key in environ: return doc prefix = environ[key] def replacement(match): base, path = match.groups() return '%s/%s%...
ter(self.keys, self.regex, replacement) return rewriter(doc) class RewriteMiddleware(object): def __init__(self, app, rewriter): self.app = app self.rewriter = rewriter @staticmethod def content_type(headers): return dict([(k.lower(), v) for k, v in headers]).get('content...
Sergiy-DBX/pynet_test-
Files/Ex_1.py
Python
unlicense
661
0
#!/usr/bin/env python from __future__ import print_function with open("../File_example.txt")
as file_in: for line in file_in: print(line.strip()) print('#' * 40) file_to_write = open("../File_example.txt", "wt") print(file_to_write) file_to_write.write
("Line one\nLine two\nLine three\n") file_to_write.flush() file_to_write.close() print('#' * 40) append_file = open("../File_example.txt", "at") append_file.write("Line Three and Half\n") append_file.flush() append_file.seek(0) append_file.write("Line addition\n") append_file.flush() append_file.close() print(appen...
powervm/pypowervm
pypowervm/tests/utils/test_uuid.py
Python
apache-2.0
2,049
0
# Copyright 2015, 2018 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 require...
3D4e5F') self.asse
rtEqual((True, uuid), uuid_utils.id_or_uuid(uuid)) # This one has too many digits self.assertRaises(ValueError, uuid_utils.id_or_uuid, conv('12345678-abcd-ABCD-0000-0a1B2c3D4e5F0'))
baike21/blog
blogadmin/migrations/0007_auto_20170828_2317.py
Python
gpl-3.0
3,940
0.005076
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-28 15:17 from __future__ import unicode_literals import DjangoUeditor.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogadmin', '0006_auto_20170827_1142'), ] operations = ...
rue, max_length=32, null=True, verbose_name='\u6807\u7b7e')), ('pub_time', models.DateTimeField(auto_now_add=True, verbose_name='\u53d1\u5e03\u65f6\u95f4')), ('update_time', models.DateTimeField(auto_now=True, null=True, verbose_name='\u66f4\u65b0\u65f6\u95f4')), ('conten...
'verbose_name': '\u6742\u6587', 'verbose_name_plural': '\u6742\u6587', }, ), migrations.CreateModel( name='FilmReview', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name...
stefanklug/mapnik
scons/scons-local-2.3.6/SCons/Tool/pdf.py
Python
lgpl-2.1
3,010
0.007641
"""SCons.Tool.pdf Common PDF Builder definition for various other Tool modules that use it. Add an explicit action to run epstopdf to convert .eps files to .pdf """ # # Copyright (c) 2001 - 2015 The SCons Foundation
# # Permission is hereby granted, free of charge, to any person obtaining # a copy o
f 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, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to d...
analysiscenter/dataset
batchflow/tests/config_test.py
Python
apache-2.0
2,864
0.000349
# pylint: disable=redefined-outer-name, missing-docstring import sys import pytest sys.path.append('..') from batchflow import Config @pytest.fixture def config(): _config = dict(key1='val1', key2=dict()) _config['key2']['subkey1'] = 'val21' return Config(_config) class TestConfig: def test_getitem...
f test_get_nested_key(self, config): assert config.get('key2/subkey1') == config.config['key2']['subkey1'] def test_get_missing_key(self, config): assert config.get('missing key') is None def test_get_missing_key_
with_default(self, config): assert config.get('missing key', default=1) == 1 def test_get_nested_missing_key_with_default(self, config): assert config.get('key2/missing key', default=1) == 1 def test_pop_key(self, config): val = config.config.get('key1') assert config.pop('key1...
flaub/plaidml
plaidml/context.py
Python
agpl-3.0
865
0
# Copyright Vertex.AI import ctypes import json class Context(object): def __init__(self, lib): self._as_parameter_ = lib.vai_alloc_ctx() if not self._as_parameter_: raise MemoryError('PlaidML operation context') self._free = lib.vai_free_ctx self._cancel = lib.vai_ca...
config = { '@type': 'type.vertex.ai/vertexai.eventing.file.proto.EventLog', 'filename': filename } self._set_eventlog(self, json.dumps(config)) def shutdown(self): if hasattr(self, '_free')
and self._as_parameter_: self._free(self) self._as_parameter_ = None
cwacek/python-jsonschema-objects
test/test_regression_156.py
Python
mit
1,032
0
import pytest # noqa import python_jsonschema_objects as pjo def test_regression_156(markdown_examples): builder = pjo.ObjectBuilder( markdown_examples["MultipleObjects"], resolved=markdown_examples ) classes = builder.build_classes(named_only=True) er = classes.ErrorResponse(message="Danger...
) vgr = classes.VersionGetResponse(local=False, version="1.2.3") # round-trip serialize-deserialize into named classes classes.ErrorResponse.from_json(er.serialize()) classes.VersionGetResponse.from_json(vgr.serialize()) # round-trip serialize-deserialize into class defined with `oneOf` classe...
bjects.from_json(er.serialize()) classes.Multipleobjects.from_json(vgr.serialize()) def test_toplevel_oneof_gets_a_name(markdown_examples): builder = pjo.ObjectBuilder( markdown_examples["MultipleObjects"], resolved=markdown_examples ) classes = builder.build_classes(named_only=True) asser...
kreatorkodi/repository.torrentbr
plugin.video.yatp/site-packages/hachoir_parser/misc/gnome_keyring.py
Python
gpl-2.0
6,255
0.003357
""" Gnome keyring parser. Sources: - Gnome Keyring source code, function generate_file() in keyrings/gkr-keyring.c, Author: Victor Stinner Creation date: 2008-04-09 """ from hachoir_core.tools import paddingSize from hachoir_parser import Parser from hachoir_core.field import (FieldSet, Bit, NullBits, NullBy...
scription(self): return "Item #%s: %s attributes" % (self["id"].value, self["attr_count"].value) class Items(FieldSet): def createFields(self): yield UInt32(self, "count") for index in xrange(self["count"].value): yield Item(self, "item[]") class EncryptedItem(
FieldSet): def createFields(self): yield KeyringString(self, "display_name") yield KeyringString(self, "secret") yield TimestampUnix64(self, "mtime") yield TimestampUnix64(self, "ctime") yield KeyringString(self, "reserved[]") for index in xrange(4): yield...
beebyte/irisett
irisett/contact.py
Python
mit
17,565
0.003985
"""Basic contact management functions. Contacts are linked to monitors and are used to determine where to send alerts for monitors. Contacts are basic name/email/phone sets. Contacts are only stored in the database and not in memory, they are loaded from the database each time an alert is sent. """ from typing impo...
_id,)) async def get_all_contacts_for_active_monitor(dbcon: DBConnection, monitor_id: int) -> Iterable[object_models.Contact]: """Get a list of all contacts for an active monitor. This includes directly attached contacts, contacts from contact groups, monitor groups etc. """ contacts = set() ...
_contacts(dbcon, monitor_id)) contacts.update(await _active_monitor_contact_groups(dbcon, monitor_id)) contacts.update(await _active_monitor_monitor_group_contacts(dbcon, monitor_id)) contacts.update(await _active_monitor_monitor_group_contact_groups(dbcon, monitor_id)) return list(contacts) async def...
nicolashainaux/mathmaker
mathmaker/lib/old_style_sheet/AlgebraMiniTest0.py
Python
gpl-3.0
2,680
0
# -*- coding: utf-8 -*- # Mathmaker creates automatically maths exercises sheets # with their answers # Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com> # This file is part of Mathmaker. # Mathmaker is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License...
-------- lines_nb col_widths exercises SHEET_LAYOUT = {'exc': [None, 'all'], 'ans': [None, 'all'] } # ------------------------------------------------------------------------------ # -------------------------------------------------------------------------- # --------------------...
_Structure): # -------------------------------------------------------------------------- ## # @brief Constructor # @param **options Any options # @return One instance of sheet.Model def __init__(self, **options): self.derived = True S_Structure.__init__(self, FONT_SIZE_OF...
LYZhelloworld/Courses
50.020/08/ecb.py
Python
mit
1,521
0.011834
# ECB wrapper skeleton file for 50.020 Security # Oka, SUTD, 2014 from present import * import argparse nokeybits=80 blocksize=64 def ecb(infile,outfile,keyfile,mode): key = 0x0 with open(keyfile, 'rb') as fkey:
for i in range(nokeybits / 8): key |= ord(fkey.read(1)) << i * 8 with open(infile, 'rb') as fin: with open(outfile, 'wb') as fout: while True: buf = fin.read(blocksize / 8) chunk = 0x0 if buf == '': break ...
chunk |= ord(buf[i]) << i * 8 if mode == 'c': result = present(chunk, key) else: result = present_inv(chunk, key) for i in range(blocksize / 8): fout.write(chr((result >> i * 8) & 0xff)) if __...
EricMuller/mynotes-backend
requirements/twisted/Twisted-17.1.0/src/twisted/mail/test/test_mail.py
Python
mit
84,944
0.00292
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for large portions of L{twisted.mail}. """ import os import errno import shutil import pickle import StringIO import email.message import email.parser import tempfile import signal import time from hashlib import md5 from zope.interfac...
the
class name of a L{mail.mail.DomainWithDefaultDict} instance and the string-formatted underlying domain dictionary both appear in the string produced by the given string-returning function. @type stringifier: one-argument callable @param stringifier: either C{str} or C{repr}, to be used...
healthchecks/healthchecks
hc/accounts/management/commands/pruneusers.py
Python
bsd-3-clause
1,501
0
from datetime import timedelta from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.db.models import Count, F from django.utils.timezone import now from hc.accounts.models import Profile class Command(BaseCommand): he
lp = """Prune old, inactive user accounts. Conditions for removing an user acc
ount: - created 1 month ago and never logged in. Does not belong to any team. Use case: visitor types in their email at the website but never follows through with login. """ def handle(self, *args, **options): month_ago = now() - timedelta(days=30) # Old ...
timlev/Proxy-Hours
main.py
Python
mit
1,572
0.022901
#!/usr/bin/python import Proxy_Hours, proxyhours_gather_all_data try: from PyQt4 import QtCore, QtGui qtplatform = "PyQt4" except: from PySide import QtCore, QtGui qtplatform = "PySide" import os def which(pgm): path=os.getenv('PATH') for p in path.split(os.path.pathsep): p=os.path.jo...
== "PySide": name = name[0] print name ui.FilelineEdit.setText(name) nametxt = str(ui.FilelineEdit.text()) nametxt = os.path.abspath(nametxt) print "Nametxt:", namet
xt write_out_0, write_out_1, write_out_2, write_out_3 = proxyhours_gather_all_data.proxy_hours(nametxt) ui.log_lineEdit.setText(write_out_1) ui.all_data_lineEdit.setText(write_out_2) ui.time_lineEdit.setText(write_out_3) ui.tableWidget.setRowCount(len(write_out_0)) for pos, row in enumerate(write_out_0): add_ro...
riga/luigi
test/config_toml_test.py
Python
apache-2.0
3,012
0
# -*- coding: utf-8 -*- # # Copyright 2018 Vote inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
= get_config('toml')
self.assertTrue(config.has_option('hdfs', 'client')) self.assertFalse(config.has_option('hdfs', 'nope')) self.assertFalse(config.has_option('nope', 'client')) class HelpersTest(LuigiTestCase): def test_add_without_install(self): enabled = LuigiTomlParser.enabled LuigiTomlParser.e...
Dangetsu/vnr
Frameworks/Sakura/py/libs/qtbrowser/qtplayer.py
Python
gpl-3.0
2,795
0.025045
# coding: utf8 # qtplayer.py # 10/1/2014 jichi __all__ = 'HiddenPlayer', from PySide.QtCore import QUrl from sakurakit.skdebug import dprint class _HiddenPlayer: def __init__(self, parent): self.parent = parent # QWidget self._webView = None # QWebView @property def webView(self): if not self._web...
.setAttribute(QWebSettings.AutoLoadImages, False) # do NOT load images #ws.setAttribute(QWebSettings.JavascriptCanOpenWindows, True) #ws.setAttribute(QWebSettings.JavascriptCanAccessClipboard, True) #ws.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) #w
s.setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) #ws.setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True) #ws.setAttribute(QWebSettings.LocalStorageEnabled, True) #ws.setAttribute(QWebSettings.LocalContentCanAccessRemoteUrls, True) #ws.setAttribute(QWebSettings.ZoomTextOnly, Fals...
totoro72/pt1
ep/item_26_multiple_inheritance_for_mixin_only.py
Python
mit
2,705
0.001479
import json from collections import abc # item 26: use muptiple inheritance for mixin only # a mixin that transforms a python object to a dictionary that's ready for seralization class ToDictMixin(object): def to_dict(self): """Return a dictionary representation of this object""" return self._traver...
other): return self.__dict__ == other.__dict__ class Switch(EqualityMixin): def __init__(s
elf, ports, speed): self.ports = ports self.speed = speed class Machine(EqualityMixin): def __init__(self, ram, cpu, disk): self.ram = ram self.cpu = cpu self.disk = disk class DatacenterRack(ToJsonMixin, ToDictMixin, EqualityMixin): def __init__(self, switch, machin...
IAryan/edCTF
edctf/api/views/challengeboard.py
Python
apache-2.0
2,095
0.012411
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from edctf.api.models import challengeboard, category, challenge from edctf.api.serializers import challengeboard_serializer, category_serializer, challenge_serializer class cha...
a. return Response({ 'challengeboards': challengeboards_serializer.data, 'categories': categories_serializer.data, 'challenges': challenges_serializer.data, }) else: # Retrieve and serialize the requested challengeboard data. challengeboards = challengeboard.obj...
Return the serialized data. return Response({ 'challengeboards': serializer.data, })
gmartinvela/Incubator
Incubator/wsgi.py
Python
mit
1,428
0.0007
""" WSGI config for Incubator project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`...
framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This break
s # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "Incubator.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Incubator.settings") # This application object is used by a...
cgvarela/vitess
test/custom_sharding.py
Python
bsd-3-clause
7,223
0.005399
#!/usr/bin/env python # # Copyright 2015, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. import unittest import environment import utils import tablet # shards shard_0_master = tablet.Tablet() shard_0_rdonly = tablet.Tablet() sh...
) for t in [shard_1_master, shard_1_rdonly]: t.start_vttablet(wait_for_state=None) for t in [shard_1_master, shard_1_rdonly]: t.wait_for_vttablet_state('NOT_SERVING') s = utils.run_vtctl_json(['GetShard', 'test_keyspace/1']) self.assertEqual(len(s['served_types']), 3) utils.run_vtctl(['...
ias, 'test_keyspace/1'], auto_log=True) for t in [shard_1_master, shard_1_rdonly]: utils.run_vtctl(['RefreshState', t.tablet_alias], auto_log=True) t.wait_for_vttablet_state('SERVING') # rebuild the keyspace serving graph now that the new shard was added utils.run_vtctl(['R...
opethe1st/CompetitiveProgramming
Hackerrank/WeekOfCode/WoC29/minimalbruteforce.py
Python
gpl-3.0
1,231
0.028432
#!/bin/python import sys from decimal import Decimal, getcontext,Context from math import pi as PI pi = Context(prec=60).create_decimal('3.1415926535897932384626433832795028841971693993751') PI = pi def calc(fun, n): temp = Decimal("0.0") for ni in xrange(n+1, 0, -1): (a, b) = fun(ni) temp =...
if n > 0 else 3, (2 * n - 1) ** 2) #print "%.50f"%(calc(fpi, 1001)) #mini,maxi = raw_input().strip().split(' ') mini,maxi = 200,231#[long(mini),long(maxi)] # your code goes here minifraction = (3,1) minidecimal = Decimal(3.0) #print PI for d in xrange(mini,maxi+1):
#print d n = int(pi*d) d1 = n/Decimal(d) d2 = (n+1)/Decimal(d) #print n,d,d1,d2 if abs(d1-pi)<abs(d2-pi): if abs(d1-pi)<abs(minidecimal-pi): minifraction = (n,d) minidecimal = n/Decimal(d) if abs(d1-pi)>abs(d2-pi): if abs(d2-pi)<abs(minidecimal-pi): ...
marcydoty/geraldo
site/newsite/site-geraldo/django/db/backends/sqlite3/client.py
Python
lgpl-3.0
283
0.003534
from django.db.backends import BaseDatabaseClient from django.conf import settings import os class DatabaseClient
(BaseDatabaseClient): executable_name = 'sqlite3' def runshell(self): args = ['', settings.DATABASE_NAME] os.execvp(self.e
xecutable_name, args)
abadger/stellarmagnate
magnate/ui/urwid/numbers.py
Python
agpl-3.0
1,371
0.001459
# Stellar Magnate - A space-themed commodity trading game # Copyright (C) 2017 Toshio Kuratomi <toshio@fedoraproject.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version ...
otation. :kwarg max_chars: The maximum number of characters a number can take on the screen before it is turned into scientific notation. """ formatted_number = locale.format('%d', number, grouping=True) if len(fo
rmatted_number) > max_chars: formatted_number = '{:.1E}'.format(number) return formatted_number
madbook/reddit-plugin-adzerk
reddit_adzerk/lib/events.py
Python
bsd-3-clause
7,482
0.000668
from baseplate.events import FieldKind from pylons import app_globals as g from r2.lib.eventcollector import ( EventQueue, Event, squelch_exceptions, ) from r2.lib.utils import sampled from r2.models import ( FakeSubreddit, ) class AdEvent(Event): @classmethod def get_context_data(cls, reques...
placements: Array of placement objects (name, types) to be filled. is_refresh: Whether or not the request is for the initi
al ad or a refresh after refocusing the page. subreddit: The Subreddit of the ad was displayed on. request, context: Should be pylons.request & pylons.c respectively; """ event = AdEvent( topic="ad_serving_events", event_type="ss.ad_request", ...
viswimmer1/PythonGenerator
data/python_files/30552411/__init__.py
Python
gpl-2.0
4,785
0.002508
import inspect import os.path import django import SocketServer import sys from django.conf import settings from django.views.debug import linebreak_iter # Figure out some paths django_path = os.path.realpath(os.path.dirname(django.__file__)) socketserver_path = os.path.realpath(os.path.dirname(SocketServer.__file__)...
if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'): name = obj.__class__.__name__ else: name = '<unknown>' if hasattr(obj, '__module__'): module = obj.__module__ name = '%s.%s' % (module, name) return name def getframeinfo(frame, context=1): """ Ge...
t from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line. This originally comes from ``inspect`` but is modified to handle issues with ``findsource()``. ...
ringw/MetaOMR
metaomr_tests/eval_kanungo_est.py
Python
gpl-3.0
1,954
0.005629
import env import numpy as np import metaomr import metaomr.kanungo as kan from metaomr.page import Page import glob import pandas as pd import itertools import os.path import sys from datetime import datetime from random import random, randint IDEAL = [path for path in sorted(glob.glob('testset/modern/*.png')) ...
a b0 b k'.split()]) columns = columns.append(pd.MultiIndex.from_product([['estimate'],['stat','time','status','nfev']])) cols = [] results = [] fun = 'ks' method = 'Nelder-Mead' for image in IDEAL: name = os.path.basename(image).split('.')[0] page, = metaomr.open(image) kimg = kan.KanungoImage(kan.normalize...
synth.staff_dist = 8 for maxfev in [25, 50]: start = datetime.now() est_params = kan.est_parameters(synth, test_fn=kan.test_hists_ks if fun == 'ks' else kan.test_hists_chisq, opt_method=method, maxfev=maxfev) end = datetime.now() cols.append((name, fun, maxfev...
crisis-economics/CRISIS
CRISIS/test/eu/crisis_economics/abm/household/market.py
Python
gpl-3.0
1,926
0.021807
#!/bin/env/python # # This file is part of CRISIS, an economics simulator. # # Copyright (C) 2015 John Kieran Phillips # # CRISIS 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...
//www.gnu.org/licenses/>. import math class Market: def __init__(self, buyer): sel
f.buyer = buyer self.askPrices = {} self.bidPrices = {} self.supply = {} self.demand = {} def setAskPrice(self, type, price): self.askPrices[type] = price def setBidPrice(self, type, price): self.bidPrices[type] = price def setSupply(self, type, supply): se...
datacommonsorg/data
scripts/eurostat/regional_statistics_by_nuts/population_density/csv_template_mcf_compatibility_checker.py
Python
apache-2.0
976
0
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # U
nless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import...
"""Check if all the column names specified in the template mcf is found in the CSV file.""" cols = pd.read_csv(cleaned_csv, nrows=0).columns with open(tmcf, "r") as file: for line in file: if " C:" in line: col_name = line[:-1].split("->")[1] assert c...
C3BI-pasteur-fr/Galaxy-playbook
galaxy-pasteur/roles/galaxy_tools/files/install_tool_shed_tools.py
Python
gpl-2.0
28,649
0.001571
""" A script to automate installation of tool repositories from a Galaxy Tool Shed into an instance of Galaxy. Galaxy instance details and the installed tools can be provided in one of three ways: 1. In the YAML format via dedicated files (see ``tool_list.yaml.sample`` for a sample of such a file) 2. On the command...
) url = tl['galaxy_instance'] api_key = tl
['api_key'] return GalaxyInstance(url, api_key) def tool_shed_client(gi=None): """ Get an instance of the `ToolShedClient` on a given Galaxy instance. If no value is provided for the `galaxy_instance`, use the default provided via `load_input_file`. """ if not gi: gi = galaxy_insta...
tshi04/machine-learning-codes
deliberation_network/utils.py
Python
gpl-3.0
9,232
0.005199
import numpy as np import torch import time from torch.autograd import Variable ''' fast beam search ''' def repackage_hidden(h): """Wraps hidden states in new Variables, to detach them from their history.""" if type(h) == Variable: return Variable(h.data) else: return tuple(repackage_hidden...
beam_size, trg_len, encoder_hy, hidden_, h_attn_new, p_gen_new, past_attn_new,
pt_idx ): (h0_new, c0_new) = hidden_ beam_seq = Variable(torch.LongTensor( batch_size, beam_size, trg_len+1).fill_(vocab2id['<pad>'])).cuda() beam_seq[:, :, 0] = vocab2id['<s>'] beam_prb = torch.FloatTensor(batch_size, beam_size).fill_(0.0) last_wd = Variable(torch.LongTensor( bat...
dev1x-org/python-example
lib/model/task.py
Python
mit
1,058
0.006616
#coding:utf-8 """ """ class Task(object): def __init__(self, id_, project_name, title, serial_no, timelimit, timestamp, note, status): self.id_ = id_ self.project_name = project_name self.title = title self.serial_no = serial_no self.timelimit = timelimit self.timesta...
rn self.status def get_note(self): return self.note
def get_created(self): return self.timestamp
hookehu/utility
editors/studio/core/logic_center.py
Python
gpl-2.0
88
0.056818
#
-*- coding:utf-8 -*- import wx if evt_handler == None:
evt_handler = wx.EvtHandler()
kidburglar/audible-activator
unused/extract-activation-bytes.py
Python
gpl-3.0
1,379
0.00145
#!/usr/bin/env python import traceback import binascii import sys if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("Usage: %s <licenseForCustomerToken file>\n" % sys.argv[0]) sys.exit(-1) try: data = open(sys.argv[1], "rb").read() if ...
for i in range(0, 8): key = keys[i * 70 + i:(i + 1) * 70
+ i] h = binascii.hexlify(bytes(key)) h = [h[i:i+2] for i in range(0, len(h), 2)] h = b",".join(h) output_keys.append(h) except SystemExit as e: sys.exit(e) except: traceback.print_exc() # only 4 bytes of output_keys[0] are necessary for decry...
xeroc/uptick
uptick/htlc.py
Python
mit
3,974
0.001761
import click from bitshares.amount import Amount from .decorators import online, unlock from .main import main, config from .ui import print_tx @main.group() def htlc(): pass @htlc.command() @click.argument("to") @click.argument("amount") @click.argument("symbol") @click.option( "--type", type=click.Choice(...
eimage, this version of htlc_create will compute the hash for yo
u from the supplied preimage, and create the HTLC with the resulting hash. """ if length != 0 and length != len(secret): raise ValueError("Length must be zero or agree with actual preimage length") ctx.blockchain.blocking = True tx = ctx.blockchain.htlc_create( Amount(amount, symbol...
bioasp/shogen
setup.py
Python
gpl-3.0
1,416
0.029661
# Copyright (c) 2014, Sven Thiele <sthiele78@gmail.com> # # This file is part of shogen. # # shogen 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)...
with shogen. If not, see <http://www.gnu.org/licenses/>. # -*- coding: utf-8 -*- from setuptools import setup setup( name = 'shogen', version = '2.0.0', url = 'http://pypi.python.org/pypi/shogen/', license = 'GPLv3+', descriptio...
genome segments that regulate metabolic pathways', long_description = open('README.rst').read(), author = 'Sven Thiele', author_email = 'sthiele78@gmail.com', packages = ['__shogen__'], package_dir = {'__shogen__' : 'src'}, package_data = {'__shogen__' : ['encodings/*.lp...
bairdj/beveridge
src/scrapy/afltables/afltables/common.py
Python
mit
1,563
0.007678
team_mapping = { "SY": "Sydney", "WB": "Western Bulldogs", "WC": "West Coast", "HW": "Hawthorn", "GE": "Geelong", "FR": "Fremantle", "RI": "Richmond", "CW": "Collingwood", "CA": "Carlton", "GW": "Greater Western Sydney", "AD": "Adelaide", "GC": "Gold Coast", "ES": "Es...
nse.xpath("//td[@colspan = '5' and @align = 'center']")[0] match_details = match_container.xpath(".//text()").extract() return { "round": match_details[1], "venue": match_details[3], "date": match_details[6], "attendance": match_details[8],
"homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(), "awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(), "homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()), "awayScore": int(response.xpath...
project-zerus/blade
src/blade/configparse.py
Python
bsd-3-clause
11,273
0.003193
# Copyright (c) 2011 Tencent Inc. # All rights reserved. # # Author: Michaelpeng <michaelpeng@tencent.com> # Date: January 09, 2012 """ This is the configuration parse module which parses the BLADE_ROOT as a configuration file. """ import os import sys import console from blade_util import var_to_list from cc_t...
}, 'java_config': { 'version': '1.6', 'source_version': '', 'target_version': '', 'maven': 'mvn', 'maven_central': '', 'warnings':['-Werror'
, '-Xlint:all'], 'source_encoding': None, 'java_home':'' }, 'java_binary_config': { 'one_jar_boot_jar' : '', }, 'java_test_config': { 'junit_libs' : [], 'jacoco_home' : '', 'c...
gmathers/iii-addons
mrp_custom/__openerp__.py
Python
agpl-3.0
1,656
0.004227
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
est_for_quotation.jpeg'], 'depends': ['product','base'
,'mrp_repair'], 'data': [ #'abc_report.xml', 'mrp_custom.xml' ], 'installable': True, 'auto_install': False, 'application': True, }
akrherz/pyWWA
parsers/pywwa/workflows/afos_dump.py
Python
mit
2,891
0
"""AFOS Database Workflow.""" # 3rd Party from twisted.internet import reactor from txyam.client import YamClient from pyiem.util import LOG from pyiem.nws import product # Local from pywwa import common from pywwa.ldm import bridge from pywwa.database import get_database DBPOOL = get_database("afos", cp_max=5) MEMCA...
if nws.warnings: common.email_error("\n".join(nws.warnings), buf) if nws.afos is None: if nws.source[0] not in ["K", "P"]: return None raise Exception("TextProduct.afos is null") if common.replace_en
abled(): args = [nws.afos.strip(), nws.source, nws.valid] bbb = "" if nws.bbb: bbb = " and bbb = %s " args.append(nws.bbb) txn.execute( "DELETE from products where pil = %s and source = %s and " f"entered = %s {bbb}", args, ...
camilonova/sentry
src/sentry/models/file.py
Python
bsd-3-clause
3,050
0.000328
""" sentry.models.file ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2015 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from django.conf import settings from django.core.files.storage import get_storage_class from django.db import ...
return '/'.join(pieces) def get_storage(self): backend = self.storage options = self.storage_options storage = get_st
orage_class(backend) return storage(**options) def deletefile(self, commit=False): assert self.path storage = self.get_storage() storage.delete(self.path) self.path = None if commit: self.save() def putfile(self, fileobj, commit=True): """...
bcoca/ansible-modules-extras
database/misc/redis.py
Python
gpl-3.0
10,653
0.00169
#!/usr/bin/python # -*- coding: utf-8 -*- # 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. #...
st running the database required: false default: localhost login_port: description: - The port to connect to required: false default: 6379 master_host: description: - The host of the master instance [slave command] required: false ...
equired: false default: null slave_mode: description: - the mode of the redis instance [slave command] required: false default: slave choices: [ "master", "slave" ] db: description: - The database to flush (used in db mode) [flush command] ...
Antikythera/hoot
Application/central_service/settings.py
Python
gpl-2.0
3,154
0
""" Django settings for central_service project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR,...
= { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Cache CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } # Internationalization # https://...
.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' # Used in production to define where collectstatic stores st...
charanpald/wallhack
wallhack/clusterexp/LaplacianExp.py
Python
gpl-3.0
2,822
0.013466
""" Observe the effect in the perturbations of Laplacians """ import sys import logging import numpy import scipy import itertools import copy import matplotlib.pyplot as plt from apgl.graph import * from sandbox.util.PathDefaults import PathDefaults from sandbox.misc.IterativeSpectralClustering import IterativeS...
numGraphs, 5)) for r in range(numRepetitions): iterator = BoundGraphIterator(numGraphs=numGraphs) clusterer = IterativeSpectralClustering(k1, k2, T=100, computeBound=True, alg="IASC") clusterer.nb_iter_kmeans = 20 logging.debug("Starting clustering") clusterLis...
for i in range(len(clusterList)): errors[i, r] = GraphUtils.randIndex(clusterList[i], iterator.realClustering) print(allBoundLists.mean(0)) numpy.save(fileName, allBoundLists) logging.debug("Saved results as " + fileName) else: allBoundLists = numpy.load(fil...
adsabs/ADSDeploy
ADSDeploy/pipeline/workers.py
Python
gpl-3.0
216
0.00463
# encoding: utf-8 """ Place holder for all wor
kers """ from .integration_tester import IntegrationTestWorker from .db_writer import DatabaseWriterWorker from .deploy import Before
Deploy, Deploy, Restart, GithubDeploy
weissercn/learningml
learningml/GoF/optimisation_and_evaluation/automatisation_gaussian_same_projection/automatisation_Gaussian_same_projection_optimisation_and_evaluation_euclidean.py
Python
mit
3,583
0.017304
import numpy as np import math import sys import os sys.path.insert(0,os.environ['learningml']+'/GoF/') import classifier_eval from classifier_eval import name_to_nclf, nclf, experiment, make_keras_model from sklearn import tree from sklearn.ensemble import AdaBoostClassifier from sklearn.svm import SVC from rep.estim...
t =
[name_to_nclf("svm")] #nclf_list = [nclf('bdt',AdaBoostClassifier(base_estimator=tree.DecisionTreeClassifier(max_depth=2)), ['learning_rate','n_estimators'], [[0.01,2.0],[1,1000]], param_opt=[1.181, 319]), nclf('xgb',XGBoostClassifier(), ['n_estimators','eta'], [[10,1000],[0.01,1.0]], param_opt=[524, 0.151]), nclf(...
wgwoods/anaconda
pyanaconda/ui/gui/spokes/advstorage/zfcp.py
Python
gpl-2.0
6,251
0.0016
# zFCP configuration dialog # # Copyright (C) 2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed...
self._discoveryError = str(e) return def on_entry_activated(self, entry, user
_data=None): # When an entry is activated, press the discover or retry button current_page = self._conditionNotebook.get_current_page() if current_page == 0: self._startButton.clicked() elif current_page == 2: self._retryButton.clicked()
rsnakamura/iperflexer
tests/testoatbran.py
Python
mit
4,746
0.001896
from unittest import TestCase import re from iperflexer import oatbran bran = oatbran COW = 'cow' class TestOatBran(TestCase): def test_brackets(self): L_BRACKET = '[' R_BRACKET = "]" self.assertRegexpMatches(L_BRACKET, bran.L_BRACKET) self.assertNotRegexpMatches(R_BRACKET, bran.L...
otRegexpMatches("9", bran.TWO_DIGITS) self.assertNotRegexpMatches("100", bran.TWO_DIGITS) return def test_zero_or_one(self): s = "Gb" s2 = "Gab" s3 = "Gaab" e = "G(a)" + bran.ZERO_OR_ONE + 'b' self.assertRegexpMatches(s, e) match = r...
f.assertEqual("a", match.groups()[0]) self.assertNotRegexpMatches(s3, e) return def test_range(self): s = "1" s3 = "315" s2 = "a" + s3 + "21" e = bran.NAMED(n="octet", e=bran.M_TO_N(m=1, n=3, e=bran.DIGIT)) self.assertRegexpMatches(s, e) self.assertRe...
mrDoctorWho/vk4xmpp
library/longpoll.py
Python
mit
10,264
0.029529
# coding: utf-8 # © simpleApps, 2014 — 2016. __authors__ = ("Al Korgun <alkorgun@gmail.com>", "John Smith <mrdoctorwho@gmail.com>") __version__ = "2.3" __license__ = "MIT" """ Implements a single-threaded longpoll client """ import select import socket import json import httplib import threading import time import v...
nable to set socket parameters") # TODO: make it abstract, to reuse in Steampunk class Poll(object): """ Class used to
handle longpoll """ __list = {} __buff = set() __lock = threading.Lock() clear = staticmethod(__list.clear) watchdogRunning = False @classmethod def init(cls): cls.watchdogRunning ^= True cls.watchdog() @classmethod def __add(cls, user): """ Issues a readable socket to use it in select() Adds user...
ianstalk/Flexget
flexget/tests/test_content_filter.py
Python
mit
3,857
0.001296
import pytest @pytest.mark.usefixtures('tmpdir') @pytest.mark.filecopy('test.torrent', '__tmp__/') class TestContentFilter: config = """ tasks: test_reject1: mock: - {title: 'test', file: '__tmp__/test.torrent'} accept_all: yes content_filter: ...
'accepted', title='test' ), 'should have accepted, doesn\t contain *.avi' def test_require1(self, execute_task): task = execute_task('test_require1') assert task.find_entry('accepted', title='test'), 'should have accepted, contains *.iso' def test_require2(self, execute_tas...
st' ), 'should have rejected, doesn\t contain *.avi' def test_require_all1(self, execute_task): task = execute_task('test_require_all1') assert task.find_entry( 'accepted', title='test' ), 'should have accepted, both masks are satisfied' def test_require_all2(self, ...
vladikoff/fxa-mochitest
tests/mozbase/manifestparser/tests/test_default_skipif.py
Python
mpl-2.0
1,518
0.006588
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import os import unittest from manifestparser import ManifestParser here = os.path.dirname(os.pa...
elif test['name'] == 'test2': self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (os == 'linux')") elif test['name'] == 'test3': self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (os == 'win')") elif test['name'] == 'test4': ...
|| (os == 'win' && debug)") elif test['name'] == 'test5': self.assertEqual(test['skip-if'], "os == 'win' && debug # a pesky comment") elif test['name'] == 'test6': self.assertEqual(test['skip-if'], "(os == 'win' && debug ) || (debug )") if __name__ == '__main__':...
anaruse/chainer
chainer/functions/connection/shift.py
Python
mit
4,492
0
import numpy from chainer.backends import cuda from chainer import function_node from chainer.utils import type_check def _pair(x): if hasattr(x, '__getitem__'): return x return x, x class Shift(function_node.FunctionNode): def __init__(self, ksize=3, dilate=1): super(Shift, self).__in...
b, c, h, w = x.shape y = cuda.cupy.empty_like(x) cuda.elementwise( 'raw T x, int32 c, int32 h, int32 w,' 'int32 kh, int32 kw,' 'int32 dy, int32 dx',
'T y', ''' int b0 = i / (c * h * w); int rest = i % (c * h * w); int c0 = rest / (h * w); rest %= h * w; int out_row = rest / w; int out_col = rest % w; int n_groups = kh * kw; ...