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
TeePaps/estreamer
estreamer/eventrequest.py
Python
apache-2.0
5,410
0.0122
#local from message import MessageHeader from base import Struct, StructArray #standard from datetime import datetime from ctypes import LittleEndianStructure, Union, c_uint32 from six import iteritems, raise_from import inspect import config import sys class Error(Exception): pass class InvalidTimestampError(Error):...
1), ('discovery_v4', c_uint32, 1), (
'connection_v4', c_uint32, 1), ('correlation_v4', c_uint32, 1), ('metadata_v4', c_uint32, 1), ('user', c_uint32, 1), ('correlation_v5', c_uint32, 1), ('timestamp', c_uint32, 1), ('discovery_v5', c_uint32, 1), ('discovery_v6', c_uint32, 1), ('connection_v5'...
tapo-it/odoo-addons-worktrail
addons_worktrail/tapoit_worktrail/model/tapoit_worktrail.py
Python
agpl-3.0
13,254
0.003546
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2012 TaPo-IT (http://tapo-it.at) All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the ...
/rest/token/request/" % (protocol, vals[
'host'], vals['port']) return self.pool.get('tapoit_worktrail.sync.execution').json_request(cr, uid, url, data, header=header) def test_auth_token(self, cr, uid, vals): protocol = 'http' if 'secure' in vals: protocol = 'https' header = { 'Content-Type': 'app...
rednaxelafx/apache-spark
python/pyspark/tests/test_appsubmit.py
Python
apache-2.0
10,321
0.00126
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
nse. # import os import re import shutil import subprocess import tempfile import unittest import zipfile class SparkSubmitTests(unittest.TestCase): def setUp(self): self.programDir = tempfile.mkdtemp() tmp_dir = tempfile.gettempdir() self.sparkSubmit = [ os.path.join(os.envi...
iver.extraJavaOptions=-Djava.io.tmpdir={0}".format(tmp_dir), "--conf", "spark.executor.extraJavaOptions=-Djava.io.tmpdir={0}".format(tmp_dir), ] def tearDown(self): shutil.rmtree(self.programDir) def createTempFile(self, name, content, dir=None): """ Create a temp f...
alexises/python-cah
pythonCah/log.py
Python
lgpl-3.0
431
0
import logging import sys def prepareLogging(loggingLevel): logger = logging.get
Logger() logger.setLevel(loggingLevel) formatStr = \ '%(asctime)s [%(levelname)-8s] %(filename)s:%(lineno)s %(message)s' formater = logging.Formatter(formatStr, '%H:%M:%S') handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formater) handler.setLevel(loggingLevel) logger.addHandler(handler)
laslabs/vertical-medical
sale_medical_prescription/tests/test_sale_order.py
Python
agpl-3.0
1,725
0
# -*- coding: utf-8 -*- # Copyright 2016 LasLabs Inc. # License GPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). from odoo.tests.common import TransactionCase class TestSaleOrder(TransactionCase): def setUp(self): super(TestSaleOrder, self).setUp() self.sale_7 = self.env.ref( ...
rted(self.sale_7.prescription_order_line_ids
.ids) self.assertEqual( res, exp, ) def test_compute_prescription_order_line_count(self): """ Test rx line count properly computed """ exp = self.sale_7.order_line.mapped('prescription_order_line_id').ids exp = len(exp) res = len(self.sale_7.prescription_...
sivaprakashniet/push_pull
p2p/lib/python2.7/site-packages/celery/tests/concurrency/test_concurrency.py
Python
bsd-3-clause
3,179
0
from __future__ import absolute_import import os from itertools import count from mock import Mock from celery.concurrency.base import apply_target, BasePool from celery.tests.case import AppCase class test_BasePool(AppCase): def test_apply_target(self): scratch = {} counter = count(0) ...
10) self.assertFalse(p.active) p._state = p.RUN self.assertTrue(p.active) def test_restart(self):
p = BasePool(10) with self.assertRaises(NotImplementedError): p.restart() def test_interface_on_terminate(self): p = BasePool(10) p.on_terminate() def test_interface_terminate_job(self): with self.assertRaises(NotImplementedError): BasePool(10).term...
yelizariev/addons-yelizariev
web_multi_attachment_base/__init__.py
Python
lgpl-3.0
70
0
#
License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.ht
ml).
detrout/debian-statsmodels
statsmodels/tsa/api.py
Python
bsd-3-clause
661
0
from .ar_model import AR from .arima_model import ARMA, ARIMA from . import vector_ar as var from .arima_process import arma_generate_sample, ArmaProcess from .vector_ar.var_model import VAR from .vector_ar.svar_model import SVAR from .vector_ar.dynamic import DynamicVAR from .filters import api as filters from . impor...
s from .tsatools import (ad
d_trend, detrend, lagmat, lagmat2ds, add_lag) from . import interp from . import stattools from .stattools import * from .base import datetools from .seasonal import seasonal_decompose from ..graphics import tsaplots as graphics from .x13 import x13_arima_select_order from .x13 import x13_arima_analysis
mattbernst/polyhartree
support/ansible/modules/extras/packaging/os/svr4pkg.py
Python
gpl-3.0
7,426
0.008888
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2012, Boyd Adamson <boyd () boydadamson.com> # # 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 th...
tion: - HTTP[s] proxy to be used if C(src) is a URL. response_file: description: - Specifies the location of a response file to be used if package expects input on install. (added in Ansible 1.4) required: false zone:
description: - Whether to install the package only in the current zone, or install it into all zones. - The installation into all zones works only if you are working with the global zone. required: false default: "all" choices: ["current", "all"] version_added: "1.6" category: descrip...
robinson96/GRAPE
test/testClone.py
Python
bsd-3-clause
4,326
0.005779
import os import shutil import sys import tempfile import unittest import testGrape if not ".." in sys.path: sys.path.insert(0, "..") from vine import grapeMenu, clone, grapeGit as git class TestClone(testGrape.TestGrape): def testClone(self): self.setUpConfig() self.queueUserInput(['\n', '\n',...
"--nested", "--noverify"]) grapeMenu.menu().applyMenuChoice("commit",["-m", "\"added subproject1\""]) print git.log("--decorate") #Now clone the repo into a temp dir and make sure the subproject is in the clone try:
tempDir = tempfile.mkdtemp() self.queueUserInput(["\n", "\n", "\n", "\n"]) args = [self.repo, tempDir, "--recursive", "--allNested"] ret = grapeMenu.menu().applyMenuChoice("clone", args) self.assertTrue(ret, "vine.clone returned failure") # ensure we ar...
modoboa/modoboa
modoboa/core/migrations/0021_localconfig_need_dovecot_update.py
Python
isc
403
0
# Generated by Dja
ngo 2.2.10 on 2020-04-29 12:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '
0020_auto_20200421_0851'), ] operations = [ migrations.AddField( model_name='localconfig', name='need_dovecot_update', field=models.BooleanField(default=False), ), ]
jonathanverner/brython
www/tests/test_indexedDB.py
Python
bsd-3-clause
1,790
0.018436
from browser import window _kids=['Marsha', 'Jan', 'Cindy'] def continue1(event): _objectStore.get('Jan', onsuccess=exists, onerror=continue2) def continue2(event): for _kid in _kids:
_rec={'name': _kid} _objectStore.put(_rec, _kid, onsuccess=printmsg, onerror=printerr) _objectStore.g
et('Jan', onsuccess=continue3, onerror=printerr) def continue3(event): print ("Async operations complete..") def exists(event): if event.target.pyresult() is None: #handle cause of when get returns undefined if the key doesn't exist #in the db.. continue2(event) else: print(eve...
WojciechMula/toys
fpc-compression/compress.py
Python
bsd-2-clause
5,796
0.002415
import sys import heapq import uvint from pathlib import Path from status import Status def main(): path = Path(sys.argv[1]) out = Path(sys.argv[2]) bytes = path.read_bytes() min_length = 4 max_length = 10 compressor = Compressor(bytes, min_length, max_length) with open(out, 'wb') as f: ...
_build_histogram() symbols = [] status = Status() total = len(self.histogram) while True: proc = 100 * (total - len(self.histogram)) / total status(f"Compressing {proc:.2f}%
") best = self.get_best() if best is None: break n = len(best.word) symbol = len(symbols) image = self.image for idx in best.indices: if image.is_free(idx, n): self.image.put_symbol(symbol, idx, ...
AnCh7/sweetshot
python3-src/steem/transactionbuilder.py
Python
unlicense
446
0.002242
from piston.transactionbuilder import TransactionBuilder as PistonTransactionBuilder import warnings warnings.simplefilter('always', DeprecationWarnin
g) class TransactionBuilder(
PistonTransactionBuilder): def __init__(self, *args, **kwargs): warnings.warn( "Please use the API compatible 'piston-lib' in future", DeprecationWarning ) super(TransactionBuilder, self).__init__(*args, **kwargs)
seales/spellchecker
spelling/spelling_error.py
Python
mit
1,021
0.001959
class SpellingError: def __init__(self, file, word, line, line_number): """ Takes file_path, misspelled word, line where misspelling occurs, and line number of misspelling. :param file: str :param word: str :param line: str :param line_number: int """ ...
.setter def line_number(self, line_number): self.__line_n
umber = line_number
iulian787/spack
var/spack/repos/builtin/packages/py-terminado/package.py
Python
lgpl-2.1
1,010
0.005941
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyTerminado(PythonPackage): """Terminals served to term.js using Tornado websockets""" homepage = "https:/...
s_on('py-ptyprocess', type=('build', 'run')) depends_on('[email protected]:2.8,3.4:', when='@0.8.2:', type=('
build', 'run'))
krafczyk/spack
var/spack/repos/builtin/packages/libfs/package.py
Python
lgpl-2.1
1,873
0.000534
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-64...
such as xfsinfo, fslsfonts, and the X servers themselves.""" homepage = "http://cgit.freedesktop.org/xorg/lib/libFS" url = "htt
ps://www.x.org/archive/individual/lib/libFS-1.0.7.tar.gz" version('1.0.7', 'd8c1246f5b3d0e7ccf2190d3bf2ecb73') depends_on('[email protected]:', type='build') depends_on('fontsproto', type='build') depends_on('xtrans', type='build') depends_on('pkgconfig', type='build') depends_on('util-macros', ty...
oscaro/django
tests/field_deconstruction/tests.py
Python
bsd-3-clause
17,552
0.000855
from __future__ import unicode_literals import warnings from django.db import models from django.test import TestCase, override_settings from django.utils import six class FieldDeconstructionTests(TestCase): """ Tests the deconstruct() method on all core fields. """ def test_name(self): """...
name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.AutoField") self.assertEqual(args, []) self.assertEqual(kwargs, {"primary_key": True}) def test_big_integer_field(self): field = models.BigIntegerField() name, path, args, kwargs = fiel...
Equal(path, "django.db.models.BigIntegerField") self.assertEqual(args, []) self.assertEqual(kwargs, {}) def test_boolean_field(self): field = models.BooleanField() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.db.models.BooleanField") ...
UU-Hydro/PCR-GLOBWB_model
model/deterministic_runner.py
Python
gpl-3.0
6,069
0.012034
#!/usr/bin/env python # -*- coding: utf-8 -*- # # PCR-GLOBWB (PCRaster Global Water Balance) Global Hydrological Model # # Copyright (C) 2016, Edwin H. Sutanudjaja, Rens van Beek, Niko Wanders, Yoshihide Wada, # Joyce H. C. Bosmans, Niels Drost, Ruud J. van der Ent, Inge E. M. de Graaf, Jannis M. Hoch, # Kor de Jong,...
dynamic_framework.run() if __name__ == '__m
ain__': # print disclaimer disclaimer.print_disclaimer(with_logger = True) sys.exit(main())
degoldcode/PyNaviSim
objects.py
Python
gpl-3.0
424
0.03066
from vec2d import vec2d from math import e, exp, pi, c
os, sin, sqrt, atan2 class Goal: def __init__(self, pos): self.pos= pos self.size = 8 self.theta = atan2(pos.y,pos.x) class Landmark: def __init__(self): self.pos= vec2d(0,0) self.size
= 4 class Pipe: def __init__(self): self.pos0= vec2d(0,0) self.pos1= vec2d(0,0) self.width = 3
zzcclp/carbondata
python/pycarbon/tests/mnist/dataset_with_unischema/tests/conftest.py
Python
apache-2.0
1,952
0.007684
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
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 permis
sions and # limitations under the License. import numpy as np import pytest from pycarbon.tests import DEFAULT_CARBONSDK_PATH MOCK_IMAGE_SIZE = (28, 28) MOCK_IMAGE_3DIM_SIZE = (28, 28, 1) SMALL_MOCK_IMAGE_COUNT = { 'train': 30, 'test': 5 } LARGE_MOCK_IMAGE_COUNT = { 'train': 600, 'test': 100 } class MockDa...
lsst/sims_catalogs_measures
tests/testMethodRegistry.py
Python
gpl-3.0
2,280
0.00614
from __future__ import with_statement import unittest import lsst.utils.tests as utilsTests from lsst.sims.catalogs.measures.instance im
port register_class, register_method @register_class class ClassA(object): def call(self, key): return self._methodRegistry[key](self) @register_method('a') def _a_method(self): return 'a' @register_class class ClassB(ClassA): @register_method('b') def _b_method(self): ...
@register_method('c') def _c_method(self): return 'c' @register_class class ClassD(ClassA): @register_method('d') def _d_method(self): return 'd' class MethodRegistryTestCase(unittest.TestCase): def testMethodInheritance(self): """ Test that the register_class an...
deepmind/deep-verify
deep_verify/src/formulations/semidefinite/__init__.py
Python
apache-2.0
1,083
0
# coding=utf-8 # Copyright 2019 DeepMind Technologies Limited. # # 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, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions an
d # limitations under the License. """Semidefinite verification formulation. Going beyond the 'standard' formulation (`src.formulations.standard`), this module implements a tighter Lagrangian relaxation based on semidefinite programming. For more details see paper: "Efficient Neural Network Verification with Exactne...
jriehl/numba
examples/laplace2d/laplace2d-pa.py
Python
bsd-2-clause
1,199
0.006672
#!/usr/bin/env python from __future__ import print_function import time import numpy as np from numba import jit, stencil @stencil def jacobi_kernel(A): return 0.25 * (A[0,1] + A[0,-1] + A[-1,0] + A[1,0]) @jit(parallel=True) def jacobi_relax_core(A, Anew): error = 0.0 n = A.shape[0] m = A.shape[1]...
error = np.max(np.abs(Anew - A)) return error def main(): NN = 3000 NM = 3000 A = np.zeros((NN, NM), dtype=np.float64) Anew = np.zeros((NN, NM), dtype=np.float64) n = NN m = NM iter_max = 1000 tol = 1.0e-6 error = 1.0 for j in range(n): A[j, 0] = 1.0 Ane...
iter = 0 while error > tol and iter < iter_max: error = jacobi_relax_core(A, Anew) # swap A and Anew tmp = A A = Anew Anew = tmp if iter % 100 == 0: print("%5d, %0.6f (elapsed: %f s)" % (iter, error, time.time()-timer)) iter += 1 runtime...
a1ezzz/wasp-backup
wasp_backup/file_archiver.py
Python
lgpl-3.0
2,627
0.012562
# -*- coding: utf-8 -*- # wasp_backup/file_archiver.py # # Copyright (C) 2017 the wasp-backup authors and contributors # <see AUTHORS file> # # This file is part of wasp-backup. # # wasp-backup is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
nses/>. # TODO: document the code # TODO: write tests for the code # noinspection PyUnresolvedReferences from wasp_backup.version import __author__, __version__, __credits__, __license__, __copyright__, __email__ # noinspection PyUnresolvedReferences from wasp_backup.version import __status__ import io from wasp_ge...
ackup.core import WBackupMeta from wasp_backup.archiver import WBasicArchiveCreator class WFileArchiveCreator(WBasicArchiveCreator): @verify_type('paranoid', archive_path=str, io_write_rate=(float, int, None)) @verify_value('paranoid', archive_path=lambda x: len(x) > 0, io_write_rate=lambda x: x is None or x > 0) ...
dakcarto/QGIS
python/plugins/processing/algs/saga/versioncheck.py
Python
gpl-2.0
2,449
0
import os import subprocess def getAlgParams(f): params = [] booleanparams = [] numparams = [] lines = open(f) line = lines.readline().strip('\n').strip() name = line if '|' in name: tokens = name.split('|') cmdname = tokens[1] else: cmdname = name line = li...
.startswith("_"): print "-" * 50 print
f + " [ERROR]" print lines print usage print "Name in description:" + cmdname print "Parameters in description:" + unicode(params) print "-" * 50 print if __name__ == '__main__': folder = os.path.join(os.path.dirname(__file__), "description") for descriptionFile...
miniworld-project/miniworld_core
miniworld/model/network/linkqualitymodels/LinkQualityModelRange.py
Python
mit
6,220
0.002412
from miniworld import log from miniworld.Scenario import scenario_config from miniworld.model.network.linkqualitymodels import LinkQualityModel, LinkQualityConstants __author__ = 'Nils Schmidt' class LinkQualityModelRange(LinkQualityModel.LinkQualityModel): ##################################################### ...
delay_var=delay_variation_str) # delay_cmd = "{delay_const} {delay_var} distribution normal".format(delay_const=delay_const, delay_var=delay_variation) default_link_quality[self.NETEM_KEY_DELAY] = delay_cmd # return bandwidth, delay_const, delay_variatio...
return False, default_link_quality class LinkQualityModelWiFiExponential(LinkQualityModelWiFiLinear): ##################################################### # Implement these methods in a subclass ##################################################### # TODO: Abstract! def _distance_2_lin...
ryonsherman/rcbot
utils/text.py
Python
mit
190
0
#!/usr/bin/e
nv python2 class style: @staticmethod def bold(text): return "\x02%s\x02" % text @staticmethod def underline(text): return "\x1F%s\x1F" % tex
t
geraldoandradee/pytest
testing/test_assertion.py
Python
mit
11,084
0.001804
import sys import py, pytest import _pytest.assertion as plugin from _pytest.assertion import reinterpret, util needsnewassert = pytest.mark.skipif("sys.version_info < (2,6)") @pytest.fixture def mock_config(): class Config(object): verbose = False def getoption(self, name): if name =...
assert x == y """) result = testdir.runpytest() result.stdout.fnmatch_lines([ "*def test_hello():*", "*assert x == y*", "*E*Extra items*left*", "*E*'x'*", "*E*Extra items*right*",
"*E*'y'*", ]) @pytest.mark.xfail("sys.version_info < (2,6)") def test_assert_compare_truncate_longmessage(testdir): testdir.makepyfile(r""" def test_long(): a = list(range(200)) b = a[::2] a = '\n'.join(map(str, a)) b = '\n'.join(map(str, b)) ...
aneumeier/userprofile
userprofile/mail.py
Python
mit
494
0
from django.conf import settings from django.core.mail import send_mail from django.core.urlresol
vers import reverse def send_validation(strategy, backend, code): url = '{0}?verification_code={1}'.format( reverse('social:complete', args=(backend.name,)), code.code ) url = strategy.request.build_absolute_uri(url) send_mail('Validate your account', 'Validate your account {0}'.format...
M, [code.email], fail_silently=False)
kensonman/webframe
management/commands/pref.py
Python
apache-2.0
18,742
0.031267
# -*- coding: utf-8 -*- # # File: src/webframe/management/commands/pref.py # Date: 2020-04-22 21:35 # Author: Kenson Man <[email protected]> # Desc: Import / Create / Update / Delete preference # from django.conf import settings from django.contrib.auth import get_user_model from django.core.management.base import B...
filepath', action='store_true', help='[import]; Import the file-path in preferences; Default False') parser.add_argument('--force', '-f ', dest='force', action='store_true', help='[import]; Force the import', default=False) #Generate Doc parser.add_argument('--tmpl', dest='tm
pl', type=str, help="[gendoc]; The template name when generating document; Default: {0}".format(tmpl), default=tmpl) def __get_owner__(self, owner=None): if not owner: return None logger.debug('Getting owner by: "%s"', owner) owner=owner if owner else self.kwargs['owner'] return get_user_mod...
clarkyzl/flink
flink-python/pyflink/fn_execution/timerservice_impl.py
Python
apache-2.0
4,824
0.001451
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
erservice import InternalTimer, K, N, InternalTimerService from pyflink.fn_execution.state_impl import RemoteKeyedStateBackend class InternalTimerImpl(InternalTimer[K, N]): def __init__(self, timestamp: int, key: K, namespace: N): self._timestamp = timestamp self._key = key self._namespac...
self._timestamp def get_key(self) -> K: return self._key def get_namespace(self) -> N: return self._namespace def __hash__(self): result = int(self._timestamp ^ (self._timestamp >> 32)) result = 31 * result + hash(tuple(self._key)) result = 31 * result + hash(self...
eljost/pysisyphus
deprecated/tests/test_baker_ts/test_baker_ts.py
Python
gpl-3.0
6,474
0.000618
#!/usr/bin/env python3 import itertools as it from pathlib import Path from pprint import pprint import shutil import time import numpy as np import pandas as pd from pysisyphus.calculators.Gaussian16 import Gaussian16 from pysisyphus.calculators.PySCF import PySCF from pysisyphus.color import red, green from pysisy...
opyl.xyz": geoms["05_cyclopropyl.xyz"]} results, duration, cycles = run_baker_ts_opts( geoms,
meta, coord_type, thresh, runid=i ) all_results.append(results) durations.append(duration) all_cycles.append(cycles) pri...
zhouyao1994/incubator-superset
superset/migrations/versions/ad82a75afd82_add_query_model.py
Python
apache-2.0
3,118
0.001924
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
rue), sa.Column("progress", sa.Integer(), nullable=True), sa.Column("rows", sa.Integer(), nullable=True), sa.Column("error_message", sa.Text(), nullable=True), sa.Column("start_time", sa.Numeric(precision=
20, scale=6), nullable=True), sa.Column("changed_on", sa.DateTime(), nullable=True), sa.Column("end_time", sa.Numeric(precision=20, scale=6), nullable=True), sa.ForeignKeyConstraint(["database_id"], ["dbs.id"]), sa.ForeignKeyConstraint(["user_id"], ["ab_user.id"]), sa.PrimaryKeyC...
rogerlindberg/autopilot
src/lib/wrappers/passwordentrydialog.py
Python
gpl-3.0
2,034
0.000492
# Copyright (C) 2009-2015 Contributors as noted in the AUTHORS file # # This file is part of Autopilot. # # Autopilot 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 y...
yDialog, Wrapper): def __init__(self, *args, **kw): wxPasswordEntryDialog.__init__(self, *args, **kw) Wrapper.__init__(self) def
ShowModal(self, *args, **kw): self.shown = True Logger.add_result("Dialog opened") wx.CallLater(TIME_TO_WAIT_FOR_DIALOG_TO_SHOW_IN_MILLISECONDS, self._register_and_explore) super(PasswordEntryDialog, self).ShowModal(*args, **kw) @Overrides(wxPasswordEntryDialog) def IsShown(sel...
JorgeDeLosSantos/metal-forming-itc
forming_2D.py
Python
mit
37,581
0.015114
# -*- coding: mbcs -*- from part import * from material import * from section import * from assembly import * from step import * from interaction import * from load import * from mesh import * from optimization import * from job import * from sketch import * from visualization import * from connectorBehavior import * i...
8066, 5.201), (69521.936, 5.28), (69665.95844, 5.359), (69781.40845, 5.438), (69915.13321, 5.517), ( 70051.75872, 5.595), (70168.51407, 5.674), (70323.41434, 5.753
), ( 70415.65831, 5.832), (70540.39073, 5.911), (70648.00871, 5.989), ( 70769.5503, 6.068), (70848.0157, 6.147), (70950.55735, 6.226), ( 71035.11433, 6.305), (71122.42702, 6.384), (71228.44958, 6.462), ( 71316.92258, 6.541), (71433.82297, 6.62), (71501.12046, 6.699), ( 71590.31864, 6.777), (71635.57...
carlcarl/rcard
waterfall_wall/views.py
Python
mit
455
0.002198
from django.sho
rtcuts import render from rest_framework import viewsets from waterfall_wall.serializers import ImageSerializer from waterfall_wall.models import Image def index(request): context = {} return render(request, 'waterfall_wall/index.html', context) class ImageViewSet(viewsets.ModelViewSet): """ API endp...
" queryset = Image.objects.all() serializer_class = ImageSerializer
winhamwr/calabar
calabar/tunnels/__init__.py
Python
bsd-3-clause
6,085
0.002794
""" calabar.tunnels This module encapsulates various tunnel processes and their management. """ import signal import os import sys import psi.process TUN_TYPE_STR = 'tunnel_type' # Configuration/dictionary key for the type of tunnel # Should
match the tunnel_type argument to Tunnel __init__ methods PROC_NOT_RUNNING = [ psi.process.PROC_STATU
S_DEAD, psi.process.PROC_STATUS_ZOMBIE, psi.process.PROC_STATUS_STOPPED ] def is_really_running(tunnel): pt = psi.process.ProcessTable() try: proc = pt.get(tunnel.proc.pid, None) except AttributeError: # we might not actually have a tunnel.proc or it might poof while we're checking ...
steny138/twss
twss/__init__.py
Python
apache-2.0
23
0
impor
t fetch_from_twse
Shanto/ajenti
plugins/users/main.py
Python
lgpl-3.0
10,193
0.001373
from ajenti.ui import * from ajenti.com import implements from ajenti.app.api import ICategoryProvider from ajenti.app.helpers import * from ajenti.utils import * import backend class UsersPlugin(CategoryPlugin): text = 'Users' icon = '/dl/users/icon_small.png' folder = 'system' platform =['Ubuntu', ...
= UI.VContainer(tc, UI.InputBox(text=self.params[self._editing], id='dlgEdit')) return tc def get
_ui_users(self): t = UI.DataTable(UI.DataTableRow( UI.Label(text='Login'), UI.Label(text='UID'), UI.Label(text='Home'), UI.Label(text='Shell'), UI.Label(), header=True )) for u in self.users: t.app...
BuildmLearn/University-Campus-Portal-UCP
UCP/discussion/migrations/0012_auto_20160623_1849.py
Python
bsd-3-clause
442
0.002262
# -*- coding: utf-8 -*- from __future__
import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('discussion', '0011_attachment_name'), ] operations = [ migrations.AlterField( model_name='attachment', name='reply', field=mode...
), ]
maxive/erp
addons/l10n_ec/__manifest__.py
Python
agpl-3.0
782
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 201
0-2012 Cristian Salamea Gnuthink Software Labs Cia. Ltda { 'name': 'Ecuador - Accounting', 'version': '1.1', 'category': 'Localization', 'description': """ This is the base module to manage the accounting chart for Ecuador in Odoo. =======================================================================...
ion for Ecuador. """, 'author': 'Gnuthink Co.Ltd.', 'depends': [ 'account', 'base_iban', ], 'data': [ 'data/l10n_ec_chart_data.xml', 'data/account_data.xml', 'data/account_tax_data.xml', 'data/account_chart_template_data.xml', ], }
rezoo/chainer
tests/chainer_tests/functions_tests/normalization_tests/test_local_response_normalization.py
Python
mit
2,648
0
import unittest import numpy import six from chainer.backends import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import backend @testing.parameterize(*testing.product({ 'dtype': [numpy.float16, numpy.float32, numpy.float64], })) @backend...
ns.local_response_normalization(*
inputs) assert y.data.dtype == self.dtype testing.assert_allclose(y_expect, y.data, **self.check_forward_options) def test_forward(self, backend_config): self.check_forward(self.inputs, backend_config) def check_backward(self, inputs, grad_outputs, backend_config): if backend_...
andy-sheng/leetcode
234-Palindrome-Linked-List.py
Python
mit
998
0.006012
import math class Solution(object): def isPalin
drome(self, head): """ :type head: ListNode :rtype: bool """ if not head or not head.next: return True length = 0 forward = head backward = head while forward: forward = forward.next length += 1 mid = mat...
s 0 mid -= 1; backward = forward forward = forwardTmp forwardTmp = forwardTmp.next forward.next = backward if not flag: backward = forward forward = forwardTmp while(forward): if forward.val != backward.val: ...
iedparis8/django-helpdesk
management/commands/escalate_tickets.py
Python
bsd-3-clause
5,876
0.003063
#!/usr/bin/python """ django-helpdesk - A Django powered ticket tracker for small enterprise. (c) Copyright 2008 Jutda. All Rights Reserved. See LICENSE for details. scripts/escalate_tickets.py - Easy way to escalate tickets based on their age, designed to be run from Cron or similar. ""...
it(',') for queue in queue_set: try: q = Queue.objects.get(slug__exact=queue) except Queue.DoesNotExist: print "Queue %s does not exist." % queue sys.exit(2) queues.append(queue) escalate_tickets(queues=queue
s, verbose=verbose)
codemonkey2841/tradebot
run.py
Python
mit
6,871
0.001746
#!/usr/bin/env python """ It's a TradeBot """ import configparser import curses from httplib import HTTPException import os import signal import socket from ssl import SSLError import sys import time from tradebot import TradeBot def on_exit(sig, func=None): curses.nocbreak() stdscr.keypad(0) curses.echo...
_btc' if 'wait' in config['TRADE']: args['wait'] = int(config['TRADE']['refresh']) else: args['wait'] = 15 if 'simulation' in config['MAIN']: args['simulation'] = str(config['MAIN']['simulation']) else: args['simulation'] = 'off' if
'verbosity' in config['MAIN']: args['verbosity'] = config['MAIN']['verbosity'].upper() else: args['verbosity'] = "ERROR" if 'logfile' in config['MAIN']: args['logfile'] = str(config['MAIN']['logfile']) else: args['logfile'] = 'tradebot.log' if 'db' in config['MAIN']: args['db'] = str(config['MAIN'][...
Nolski/airmozilla
airmozilla/main/tests/views/test_eventdiscussion.py
Python
bsd-3-clause
4,385
0
from django.contrib.auth.models import User from funfactory.urlresolvers import reverse from nose.tools import eq_, ok_ from airmozilla.main.models import Event, EventOldSlug from airmozilla.comments.models import Discussion from airmozilla.base.tests.testbase import DjangoTestCase class TestEventDiscussion(DjangoT...
(url, data) eq_(response.status_code, 302) # should have worked discussion = Discussion.objects.get( id=discussion.id, enabled=True, closed=True, notify_all=True, moderate_all=True, ) eq_( sorted(x.email for ...
erator email address we don't know about response = self.client.post(url, dict( data, moderators='[email protected]' )) eq_(response.status_code, 200) ok_( '[email protected] does not exist as a Air Mozilla user' in response.content ) ...
ActiveState/code
recipes/Python/83698_Patterns_using_classes_dictionary/recipe-83698.py
Python
mit
1,519
0.045425
class Base: def __init__(self,v): self.v=v class StaticHash(Base): def __hash__(self):
if not hasattr(self,"hashvalue"): self.hashvalue=hash(self.v) return self.hashvalue class ImmutableHash(Base): def __init__(self,v): self.__dict__["protect"]=[] Base.__init__(self
,v) def __hash__(self): self.protect.append("v") return hash(self.v) def __setattr__(self,k,v): if k in self.protect: raise NameError,"%s is protected." % k else: self.__dict__[k]=v class Va...
STIXProject/stix-ramrod
ramrod/test/stix/stix_1_1_test.py
Python
bsd-3-clause
4,360
0.002752
# Copyright (c) 2015, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. import unittest from six import StringIO import ramrod import ramrod.stix import ramrod.stix.stix_1_1 import ramrod.utils as utils from ramrod.test import (_BaseVocab, _BaseTrans) UPDATER_MOD = ramrod.stix.stix_1_...
paign/stixCommon:Campaign/stixCommon:Names/stixCommon:Name" TRANS_VALUE = _BaseTrans.TRANS_VALUE TRANS_COUNT = 2 TRANS_XML = \ """ <indicator:Related_Campaigns> <indicator:Related_Campaign> <stixCommon:Names> <stixCommon:Name>{0}</stixCommon:Name>
</stixCommon:Names> </indicator:Related_Campaign> <indicator:Related_Campaign> <stixCommon:Names> <stixCommon:Name>{0}</stixCommon:Name> </stixCommon:Names> </indicator:Related_Campaign> </indicator:Related_Campaigns> """.format(TRANS_VA...
Inboxen/Inboxen
inboxen/account/views/otp.py
Python
agpl-3.0
3,760
0.00266
## # Copyright (C) 2014 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen 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 #...
# GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django import forms from
django.contrib import messages from django.http import Http404 from django.template.response import TemplateResponse from django.utils.translation import gettext as _ from django.views.decorators.cache import never_cache from django_otp.decorators import otp_required from elevate.decorators import elevate_required fro...
virtool/virtool
tests/dev/test_api.py
Python
mit
365
0
import pytest @pytest.mark.parametrize("dev", [True, False]) async def test_dev_mode(dev, spawn_client): """ En
sure that developer endpoint is not a
vailable when not in developer mode. """ client = await spawn_client(authorize=True, dev=dev) resp = await client.post("/dev", {"command": "foo"}) assert resp.status == 204 if dev else 404
VirgiAgl/V_AutoGP
test/likelihoods_test/softmax_test.py
Python
apache-2.0
2,571
0.004667
import unittest import numpy as np import tensorflow as tf from autogp import util from autogp import likelihoods SIG_FIGS = 5 class TestSoftmax(unittest.TestCase): def log_prob(self, outputs, latent): softmax = likelihoods.Softmax() return tf.Session().run(softmax.log_cond_prob(np.array(outpu...
np.array(latent, dtype=np.float32))) def predict(self, latent_means, latent_vars): softmax = likeliho
ods.Softmax() return tf.Session().run(softmax.predict(np.array(latent_means, dtype=np.float32), np.array(latent_vars, dtype=np.float32))) def test_single_prob(self): log_prob = self.log_prob([[1.0, 0.0]], [[[5.0, 2.0]]]) self.assertAlmostEqual...
Lektorium-LLC/edx-platform
common/djangoapps/student/views.py
Python
agpl-3.0
123,198
0.002792
""" Student Views """ import datetime import json import logging import uuid import warnings from collections import defaultdict, namedtuple from urlparse import parse_qs, urlsplit, urlunsplit import analytics import edx_oauth2_provider import waffle from django.conf import settings from django.contrib import message...
ompletely refactor tests to appease Pylint # pylint: disable=logging-format-interpolation def csrf_token(context): """A csrf token that can be included in a form.""" token = context.get('csrf_token', '') if token == 'NOTPROVIDED': return '' return (u'<di
v style="display:none"><input type="hidden"' ' name="csrfmiddlewaretoken" value="%s" /></div>' % (token)) # NOTE: This view is not linked to directly--it is called from # branding/views.py:index(), which is cached for anonymous users. # This means that it should always return the same thing for anon # use...
yanheven/neutron
neutron/agent/dhcp/agent.py
Python
apache-2.0
24,464
0.000082
# Copyright 2012 OpenStack Foundation # 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 requ...
DHCP-driver does not support retrieving of a " "list of existing networks", self.conf.dhcp_dri
ver) def after_start(self): self.run() LOG.info(_LI("DHCP agent started")) def run(self): """Activate the DHCP agent.""" self.sync_state() self.periodic_resync() def call_driver(self, action, network, **action_kwargs): """Invoke an action on a DHCP driver i...
kzys/buildbot
contrib/github_buildbot.py
Python
gpl-2.0
6,842
0.010085
#!/usr/bin/env python """ github_buildbot.py is based on git_buildbot.py github_buildbot.py will determine the repository information from the JSON HTTP POST it receives from github.com and build the appropriate repository. If your github repository is private, you must add a ssh key to the github repository for the ...
iles.extend(commit['removed']) change = {'revision': commit['id'], 'revlink': commit['url'], 'comments': commit['message'], 'branch': branch, 'who': commit['author']['name'] + " <" + commit['...
itory': self.repo_url(user, repo, github_url)}, } changes.append(change) # Submit the changes, if any if not changes: logging.warning("No changes found") return host, port = ...
romses/LXC-Web-Panel
tests/api.py
Python
mit
2,899
0.006554
import subprocess import unittest import urllib2 import shutil import json import ast import os from flask import Flask from flask.ext.testing import LiveServerTestCa
se from lwp.app import app from lwp.utils import connect_db t
oken = 'myrandomapites0987' class TestApi(LiveServerTestCase): db = None type_json = {'Content-Type': 'application/json'} def create_app(self): shutil.copyfile('lwp.db', '/tmp/db.sql') self.db = connect_db('/tmp/db.sql') self.db.execute('insert into api_tokens(description, token) ...
txomon/vdsm
vdsm/rpc/bindingxmlrpc.py
Python
gpl-2.0
48,255
0.000041
# # Copyright 2012 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in th...
.server.timeout = 1 self._enabled = True while self._enabled: try: self.server.handle_request() except Exception as e: if e[0] != EINTR: self.log.error("xml-rpc handler exception", ...
name='BindingXMLRPC') self._thread.daemon = True self._thread.start() def add_socket(self, connected_socket, socket_address): self.server.add(connected_socket, socket_address) def stop(self): self._enabled = False self.server.server_clo...
kjedruczyk/phabricator-tools
py/abd/abdt_landinglog__t.py
Python
apache-2.0
4,640
0
"""Test suite for abdt_landinglog.""" # ============================================================================= # TEST PLAN # ----------------------------------------------------------------------------- # Here we detail the things we are concerned to test and specify which tests...
future__ import print_function import unittest import phlsys_fs import phlsys_git import phlsys_subprocess import abdt_landinglog class Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_A_Breathing(self): with phlsys_fs.chtmpdir_context(): ...
h=+refs/arcyd/landinglog' ':refs/arcyd/origin/landinglog') run = phlsys_subprocess.run_commands run('git init --bare origin') run('git clone origin dev --config ' + fetch_config) with phlsys_fs.chdir_context('dev'): # make an initial co...
zsdonghao/tensorlayer
tests/models/test_seq2seq_with_attention.py
Python
apache-2.0
3,633
0.003303
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import numpy as np import tensorflow as tf from sklearn.utils import shuffle from tqdm import tqdm import tensorlayer as tl from tensorlayer.cost import cross_entropy_seq from tensorlayer.models.seq2seq_with_attention import Seq2seqLuongAttentio...
ze, embedding_size=self.embedding_size), method='dot' ) optimizer = tf.optimizers.Adam(learning_rate=0.001) for epoch in range(self.num_epochs): model_.train() trainX, trainY = shuffle(self.trainX, self.trainY) ...
shuffle=False), total=self.n_step, desc='Epoch[{}/{}]'.format(epoch + 1, self.num_epochs), leave=False): dec_seq = Y[:, :-1] target_seq = Y[:, 1:] with tf.GradientTape() as tape: ...
easytaxibr/redash
redash/handlers/queries.py
Python
bsd-2-clause
5,877
0.003233
from flask import request from flask_restful import abort from flask_login import login_required import sqlparse from funcy import distinct, take from itertools import chain from redash.handlers.base import routes, org_scoped_rule, paginate from redash.handlers.query_results import run_query from redash import models...
f): term = request.args.get('q', '') return [q.to_dict(with_last_modified_by=False) for q in models.Query.search(term, self.current_user.groups)] class QueryRecentResource(BaseResource): @require_permission('view_query') def get(self): queries = models.Query.recent(self.current_user.g...
ent_user.id) recent = [d.to_dict(with_last_modified_by=False) for d in queries] global_recent = [] if len(recent) < 10: global_recent = [d.to_dict(with_last_modified_by=False) for d in models.Query.recent(self.current_user.groups)] return take(20, distinct(chain(recent, glo...
lostcaggy/coderbot
config.py
Python
gpl-2.0
1,410
0.007092
############################################################################ # CoderBot, a didactical programmable robot. # Copyright (C) 2014, 2015 Roberto Previtera <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public L...
ould have received a copy of the GNU General Public License along # with this program; if not, write to the F
ree Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################ import json CONFIG_FILE = "coderbot.cfg" class Config: _config = {} @classmethod def get(cls): return cls._config @classmethod ...
signal/suropy
suro/thriftgen/constants.py
Python
apache-2.0
244
0.008197
# # Autogenerated by Thrift Compiler (0.9.2) # # DO
NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from ttypes import *
aliksey/projecteuler
problems/problem_062.py
Python
mit
1,000
0
# ------------------------------------------------------------------------------- # Name: Problem 62 # Purpose: projecteuler.net # # Author: aliksey # # Created: 06.04.2012 # Copyright: (c) aliksey 2012 # Licence: <your licence> # ---------------------------------------------------------------
---------------- import sys def getID(n): arr = [] number = 0 while n > 0: arr.append(n % 10) n //= 10 arr = sorted(arr) for i in range(len(arr)): number += arr[i] * 10 ** i return number def main(): amount = dict() number = dict() for i in range(1, 1000...
= i ** 3 m = getID(n) if m in amount.keys(): amount[m] += 1 if n < number[m]: number[m] = n else: amount[m] = 1 number[m] = n if amount[m] == 5: print "Found 5er:", number[m] sys.exit() if __name__...
gi0baro/weppy-assets
weppy_assets/webassets/script.py
Python
bsd-3-clause
22,478
0.000667
from __future__ import print_function import shutil import os, sys import time import logging from .loaders import PythonLoader, YAMLLoader from .bundle import get_all_bundle_files from .exceptions import BuildError from .updater import TimestampUpdater from .merge import MemoryHunk from .version import get_manifest f...
h how nice it would be to use the future options stack. if ma
nifest is not None: try: manifest = get_manifest(manifest, env=self.environment) except ValueError: manifest = get_manifest( # abspath() is important, or this will be considered # relative to Environment.directory. ...
pjdelport/pip
tests/functional/test_install.py
Python
mit
24,544
0
import os import textwrap import glob from os.path import join, curdir, pardir import pytest from pip.utils import rmtree from tests.lib import pyversion from tests.lib.local_repos import local_checkout from tests.lib.path import Path @pytest.mark.network def test_without_setuptools(script): script.run("pip",...
'INITools', without_egg_link=True, with_files=['.svn'], ) result = script.pip( 'install', '-e', '%s#egg=initools-dev' % local_checkout( 'svn+http
://svn.colorstudy.com/INITools/trunk', tmpdir.join("cache"), ), '--no-download', expect_error=True, ) result.assert_installed('INITools', without_files=[curdir, '.svn']) @pytest.mark.network def test_no_install_followed_by_no_download(script): """ Test installing in...
antoinecarme/pyaf
tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_Lag1Trend_Seasonal_DayOfWeek_SVR.py
Python
bsd-3-clause
170
0.047059
import tests
.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['RelativeDifference'] , ['Lag1Trend'] , ['Seasonal_DayOfWeek'] ,
['SVR'] );
MinchinWeb/wm_todo
tests/test_append.py
Python
gpl-3.0
1,200
0.0075
# TODO.TXT-CLI-python test script # Copyright (C) 2011-2012 Sigmavirus24, Jeff Stein # # 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) an...
ITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have
received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # TLDR: This is licensed under the GPLv3. See LICENSE for more details. import unittest import base import todo class AppendTest(base.BaseTest): def test_append(self): todo.cli.ad...
boerngen-schmidt/commuter-simulation
code/simulation/car.py
Python
gpl-3.0
5,072
0.001577
""" Created on 11.09.2014 @author: [email protected] """ from abc import ABCMeta, abstractmethod import random import datetime class BaseCar(metaclass=ABCMeta): """ Represents the fundamentals of a car """ def __init__(self, env, tank_size): """ Constructor :type ta...
ation""" self._tankFilling = self._tankSize def drive(self, ignore_refill_warning=False): """Lets the car drive the given route On arriv
al at the destination the a CommuterAction for the route is returned or if the car needs refilling the action to search for a refilling station is returned. :param ignore_refill_warning: Tells the function not to raise a RefillWarning (default: False) :type ignore_refill_warning: bool :...
lucperkins/heron
heron/tools/ui/src/python/handlers/common/utils.py
Python
apache-2.0
834
0.003597
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2016 Twitter. All rights reserved. # # Licensed under the Apache Lic
ense, 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 "...
S" 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. ''' utils.py ''' # pylint: disable=invalid-name def className(selected, item): ''' :param selected: :param item: :return: ...
jinnykoo/christmas
src/oscar/apps/order/south_migrations/0012_auto__add_field_paymentevent_reference.py
Python
bsd-3-clause
33,777
0.007786
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models from oscar.core.compat import AUTH_USER_MODEL, AUTH_USER_MODEL_NAME class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PaymentEvent.reference' ...
# Deleting field 'PaymentEvent.reference' db.delete_column('order_paymentevent', 'reference') models = { 'address.country': { 'Meta': {'ordering': "('-is_highlighted', 'name')", 'object_name': 'Country'}, 'is_highlighted': ('django.db.models.fields.BooleanField', [], {'...
s_shipping_country': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'iso_3166_1_a2': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}), 'iso_3166_1_a3': ('django.db.models.fields.CharField', [], {'max_length': '3', 'nul...
Urinx/Project_Euler_Answers
033.py
Python
gpl-2.0
995
0.030151
#!/usr/bin/env python #coding:utf-8 """ Digit canceling fractions The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by
cancelling the 9s. We shall consider fractions like, 30/50 = 3/5, to be trivial examples. There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator. If
the product of these four fractions is given in its lowest common terms, find the value of the denominator. """ ''' ab/bc=a/c b=[2-9] a<b ''' def answer(): denominator=numerator=1 for b in xrange(2,10): for a in xrange(1,b): for c in xrange(1,10): m1=(10*a+b)/float(10*b+c) m2=a/float(c) if m1==m2...
huggingface/pytorch-transformers
src/transformers/models/herbert/__init__.py
Python
apache-2.0
1,766
0.000566
# flake8: noqa # There's no way to ignore "F401 '...' imported but unused" warnings in this # module, but to preserve other warnings. So, don't check this module at all. # Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
r if is_tokenizers_available(): from .tokenization_herbert_fast import HerbertTokenizerFast else: import importlib import os import sys class _LazyModule(_BaseLazyModule): """ Module class that surfaces all objects but only performs associated imports when the ob
jects are requested. """ __file__ = globals()["__file__"] __path__ = [os.path.dirname(__file__)] def _get_module(self, module_name: str): return importlib.import_module("." + module_name, self.__name__) sys.modules[__name__] = _LazyModule(__name__, _import_structure)
oVirt/ovirt-hosted-engine-setup
src/ovirt_hosted_engine_setup/connect_storage_server.py
Python
lgpl-2.1
1,127
0
# # ovirt-hosted-engine-setup -- ovirt hosted engine setup # Copyright (C) 2015 Red Hat, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at...
; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 F...
lient import client from ovirt_hosted_engine_setup import constants as ohostedcons if __name__ == "__main__": ha_cli = client.HAClient() ha_cli.connect_storage_server( timeout=ohostedcons.Const.STORAGE_SERVER_TIMEOUT, )
schieb/angr
angr/procedures/posix/readdir.py
Python
bsd-2-clause
2,207
0.009515
import angr from collections import namedtuple import logging l = logging.getLogger(name=__name__) Dirent = namedtuple('dirent', ('d_ino', 'd_off', 'd_reclen', 'd_type', 'd_name')) class readdir(angr.SimProcedure): struct = None condition = None def run(self, dirp): # pylint: disable=arguments-differ ...
l.error('readdir SimProcedure is only implemented for AMD64') return 0 self._build_amd64() self.instrument() malloc = angr.SIM_PROCEDURES['libc']['malloc'] pointer = self.inline_call(malloc, 19 + 256).ret_expr self._store_amd64(pointer) return self.s...
ment the SimProcedure. The two useful variables you can override are self.struct, a named tuple of all the struct fields, and self.condition, the condition for whether the function succeeds. """ pass def _build_amd64(self): self.struct = Dirent(self.state.solver.BVV(0, 64),...
poppogbr/genropy
packages/test15/webpages/tools/server_store.py
Python
lgpl-2.1
1,125
0.006222
# -*- coding: UTF-8 -*- # """ServerStore tester""" class GnrCustomWebPage(object): py_requires = "gnrcomponents/testhandler:TestHandlerFull,storetester:StoreTester" dojo_theme = 'claro' def test_1_current_page(self, pane): """On current page """ self.common_form(pane, datapath='test_1') ...
e): """Set in external store""" center = self.common_pages_container(pane, height='350px', background='whitesmoke', datapath='test_2') self.common_form(center) def test_3_server_data(self, pane): """Server shared data """ center =...
ackground='whitesmoke', datapath='test_3') center.data('.foo.bar', _serverpath='xx') fb = center.formbuilder(cols=1, border_spacing='3px') fb.textbox(value='^.foo.bar', lbl='Server store value') fb.textbox(value='^.foo.baz', lbl='Value not in ...
tychoish/dtf
docs/bin/makefile_builder.py
Python
apache-2.0
6,931
0.002453
#!/usr/bin/python # Copyright 2012 10gen, 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 agreed ...
builder: raise MakefileError('Cannot add "' + block + '" to Makefile. ' + block + ' already exists.') else: self.builder[block] = [] self.section_break(block, block) def raw(self, lines, block='_all'): if type(lines) is list: o = [] for li...
with raw().') else: o.append(line) self._add_to_builder(data=o, block=block, raw=True) else: raise MakefileError('Cannot add non-list raw() content to Makefile.') # The following methods constitute the 'public' interface for # building makefile...
melrcm/Optimizepy
allocation_sharpe_optimizer.py
Python
lgpl-2.1
7,000
0.016
import datetime as dt import numpy as np import simulate_portfolio_allocation as smlt import all_permutes as permutes import get_data def allocation_op(symbols, exchange, allow_short, days = None, filter_symbols = 5, data_allocate = None, dt_start = None, dt_end = None): ''' Function ALLOCATION / SHARPE RATION OP...
a(symbols, exchange, dt_start, dt_end) # 2. Fli
p symbols & na_price if needed flip_symbols = symbols[:] if allow_short == 1: long_or_short = data_allocate[-1,1:] / data_allocate[0,1:] for i in range(len(long_or_short)): if long_or_short[i] < 1: data_allocate[:,i+1] = np.flipud(data_allocate[:,i+1]) ...
neurokernel/retina-lamina
examples/retlam_demo/retlam_demo.py
Python
bsd-3-clause
11,654
0.002231
#!/usr/bin/env python import os, resource, sys import argparse import numpy as np import networkx as nx import neurokernel.core_gpu as core from neurokernel.pattern import Pattern from neurokernel.tools.logging import setup_logger from neurokernel.tools.timing import Timer from neurokernel.LPU.LPU import LPU import...
essor = FileOutputProcessor([('V',None)], output_file, sample_interval=1) # retina also allows a subset of its graph to be t
aken # in case it is needed later to split the retina model to more # GPUs G = retina.get_worker_nomaster_graph() nx.write_gexf(G, gexf_file) (comp_dict, conns) = LPU.graph_to_dicts(G) retina_id = get_retina_id(retina_index) extra_comps = [PhotoreceptorModel, BufferPhoton] manager.add...
inspirehep/invenio-search
invenio_search/registry.py
Python
gpl-2.0
5,066
0.000395
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
y( 'searchext.units', DictModuleAutoDiscoverySubRegistry, 'units', keygetter=lambda key, value, new_value: value.__name__.split('.')[-1], valuegetter=lambda value: value.search_unit, registry_namespace=searchext, ) mappings_proxy = RegistryProxy( "searchext.mappings", PkgResourcesDirDiscoveryRegist...
t in out: out[os.path.basename(f)] = f return out mappings = LazyDict(create_mappings_lookup) ___all__ = ('mappings_proxy', 'mappings')
nemothekid/Colosseum--Year-3XXX
GameClient.py
Python
mit
7,613
0.005517
import Network from time import sleep from threading import Thread CALL_ROOMLIST = 0 CALL_WEAPLIST = 1 CALL_PLAYERLIST = 2 CALL_NEWPLAYER = 3 CALL_PLAYERLEFT = 4 CALL_CHAT = 5 CALL_PLAYERDAT = 6 CALL_ROOMSTAT = 7 CALL_LEAVEROOM = 8 CALL_SHOOT = 9 CALL_SCORE = 10 class GameClient(Network.Client): CONNECTING = 0 ...
inRoom(self, roomid, roomName, block=False): if block:
self.status = self.JOINING_ROOM self.sendDataReliable(Network.Structs.joinRoom.dataType, Network.Structs.joinRoom.pack(roomid)).join() # This function blocks... return self.onRoomSwitch(self.JOINING_ROOM, self.complete(self.JOINING_ROOM)) else: self.winnerId...
stickybath/BetaMaleBot
src/utilRegex/regex.py
Python
gpl-3.0
2,247
0.012461
import re from utilRegex import database class regex: def __init__(self, botCfg): """class initialization function """ #intitialize database variables self.db = database() #initialize regex variables self.phrase = '' self.url = '' #initialize s...
+ \ ' FROM phraseprint()' + \ ' f(id bigint, phrase text, username text)') records = self.db.cursor.fetchall() except: print 'utilRegex/regex.buildPhrase: failed to retrieve
records from database.' self.db.cursor.close() self.db.disconnect() return False #close database connection self.db.cursor.close() self.db.disconnect() #build pattern string if len(records) > 0: #only build the string if records are present ...
jawr/kontrolvm
apps/network/urls.py
Python
mit
239
0.004184
from d
jango.conf.urls.defaults import * urlpatterns = patterns('apps.network.views', url(r'^add/', 'add'), url(r'^edit/', 'edit'), url(r'^delete/(?P<pk>\d+)/', 'delete'), url(r'^(?P<pk>\d+)/', 'overview'), url(r'$', 'i
ndex'), )
opendaylight/spectrometer
server/spectrometer/api/gerrit.py
Python
epl-1.0
5,172
0.00116
#!/usr/bin/python # -*- coding: utf-8 -*- # @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0> ############################################################################## # Copyright (c) 2016 The Linux Foundation and others. # # All rights reserved. This program and the accompanying materials # are made available ...
ns a list of merged changes in a given repository by querying Gerrit. GET /gerrit/changes?param=<value> :arg str project: Project to query changes from. (required) :arg str branch: Branch to pull changes from. (default: master) JSON:: {
"changes": [ { "_number": 37706, "branch": "master", "change_id": "I4168e023b77bfddbb6f72057e849925ba2dffa17", "created": "2016-04-18 02:42:33.000000000", "deletions": 0, "hashtags": [], "id": "spect...
anestv/pa
test/myRequest.py
Python
artistic-2.0
1,697
0.030642
from external import requests as reqs class request: sessions = {0: reqs.Session()} # static def __init__(self, url, expect = {}, get = {}, post = {}): self.url = url self.get = get self.post = post self.expect = expect self.kind = 'POST' if post else 'GET' self.session = 0 ...
pect: if not expHeader in r.headers: print('No header "' + expHeader + '" found in response to ' + self.kind + ' request to ' + self.url) exit(1) if r.headers[expHeader] != self.e
xpect[expHeader]: print('Header "' + expHeader + '" in ' + self.kind + ' request to ' + self.url + ' was not '+ self.expect[expHeader] + ' but ' + r.headers[expHeader]) exit(1) print(' - ' + self.kind + ' request to ' + self.url + ' successful') def send(self, USE_SESSION): ...
fhoring/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/operations/paths_operations.py
Python
mit
2,859
0.001399
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
'host': self._serialize.url("self.config.host", self.config.host, 'str', skip_quote=True) } url = self._client.format_url(url, **path_format_arguments) # Construct parameters
query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if custom_headers: header_parameters.update(custom_headers) # Construct and send request request = self._client.get(url, ...
Terhands/saskdance
app/web/users/__init__.py
Python
gpl-3.0
23
0
__author__ = 'tere
sah'
punithpatil/tkinter-text-editor
help_menu.py
Python
mit
483
0.031056
from common_imports import * fr
om tkMessageBox import * import sys class Help(): def about(root): showinfo(title="About", message="This a simple text editor implemented in Python's Tkinter") def main(root,text,menubar): help = Help() helpMenu = Menu(menubar) helpMenu.add_command(label="About", command=help.about) menubar.ad...
helpMenu) root.config(menu=menubar) if __name__=="__main__": print ("Please run 'main.py'")
cvsuser-chromium/chromium
chrome/common/extensions/docs/server2/test_util.py
Python
bsd-3-clause
1,383
0.015184
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function import logging import os import sys def CaptureLogging(f): '''Call the function |f|, capturing any logging output ...
the decorated function. ''' return _ReplaceLogging(name, lambda _, *args: None) def _ReplaceLogging(name, replacement): def decorator(fn): def impl(*args, **optargs): saved = getattr(logging, name) setattr(logging, name, replacement) try: return fn(*args, **optargs) finally
: setattr(logging, name, saved) return impl return decorator def ReadFile(*path): with open(os.path.join(sys.path[0], '..', '..', *path)) as f: return f.read()
sharanramjee/TensorFlow-plant-and-animal-cell-image-classifier
label_image.py
Python
apache-2.0
1,364
0.004399
import tensorflow as tf, sys image_path = sys.argv[1] # Read in the image_data image_data = tf.gfile.FastGFile(image_path, 'rb').read() # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile("/cellule/retrained_labels.txt")] # Unpersists graph from ...
graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') with tf.Session() as sess: # Feed the image_data as input to the graph and get first prediction softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') predictions = sess.run(softma...
en(predictions[0]):][::-1] for node_id in top_k: human_string = label_lines[node_id] score = predictions[0][node_id] print('%s (score = %.5f)' % (human_string, score)) # To run the program - docker run -it -v ~/Desktop/cellule/:/cellule/ gcr.io/tensorflow/tensorflow:latest-devel # Enter t...
gwpy/gwsumm
gwsumm/plot/guardian/__main__.py
Python
gpl-3.0
6,353
0
# -*- coding: utf-8 -*- # Copyright (C) Duncan Macleod (2018) # # This file is part of GWSumm. # # GWSumm 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) ...
ype=str, help="suffix of INI tab section to read, e.g. give " "--section='ISC_LOCK' to read [tab-ISC_LOCK] " "section, defaults to
{node}", ) parser.add_argument( '-t', '--epoch', type=to_gps, help="Zero-time for plot, defaults to GPSSTART", ) parser.add_argument( '-p', '--plot-params', action='append', default=[], help="extra plotting keyword argument", ) ...
hmgoalie35/ui_testing_tool
ui_testing.py
Python
mit
29,427
0.004826
# Import necessary modules from selenium.common.exceptions import NoSuchElementException from PIL import Image import platform import os import inspect import time import math import sys # Valid methods selenium can use to search for an element on a page. See # selenium python API for more info if desired. VALID_METHO...
', 'partial_link_text', 'tag_name', 'class_name', 'css_selector'. This is to be passed if you want to crop the screenshot to just an element of the page (ex: just have a picture of a certain button). It is required if you pass in element_specifier. [OPTIONAL] element_specifier: the element_...
This is to be passed if you want to crop the screenshot to just an element of the page (ex: just have a picture of a certain button). It is required if you pass in method. *****Element cropping is not supported on chrome!!!! This is due to a limitation of chromedriver***** If method is pa...
mkhutornenko/incubator-aurora
src/test/python/apache/aurora/executor/test_thermos_executor.py
Python
apache-2.0
18,559
0.009268
# # 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 ...
_runner_class=runner_class, ) def make_executor( proxy_driver, checkpoint_root, task, ports={}, fast_status=False, runner_class=ThermosTaskRunner, status_providers=()): status_manager_class = FastStatusManager if fast_status else StatusManager runner_provider = make_provider(checkpo...
runner_provider=runner_provider, status_manager_class=status_manager_class, sandbox_provider=DefaultTestSandboxProvider, status_providers=status_providers, ) ExecutorTimeout(te.launched, proxy_driver, timeout=Amount(100, Time.MILLISECONDS)).start() task_description = make_task(task, assigned_po...
robwarm/gpaw-symm
doc/tutorials/lattice_constants/al.agts.py
Python
gpl-3.0
1,167
0.000857
def agts(queue): al = queue.add('al.py', ncpus=8, walltime=12 * 60) queue.add('al.agts.py', deps=[al], creates=['Al_conv_ecut.png', 'Al_conv_k.png']) if __name__ == '__main__': import pylab as plt from ase.utils.eos import EquationOfState from ase.io import read def fit(filename)...
s, energies) v0, e0, B = eos.fit() return (4 * v0)**(1 / 3.0) cutoffs = range(200, 501, 50) a = [fit('Al-%d.txt' % ecut) for ecut in cutoffs] plt.figure(figsize=(6, 4)) plt.plot(cutoffs, a, 'o-') plt.axis(ymin=4.03, ymax=4.05) plt.xlabel('Plane-wave cutoff energy [eV]') plt....
g') kpoints = range(4, 17) plt.figure(figsize=(6, 4)) a = [fit('Al-%02d.txt' % k) for k in kpoints] plt.plot(kpoints, a, '-') plt.xlabel('number of k-points') plt.ylabel('lattice constant [Ang]') plt.savefig('Al_conv_k.png') plt.show()
Code4SA/umibukela
umibukela/migrations/0002_auto_20160120_1337.py
Python
mit
1,080
0.001852
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('umibukela', '0001_initial'), ] operations = [ migrations.CreateModel( name='SurveyType', fields=[ ...
name='partner', name='context_statement', field=models.TextField(), ), migrations.AlterField( model_name='partner', name='intro_statement', field=models.TextField(), ), migrations.AddField( model_name='cycleresultset...
), ]
khchine5/xl
lino_xl/lib/cal/models.py
Python
bsd-2-clause
36,436
0.001729
# -*- coding: UTF-8 -*- # Copyright 2011-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) from __future__ import unicode_literals from builtins import str import six import datetime from django.db import models from django.db.models import Q from django.conf import settings from django.core.validat...
return "{} {}".format(t, u) def w(pc, verbose_name): def func(fld, obj, ar): # obj is the DailyPlannerRow instance pv = ar.param_values qs = Event.objects.f
ilter(event_type__planner_column=pc) if pv.user: qs = qs.filter(user=pv.user) if pv.date: qs = qs.filter(start_date=pv.date) if obj.start_time: qs = qs.filter(start_time__gte=obj.start_time, ...
noironetworks/networking-cisco
networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/203b495958cf_add_port_profile_delete_table_for_ucsm_.py
Python
apache-2.0
1,179
0.000848
# Copyright 2017 Cisco Systems, 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 o...
ibuted under the License is distributed on an "AS
IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from alembic import op import sqlalchemy as sa """Add Port Profile delete table for UCSM plugin Revision ID: 203b4959...
digitalocean/netbox
netbox/dcim/migrations/0104_correct_infiniband_types.py
Python
apache-2.0
914
0
from django.db import migrations INFINIBAND_SLUGS = ( ('inifiband-sdr', 'infiniband-sdr'), ('inifiband-ddr', 'infiniband-ddr'), ('inifiband-qdr', 'infiniband-qdr'), ('inifiband-fdr10', 'infiniband-fdr10'), ('inifiband-fdr', 'infiniband-fdr'), ('inifiban
d-edr', 'infiniband-edr'), ('inifiband-hdr', 'infiniband-hdr'), ('inifiband-ndr', 'infiniband-ndr'), ('inifiband-xdr', 'infin
iband-xdr'), ) def correct_infiniband_types(apps, schema_editor): Interface = apps.get_model('dcim', 'Interface') for old, new in INFINIBAND_SLUGS: Interface.objects.filter(type=old).update(type=new) class Migration(migrations.Migration): dependencies = [ ('dcim', '0103_standardize_desc...
jn-gautier/exercices_moodle
phys/elec/elec_base.py
Python
gpl-3.0
23,892
0.054767
#! /usr/bin/python3 # -*- coding: utf-8 -*- import random """A faire : convertir les questions en cloze pour gérer les unités réécrire les feedback en respectant la présentation DIER écrire les dernière questions """ def convert_sci(nombre): if (nombre>1000) or (nombre<0.1): nombre_sciE='%.4E' %(nomb...
%(self.puissance) self.unites='[W]' self.unites_fausses=['[C]','[s]','[A]','[ohm]','[W]','[J]','[V]'] random.shuffle(self.unites_fausses) def type_8(self): """ P=Uq/dt """ self.enonce="Une batterie contenant une charge totale de %s [C] est capa...
te batterie?"%(self.charge,self.potentiel,self.duree
jittat/adm2
scripts/export_scores_for_registered.py
Python
agpl-3.0
770
0.011688
import codecs import sys import os from django.conf import settings from django_bootstrap import bootstrap bootstrap(__file__) from result.models import NIETSScores from application.models import Applicant from confirmation.models import StudentRegistration, AdmissionWaiver def main(): uses_nat_id = ('--nat' in s...
d not AdmissionWaiver.is_waived(a): niets_scores = a.NIETS_scores k = a.id if uses_nat_id: k = a.national_id
print "%s,%f" % (k,niets_scores.get_score()) c += 1 if __name__=='__main__': main()
plilja/adventofcode
2018/day19/day19.py
Python
gpl-3.0
2,591
0.000772
import sys from math import sqrt def opr(f): def op(registers, args): registers[args[2]] = f(registers[args[0]], registers[args[1]]) return op def opi(f): def op(registers, args): registers[args[2]] = f(registers[args[0]], args[1]) return op def opir(f): def op(registers, args)...
if registers[ip] + 1 >= len(instructions): break registers[ip] += 1 return registers[0] def step2(ip, instructions): registers = [1, 0, 0, 0, 0, 0] while 0 <= registers[ip] < len(instructions): if 2 == registers[ip] or 13 == r
egisters[ip]: # The instructions are an algorithm for summing divisors of register 2 num = registers[2] r = 0 for i in range(1, int(sqrt(num)) + 1): if num % i == 0: r += i + num // i return r instruction = instruct...