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
aroquemaurel/Cuis-In
cuisin/tasting/models.py
Python
gpl-2.0
1,752
0.001712
from django.db import models class TastingCategory(models.Model): title = models.CharField(max_length=128) singularTitle = models.CharField(max_length=128) slug = models.SlugField(max_length=128) def __unicode__(self): return self.title class Tasting(models.Model): category = models.For...
ax_length=128) def __unicode__(self): return self.type class CoffeeCountry(models.Model): country = models.CharField(max_length=128) def __unicode__(self): return self.country class Whisky(Tasting): old = models.IntegerField() type = models.ForeignKey('WhiskyType', on_delete=mo...
class Coffee(Tasting): country = models.ForeignKey('CoffeeCountry', on_delete=models.CASCADE) altitude = models.IntegerField() strength = models.IntegerField() def __str__(self): return self.category.title + " " + self.country.country + " " + self.name class Wine(Tasting): year = models.I...
pusnik/django-libtech-emailuser
emailuser/models.py
Python
bsd-3-clause
3,681
0.002717
from django.core.exceptions import ImproperlyConfigured from django.core.mail import send_mail from django.db import models from django.utils import timezone from django.utils.http import urlquote from django.utils.translation import ugettext_lazy as _ import warnings from django.contrib.auth.models import ( BaseUs...
en username, email and password. """ #assert False, "in user manager" now = timezone.now() if not email: raise ValueError('The given email must be set') #email = UserManager.normalize_email(email) user = EmailUser(email=email, is_staf...
ord) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): u = self.create_user(email, password, **extra_fields) u.is_staff = True u.is_active = True u.is_superuser = True u.save(using=self._db) return u ...
willkg/postatus
postatus/status.py
Python
bsd-3-clause
4,559
0.001535
import requests class Status(object): SKIP_LOCALES = ['en_US'] def __init__(self, url, app=None, highlight=None): self.url = url self.app = app self.highlight = highlight or [] self.data = [] self.created = None def get_data(self): if self.data: ...
nd({ 'locale': loc, 'percent': percent, 'total': total, 'translated': translated, 'untranslated': total - translated, 'untranslated_words': untranslated_words
}) output['highlighted'] = highlighted locales = [] for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']): if loc in self.SKIP_LOCALES: continue item = get_item(loc_data) total = item.get('total', -1) translated =...
eneldoserrata/marcos_openerp
addons/report_xls/report_xls.py
Python
agpl-3.0
9,067
0.002207
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2013 Noviat nv/sa (www.noviat.com). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under...
ap': 'align: wrap true;', 'top': 'align: vert top;', 'bottom': 'align: vert bottom;', } # TO DO: move parameters supra to configurable data def creat
e(self, cr, uid, ids, data, context=None): self.pool = pooler.get_pool(cr.dbname) self.cr = cr self.uid = uid report_obj = self.pool.get('ir.actions.report.xml') report_ids = report_obj.search(cr, uid, [('report_name', '=', self.name[7:])], context=context) ...
grevutiu-gabriel/sympy
sympy/concrete/summations.py
Python
bsd-3-clause
24,412
0.001106
from __future__ import print_function, division from sympy.concrete.expr_with_limits import AddWithLimits from sympy.concrete.expr_with_intlimits import ExprWithIntLimits from sympy.core.function import Derivative from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Du...
nts) return f def _eval_derivative(self, x): """ Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. ...
ned. """ # diff already confirmed that x is in the free symbols of self, but we # don't want to differentiate wrt any free symbol in the upper or lower # limits # XXX remove this test for free_symbols when the default _eval_derivative is in if x not in self.free_symbols:...
dtg01100/edi-to-csv-converter
button.py
Python
gpl-3.0
224
0.03125
import Tkinter import tkMessageBox top = Tkinter.Tk() def helloCallBack(): tkMessageBox.showinfo( "Hell
o Python", "Hello World") B = Tkinter.Button(top, text ="Hello", command = helloCallBack) B.pack() top.mainlo
op()
jmolloy/pedigree
scripts/buildLibc.py
Python
isc
2,327
0.005161
#! /usr/bin/env python # coding=utf8 # # Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. #...
, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # import tempfile import shutil import os def doLibc(bu...
= os.getcwd() os.chdir(tmpdir) shutil.copy(inputLibcA, tmpdir + "/libc.a") os.system(ar + " x libc.a") glue = glue_name shutil.copy(glue, tmpdir + "/" + os.path.basename(glue_name)) shutil.copy(pedigree_c_name, tmpdir + "/" + os.path.basename(pedigree_c_name)) objs_to_remove = ["init", "g...
kshimo69/IkaLog
ikalog/outputs/alive_squids_csv.py
Python
apache-2.0
3,445
0.001462
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # IkaLog # ====== # Copyright (C) 2015 Takeshi HASEGAWA # # 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/l...
g: print('tower sample = %s', sample) time = sample[0] samp
le = sample[1] csv = "%s%d, %d, %d, %d\n" % ( csv, time, sample['pos'], sample['max'], sample['min']) self.write_record('%s/%s_tower.csv' % (self.dest_dir, basename), csv) ## # on_game_individual_result Hook # @param self The Object Pointer # @param context I...
SimenB/thefuck
tests/rules/test_git_push_without_commits.py
Python
mit
659
0
import pytest from thefuck.types import C
ommand from thefuck.rules.git_push_without_commits import ( fix, get_new_command, match, ) command = 'git push -u origin master' expected_error = ''' error: src refspec master does not match any. error: failed to push some refs to 'git@github.com:User/repo.git' ''' @pytest.mark.parametrize('command', [Co...
rametrize('command, result', [( Command(command, expected_error), fix.format(command=command), )]) def test_get_new_command(command, result): assert get_new_command(command) == result
lordscales91/blender_mmd_tools
mmd_tools/properties/bone.py
Python
mit
4,418
0.001132
# -*- coding: utf-8 -*- from bpy.types import PropertyGroup from bpy.props import StringProperty, IntProperty, BoolProperty, FloatProperty, FloatVectorProperty from mmd_tools.core.bone import FnBone def _updateMMDBoneAdditionalTransform(prop, context): prop['is_additional_transform_dirty'] = True p_bone = co...
description='Local z-axis', subtype='XYZ', size=3, default=[0, 0, 1], ) is_tip = BoolProperty( name='Tip Bone', description='Is zero length bone', default=False, ) ik_rotation_constraint = FloatProperty( name='IK Rotation Constraint',...
additional_rotation = BoolProperty( name='Additional Rotation', description='Additional rotation', default=False, update=_updateMMDBoneAdditionalTransform, ) has_additional_location = BoolProperty( name='Additional Location', description='Additional location'...
ntt-sic/neutron
neutron/plugins/ml2/drivers/mech_openvswitch.py
Python
apache-2.0
2,288
0
# Copyright (c) 2013 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 ...
ensions import portbindings from neutron.openstack.common import log from neutron.plugins.ml2 import driver_api as api from neutron.plugins.ml2.drivers import mech_agent LOG = log.getLogger(__name__) class OpenvswitchMechanismDriver(mech_agent.AgentMechanismDriverBase): """Attach to networks using openvswitch L2...
anismDriver integrates the ml2 plugin with the openvswitch L2 agent. Port binding with this driver requires the openvswitch agent to be running on the port's host, and that agent to have connectivity to at least one segment of the port's network. """ def __init__(self): super(Openvswitc...
klangner/iclogger
src/dev_server.py
Python
bsd-2-clause
223
0.004484
# -*- coding: utf-8 -*- ''' Created on 2014-04-09 @author: Krzysztof Langner ''
' # import iclogger.file_logger as Logger import iclogger.dynamodb_logger as Logger if __name__ == "__main__": Logger.app.run(de
bug=True)
daniellawrence/external_naginator
tests/test_basic.py
Python
mit
341
0.002933
import unittest c
lass TestGenearate(unittest.TestCase): def setUp(self): self.seq = range(10) def test_smoke(self): "Basic smoke test that should pickup any silly errors" import external_naginator external_naginator.__name__ == "external_naginator" if __name__ == '
__main__': unittest.main()
Jan-zou/LeetCode
python/Array/53_maximum_subarray.py
Python
mit
942
0.003297
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' Description: Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarr
ay [4,−1,2,1] has the largest sum = 6. More practice: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. Tags: Array, Dynami
c Programming, Divide and Conquer ''' class Solution(object): # O(n) runtime; O(1) space - 局部最优和全局最优解法 def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ global_max, local_max = float("-inf"), 0 for i in nums: local_max = max(i, i+...
citrix-openstack/horizon
horizon/horizon/dashboards/nova/containers/tests.py
Python
apache-2.0
10,798
0.000648
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
def test_index(self): self.mox.StubOutWithMock(api, 'swift_get_containers') api.swift_get_containers( IsA(http.HttpRequest), marker=None).AndReturn( ([self.container], False)) self.mox.ReplayAll() res = self.client.get(CONTAINER_INDEX_URL) ...
ontext['table'].data self.assertEqual(len(containers), 1) self.assertEqual(containers[0].name, 'containerName') def test_delete_container(self): self.mox.StubOutWithMock(api, 'swift_delete_container') api.swift_delete_container(IsA(http.HttpRequest), ...
vileopratama/vitech
src/addons/calendar/calendar.py
Python
mit
87,632
0.004211
# -*- coding: utf-8 -*- import pytz import re import time import openerp import openerp.service.report import uuid import collections import babel.dates from werkzeug.exceptions import BadRequest from datetime import datetime, timedelta from dateutil import parser from dateutil import rrule from dateutil.relativedelta...
import request from operator import itemgetter from openerp.exceptions import UserError import logging _logger = logging.getLogger(__name__) def calendar_id2real_id(calendar_id=None, with_date=False): """ Convert a "virtual/recurring event id" (type string) into a real event id (type int). E.g. virtual/...
so it will return 4. @param calendar_id: id of calendar @param with_date: if a value is passed to this param it will return dates based on value of withdate + calendar_id @return: real event id """ if calendar_id and isinstance(calendar_id, (basestring)): res = filter(None, calendar_id.split...
jonaustin/advisoryscan
django/django/test/utils.py
Python
mit
6,373
0.006433
import sys, time from django.conf import settings from django.db import connection, transaction, backend from django.core import management, mail from django.dispatch import dispatcher from django.test import signals from django.template import Template # The prefix to put on the default database name when creating # ...
ginal_render mail.SMTPConnection = mail.original_SMTPConnection del mail.original_SMTPConnection del mail.outbox def _set_autocommit(connection): "Make sure a connection is in autocommit mode." if hasattr(connection.connection, "autocommit"): con
nection.connection.autocommit(True) elif hasattr(connection.connection, "set_isolation_level"): connection.connection.set_isolation_level(0) def get_mysql_create_suffix(): suffix = [] if settings.TEST_DATABASE_CHARSET: suffix.append('CHARACTER SET %s' % settings.TEST_DATABASE_CHARSET) i...
SpaceVim/SpaceVim
bundle/defx.nvim/rplugin/python3/defx/column/size.py
Python
gpl-3.0
1,686
0
# ============================================================================ # FILE: size.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # License: MIT license # ============================================================================ from defx.base.column import Base, Highlights from defx.context im...
.is_dir(): return (' ' * self._length, []) size = self._get_size(path.stat().st_size) text = '{:>6s}{:>3s}'.format(size[0], size[1]) return (text, [(self.highlight_name, self.start, self._length)]) def _get_size(self, size: float) -> typing.Tuple[str, str]: multiple = 10...
ix in suffixes: size /= multiple if size < multiple: return ('{:.1f}'.format(size), suffix) return ('INF', '') def length(self, context: Context) -> int: return self._length def highlight_commands(self) -> typing.List[str]: commands: typing.List[...
jdpepperman/houseSimulation
modules/House.py
Python
gpl-2.0
2,102
0.001903
import random from Person import Person class House(object): def __init__(self): self.rooms = [] self.actors = [] def __str__(self): house_string = "" for room in self.rooms: house_string = house_string + str(room) + "\n\n" return house_string[:-2] def...
rue return False def tick(self): for actor in self.actors: actor.tick() def toString_people(self): string = "People in house\n[name,\t\tage,\thngr,\tbthrm,\tstatus]:\n" for actor in self.actors: if isinstance(actor, Person): if len(a
ctor.name) < 6: string = (string + "[" + actor.name + ",\t\t" + str(actor.age) + ",\t" + str(actor.hunger) + ",\t" + str(actor.bathroom_need) + ",\t" + actor.status + "]\n") else: string = (string + "[" +...
tensorflow/data-validation
tensorflow_data_validation/statistics/generators/sparse_feature_stats_generator.py
Python
apache-2.0
7,813
0.004736
# Copyright 2019 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, ...
pb2.SparseFeature]]: """Helper function that is used in finding sparse featur
es in a tree.""" result = [] for sf in container.sparse_feature: # Sparse features do not have a struct_domain, so they cannot be parent # features. Thus, once this reaches a sparse feature, add it to the # result. result.append((parent_path.child(sf.name), sf)) for f in container.fe...
murphybytes/royalty
models/school.py
Python
mit
841
0.042806
# -*- coding: utf-8 -*- from openerp import models, fields, api class School(models.Model): _name = 'royalty.school' name = fields.Char('Name', size=255, required=True) address_line1 = fields.Char( 'Address 1', size=255 ) address_line2 = fields.Char( 'Address 2', size=255 ) city...
roduct.product', 'school_id', 'Products' ) contacts = fields.One2many( 'royalty.contact', 'school_id', 'Co
ntacts' )
ujjwal96/mitmproxy
test/mitmproxy/proxy/protocol/test_http1.py
Python
mit
3,325
0.000902
from unittest import mock import pytest from mitmproxy.test import tflow from mitmproxy.net.http import http1 from mitmproxy.net.tcp import TCPClient from mitmproxy.test.tutils import treq from ... import tservers class TestHTTPFlow: def test_repr(self): f = tflow.tflow(resp=True, err=True) asse...
rfile.readline() == b"\r\n" client.wfile.write(b"0123456789abcdef\r\n") client.wfile.flush() resp = http1.read_response(client.rfile, treq()) assert resp.status_code == 200 client.finish() client.close() class TestHeadContentLength(tservers.HTTPProxyTest): def t...
"""head:'%s/p/200:h"Content-Length"="42"'""" % self.server.urlbase ) assert resp.headers["Content-Length"] == "42" class TestStreaming(tservers.HTTPProxyTest): @pytest.mark.parametrize('streaming', [True, False]) def test_streaming(self, streaming): class Stream: ...
liyi193328/seq2seq
run_scripts/vocab.py
Python
apache-2.0
3,713
0.011869
#encoding=utf-8 from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = "liyi" __date__ = "2017-07-06" import os import sys import argparse import collections import logging import codecs import charset def generate_vocab(source_paths, save_path, d...
True if skip is True: break if skip is False: new_vocab_cnt[word] = vocab_cnt[word] vocab_cnt = new_vocab_cnt logging.info("Found %d unique tokens in the vocabulary.", len(vocab_cnt)) # Filter tokens below the frequency threshold if min_freq > 0: filtered_tokens = [(w,
c) for w, c in vocab_cnt.most_common() if c > min_freq] cnt = collections.Counter(dict(filtered_tokens)) logging.info("Found %d unique tokens with frequency > %d.", len(vocab_cnt), min_freq) # Sort tokens by 1. frequency 2. lexically to break ties word_with_counts = vo...
Pontianak/Python-For-Informatics-Assignments
2.2.py
Python
mit
58
0.017241
name = raw_input("En
ter your name:") print
"Hello" , name
tomjelinek/pcs
pcs/cli/common/parse_args.py
Python
gpl-2.0
21,092
0.000379
from typing import ( Iterable, Mapping, Union, ) from pcs.cli.common.errors import ( SEE_MAN_CHANGES, CmdLineInputError, ) from pcs.common.str_tools import ( format_list, format_plural, ) from pcs.common.tools import timeout_to_seconds ModifierValueType = Union[None, bool, str] ARG_TYPE_D...
options[name] = [value] else: options[name] = value elif name in allowed_repeatable_options: options[name].append(value) elif options[name] != value: raise CmdLineInputError( ( "duplicate option '{0}' with different ...
return options def prepare_options_allowed( cmdline_args, allowed_options, allowed_repeatable_options=() ): """ Get a dict of options from cmdline key=value args, raise on unallowed key iterable cmdline_args -- command line arguments iterable allowed_options -- list of allowed options ite...
Zing22/Moogle
moogle/mooc/apps.py
Python
mit
83
0
from
django.apps import AppConfig class MoocConfig(AppConfig
): name = 'mooc'
escorciav/amcs211
hw3/hw3_2a.py
Python
bsd-2-clause
502
0.007968
import sympy x1, x2 = sympy.symbols('x1 x2') f = 100*(x2 - x1**2)**2 + (1-x1)**2 df_dx1 = sympy.diff(f,x1) df_dx2 = sympy.diff(f,x2) H = sympy.hessian(f, (x1, x2)) xs = sympy.solve([df_dx1, df_dx2], [x1, x2]) H_xs = H.subs([(x1,xs[0][0]), (x2,xs[0][1])]) lambda_xs = H_xs.eigenvals() count = 0 for i in lambda_xs.ke...
alf() <= 0: count += 1 if count == 0: prin
t 'Local minima' elif count == len(lambda_xs.keys()): print 'Lacal maxima' else: print 'Saddle point'
supriti/DeepSea
srv/modules/runners/net.py
Python
gpl-3.0
8,475
0.009558
# -*- coding: utf-8 -*- import logging import re import salt.client from netaddr import IPNetwork, IPAddress log = logging.getLogger(__name__) def ping(cluster = None, exclude = None, **kwargs): """ Ping all addresses from all addresses on all minions. If cluster is passed, restrict addresses to public...
log.debug( "ping: search {} ".format(search)) addresses = local.cmd(search , 'grains.get', [ 'ipv4' ], expr_form="compound") addresses = _flatten(addresses.values()) # Lazy loopback removal - use ipaddress when adding IPv6 try: if addresses: addresses.r...
r ex_ip in exclude_iplist: log.debug( "ping: removing {} ip ".format(ex_ip)) addresses.remove(ex_ip) except ValueError: log.debug( "ping: remove {} ip doesn't exist".format(ex_ip)) pass #print addresses results = local.cmd(search, 'multi.pi...
patrickleweryharris/anagram-solver
anagram_solver/anagram_solver.py
Python
mit
1,532
0
#!/usr/local/bin/python3.5 import itertools import sys from .stuff import word_set __version__ = "1.1.0" def find_possible(lst): """ Return all possible combinations of letters in lst @type lst: [str] @rtype: [str] """ returned_list = [] for i in range(0, len(lst) + 1): for subs...
possible = '' for letter in subset: possible += letter if len(possible) == len(lst): # itertools.permutations returns smaller lists r
eturned_list.append(possible) return returned_list def return_words(lst, word_set): """ Return combinations in that are words in word_set @type lst: [str] @type word_set: set(str) @rtype: [str] """ returned_list = [] for word in lst: if word in word_set or word.capitaliz...
nok/sklearn-porter
examples/estimator/classifier/RandomForestClassifier/js/basics_embedded.pct.py
Python
mit
1,213
0.004122
# %% [markdown] # # sklearn-porter # # Repository: [https://github.com/nok/sklearn-porter](https://github.com/nok/sklearn-porter) # # ## RandomForestClassifier # # Documentation: [sklearn.ensemble.RandomForestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html) # %...
ode 2/dev/null; then # node RandomForestClas
sifier.js 1 2 3 4 # fi
evernym/plenum
plenum/bls/bls_bft_replica_plenum.py
Python
apache-2.0
16,403
0.002561
from typing import Optional from common.serializers.serialization import state_roots_serializer from crypto.bls.bls_bft import BlsBft from crypto.bls.bls_bft_replica import BlsBftReplica from crypto.bls.bls_multi_signature import MultiSignature, MultiSignatureValue from crypto.bls.indy_crypto.bls_crypto_indy_crypto im...
[TXN_PAYLOAD_DATA]
for lid, sig in commit.blsSigs.items(): lid = int(lid) if lid not in audit_payload[AUDIT_TXN_STATE_ROOT] or lid not in audit_payload[AUDIT_TXN_LEDGER_ROOT]: return BlsBftReplicaPlenum.CM_BLS_SIG_WRONG if not self._validate_signature(sender, sig, ...
Avinash-Raj/appengine-django-skeleton
todo/migrations/0001_initial.py
Python
bsd-3-clause
599
0.001669
# -*- c
oding: utf-8 -*- # Generated by Django 1.9 on 2015-12-28 14:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Employee', ...
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('s_no', models.IntegerField()), ('name', models.CharField(max_length=200)), ], ), ]
helixyte/TheLMA
thelma/repositories/rdb/schema/tables/moleculedesignlibrary.py
Python
mit
1,817
0.002201
""" This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Molecule design set library table. """ from sqlalchemy import CheckConstraint from sqlalchemy import Column from sqlalchemy import Float from sqlalchemy impo...
__docformat__ = "reStructuredText en" __all__ = ['create_table'] def create_table(metadata, rack_layout_tbl, molecule_design_pool_set_tbl): "Table factory." tbl = Table('molecule_design_library', metadata, Column('molecule_design_library_id', Integer, primary_key=True), Column(...
molecule_design_pool_set_id, ondelete='CASCADE', onupdate='CASCADE'), nullable=False), Column('label', String, nullable=False, unique=True), Column('final_volume', Float, CheckConstraint('final_volume > 0'...
maxim-borisyak/craynn
craynn/updates/__init__.py
Python
mit
121
0.008264
from .careful import * from .noisy import *
from . import streams from . import resetable from
lasagne.updates import *
motlib/mqtt-ts
src/pub/evtpub.py
Python
gpl-3.0
1,817
0.003302
'''Publish sensor events to MQTT broker.''' import logging import paho.mqtt.publish as mqtt_pub import paho.mqtt.client as mqtt import socket class MqttPublisher(): '''Publish sensor events to an MQTT broker.''' def __init__(self, broker, topic_prefix='/sensors'): '''Initialize a MqttPublisher inst...
# the exception and try again next time. try: topic = self.get_topic(evt) msg = "Publishing to topic '{0}'." logging.debug(msg.format(topic)) # This fixes the protocol version to MQTT v3.1, because # the current version of the MQTT broker avail...
name=self.broker, protocol=mqtt.MQTTv31) except: logging.exception('Publish of MQTT value failed.') def publish_events(self, evts): '''Publish a list of sensor events.''' for evt in evts: self.publish_event(evt)
shiroyuki/passerine
test/ft/db/test_uow_association_one_to_many.py
Python
mit
4,063
0.001969
from ft.db.dbtestcase import DbTestCase from passerine.db.session import Session from passerine.db.common import ProxyObject from passerine.db.uow import Record from passerine.db.entity import entity from passerine.db.mapper import link, CascadingType, AssociationType @entity('test_db_uow_ass_one_to_many_computer') cl...
architect = Developer('architect', delegates=[boss.delegates[0]]) self.session.persist(architect) self.session.flush() self.session.delete(architect) self.session.delete(boss) self.session.flush() count = len(c.filter()) self.assertEqual(0, count, 'There shoul...
__data_provider(self): return [ { 'class': Developer, 'fixtures': [ {'_id': 1, 'name': 'a'}, {'_id': 2, 'name': 'b'}, {'_id': 3, 'name': 'boss', 'delegates': [1, 2]} ] } ]...
HaebinShin/tensorflow
tensorflow/tools/test/run_and_gather_logs.py
Python
apache-2.0
3,287
0.006693
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
s) if not flag.startswith("-i")] build_config.cc_flags.extend(cc_flags) return build_config def main(unused_args): test_name = FLAGS.test_name test_args = FLAGS.test_args test_results, _ =
run_and_gather_logs_lib.run_and_gather_logs( test_name, test_args) # Additional bits we receive from bazel test_results.build_configuration.CopyFrom(gather_build_configuration()) serialized_test_results = text_format.MessageToString(test_results) if not FLAGS.test_log_output: print(serialized_test_...
sunqm/pyscf
pyscf/cc/ccsd_t.py
Python
apache-2.0
10,987
0.012469
#!/usr/bin/env python # Copyright 2014-2020 The PySCF Developers. 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 # # U...
umpy.int32) oo_ir_loc = oo_ir_loc.astype(numpy.int32) if dtype == numpy.complex128: drv = _ccsd.libcc.CCsd_t_zcontract else: drv = _ccsd.libcc.CCsd_t_contract et_sum = numpy.zeros(1, dtype=dtype) def contract(a0, a1, b0, b1, cache): cache_row_a, cache_col_a, cache_row_b, cach...
col_b = cache drv(et_sum.ctypes.data_as(ctypes.c_void_p), mo_energy.ctypes.data_as(ctypes.c_void_p), t1T.ctypes.data_as(ctypes.c_void_p), t2T.ctypes.data_as(ctypes.c_void_p), vooo.ctypes.data_as(ctypes.c_void_p), fvo.ctypes.data_as(ctypes.c_void_p), ...
alex-ip/agdc
api/source/main/python/datacube/api/__init__.py
Python
bsd-3-clause
6,195
0.002744
# =============================================================================== # Copyright (c) 2014 Geoscience Australia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions...
NTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PR...
ER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # =============================================================================== from datacube.api.query import Month __author__ = "S...
fsuarez6/rate_position_controller
scripts/bubble_technique.py
Python
bsd-3-clause
12,314
0.013805
#! /usr/bin/env python """ Notes ----- Calculations are carried out with numpy.float64 precision. This Python implementation is not optimized for speed. Angles are in radians unless specified otherwise. Quaternions ix+jy+kz+w are represented as [x, y, z, w]. """ import rospy # Messages from std_msgs.msg import Float...
f.rate_gain * penetration) / self.position_ratio # Move the workspace self.slave_synch_pos = self.slave_pos - self.master_pos / self.position_ratio return 'stay' else: self.command_pos = np.array(self.slave_pos) self.force_feedback = np.zeros(3) self.loginfo('State machine transi...
.cb_interface(outcomes=[
kobotoolbox/kpi
kpi/views/v2/user_asset_subscription.py
Python
agpl-3.0
863
0
# coding: utf-8 from rest_framework import viewsets from kpi.models import UserAssetSubscription from kpi.serializers.v2.user_asset_subscription import ( UserAssetSubscriptionSerializer, ) from kpi.utils.object_permission import get_database_user class UserAssetSubscriptionViewSet(viewsets.ModelViewSet): que...
) serializer_class = UserAssetSubscriptionSerializer lookup_field = 'uid' def get_queryset(self): user = get_database_user(self.request.user) criteria = {'user':
user} if 'asset__uid' in self.request.query_params: criteria['asset__uid'] = self.request.query_params[ 'asset__uid'] return UserAssetSubscription.objects.filter(**criteria) def perform_create(self, serializer): serializer.save(user=self.request.user)
artourkin/Cinnamon
files/usr/share/cinnamon/desklets/launcher@cinnamon.org/editorDialog.py
Python
gpl-2.0
8,165
0.004776
#!/usr/bin/env python2 #-*-indent-tabs-mode: nil-*- import sys import os.path import gi from gi.repository import Gtk, Gio SCHEMAS = "org.cinnamon.desklets.launcher" LAUNCHER_KEY = "launcher-list" HOME_DIR = os.path.expanduser("~")+"/" CUSTOM_LAUNCHERS_PATH = HOME_DIR + ".cinnamon/panel-launchers/" EDITOR_DIALOG_UI...
Icon=" + icon_name + "\n"] _file.writelines(write_list) _file.close() return file_name class Application: def __init__(self, file_name): self.file_name = file_name self._path = None
self.icon_name = None self.title = None self.command = None if (os.path.exists(CUSTOM_LAUNCHERS_PATH + file_name)): self._path = CUSTOM_LAUNCHERS_PATH + file_name elif (os.path.exists("/usr/share/applications/" + file_name)): self._path = "/usr/share/applic...
oliver-sanders/cylc
tests/unit/tui/test_data.py
Python
gpl-3.0
1,331
0
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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 Licen...
NY WARRANTY; without even the implied warranty of # MERCHANTABILITY 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/>. import cylc.flo...
a GraphQL mutation with the args filled in.""" arg_types = { 'foo': 'String!', 'bar': '[Int]' } monkeypatch.setattr(cylc.flow.tui.data, 'ARGUMENT_TYPES', arg_types) assert generate_mutation( 'my_mutation', ['foo', 'bar'] ) == ''' mutation($foo: String!, $bar:...
napsternxg/gensim
gensim/models/poincare.py
Python
gpl-3.0
75,098
0.003356
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Jayant Jain <jayantjain1992@gmail.com> # Copyright (C) 2017 Radim Rehurek <me@radimrehurek.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Python implementation of Poincaré Embeddings. These embeddings are better at capturing...
Seed for random to ensure reproducibility. Examples -------- Initialize a model from a
list: .. sourcecode:: pycon >>> from gensim.models.poincare import PoincareModel >>> relations = [('kangaroo', 'marsupial'), ('kangaroo', 'mammal'), ('gib', 'cat')] >>> model = PoincareModel(relations, negative=2) Initialize a model from a file containing one relat...
tungvx/deploy
Django-0.90/django/middleware/common.py
Python
apache-2.0
3,684
0.004343
from django.conf import settings from django.utils import httpwrappers from django.core.mail import mail_managers import md5, os class CommonMiddleware: """ "Common" middleware for taking care of some basic operations: - Forbids access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL r...
""" Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for
denied User-Agents if request.META.has_key('HTTP_USER_AGENT'): for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): return httpwrappers.HttpResponseForbidden('<h1>Forbidden</h1>') # Check f...
tschaefer/remote
remote/tv.py
Python
bsd-3-clause
1,157
0.001729
# -*- coding: utf-8 -*- import requests import urlparse class TV(object): def __init__(self, url): self.url = url self.chan = None self.stream = None def _post(self, endpoint, json): url = urlparse.urljoin(self.url, endpoint) try: requests.post(url, json=j...
n = None self.stream = None json = self._json('stop') self._post('playback', json) def play(self): json = self._json('play') self._post('
playback', json) def pause(self): json = self._json('pause') self._post('playback', json) def vol(self, action): json = self._json(action) self._post('volume', json)
alexandrul-ci/robotframework
utest/utils/test_etreesource.py
Python
apache-2.0
1,816
0
import os import unittest from robot.utils.asserts import assert_equal, assert_true from robot.utils.etreewrapper import ETSource, ET from robot.utils import IRONPYTHON, PY3 PATH = os.path.join(os.path.dirname(__file__), 'test_etreesource.py') if PY3: unicode = str class TestETSource(unittest.TestCase): d...
PATH) self._verify_string_representation(source, PATH) assert_true(source._opened is None) def test_opened_file_object(self): source = ETSource(open(PATH)) with source as src: assert_true(src.read().startswith('import os')) assert_true(src.closed is False) ...
est_string('\n<tag>content</tag>\n') def test_unicode_string(self): self._test_string(u'\n<tag>hyv\xe4</tag>\n') def _test_string(self, xml): source = ETSource(xml) with source as src: content = src.read() if not IRONPYTHON: content = content.dec...
kamsuri/vms
vms/organization/urls.py
Python
gpl-2.0
585
0.001709
# Django from django.conf.urls import patterns, url # local Django from organization.views import Organizati
onCreateView, OrganizationDeleteView, OrganizationListView, OrganizationUpdateView urlpatterns = patterns( '',
url(r'^create/$', OrganizationCreateView.as_view(), name='create'), url(r'^delete/(?P<organization_id>\d+)$', OrganizationDeleteView.as_view(), name='delete'), url(r'^edit/(?P<organization_id>\d+)$', OrganizationUpdateView.as_view(), name='edit'), url(r'^list/$', Organizatio...
SheffieldML/GPy
doc/source/conf.py
Python
bsd-3-clause
12,464
0.007221
# -*- coding: utf-8 -*- # # GPy documentation build configuration file, created by # sphinx-quickstart on Fri Sep 18 18:16:28 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All c...
his directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_t
itle. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #ht...
lioupayphone/gdeploy
gdeploylib/helpers.py
Python
gpl-2.0
21,630
0.001803
# -*- coding: utf-8 -*- # # Copyright 2015 Nandaja Varma <nvarma@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later ve...
nup_and_quit() return False def split_comma_separated_options(self, options): if options: pat_group = re.search("(.*){(.*)}(.*)", options
) if not pat_group: return filter(None, options.split(',')) else: result = [] for i in range(1,3): if i == 2: result[-1] += '{' + pat_group.group(2) + '}' else: ...
e1528532/libelektra
src/bindings/gi/python/testgi_kdb.py
Python
bsd-3-clause
1,632
0.03125
import unittest from gi.repository import GElektra as kdb TEST_NS = "user/tests/gi_py3" class Constants(unittest.TestCase): def setUp(self): pass def test_kdbcon
fig_h(self): self.assertIsInstance(kdb.DB_SYSTEM, str) self.assertIsInstance(kdb.DB_USER, str) self.assertIsInstance(kdb.DB_HOME, str) self.assertIsInstance(kdb.DEBUG, int) def test_kdb_h(self): self.assertIsInstance(kdb.VERSION, str) self.ass
ertIsInstance(kdb.VERSION_MAJOR, int) self.assertIsInstance(kdb.VERSION_MINOR, int) self.assertIsInstance(kdb.VERSION_MICRO, int) self.assertIsNone(kdb.KS_END) class KDB(unittest.TestCase): def test_ctor(self): self.assertIsInstance(kdb.KDB(), kdb.KDB) error = kdb.Key() self.assertIsInstance(kdb.KDB(error...
otfried/cs101
code/files/krw1.py
Python
gpl-3.0
1,258
0.031797
# # Read KRW-USD rates # # We have data from 1994 to 2009 years = range(1994, 2010) # read one year into list data def read_year(yr, data): fname = "data/%d.txt" % yr f = open(fname, "r") for l in f: date1, value1 = l.split() value = float(value1) # convert to KRW per USD value = int(1.0 / value...
0 count = 0 start = yr * 10000 end = (yr + 1) * 10000 for d, v in data: if start <= d < end: sum += v count += 1 return sum / count def find_min(data): vm = 99999 dm = None for d, v in data: if v < vm: vm = v dm = d return dm, vm def find_max(data): vm = 0 dm = N...
vm = v dm = d return dm, vm def main(): data = read_all() print "Minimum:", find_min(data) print "Maximum:", find_max(data) for yr in years: avg = average(data, yr) print yr, avg main()
sergecodd/FireFox-OS
B2G/gecko/ipc/ipdl/ipdl/cgen.py
Python
apache-2.0
3,280
0.007927
# 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, sys from ipdl.ast import Visitor from ipdl.ast import IN, OUT, INOUT, ASYNC, SYNC, RPC class CodePrinter: def __init__(self, outf=sys.stdout, indentCols=4): self.outf = outf
self.col = 0 self.indentCols = indentCols def write(self, str): self.outf.write(str) def printdent(self, str=''): self.write((' '* self.col) + str) def println(self, str=''): self.write(str +'\n') def printdentln(self, str): self.write((' '* self.col)...
mmadsen/axelrod-ct
madsenlab/axelrod/utils/convergence.py
Python
apache-2.0
839
0.004768
#!/usr/bin/env python # Copyright (c) 2013. Mark E. Madsen <mark@madsenlab.org> # # This work is licensed under the terms of the Apache Software License, Version 2.0. See the file LICENSE for details. """ Description here """ import logging as log def check_liveness(ax, model, args, simconfig, timestep): dif...
("No interactions have occurred since %s - for %s ticks, which is 5 * %s network edges", model.get_time_last_interaction(), diff, num_links) if ax.get_fraction_links_active() == 0.0:
log.debug("No active links found in the model, clear to finalize") return False else: return True else: return True
dhardtke/foostat
Daemon.py
Python
mit
5,006
0.001798
#!/usr/bin/env python3 import sys import os import time import atexit from signal import SIGTERM import logging import logging.handlers # load the config from foostat import config logger = logging.getLogger() logger.setLevel(logging.DEBUG) filehandler = logging.handlers.TimedRotatingFileHandler(config["files"]["lo...
sys.exit(1) # Start daemon. self.daemonize() self.run() def status(self): """ Get status of daemon. """ try: pf = open(self.pidfile, 'r') pid = int(pf.read().strip()) pf.c
lose() except IOError: message = "There is no PID file. Daemon already running?\n" sys.stderr.write(message) sys.exit(1) try: procfile = open("/proc/{}/status".format(pid), 'r') procfile.close() message = "There is a process with t...
Shadi-A/ExpediaCrawler
expediacrawler/soupParser.py
Python
mit
2,286
0.002625
from bs4 import BeautifulSoup import time from selenium import webdriver from pyvirtualdisplay import Display __PROCESSOR = 'lxml' __OFFERS_CLASS = 'offer-listing' __PRICE_CLASS = 'dollars' __FLIGHT_DURATION_CLASS = 'duration-emphasis' __LAYOVR_CLASS = '' __AIRLINE_CLASS = '' def get_page_offers(url): display =...
l) time.sleep(25) full_content = browser.execute_script("return document.getElementsByTagName('html')[0].innerHTML") browser.quit() display.stop() return __parse_offers_page(full_content) def __parse_offers_page(html_content): offers_list = __parse_offers_list(html_content) prices_list = [...
es_list def __parse_offers_list(html_content): soup = BeautifulSoup(html_content, __PROCESSOR) offers = soup.find_all('li', class_=__OFFERS_CLASS) return offers def __get_offer_object(offer_html): offer_price = __get_offer_price(offer_html) offer_duration = __get_offer_duration(offer_html) o...
tvenkat/askbot-devel
askbot/search/postgresql/__init__.py
Python
gpl-3.0
723
0.004149
"""Procedures to initialize the full text search in PostgresQL""" from django.db import connection def setup_full_text_search(script_path): """using postgresql database connection, installs
the plsql language, if necessary and runs the stript, whose path is given as an argument """ fts_init_query = open(script_path).read() cursor = connection.cursor() try: #test if language exists cursor.execute("SELECT * FROM pg
_language WHERE lanname='plpgsql'") lang_exists = cursor.fetchone() if not lang_exists: cursor.execute("CREATE LANGUAGE plpgsql") #run the main query cursor.execute(fts_init_query) finally: cursor.close()
i3visio/osrframework
osrframework/wrappers/pending/cloudflare/forocoches.py
Python
agpl-3.0
4,071
0.004914
################################################################################ # # Copyright 2015-2020 Félix Brezo and Yaiza Rubio # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Softwa...
r expressions to be searched in usufy mode self.fieldsRegExp["usufy"] = {} # Example of fields: #self.fieldsRegExp["usufy"]["i3visio.location"] = "" # Definition of regular expressions to be searched in searchfy mode #self.fieldsRegExp["searchfy"] = {} # Example of
fields: #self.fieldsRegExp["searchfy"]["i3visio.location"] = "" ################ # Fields found # ################ # This attribute will be feeded when running the program. self.foundFields = {}
shivan1b/pydelhi_mobile
pydelhiconf/libs/garden/garden.mapview/mapview/clustered_marker_layer.py
Python
agpl-3.0
13,896
0.001007
# coding=utf-8 """ Layer that support point clustering =================================== """ from os.path import dirname, join from math import sin, log, pi, atan, exp, floor, sqrt from mapview.view import MapLayer, MapMarker from kivy.lang import Builder from kivy.metrics import dp from kivy.properties import (Obje...
right = stack.pop() left = stack.pop() if right - left <= node_size: for i in range(left, right + 1): x = coords[2 * i] y = coords[2 * i + 1
] if (x >= min_x and x <= max_x and y >= min_y and y <= max_y): result.append(ids[i]) continue m = int(floor((left + right) / 2.)) x = coords[2 * m] y = coords[2 * m + 1] if (x >= m...
appsembler/mayan_appsembler
fabfile/conf.py
Python
gpl-3.0
2,675
0.00972
import os import string import random from fabric.api import env from fabric.colors import green from literals import (DEFAULT_INSTALL_PATH, DEFAULT_VIRTUALENV_NAME, DEFAULT_REPOSITORY_NAME, DEFAULT_OS, OS_CHOICES, DEFAULT_DATABASE_MANAGER, DB_CHOICES, DEFAULT_DATABASE_NAME, DEFAULT_WEBSERVER, WEB_CHOIC...
river'] = DJANGO_DB_DRIVERS[env.database_manager] def print_supported_configs():
print('Supported operating systems (os=): %s, default=\'%s\'' % (dict(OS_CHOICES).keys(), green(DEFAULT_OS))) print('Supported database managers (database_manager=): %s, default=\'%s\'' % (dict(DB_CHOICES).keys(), green(DEFAULT_DATABASE_MANAGER))) print('Supported webservers (webserver=): %s, default=\'%s\'' % ...
datamade/scrapers_ca_app
scrapers_ca_app/urls.py
Python
mit
423
0.007092
from d
jango.conf.urls import patterns, url, include urlpatterns = patterns('', ('', include('imago.urls')), url(r'^report/(?P<module_name>[a-z0-9_]+)/$', 'reports.views.report', name='report'), url(r'^represent/(?P<modu
le_name>[a-z0-9_]+)/$', 'reports.views.represent', name='represent'), url(r'^warnings/$', 'reports.views.warnings', name='warnings'), url(r'^$', 'reports.views.home', name='home'), )
amexperts/bounty
projects/views.py
Python
gpl-3.0
1,079
0.007414
from django.http import Http404 from django.shortcuts import render from . import models def index(request): # Generate counts of some of the main ob
jects num_projects = models.Project.objects.all().count() num_tasks = models.Tasks.objects.all().count() num_fundings = models.Fundings.objects.all().count() num_projects_goal = (models.Project.objects.all().count() / 10) * 100; projects = models.Project.objects.all()[:4] featured_projects = mod...
d=1) # Render the HTML template return render( request, 'home.html', context={'projects': projects, 'featured': featured_projects, 'num_projects':num_projects, 'num_tasks':num_tasks, 'num_fundings':num_fundings, 'num_projects_goal':num_projects_goal}, ) def project(request, slug):...
jay4ek/cs3240-labdemo
hello.py
Python
mit
75
0.026667
f
rom helper import greeting if "__name__" == "__main__":
greeting('hello')
rschnapka/purchase-workflow
framework_agreement/tests/test_framework_agreement_price_list.py
Python
agpl-3.0
4,066
0
from datetime import timedelta from openerp.tools import DEFAULT_SERVER_DATE_FORMAT from openerp.osv import orm import openerp.tests.common as test_common from .common import BaseAgreementTestMixin class TestAgreementPriceList(test_common.TransactionCase, BaseAgreementTestMixin): """...
elf.agreement.get_price( 999, currency=self.browse_ref('base.EUR') ), 50.0) self.assertEqual( self.agreement.get_price( 1000, currency=self.browse_ref('base.EUR') ), 45.0) self.assertEqual( self.agreement.get_price(
10000, currency=self.browse_ref('base.EUR') ), 45.0) self.assertEqual( self.agreement.get_price( -10, currency=self.browse_ref('base.EUR') ), 70.0) def test_01_failed_wrong_currency(self): """Tests that wrong currency raise an exception""...
fatrix/django-golive
golive/layers/queue.py
Python
bsd-2-clause
2,683
0.002609
from fabric.context_managers import settings from golive.layers.base import BaseTask, DebianPackageMixin, IPTablesSetup from golive.stacks.stack import environment from golive.utils import get_remote_envvar class RabbitMqSetup(BaseTask, DebianPackageMixin): package_name = "rabbitmq-server" GUEST_USER = "guest...
ole(self.ROLE).hosts[0]) password = get_remote_envvar(self.VAR_BROKER_PASSWORD, environment.get_role(self.ROLE).hosts[0]) with settings(warn_only=True): self.sudo("rabbitmqctl add_user %s %s" % (username, password)) self.sudo("rabbitmqctl set_permissions -p / %s \".*\
" \".*\" \".*\"" % username) # TODO: create vhost def _delete_user(self, username): with settings(warn_only=True): self.sudo("rabbitmqctl delete_user %s" % username)
mvaled/sentry
src/sentry/interfaces/debug_meta.py
Python
bsd-3-clause
1,172
0
from __future__ import absolute_import __all__ = ("DebugMeta",) from sentry.interfaces.base import Interface from sentry.utils.json import prune_empty_keys class DebugMeta(Interface): """ Holds debug meta information for processing stacktraces and similar things. This information is deleted after event...
es", None) or [], sdk_info=data.get("sdk_info"), is_debug_build=data.get("is_debug_build"), ) def to_json(self): return prune_empty_keys(
{ "images": self.images or None, "sdk_info": self.sdk_info or None, "is_debug_build": self.is_debug_build, } )
jason-weirather/IDP
bin/selectrow.py
Python
apache-2.0
1,076
0.01487
#!/usr/bin/python import sys import os if len(sys.argv) >= 4 : filename = sys.argv[1] row_i = int(sys.argv[2])-1 target_ls_filename = sys.argv[3] output_filename = sys.argv[4] else: print("usage: python selectrow.py filename row_i target_ls_filename") print("or ./selectrow.py filename row_i ta...
(dt[id])) for item in dt[id]: output.write( item + '\n') output.close() target_ls_fil
e.close()
delete/estofadora
estofadora/login/tests.py
Python
mit
3,269
0.001835
from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from django.contrib.auth.models import User from .forms import LoginForm class LoginViewTest(TestCase): def setUp(self): self.client = Client() self.response = self.client.get(reve...
n(self): 'With invalid login, will not have a redirect, so, must return code 200' self.response = self.client.post(
reverse('login:login'), self.make_validated_data(password='1') ) self.assertEqual(self.response.status_code, 200) def make_validated_data(self, **kwargs): data = { 'username': 'admin', 'password': '123' } data.update(kwargs) ...
SUSE/azure-sdk-for-python
azure-mgmt-storage/azure/mgmt/storage/v2015_06_15/models/usage.py
Python
mit
1,829
0
# 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 ...
ces in the subscription. :type current_value: int :param limit: The maximum count of the resources that can be allocated in the subscription. :type limit: int
:param name: The name of the type of usage. :type name: :class:`UsageName <azure.mgmt.storage.v2015_06_15.models.UsageName>` """ _validation = { 'unit': {'required': True}, 'current_value': {'required': True}, 'limit': {'required': True}, 'name': {'required': True}, ...
SlashRoot/WHAT
what_apps/utility/admin.py
Python
mit
665
0.006015
""" Django-admin autoregister -- automat
ic model registration ## sample admin.py ## from yourproject.autoregister import autoregister # register all models defined on each app autoregister('app1', 'app2', 'app3', ...) """ from django.db.models import get_models, get_app from django.contrib import admin from django.contrib.admin.sites import AlreadyRegis...
admin.site.register(model) except AlreadyRegistered: pass autoregister('utility')
arsfeld/conduit
test/python-tests/TestCoreTempFile.py
Python
gpl-2.0
4,008
0.010729
from common import * import conduit.datatypes.File as File import conduit.utils as Utils import os import tempfile import datetime import random import stat tmpdir = tempfile.mkdtemp() ok("Created temp
dir %s" % tmpdir, True) contents = Utils.rand
om_string() name = Utils.random_string()+".foo" tmpFile = File.TempFile(contents) tmpFile.force_new_filename(name) ok("Set filename to %s" % name, tmpFile._newFilename == name) newPath = os.path.join(tmpdir, name) tmpFile.transfer(tmpdir) ok("Transferred -> %s" % newPath, os.path.isfile(newPath)) f = File.File(newPa...
tboyce1/home-assistant
tests/components/hyperion/test_config_flow.py
Python
apache-2.0
26,352
0.002277
"""Tests for the Hyperion config flow.""" import logging from typing import Any, Dict, Optional from hyperion import const from homeassistant import data_entry_flow from homeassistant.components.hyperion.const import ( CONF_AUTH_ID, CONF_CREATE_TOKEN, CONF_PRIORITY, DOMAIN, ) from homeassistant.compo...
base"] == "cannot_connect" # Fail the auth check call. client.async_client_con
nect = AsyncMock(return_value=True) client.async_is_auth_required = AsyncMock(return_value={"success": False}) with patch( "homeassistant.components.hyperion.client.HyperionClient", return_value=client ): result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT) assert ...
SymbiFlow/symbiflow-arch-defs
ice40/utils/ice40_list_layout_in_icebox.py
Python
isc
972
0
#!/usr/bin/env python3 # Python libs import os.path import sys import icebox # FIXME: Move this into icebox parts = [ # LP Series (Low Power) "lp384", "lp1k", "lp8k", # Unsupported: "lp640", "lp4k" (alias for lp8k),
# LM Series (Low Power, Embedded IP) # Unsupported: "lm1k", "lm2k", "lm4k", # HX Series (High Performance) "hx1k", "
hx8k", # Unsupported: "hx4k" (alias for hx8k) # iCE40 UltraLite # Unsupported: "ul640", "ul1k", # iCE40 Ultra # Unsupported: "ice5lp1k", "ice5lp2k", "ice5lp4k", # iCE40 UltraPLus # Unsupported: "up3k", "up5k", ] def versions(part): return [p for p in parts if p.endswith(part)] ...
mandyRae/pythonic-charlieplex
charlie.py
Python
mit
5,714
0.029051
''' charlie.py ---class for controlling charlieplexed SparkFun 8x7 LED Array with the Raspberry Pi Relies upon RPi.GPIO written by Ben Croston The MIT License (MIT) Copyright (c) 2016 Amanda Cole Permission is hereby granted, free of charge, to any person obtaining a copy of this software and asso
ciated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, a
nd/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF...
smcv/vectis
vectis/commands/bootstrap.py
Python
gpl-2.0
4,115
0
# Copyright © 2016-2017 Simon McVittie # SPDX-License-Identifier: GPL-2.0+ # (see vectis/__init__.py) import os import pwd import shutil import subprocess from tempfile import TemporaryDirectory from debian.debian_support import ( Version, ) from vectis.commands.new import vmdebootstrap_argv from vectis.error im...
ize=qemu_image_size, suite=suite, uri=uri, merged_usr=args._merged_usr, ) argv.extend(vmdb_argv) argv.append('--debootstrapopts=' + ' '.join(debootstrap_argv)) argv.extend(vmdebootstrap_options) argv.append( '--customize={}'.format(...
tput.raw'.format(scratch)) subprocess.check_call(argv) subprocess.check_call([ 'qemu-img', 'convert', '-f', 'raw', '-O', 'qcow2', '-c', '-p', '{}/output.raw'.format(scratch), '{}/output.qcow2'.format(scratch), ]) if out is None: ...
recognai/spaCy
spacy/lang/ur/lemmatizer.py
Python
mit
921,455
0.000003
# coding: utf8 from __future__ import unicode_literals # Adding a lemmatizer lookup table # Documentation: https://spacy.io/docs/usage/adding-languages#lemmatizer # Entries should be added in the following format: LOOKUP = { "آ": "آنا", "آْباد": "آْباد", "آثار": "آثار", "آثارِ": "آثارِ", "آثارالصنادید": ...
"آل", "آم": "آم", "آمد": "آمد", "آمدنی": "آمدنی", "آمدنیاں": "آمدنی", "آمدنیو": "آمدنی", "آمدنیوں": "آمدنی", "آمدو": "آمد", "آمدوں": "آمد", "آمدیں": "آمد", "آملے": "آملہ", "آملہ": "آمل
ہ", "آملو": "آملہ", "آملوں": "آملہ", "آمنا": "آمنا", "آمر": "آمر", "آمرو": "آمر", "آمروں": "آمر", "آمو": "آم", "آموں": "آم", "آنے": "آنہ", "آنا": "آنا", "آندھی": "آندھی", "آندھیاں": "آندھی", "آندھیو": "آندھی", "آندھیوں": "آندھی", "آنگن": "آنگن", "آنگنو": "آنگن", "آنگنوں": "آنگن", "آن...
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_patch_panel_cfg.py
Python
apache-2.0
2,513
0.035814
""" Cisco_IOS_XR_patch_panel_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR patch\-panel package configuration. This module contains definit
ions for the following management objects\: patch\-panel\: patch\-panel service submode Copyright (c) 2013\-2016 by Cisco Systems, Inc. All rights reserved. """ import re import collections from enum import Enum from ydk.types impo
rt Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk.errors import YPYError, YPYModelError class PatchPanel(object): """ patch\-panel service submode .. attribute:: enable Enable patch\-panel service **type**\: :py:class:`Empty<ydk.types.Empty>` **mandato...
maferelo/saleor
tests/api/test_core_reordering.py
Python
bsd-3-clause
8,739
0.001831
import pytest from saleor.graphql.core.utils.reordering import perform_reordering from saleor.product import models SortedModel = models.AttributeValue def _sorted_by_order(items): return sorted(items, key=lambda o: o[1]) def _get_sorted_map(): return list( SortedModel.objects.values_list("pk", "s...
), ] ) ) operations = {null_sorted_entries[0].pk: -2} expected = [ (non_null_sorted_entries[1].pk, 0), (non_null_sorted_entries[0].pk, 1), (null_sorted_entries[0].pk, 2), (null_sorted_entries[2].pk, 3), (null_sorted_entries[1].pk, 4)...
eordering_nothing(sorted_entries_seq, assert_num_queries): """ Ensures giving operations that does nothing, are skipped. Thus only one query should have been made: fetching the nodes. """ qs = SortedModel.objects pk = sorted_entries_seq[0].pk operations = {pk: 0} with assert_num_queries...
unreal666/outwiker
src/test/plugins/statistics/test_loading.py
Python
gpl-3.0
587
0
# -*- coding: utf-8 -*- import unittest from test.basetestcases import PluginLoadingMixin class StatisticsLoadingTest (PluginLoadingMixin, unittest.TestCase): def getPluginDir(self): """ Должен возвращать путь до папки с тестируемым плагином """ return "../plugins/sta
tistics" def getPluginName(self): """ Должен возвращ
ать имя плагина, по которому его можно найти в PluginsLoader """ return "Statistics"
BrainIntensive/OnlineBrainIntensive
resources/HCP/ciftify/ciftify/config.py
Python
mit
8,757
0.006052
#!/usr/bin/env python """ These functions search the environment for software dependencies and configuration. """ from __future__ import unicode_literals import os import subprocess import logging import pkg_resources import ciftify.utilities as util def find_workbench(): """ Returns path of the workbench bi...
ildstamp, "r") as text_file: bstamp = text_file.read() except: return "freesurfer build information not found." bstamp = bstamp.replace(os.linesep,'') info = "free
surfer:{0}Path: {1}{0}Build Stamp: {2}".format( '{} '.format(os.linesep),fs_path, bstamp) return info def fsl_version(): ''' Returns version info for FSL ''' fsl_path = find_fsl() if fsl_path is None: raise EnvironmentError("FSL not found. Please check that it is " ...
jdemel/gnuradio
gr-digital/python/digital/qa_linear_equalizer.py
Python
gpl-3.0
5,126
0.013461
#!/usr/bin/env python # # Copyright 2020 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from gnuradio import gr, gr_unittest import random, numpy from gnuradio import digital, blocks, channels class qa_linear_equalizer(gr_unittest.TestCase): ...
17,0x0C,0x0A,0x41,0xD6,0x1F,0x4C,0x23,0x65,0x68,0xED,0x1C,0x77,0xA7,0x0E,0x0A,0x9E,0x47,0x82,0xA4,0x57,0x24,] self.payload_size = payload_size = 300 # bytes self.data = data = [0]*4+[random.getrandbits(8) for i
in range(payload_size)] self.gain = gain = .001 # LMS gain self.corr_thresh = corr_thresh = 3e6 self.num_taps = num_taps = 16 def tearDown(self): self.tb = None def transform(self, src_data, gain, const): SRC = blocks.vector_source_c(src_data,...
isb-cgc/ISB-CGC-Webapp
scripts/isb_auth.py
Python
apache-2.0
4,266
0.003516
# # Copyright 2015-2019, Institute for Systems Biology # # 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 ...
.refresh_token) def parse_args(): parser = ArgumentParser() parser.add_argument(
'--storage_file', '-s', default=DEFAULT_STORAGE_FILE, help='storage file to use for the credentials (default is {})'.format(DEFAULT_STORAGE_FILE)) parser.add_argument('--verbose', '-v', dest='verbose', action='store_true', help='display credentials storage location, access token, and refresh token') parser.set_...
ClemsonSoCUnix/django-sshkey
django_sshkey/south_migrations/0001_initial.py
Python
bsd-3-clause
5,536
0.008309
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'UserKey' db.create_table('sshkey_userkey', ( ('id', self.gf('django.db.models....
# Removing unique constraint on 'UserKey', fields ['user', 'name'] db.delete_unique('sshkey_userkey', ['user_id', 'name']) # Deleting model 'UserKey' db.delete_table
('sshkey_userkey') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions'...
obsh/tornado
tornado/websocket.py
Python
apache-2.0
41,216
0.000146
"""Implementation of the WebSocket protocol. `WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional communication between the browser and server. WebSockets are supported in the current versions of all major browsers, although older versions that do not support WebSockets are still in use (refer ...
u can also override `open` and `on_close` to handle opened and closed connections. See http://dev.w3.org/html5/websockets/ for details on the JavaScript interface. The protocol is specified at http://tools.ietf.org/html/rfc6455. Here is an example WebSocket handler that echos back all receive...
print("WebSocket opened") def on_message(self, message): self.write_message(u"You said: " + message) def on_close(self): print("WebSocket closed") .. testoutput:: :hide: WebSockets are not standard HTTP connections. The "handshake" is HTTP, but...
pacoqueen/bbinn
formularios/trazabilidad_articulos.py
Python
gpl-2.0
71,269
0.007906
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright (C) 2005-2008 Francisco José Rodríguez Bogado, # # Diego Muñoz Escalante. # # (pacoqueen@users.sourceforge.ne...
############################################################### ## Changelog: ## 24 de mayo de 2006 -> Inicio ## 24 de mayo de 2006 -> It's alive! ################################################################### ## DONE: Imprimir toda la información en PDF sería lo suyo. #############################################...
re('2.0') import gtk, gtk.glade, time, sqlobject import sys, os try: import pclases except ImportError: sys.path.append(os.path.join('..', 'framework')) import pclases import mx, mx.DateTime sys.path.append(os.path.join('..', 'informes')) from barcode import code39 from barcode.EANBarCode import EanBarCode...
pmaigutyak/mp-shop
product_images/fields.py
Python
isc
188
0
from images import fields from product_images
.models import ProductImage class ImagesFormField(fields.ImagesFormField): def __init__(self)
: super().__init__(ProductImage)
Lucas-C/pre-commit
pre_commit/commands/install_uninstall.py
Python
mit
3,549
0
from __future__ import print_function from __future__ import unicode_literals import io import os.path import pipes import sys from pre_commit import output from pre_commit.util import make_executable from pre_commit.util import mkdirp from pre_commit.util import resource_filename # This is used to identify the hoo...
5d0d983b2de', 'e358c9dae00eac5d06b38dfdb1e33a8c', ) CURRENT_HASH = '138fd403232d2ddd5efb44317e38bf03'
def is_our_script(filename): if not os.path.exists(filename): return False contents = io.open(filename).read() return any(h in contents for h in (CURRENT_HASH,) + PRIOR_HASHES) def install( runner, overwrite=False, hooks=False, hook_type='pre-commit', skip_on_missing_conf=False, )...
jackchi/interview-prep
leetcode/meeting_rooms.py
Python
mit
61
0.098361
intervals =
[[10,20],[6,15],[0,2
2]] print(sorted(intervals))
AdaHeads/Hosted-Telephone-Reception-System
use-cases/.patterns/adjust_recipients/test.py
Python
gpl-3.0
217
0.041667
self.Step (Message = "Receptionist-N ->> Klient-N [genvej: fokus-modtagerliste] (
måske)") sel
f.Step (Message = "Receptionist-N ->> Klient-N [retter modtagerlisten]")
ahmadRagheb/goldenHR
erpnext/accounts/doctype/money_transfere/money_transfere.py
Python
gpl-3.0
4,294
0.034958
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils.data import flt, nowdate, getdate, cint class MoneyTransfere...
acc.root_type = r_type # # pacc.is_group = 1 # # pacc.parent_account = "" # # pacc.company = company # # pacc.flags.ignore_validate = True # # pacc.insert() # if not frappe.db.exists("Account", account): # acc = frappe.new_doc("Account") # acc.account_name = account # acc.company = company ...
Payment Entry") pe.payment_type = "Internal Transfer" pe.company = company pe.paid_from = paid_from pe.paid_to = paid_to pe.paid_amount = self.transfered_amount pe.received_amount = self.transfered_amount pe.posting_date = nowdate() pe.mode_of_payment = self.mode_of_payment pe.transfere_reference = se...
oscaro/django
tests/urlpatterns_reverse/urls.py
Python
bsd-3-clause
3,830
0.003394
from django.conf.urls import patterns, url, include from .views import empty_view, empty_view_partial, empty_view_wrapped, absolute_kwargs_view other_patterns = patterns('', url(r'non_path_include/$', empty_view, name='non_path_include'), url(r'nested_path/$', 'urlpatterns_reverse.views.nested_view'), ) url...
h>\d+)\.(?P<day>\d+)/$', empty_view, name="headlines"), url(r'^windows_path/(?P<drive_name>[A-Z]):\\(?P<path>.+)/$', empty_view, name="windows"), url(r'^special_chars/(?P<chars>.+)/$', empty_view, name="special"), url(r'^(?P<name>.+)/\d+/$', empty_view, name="mixed"), url(r'^repeats/a{1,2}/$', empty_vie...
iew, name="repeats2"), url(r'^repeats/a{2}/$', empty_view, name="repeats3"), url(r'^(?i)CaseInsensitive/(\w+)', empty_view, name="insensitive"), url(r'^test/1/?', empty_view, name="test"), url(r'^(?i)test/2/?$', empty_view, name="test2"), url(r'^outer/(?P<outer>\d+)/', include('urlpatterns_reverse.i...
jsquare/hikeplanner
src/settings.py
Python
gpl-2.0
5,672
0.001234
# Django settings for hikeplanner project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Jaime', 'jaime.m.mccandless@gmail.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'ENGINE': ...
is to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/var/www/example.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http:...
this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations o...
PaulWay/spacewalk
client/solaris/smartpm/smart/interfaces/up2date/interface.py
Python
gpl-2.0
19,239
0.001663
# # Copyright (c) 2004 Conectiva, Inc. # Copyright (c) 2005--2013 Red Hat, Inc. # # From code written by Gustavo Niemeyer <niemeyer@conectiva.com> # Modified by Joel Martin <jmartin@redhat.com> # # This file is part of Smart Package Manager. # # Smart Package Manager is free software; you can redistribute it and/or # m...
pkg.installed |= 1 for loader in pkg.loaders: channel = loader.
getChannel() if channel.getType() == "solaris-rhn": retpkgs.append(pkg) if latest: apkgs = [] for pkg in retpkgs: found = False for apkg in apkgs: if pkg.name == apkg.name: fou...
rubenk/cobbler
cobbler/server/xmlrpclib2.py
Python
gpl-2.0
9,102
0.002857
#============================================================================ # This library
is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MER...
eived a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #============================================================================ # Copyright (C) 2006 Anthony Liguori <aliguori@us....
stev-0/bustimes.org.uk
busstops/management/commands/import_accessibility.py
Python
mpl-2.0
1,772
0.001693
import os import zipfile import csv from django.core.management.base import BaseCommand from django.db import transaction from django.conf import settings from ...models import Service def get_service(row): for region in 'EA', 'EM', 'WM', 'SE', 'SW': col = 'TNDS-' + region if row[col]: ...
gion=region, service_code=row[col]) if row['TNDS-NW']: return Service.objects.filter(region=region, service_code__endswith=''
.join(row['TNDS-NW'].split('_')[:-1])) def handle_file(open_file): for row in csv.DictReader(line.decode() for line in open_file): service = get_service(row) if service: if row['HighFloor'] == 'LF': low_floor = True elif row['HighFloor'] == 'HF': ...
vdloo/raptiformica-map
raptiformica_map/graph.py
Python
gpl-3.0
1,111
0
import re CJDNS_IP_REGEX = re.compile(r'^fc[0-9a-f]{2}(:[0-9a-f]{4}){7}$', re.IGNORECASE) class Node(object):
def __init__(self, ip, version=None, label=None): if not valid_cjdns_ip(ip): raise ValueError('Invalid IP address') if not valid_version(version): raise ValueError('Invalid version') self.ip = ip self.version = int(version) self.label = ip[-4:] or label...
f __repr__(self): return 'Node(ip="%s", version=%s, label="%s")' % ( self.ip, self.version, self.label) class Edge(object): def __init__(self, a, b): self.a, self.b = sorted([a, b]) def __eq__(self, that): return self.a.ip == that.a.ip and self.b.i...
jairoserrano/simpledevops
models.py
Python
apache-2.0
425
0.002353
from app import db class Pets(db.Model): __tablename__ = 'pets' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), unique=True) color = db.Column(db.String(30)) pet = db.Column(db.String(
10)) def __init__(self, name, color, pet): self.name = name self.color = color s
elf.pet = pet def __repr__(self): return '<id {}>'.format(self.id)
RobinJoe/Docs
doc/conf.py
Python
gpl-3.0
8,757
0
# -*- coding: utf-8 -*- # # Rackspace Developer Documentation documentation build configuration file, # created by sphinx-quickstart on Thu Mar 6 14:14:55 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this #...
ate names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is s
plit into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HT...
George-Gate/CERN-Video-Downloader
PerformDownload.py
Python
mit
9,240
0.018831
import urllib.request import os '''if set smallFileMode to True, the program will use simpleDownload method, which may be faster for many small files but do not support break point resume.''' smallFileMode=False def showProgress(blockNum, blockSize, totalSize): '''Called by urllib.request.urlretrieve return the...
currentPath+localname[1:]) # if download not success, raise exception if result!='Success': raise Exception(result) except urllib.error.HTTPError as errinfo: # 404 Not Found print ('\r'+str(errinfo)) ...
ecord,str(errinfo)) except KeyboardInterrupt as errinfo: # Ctrl+C Interrupt print ('\rDownload Abort!'+20*' ') if smallFileMode: # reset status to 'Queued' since smallFileMode don't support break point resume recordToFil...
jkorell/PTVS
Python/Tests/TestData/DebuggerProject/A/module1.py
Python
apache-2.0
67
0
def do_something(): for i in range(100):
print(i)