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 |
|---|---|---|---|---|---|---|---|---|
davande/IPython-notebook-extensions | config/nbextensions.py | Python | bsd-3-clause | 3,003 | 0.009324 | # Copyright (c) IPython-Contrib Team.
# Notebook Server Extension to activate/deactivate javascript notebook extensions
#
from jupyter_core.paths import jupyter_data_dir
from notebook.utils import url_path_join as ujoin
from notebook.base.handlers import IPythonHandler, json_errors
from notebook.nbextensions import _ge... | 'Main', 'Description')):
if not extension['Type'].strip().startswith('IPython Notebook Extension'):
continue
i | f not extension['Compatibility'].strip().startswith('3.'):
continue
# generate URL to extension
idx=y[0].find('nbextensions')
url = y[0][idx::].replace('\\', '/')
extension['url'] = url
# replace single quote with HTML r... |
wuminorb/discoverGithub | cache_github/views.py | Python | mit | 1,553 | 0 | from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views import generic
from .models import GithubUser, get_user_from_db, GithubRepo
def refresh_user(request, login):
user = GithubUser()
user.login = login
user.refresh_from_github()
return HttpResponse("succe... | github/user/detail.html'
context_object_name = 'user'
def get_object(self, queryset=None):
try:
return super(UserDetailView, self).get_object(queryset)
except Http404:
pk = self.kwargs.get(self.pk_url_kwarg, None)
user = GithubUser()
user.login = ... | o
template_name = 'github/repo/detail.html'
context_object_name = 'repo'
def get_object(self, queryset=None):
try:
return super(RepoDetailView, self).get_object(queryset)
except Http404:
pk = self.kwargs.get(self.pk_url_kwarg, None)
repo = GithubRepo()
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/PyKDE4/kdeui/KReplaceDialog.py | Python | gpl-2.0 | 1,146 | 0.009599 | # encoding: utf-8
# module PyKDE4.kdeui
# from /usr/lib/python2.7/dist-package | s/PyKDE4/kde | ui.so
# by generator 1.135
# no doc
# imports
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
from KFindDialog import KFindDialog
class KReplaceDialog(KFindDialog):
# no doc
def options(self, *args, **kwa... |
CARocha/simasinnovacion | empresas/urls.py | Python | mit | 785 | 0.010191 | from django.conf.urls import patterns, url
urlpatterns = patterns('empresas.views',
url(r'^empresas/$', 'empresas_index', | name="lista_empresas"),
url(r'^empresa/(?P<id>\w+)/$', 'empresas_pagina', name="empresas_pagina"),
url(r'^mapa_completo_empresa/$', 'mapa_completo_empresa', name="mapa-completo-index"),
url(r'^mejoras/$', 'mejoras_index', name="mejora_index"),
url(r'^mejora/(?P<id>\w+)/$', 'mejora... | rl(r'^fempresa/(?P<id>\w+)/$', 'fempresa', name="ficha_empresa"),
url(r'^fmejora/(?P<id>\w+)/$', 'fmejora', name="ficha_mejora"),
url(r'^mejora/$', 'mejora', name="listar_mejora")
) |
andyspiros/numbench | numbench/benchprint.py | Python | gpl-2.0 | 1,916 | 0.00261 | #=====================================================
# Copyright (C) 2011 Andrea Arteaga <andyspiros@gmail.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 F... | g as cfg
from utils import benchutils as bu
from os.path import dirname, join as pjoin
class _Print:
def __init__(self, logfile, maxlevel=10):
self._level = 0
self._maxlevel = maxlevel
self._logfile = logfile
def __call__(self, arg='', end='\n'):
printstr = str(arg) + end
... | me(self._logfile))
logfile = file(self._logfile, 'a')
print >> logfile, printstr,
logfile.close()
# Print to terminal
if self._level <= self._maxlevel:
print printstr,
def up(self, n=1):
self._level = max(self._level - n, 0)
def down(self, n=1):
... |
firemark/yellowjuice | langs/models.py | Python | mit | 408 | 0.002451 | from django.db import | models
from django.contrib.admin import site as admin_site
class Language(models.Model):
"""
Language model
"""
name = models.CharField(max_length=64)
code = models.CharField(max_length=6, db_column='shortcut')
visible = models.BooleanField(default=True)
def __str__(self):
return... | me)
admin_site.register(Language)
|
TheTimmy/spack | var/spack/repos/builtin/packages/libyogrt/package.py | Python | lgpl-2.1 | 1,739 | 0.000575 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | MPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack imp... |
wbvalid/python2 | telnetFlowMeasure.py | Python | unlicense | 1,829 | 0.001093 | #!/usr/bin/env python
import pexpect
import traceback
import time
import os
import sys
import re
addr = 'telnet 192.168.99.1 10000'
uname = ['a', 'd', 'm', 'i', 'n']
passwd = ['p', 'a', 's', 's', 'w', 'd']
cmdline = "show statistics traffic 5/1/0-1\n"
qq = ["e", "x", "i", "t", "\n"]
logName = 'Traffic_' + time.strftim... | child.send('\n.\n')
child.sendline(cmdline)
for i in qq:
child.send(i)
child.expect(['#', pexpect.EOF, pexpect.TIMEOUT])
child.close()
| timeFin = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
else:
print index
except:
traceback.print_exc()
finally:
fd.close()
with open('Telnet_raw.log', 'r') as fs, open(logName, 'a') as fd:
temp = []
content = ... |
hyde/hyde | tests/ext/test_blockdown.py | Python | mit | 1,332 | 0 | # -*- coding: utf-8 -*-
"""
Use nose
`$ pip install nose`
`$ nosetests`
"""
from hyde.generator import Generator
from hyde.site import Site
from fswrap import File
from pyquery import PyQuery
TEST_SITE = File(__file__).parent.parent.child_folder('_test')
class TestBlockdown(object):
def setUp(self):
TE... | T_SITE.delete()
def test_can_parse_blockdown(self):
s = Site(TEST_SITE)
s.config.plugins = ['hyde.ext.plugins.text.BlockdownPlugin']
txt = ("This template tests to make sure blocks can be replaced"
"with markdownish syntax | .")
templ = """
{%% extends "base.html" %%}
=====title========
%s
====/title========"""
content = (templ.strip() % txt).strip()
bd = File(TEST_SITE.child('content/blockdown.html'))
bd.write(content)
gen = Generator(s)
gen.generate_resource_at_path(bd.path)
res = ... |
lucidlylogicole/scope | plugins/outline/lang/html.py | Python | gpl-3.0 | 1,217 | 0.013969 | import re
def analyzeLine(txtlines):
outline = []
lcnt = -1
for line in txtlines:
lcnt += 1
typ = None
itmText = None
spc = (len(line) -len(line.lstrip()))*' '
tls = line.lstrip()
if tls.lower().startswith('<body'):
itmText... | itmText[:-1]
typ = 'function'
elif tls.startswith('//---'):
itmText =tls[5:]
typ = 'heading'
# CSS
elif tls.startswith('/*---'):
itmText =tls[5:].split | ('*/')[0]
typ = 'heading'
if itmText != None:
outline.append([spc+itmText,typ,lcnt])
return outline |
weinbe58/QuSpin | tests/general_spinless_majorana_opstr_test.py | Python | bsd-3-clause | 2,006 | 0.074776 | from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
from quspin.basis import spinless_fermion_basis_general
from quspin.operators import hamiltonian
import numpy as np
J=-np.sqrt(2.0) # hoppping
U=+1.0 # nn interaction
no_checks... | e=np.float64,**no_checks)
#
#
##### Hamiltonian using complex fermions
#
#
hopping_pm=[[+J,j,(j+1)%N] for j in range(N)]
hopping_mp=[[-J,j,(j+1)%N] for j in range(N)]
nn_int=[[U,j,(j+1)%N] for j in range(N)]
#
static=[["+-",hopping_pm],["-+",hopping_mp],["nn",nn_int]]
dynamic=[]
#
H=h | amiltonian(static,[],basis=basis,dtype=np.float64,**no_checks)
#######################################
print("\ntesting N={}...".format(N))
print(H.toarray())
print()
print(H_majorana.toarray())
print()
print(np.linalg.norm((H-H_majorana).toarray()))
np.testing.assert_allclose((H_majorana-H).toarray(),0... |
khalim19/gimp-plugin-export-layers | export_layers/pygimplib/gui/entries.py | Python | gpl-3.0 | 31,115 | 0.01427 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2019 khalim19
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | st of suggested items (components of the pattern) is
displayed while typing.
Additional attributes:
* `popup` (read-only) - `EntryPopup` instance serving as the popup.
"""
_BUTTON_MOUSE_LEFT = 1
_COLUMNS = [
_COLUMN_ITEM_NAMES,
_COLUMN_ITEMS_TO_INSERT,
_COLUMN_REGEX_TO_MATCH,
_CO... | 2, 3)
_COLUMN_TYPES = [
gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING]
def __init__(self, suggested_items, *args, **kwargs):
"""
Parameters:
* `suggested_items` - List of
`(item name displayed in popup, text to insert in entry,
regular ex... |
testalt/electrum-dgc | lib/ripemd.py | Python | gpl-3.0 | 14,828 | 0.013151 | ## ripemd.py - pure Python implementation of the RIPEMD-160 algorithm.
## Bjorn Edstrom <be@bjrn.se> 16 december 2007.
##
## Copyrights
## ==========
##
## This code is a derived from an implementation by Markus Friedl which is
## subject to the following license. This Python implementation is not
## subject to... | if self.dig:
return self.dig
ctx = self.ctx.copy()
self.dig = RMD160Final(self.ctx)
self.ctx = ctx
return self.dig
def hexdigest(self):
"""hexdigest() | """
dig = self.digest()
hex_digest = ''
for d in dig:
hex_digest += '%02x' % ord(d)
return hex_digest
def copy(self):
"""copy()"""
import copy
return copy.deepcopy(self)
def new(arg=None):
"""Return a new RIPEMD16... |
Juniper/neutron | neutron/db/migration/alembic_migrations/versions/1d76643bcec4_nvp_netbinding.py | Python | apache-2.0 | 2,197 | 0.001365 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 OpenStack Foundation
#
# 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... | cira.NeutronServicePlugin.NvpAdvancedPlugin',
'neutron.plugins.vmware.plugin.NsxPlugin',
'neutron.plugins.vmware.plugin.NsxServicePlugin'
]
from alembic import op
import sqlalchemy as sa
from neutron.db import migration
def upgrade(active_plugins=None, options=None):
if not migration. | should_run(active_plugins, migration_for_plugins):
return
op.create_table(
'nvp_network_bindings',
sa.Column('network_id', sa.String(length=36), nullable=False),
sa.Column('binding_type',
sa.Enum('flat', 'vlan', 'stt', 'gre',
name='nvp_net... |
apllicationCOM/youtube-dl-api-server | youtube_dl_server/youtube_dl/extractor/collegehumor.py | Python | unlicense | 3,638 | 0.001649 | from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import int_or_none
class CollegeHumorIE(InfoExtractor):
_VALID_URL = r'^(?:https?://)?(?:www\.)?collegehumor\.com/(video|embed|e)/(?P<videoid>[0-9]+)/?(?P<shorttitle>.*)$'
_TESTS = [
{
... | collegehumor.com/video/6902724/comic-con-cosplay-catastrophe',
'md5': 'dcc0f5c1c8be98dc33889a191f4c26bd',
'info_dict': {
'id': '6902724',
'ext': 'mp4',
'title': 'Comic-Con Cosplay Catastrophe',
'description': "Fans get creative this... | at's really Joss Whedon.",
'age_limit': 13,
'duration': 187,
},
}, {
'url': 'http://www.collegehumor.com/video/3505939/font-conference',
'md5': '72fa701d8ef38664a4dbb9e2ab721816',
'info_dict': {
'id': '3505939',
... |
moneymaker365/script.ustvvodlibraryautoupdate | autoexec.py | Python | mit | 300 | 0.013333 | import xbmc
#use | this if you are running Weather+ to avoid a startup conflict
#xbmc.executebuiltin('AlarmClock(ustvvodupdatelibrary,XBMC.RunScript(script.ustvvodlibraryautoupdate),1,true)')
#otherwise this one should be fine
xbmc.executebuiltin('RunScr | ipt(script.ustvvodlibraryautoupdate)')
|
rpsingh21/resultanalysis | resultAnalysis/xlsx/urls.py | Python | mit | 249 | 0.028112 | from django.conf.urls import url
from .views import (
semse | terResultxlsx,
)
urlpatterns=[
url(r'^semester-xlsx/(?P<collegeCode>\d+)/(?P<branchCode>\d+)/(?P<yearOfJoining>\d+)/(?P<semester>\d+)/$',semseterResultxlsx,name='semseterRes | ultxlsx')
]
|
tansey/gfl | pygfl/solver.py | Python | lgpl-3.0 | 10,478 | 0.005917 | '''Copyright (C) 2015 by Wesley Tansey
This file is part of the GFL library.
The GFL 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 3 of the License, or
(at you... | lam,
self.alpha, self.inflate, self.maxsteps, s | elf.converge,
self.beta, self.z, self.u)
else:
if self.weights is None:
s = graphfl(self.nnodes, self.y,
self.ntrails, self.trails, self.breakpoints,
lam,
s... |
xj9/funk | functions/_y_combinator.py | Python | mit | 96 | 0.010417 | # | -*- coding: utf-8 -*-
Y = lambda f: (lambda x: x(x))(l | ambda y: f(lambda *args: y(y)(*args)))
|
samuel-phan/mssh-copy-id | tests/func-tests/filetest.py | Python | mit | 988 | 0.002024 | import os
import pytest
import constantstest
@pytest.fixture(scope='session')
def session_test_dir():
return create_dir(os.path.join(constantstest.TEST_RUN_DIR))
@pytest.fixture(scope='module')
def module_test_dir(request):
return create_dir(os.path.join(constantstest.TEST_RUN_DIR, request.module.__name__... | e_test_dir):
return create_dir(os.path.join(module_test_dir, request.cls.__name__))
@pytest.fixture(scope='function')
def function_test_dir(request, class_test_dir):
return create_dir(os.path.join(class_test_dir, request.function.__name__))
de | f create_dir(directory, mode=0777):
"""
Ensure that the given directory is created with all intermediate directories.
:param directory: the directory to create.
:param mode: the directory mode. Default: 0777 (octal).
"""
if not os.path.exists(directory):
os.makedirs(directory, mode=mode... |
publica-io/django-attrs | attrs/models.py | Python | bsd-3-clause | 484 | 0 | # -*- coding: utf-8 -*-
from django.db import models
from entropy.mixins import GenericMixin
class Attribute(GenericMixin):
'''Generic Attribute'''
| name = models.SlugField(max_length=256)
value = models.CharField(max_length=2048)
class Meta:
ordering = ('name',)
verbose_name = 'Custom Name/Value Attribute'
| verbose_name_plural = 'Custom Name/Value Attributes'
def __unicode__(self):
return u'%s=%s' % (self.name, self.value,)
|
zephyrplugins/zephyr | zephyr.plugin.jython/jython2.5.2rc3/Lib/email/mime/text.py | Python | epl-1.0 | 1,006 | 0.000994 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Class representing text/* type MIME documents."""
__al | l__ = ['MIMEText']
from email.encoders import encode_7or8bit
from email.mime.nonmultipart import MIMENonMultipart
class MIMEText(MIMENonMultipart):
"""Class for generating text/* type MIME documents."""
def __init__(self, _text, _subtype='plain', _charset='us-ascii'):
"""Create a text/* type MIME ... | set parameter added to the Content-Type
header. This defaults to "us-ascii". Note that as a side-effect, the
Content-Transfer-Encoding header will also be set.
"""
MIMENonMultipart.__init__(self, 'text', _subtype,
**{'charset': _charset})
self.... |
BD2KGenomics/slugflow | src/toil/realtimeLogger.py | Python | apache-2.0 | 9,303 | 0.002902 | # Copyright (C) 2015-2021 Regents of the University of California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | :
assert cls.initialized > 0
cls.initialized -= 1
if cls.initialized == 0:
if cls.loggingServer:
logger.info('Stopping real-time logging server.')
cls.loggingServer.shutdown()
cls.loggingServer = None
... | rverThread:
logger.info('Joining real-time logging server thread.')
cls.serverThread.join()
cls.serverThread = None
for k in list(os.environ.keys()):
if k.startswith(cls.envPrefix):
os.environ.pop(k)
... |
shamrin/pyxtf | segy.py | Python | mit | 6,783 | 0.003243 | """segy.py - read and write SEG-Y files
From command line:
python segy.py <path-to-segy-file>
"""
from collections import OrderedDict
from pprint import pprint
import numpy as np
from sacker import Sacker
# SEG-Y spec: http://www.tritonimaginginc.com/site/content/public/downloads/FileFormatInfo/seg_y_rev1.pdf
... | ing this trace
h n_of_horizontally_summed_traces # yielding this trace
h data_use # (1 - production, 2 - test)
i source_reciever_dist
i reciever_elevation
i surface_elevation_at_source
i source_depth_below_surface # (a positive number)
i datum_elevation_at_recieve... | rce
i water_depth_at_source
i water_depth_at_reciever
h elevations_scaler # (1, 10, 100, 1000, 10000)
h coordinates_scaler # (1, 10, 100, 1000, 10000)
i source_coord_x
i source_coord_y
i reciever_coord_x
i reciever_coord_y
h coordinate_units # (1: length, 2: secs of arc, 3: decim... |
APSL/kaneda | tests/integration/django/test_django.py | Python | mit | 1,213 | 0 | from kaneda.backends import LoggerBackend, ElasticsearchBackend
from kaneda.queues import CeleryQueue
from django_kaneda import settings # NOQA
class TestDjango(object):
def test_django_kaneda_with_backend(self, mocker, django_settings_backend):
mocker.patch('django_kaneda.settings', django_settings_bac... | ce(metrics.backend, ElasticsearchBackend)
result = metrics. | gauge('test_gauge', 42)
assert result
def test_django_kaneda_with_debug(self, mocker, django_settings_debug):
mocker.patch('django_kaneda.settings', django_settings_debug)
from django_kaneda import LazyMetrics
metrics = LazyMetrics()
metrics.gauge('test_gauge', 42)
a... |
faxioman/django-storages | tests/test_s3boto3.py | Python | bsd-3-clause | 13,892 | 0.001008 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
import gzip
try:
from unittest import mock
except ImportError: # Python 3.2 and below
import mock
from django.test import TestCase
from django.conf import settings
from django.core.files.base import ContentFile
from... | should be preserved.
self.assertEqual(self.storage.url(''), 'https://example.com/')
self.assertEqual(self.storage.url('path'), | 'https://example.com/path')
self.assertEqual(self.storage.url('path/'), 'https://example.com/path/')
self.assertEqual(self.storage.url('path/1'), 'https://example.com/path/1')
self.assertEqual(self.storage.url('path/1/'), 'https://example.com/path/1/')
def test_storage_save(self):
"... |
AntonPashkowskiy/Tars | Program/monitoring/monitor.py | Python | mit | 5,353 | 0.003736 | #!/usr/bin/python3
from messaging.messaging_manager import MessagingManager, MessagingManagerType
from common.monitoring import monitor_event_types as event_types
from common.monitoring.monitor_message import MonitorMessage
from inotify.adapters import Inotify
from inotify import constants as inotify_constants
from th... | monitor_messaging_manager.send_message(str(message))
else:
for message in messages:
monitor_messaging_manager.send_message(str(message))
else:
if stop_events_processing_flag.is_set():
stop_events_processing_flag.clear()
... | /127.0.0.1:5555")
watch_paths_list = [ b'/home/anton/test/' ]
pair_events_list = []
stop_events_processing_flag = Event()
for path in watch_paths_list:
monitor.add_watch(path, inotify_constants.IN_MOVE | inotify_constants.IN_MOVED_TO | inotify_constants.IN_MOVED_FROM | inotify_constants.IN_CREA... |
0x7678/youtube-dl | youtube_dl/extractor/soundcloud.py | Python | unlicense | 14,130 | 0.001912 | # encoding: utf-8
from __future__ import unicode_literals
import re
import itertools
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_urlparse,
compat_urllib_parse,
)
from ..utils import (
ExtractorError,
int_or_none,
unified_strdate,
)
class SoundcloudIE(InfoExtra... | on': 143,
}
},
# not streamable song
{
'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
'info_dict': {
'id': '47127627',
'ext': 'mp3',
'title': '... | 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
'uploader': 'The Royal Concept',
'upload_date': '20120521',
'duration': 227,
},
'params': {
# rtmp
'skip_do... |
roboticslab-uc3m/xgnitive | programs/drl/envs/grid_world_3D_env.py | Python | lgpl-2.1 | 6,357 | 0.009596 | import numpy as np
from .base import Env
from rllab.spaces import Discrete
from rllab.envs.base import Step
from rllab.core.serializable import Serializable
MAPS = {
"chain": [
"GFFFFFFFFFFFFFSFFFFFFFFFFFFFG"
],
"4x4_safe": [
"SFFF",
"FWFW",
"FFFW",
"WFFG"
],
... | free space
'W' or 'x': wall
'H' or 'o': hole (terminates episode)
'G' : goal
"""
def __init__(self, desc='4x4'):
Serializable.quick_init(self, locals())
#print("desc before isinstance",desc)
if isinstance(desc, str):
desc = MAPS[desc]
#print("desc befor... | c[0])
desc[1] = list(map(list, desc[1]))
#print(desc[1])
desc= np.array(list(desc))
#print("desc after nparray \n",desc)
desc[desc == '.'] = 'F'
desc[desc == 'o'] = 'H'
desc[desc == 'x'] = 'W'
self.desc = desc
self.levels, self.n_row, self.n_col = ... |
francois-vincent/fabric_navitia | fabfile/component/tyr.py | Python | agpl-3.0 | 25,070 | 0.004866 | # coding=utf-8
# Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of fabric_navitia, the provisioning and deployment tool
# of Navitia, the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by C... | dir(env.tyr_migration_dir):
files.symlink('/usr/share/tyr/migrations/', env.tyr_migration_dir, use_sudo=True)
sudo("chown www-data:www-data {}".format(env | .tyr_migration_dir))
# we create a symlink for tyr manage_py
tyr_symlink = os.path.join(env.tyr_basedir, 'manage.py')
if not files.is_file(tyr_symlink):
files.symlink('/usr/bin/manage_tyr.py', tyr_symlink, use_sudo=True)
service.start('rabbitmq-server')
service.start('redis-server')
@task... |
nkgilley/home-assistant | tests/components/solarlog/test_config_flow.py | Python | apache-2.0 | 4,886 | 0.000614 | """Test the solarlog config flow."""
import pytest
from homeassistant import config_entries, data_entry_flow, setup
from homeassistant.components.solarlog import config_flow
from homeassistant.components.solarlog.const import DEFAULT_HOST, DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME
from tests.async_m... | : "http://1.1.1.1"}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
as | sert len(mock_setup_entry.mock_calls) == 1
@pytest.fixture(name="test_connect")
def mock_controller():
"""Mock a successful _host_in_configuration_exists."""
with patch(
"homeassistant.components.solarlog.config_flow.SolarLogConfigFlow._test_connection",
return_value=True,
):
yield... |
nkmk/python-snippets | notebook/pandas_crosstab.py | Python | mit | 6,511 | 0.007986 | import pandas as pd
df = pd.read_csv('data/src/titanic_train.csv', index_col=0).drop(['Name', 'Ticket', 'SibSp', 'Parch'], axis=1)
print(df.head())
# Survived Pclass Sex Age Fare Cabin Embarked
# PassengerId
# 1 0 ... | Q S
# Sex
# female 0.073718 0.105769 0.282051 |
# male 0.074523 0.067591 0.459272
# All 0.074241 0.080990 0.397075
# print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']],
# margins=True, normalize='columns'))
# ValueError: Length of new names must be 1, got 2
print(pd.crosstab(df['Sex'], [df['Pclass'], df['Embarked']]... |
almarklein/bokeh | sphinx/source/tutorial/solutions/histogram.py | Python | bsd-3-clause | 4,587 | 0.00131 | # -*- coding: utf-8 -*-
import numpy as np
import scipy.special
from bokeh.plotting import figure, output_file, show, VBox
mu, sigma = 0, 0.5 # NOTE: you can tinker with these values if you like
# sample the distribution
measured = np.random.normal(mu, sigma, 1000)
hist, edges = np.histogram(measured, density... | .pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))
cdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2
# EXERCISE: output to a static HTML file
output_file('histogram.html')
# create a new figure
p1 = figure(title="Normal Distribution (μ=0, σ=0.5)",
background_fill="#E8DDCB", tools="")
# Use the `quad` rende... | ay the histogram bars.
p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
fill_color="#036564", line_color="#033649")
# Use `line` renderers to display the PDF and CDF
p1.line(x, pdf, line_color="#D95B43", line_width=8, alpha=0.7, legend="PDF")
p1.line(x, cdf, line_color="white", line_width=2, alpha=... |
Ferdous-Al-Imran/Aqualizer | website/website/sensorValue/urls.py | Python | mit | 181 | 0.038674 | from d | jango.conf.urls import patterns,include,url
from . import views
app_name='sensorValue'
urlpatterns = [
url(r'^([0-9]+)/$',views.SensorValueView,name='sensorValue'),
|
] |
jboynyc/cmus_app | tests.py | Python | agpl-3.0 | 433 | 0.004619 | import unittest
from app import re | ad_config
class ConfigFileReaderTest(unittest.TestCase):
def test_read(self):
config = read_config('config')
self.assertEqual(config['cmus_host'], 'raspberry')
self.assertEqual(config['cmus_passwd'], 'PaSsWd')
self.assertEqual(config['app_host'], 'localhost')
self.assertEqua... | _name__ == '__main__':
unittest.main()
|
VISTAS-IVES/pyvistas | source/vistas/core/graphics/object.py | Python | bsd-3-clause | 1,952 | 0.002049 | from pyrr import Vector3
from vistas.core.bounds import BoundingBox
class Object3D:
""" Partially abstract class defining the base API for interacting with 3D objects. """
def __init__(self):
self.position = Vector3([0.] * 3)
self.scale = Vector3([1.] * 3)
self.rotation = Vector3([0.... | tersection:
""" Container for describing an in | tersection at a point on an Object3D """
def __init__(self, distance, point, obj):
self.distance = distance
self.point = point
self.object = obj
self.uv = None
self.face = None
self.face_index = None
|
clucas111/delineating-linear-elements | Code/par_pipeline.py | Python | apache-2.0 | 2,520 | 0 | # -*- coding: utf-8 -*-
"""
Computes point neighbourshood parameters and removes irrelevant points.
@author: Chris Lucas
"""
import pandas as pd
import time
import os
from scipy.spatial import cKDTree
fro | m data_preprocessing import las_to_csv, downsample
from par_computation import neighbourhood_features
# %% file paths
las_path = "/Data/ResearchArea.las"
las2txt_path = "D:/MasterThesis/LAStools/LAStools/bin/las2txt.exe"
CloudCompare_path = "C:/Program Files/CloudCompare/CloudCompare.exe"
# %% Prepare data and load i... | point cloud and convert to csv
las = downsample(las_path, 0.3, tool_path=CloudCompare_path)
csv_path = las_to_csv(las, method='las2txt', tool_path=las2txt_path)
# Load the csv point cloud file
print "Loading point cloud csv file using pandas.."
point_cloud = pd.read_csv(csv_path, delimiter=';', header=None,
... |
2ndy/RaspIM | usr/share/python-support/python-soappy/SOAPpy/Parser.py | Python | gpl-2.0 | 35,390 | 0.007884 | # SOAPpy modules
from Config import Config
from Types import *
from NS import NS
from Utilities import *
import string
import fpconst
import xml.sax
from wstools.XMLname import fromXMLname
try: from M2Crypto import SSL
except: pass
ident = '$Id: Parser.py,v 1.16 2005/02/22 04:29:42 warnes Exp $'
from v... | )
self.body = None
self.header = None
self.attrs = {}
self._data = None
self._next = "E" # Keeping state for message validity
self._stack = [self.Frame('SOAP')]
# Make two dictionaries to store the prefix <-> URI mappings, and
... | = {}
self._rules = rules
def startElementNS(self, name, qname, attrs):
# Workaround two sax bugs
if name[0] == None and name[1][0] == ' ':
name = (None, name[1][1:])
else:
name = tuple(name)
# First some checking of the layout of the message
... |
pasha369/Points | points/appls/points/models/country.py | Python | mit | 561 | 0.012478 | # -*- coding: utf-8 -*-
from django.db import models
from appls.login.models import BaseUser
class Country(mode | ls.Model):
"""
Model for Country
"""
name = models.CharField(max_length=100, blank=False, default='default category')
class Meta:
ordering = ('name',)
class City(models.Model):
"""
Model for City
"""
country = models.ForeignKey('Category', default=1)
name = models.C... | ield(max_length=100, blank=False, default='default category')
class Meta:
ordering = ('name',)
|
developerQuinnZ/this_will_work | student-work/hobson_lane/exercism/python/leap/leap.py | Python | mit | 334 | 0 | def is_leap_year(yr):
""" Is the integer year (0-100000) a leap year
return true on every year that is evenly divisible by 4
except every ye | ar that is evenly divisible by 100
unless the year is also evenly divisible by 400
"""
return boo | l(not yr % 4 and (yr % 100 or not yr % 400))
|
socradev/django-fancypages | fancypages/dashboard/forms.py | Python | bsd-3-clause | 5,558 | 0 | from django import forms
from django.db.models import get_model, QuerySet
from django.utils.translation import ugettext_lazy as _
from ..utils import unicode_slugify as slugify
from ..utils import get_page_model, get_node_model
# PageNode = get_node_model()
# FancyPage = get_page_model()
# PageType = get_model('fancy... | if fname in self.node_field_names:
node_data[fname] = fvalue
else:
page_data[fname] = fvalue
if not self.instance.id:
try:
parent = FancyPage.objects. | get(pk=self.parent_pk)
except FancyPage.DoesNotExist:
parent = None
if parent:
self.instance.node = parent.node.add_child(**node_data)
else:
self.instance.node = PageNode.add_root(**node_data)
else:
for key, value i... |
astrorafael/ema | ema/dev/photometer.py | Python | mit | 4,416 | 0.011775 | # ----------------------------------------------------------------------
# Copyright (c) 2014 Rafael Gonzalez.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including... | A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# --------... | ----------
import logging
import re
from ema.emaproto import MVI, MVD
from ema.parameter import Parameter
from ema.vector import Vector
from ema.device import Device
log = logging.getLogger('photomete')
THRESHOLD = {
'name': 'Photometer Threshold',
'logger' : 'photomete',
'mult': 10.0, ... |
sorenh/cc | vendor/Twisted-10.0.0/twisted/conch/client/direct.py | Python | apache-2.0 | 3,234 | 0.004947 | # Copyright (c) 2001-2008 Twisted Matrix Laboratories.
# See LICENSE for details.
from twisted.internet import defer, protocol, reactor
from twisted.conch import error
from twisted.conch.ssh import transport
from twisted.python import log
class SSHClientFactory(protocol.ClientFactory):
def __init__(self, d, o... | SSHClientTransport.connectionLost(self, reason))
def receiveError(self, code, desc):
if self.factory.d is None:
return
d, self.factory.d = self.factory.d, Non | e
d.errback(error.ConchError(desc, code))
def sendDisconnect(self, code, reason):
if self.factory.d is None:
return
d, self.factory.d = self.factory.d, None
transport.SSHClientTransport.sendDisconnect(self, code, reason)
d.errback(error.ConchError(reason, code))... |
lsowen/pySchannelSSL | sslcontext.py | Python | gpl-2.0 | 19,919 | 0.010442 | from ctypes import *
import ctypes
from ctypes.wintypes import *
from _ssl import SSLError
import sys
CRYPT32 = windll.Crypt32
SCHANNEL = windll.SChannel
# Lots of "Magic" constants, mainly from schannel.h
SCH_CRED_NO_SYSTEM_MAPPER = 0x00000002
SCH_CRED_NO_DEFAULT_CREDS = 0x00000010
SCH_CRED_REVOCATION_CHECK_CHAIN... | = 4
SP_PROT_SSL3_CLIENT = 0x00000020
SP_PROT_SSL2_CLIENT = 0x00000008
SP_PROT_TLS1_1_CLIENT = 0x00000200
SCHANNEL_CRED_VERSION = 0x00000004
UNISP_NAME = "Mi | crosoft Unified Security Protocol Provider"
SECPKG_CRED_OUTBOUND = 0x00000002
SECURITY_NATIVE_DREP = 0x00000010
SECBUFFER_VERSION = 0
SECBUFFER_EMPTY = 0
SECBUFFER_DATA = 1
SECBUFFER_TOKEN = 2
SECBUFFER_EXTRA = 5
SECBUFFER_STREAM_TRAILER = 6
SECBUFFER_STREAM_HEADER = 7
ISC_REQ_SEQUENCE_DETECT = 0x00000008
ISC_REQ_... |
dlshriver/pinq | tests/test_queryable_difference.py | Python | mit | 1,827 | 0 | import unittest
import pinq
class queryable_difference_tests(unittest.TestCase):
def setUp(self):
self.queryable1 = pinq.as_queryable(range(1, 11))
self.queryable2 = pinq.as_queryable(range( | 2, 10, 2))
def test_difference_list(self):
self.assertEqual(list(self.queryable1.difference(
[1, 3, 5, 7, 9])), [2, 4, | 6, 8, 10])
def test_difference_list_remove_all(self):
self.assertEqual(list(self.queryable1.difference(
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10])), [])
def test_difference_list_remove_none(self):
self.assertEqual(list(self.queryable1.difference(
[15])), [1, 2, 3, 4, 5, 6, 7, 8,... |
font/ceph-ansible | tests/functional/tests/nfs/test_nfs_ganesha.py | Python | apache-2.0 | 1,987 | 0.00302 | import json
import pytest
class TestNFSs(object):
@pytest.mark.no_docker
def test_nfs_ganesha_is_installed(self, node, host):
assert host.package("nfs-ganesha").is_installed
@pytest.mark.no_docker
def test_nfs_ganesha_rgw_package_is_installed(self, node, host):
assert host.package("nf... | nesha/ganesha.conf").contains("Entries_HWMark")
def test_nfs_is_up(self, node, host):
hostname = node["vars"]["inventory_hostname"]
cluster = node['cluster_name']
if node['docker']:
docker_exec_cmd = 'docker exec ceph-nfs-{hostname}'.format(hostname=hostname)
else:
... | ame}/keyring --cluster={cluster} --connect-timeout 5 -f json -s".format(
docker_exec_cmd=docker_exec_cmd,
hostname=hostname,
cluster=cluster
)
output = host.check_output(cmd)
daemons = [i for i in json.loads(output)["servicemap"]["services"]["rgw-nfs"]["daemon... |
quintusdias/glymur | glymur/tiff.py | Python | mit | 24,820 | 0 | # standard library imports
import io
import logging
import struct
import warnings
# 3rd party library imports
import numpy as np
from uuid import UUID
# local imports
from glymur import Jp2k
from .lib import tiff as libtiff
from .jp2box import UUIDBox
# Map the numeric TIFF datatypes to the format string used by th... | gs_position + len(buffer)
if self.version == _BIGTIFF:
tag_format_str = endian + 'HHQQ'
tag_payload_offset = 12
max_tag_payload_length = 8
else:
tag_format_str = endian + 'HHII'
tag_payload_offset = 8
max_ta | g_payload_length = 4
for idx in range(num_tags):
self.logger.debug(f'tag #: {idx}')
b.seek(start_of_tags_position + idx * little_tiff_tag_length)
tag_data = buffer[idx * tag_length:(idx + 1) * tag_length]
tag, dtype, nvalues, offset = struct.unpack(tag_format... |
Sorsly/subtle | google-cloud-sdk/lib/surface/compute/instances/add_tags.py | Python | mit | 2,551 | 0.00196 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | es when addin | g network
firewall rules. Tags can also be used to get firewall rules that
already exist to be applied to the instance. See
gcloud_compute_firewall-rules_create(1) for more details.
""",
}
|
achamely/omniwallet | api/cacher.py | Python | agpl-3.0 | 786 | 0.048346 | import config
import redis
import json
r = redis.StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB)
try:
expTime=config.BTCBAL_CACHE
except | :
expTime=600
def rGet(key):
return r.get(key)
def rSet(key,value):
return r.set(key,value)
def rExpire(key,sec):
return r.expire(key,sec)
def rDelete(key):
return r.delete(key)
def rKeys(key):
return r.keys(key)
def rSetNotUpdateBTC(baldata | ):
fresh=baldata['fresh']
if fresh!=None and len(fresh)>0:
for addr in fresh:
rSet("omniwallet:balances:address:"+str(addr),json.dumps( {"bal":baldata['bal'][addr],"error":None}))
rExpire("omniwallet:balances:address:"+str(addr),expTime)
def rExpireAllBalBTC():
for addr in rKeys("omniwallet:balan... |
74105/aspp | crypto.py | Python | mit | 1,451 | 0.004824 | import sys
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto import Random
#AES key size
AES_KEY_SIZE = 32
# Uses null character as the padding character
PADDING_VALUE = '/0'
def padAES(message):
lacking_char_num = | (AES.block_size - (len(message) % AES.block_size)) % A | ES.block_size
padded_message = message + lacking_char_num * PADDING_VALUE
return padded_message
def encryptAES(message):
# Get a random AES_BLOCK_SIZE byte key for AES
aes_key = Random.new().read(AES_KEY_SIZE)
# Initialization Vector
iv = Random.new().read(AES.block_size)
# Create a ciph... |
okwow123/djangol2 | example/cmanage/migrations/0002_auto_20170522_0728.py | Python | mit | 637 | 0.00157 | # -*- coding: utf-8 | -*-
# Generated by Django 1.11 on 2017-05-22 07:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cmanage', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='cmana... | rField(
model_name='cmanage',
name='user_email',
field=models.CharField(max_length=50),
),
]
|
buckket/mtg-deck-editor | setup.py | Python | gpl-3.0 | 1,349 | 0.000741 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='mtg-deck-editor',
version='1.0.3',
url='https://github.com/buckket/mtg-deck-editor',
author='buckket',
author_email='buckket@cock.li',
packages=['mtgdeckeditor'],
package_dir={'mtgdeckeditor': 'mtgdec... | lib',
'PyGObject',
'setuptools',
'pip'
],
entry_points={
'gui_scripts': [
'mtg-deck-editor = mtgdeckeditor.__main__:main',
]
},
description='A GUI deck editor for the card game Magic: The Gathering.',
long_description=open('./README.rst', 'r').re... | ming Language :: Python',
'Operating System :: OS Independent',
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Intended Audience :: End Users/Desktop',
'Topic :: Games/Entertainment',
],
)
|
FEniCS/dolfin | site-packages/dolfin/common/__init__.py | Python | lgpl-3.0 | 799 | 0 | # -*- coding: utf-8 -*-
"""The common module of dolfin"""
from dolfin.common import globalparameters
from dolfin.common import constants
from dolfin.common import plotting
from dolfin.common import time
from dolfin.common import memory
from dolfin.common import math
from dolfin.common import timer
from .globalparamete... | ng import *
from .time import *
from .memory import *
from .math import *
from .timer import *
# NOTE: The automatic documentation system in DOLFIN requires to _not_ define
# NOTE: classes or functions within this file. Use separate modules for that
# NOTE: purpose.
__all__ = globalparameters.__all__ + constants.__al... | plotting.__all__ + timer.__all__
|
cjaymes/pyscap | src/scap/model/ai_1_1/ExtendedInformationType.py | Python | gpl-3.0 | 933 | 0.001072 | # Copyrigh | t 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP is free software: you can redistribute it and/or modify
# it under the terms of th | e GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PySCAP is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICU... |
mmottahedi/neuralnilm_prototype | scripts/e438.py | Python | mit | 8,414 | 0.006656 | from __future__ import print_function, division
import matplotlib
import logging
from sys import stdout
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from neuralnilm import (Net, RealApplianceSource,
BLSTMLayer, DimshuffleLayer,
B | idirectionalRecurrentLayer)
from neuralnilm.source import standardise, discretize, fdiff, power_and_fdiff
from neuralnilm.experiment import run_experiment, init_experiment
from neuralnilm.n | et import TrainingError
from neuralnilm.layers import MixtureDensityLayer
from neuralnilm.objectives import (scaled_cost, mdn_nll,
scaled_cost_ignore_inactive, ignore_inactive,
scaled_cost3)
from neuralnilm.plot import MDNPlotter, CentralOutputPlott... |
Reactive-Extensions/RxPy | tests/test_group_join.py | Python | apache-2.0 | 84,360 | 0.001814 | from datetime import timedelta
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDi | sposable
on_next = ReactiveTest.o | n_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
created = ReactiveTest.created
class TimeSpan(object):
def from_ticks(self, value):
return value
class TimeInterval(obje... |
rosscdh/django-crocodoc | dj_crocodoc/tests/__init__.py | Python | gpl-2.0 | 69 | 0.014493 | # -*- coding: utf-8 -*-
f | rom .actions import *
from .signals import * | |
kyuridenamida/atcoder-tools | tests/resources/test_codegen/test_default_code_generators_and_templates/python/expected_echo_generated_code.py | Python | mit | 1,316 | 0.00228 | #!/usr/bin/env python3
import sys
MOD = 123 # type: int
YES = "yes" # type: str
NO = "NO" # type: str
def solve(N: int, M: int, H: "List[List[str]]", A: "List[int]", B: "List[float]", Q: int, X: "List[int]"):
print(N, M)
assert len(H) == N - 1
for i in range(N - 1):
assert len(H[i]) == M - 2
... | in range(M - 1 - 2 + 1)] for _ in range(N - 2 + 1)] # type: "List[List[str]]"
A = [int()] * (N - 2 + 1) # type: "List[int]"
B | = [float()] * (N - 2 + 1) # type: "List[float]"
for i in range(N - 2 + 1):
A[i] = int(next(tokens))
B[i] = float(next(tokens))
Q = int(next(tokens)) # type: int
X = [int(next(tokens)) for _ in range(M + Q)] # type: "List[int]"
solve(N, M, H, A, B, Q, X)
if __name__ == '__main__':
... |
derekwan1/practice | practice/practice.py | Python | apache-2.0 | 1,441 | 0.034698 | """
Generates HTML from markdown
Usage:
practice.py <filepath>
"""
import docopt
import os
from jinja2 import Environment
from jinja2 import PackageLoader
from jinja2 import Template
def generator(lines):
"""
>>> lines = ['Question: 1', 'Option: 1', 'Question: 2', 'Option: 3', "Question: 3", "Option: 4"]
>>> qu... | utted at', outpath)
def main():
arguments = docopt.docopt(__doc__, version='Practice 1.0')
env = Environment(loader=PackageLoader('practice', 'templates'))
template = env.get_template('index.html')
path = arguments['<filepath>']
if os.path.isdir(path):
os.makedirs(os.path.join('outputs', path), exist_ok=True)
... | path, template)
if __name__ == '__main__':
main() |
numenta/nupic.research | src/nupic/research/frameworks/vernon/mixins/multi_cycle_lr.py | Python | agpl-3.0 | 4,655 | 0.000644 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | True
super().setup_experiment(config)
if ignored_class is not None and ignored_class != OneCycleLR:
self.logger.warning("Ignoring lr_scheduler_class, using OneCycleLR")
if ignored_args is not None and len(ignored_args) > 0:
self.logger.warning("Ignoring lr_scheduler_arg... | r_args = sorted(config["multi_cycle_lr_args"],
key=lambda x: x[0])
for i, (start_epoch, cycle_config) in enumerate(multi_cycle_lr_args):
if i + 1 < len(multi_cycle_lr_args):
end_epoch = multi_cycle_lr_args[i + 1][0]
else:
... |
vjdorazio/TwoRavens | tworavensproject/urls.py | Python | bsd-3-clause | 979 | 0.001021 | from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
admin.site.site_header = 'TwoRavens Administration'
admin.site.index_title = ('TwoRavens Admin')
admin.site.site_title = ('TwoRavens Admin page')
urlpatterns = [
u... | include('tworaven_apps.configurations.urls')),
url(r'^d3m-service/', include('tworaven_apps.ta2_interfaces.urls')),
url(r'^data/', | include('tworaven_apps.test_data.urls')),
url(r'^', include('tworaven_apps.content_pages.urls')),
] + static(settings.STATIC_URL,
#document_root=settings.STATIC_ROOT)
document_root=settings.TEST_DIRECT_STATIC)
"""
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url... |
Yaco-Sistemas/yith-library-server | yithlibraryserver/scripts/backups.py | Python | agpl-3.0 | 3,033 | 0 | # Yith Library Server is a password storage server.
# Copyright (C) 2013 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | his._id.str.charCodeAt(i);
}
return sum %% 28 === %d;
}
''' % day
}).sort('date_joined')
def get_selected_users(request, *emails):
for email in emails:
for user in request.db.users.find({
'email': email,
}).sort('date_joined'):
yield user
d... | ance(result, int):
return result
else:
settings, closer, env, args = result
try:
request = env['request']
if len(args) == 0:
user_iterator = get_all_users(request)
else:
user_iterator = get_selected_users(request, *args)
tx = transaction... |
dsg-bielefeld/deep_disfluency | deep_disfluency/utils/accuracy.py | Python | mit | 2,054 | 0.01704 | # Legacy:
def save_to_disfeval_file(p, g, w, f, filename, incremental=False):
'''
INPUT:
p :: predictions
g :: groundtruth
w :: corresponding words
f :: original input gold standard file
OUTPUT:
filename :: name of the file where the predictions
are written. In right format for disf... | e
#words, but by virtue of knowing it's the end of the sequence it could change
#always have an iteration over the ground truth utt to give the prefixes
#with the predictions all the prefixes of this
for sl, sp, sw in zip(g, p, w): # for each utterance
prefix = [] # init the ... | adding an extra word position
sl.append('O')
sp[-1].append('O') #trivially not evaluated
for wl, pp, w in zip(sl, sp, sw): #for each prefix in the utt pp = prefix prediciton, not just latest word
prefix.append(w + ' ' + wl + ' ')
assert(len(prefix)==le... |
arek125/remote-GPIO-control-server | tsl2561.py | Python | mit | 9,124 | 0.014029 | #!/usr/bin/python
# Code sourced from AdaFruit discussion board: https://www.adafruit.com/forums/viewtopic.php?f=8&t=34922 and https://github.com/seanbechhofer/raspberrypi/blob/master/python/TSL2561.py
import sys
import time
import re
import smbus
class Adafruit_I2C(object):
@staticmethod
def getPiRevision():
... | g:
print ("I2C: Device 0 | x%02X returned 0x%02X from reg 0x%02X" %
(self.address, result & 0xFF, reg))
return result
except IOError, err:
return self.errMsg()
def readS8(self, reg):
"Reads a signed byte from the I2C device"
try:
result = self.bus.read_byte_data(self.address, reg)
if result > 127: ... |
orbitfp7/horizon | openstack_dashboard/dashboards/admin/volumes/volume_types/forms.py | Python | apache-2.0 | 7,679 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ('back-end',
_('back-end')))
| )
cipher = forms.CharField(label=_("Cipher"), required=False)
key_size = forms.IntegerField(label=_("Key Size (bits)"),
required=False,
min_value=1)
volume_type_id = forms.CharField(widget=forms.HiddenInput())
def handle(self, request... |
remvo/zstt-ros | src/gamecontroller_msgs/src/gamestate.py | Python | apache-2.0 | 1,560 | 0.000641 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import constants
from construct import Byte, Struct, Enum, Bytes, Const, Array, Renamed, Int16ul
Short = Int16ul
RobotInfo = "robot_info" / Struct(
"penalty" / Enum(Byte, constants.SPLPenalty),
"secs_till_unpenalised" / Byte,
"number_of_yellow_cards" / Byte,
... | o,
"players" / Array(11, RobotInfo)
)
GameState = "gamedata" / Struct(
"header" / Const(constants.GAMECONTROLLER_STRUCT_HEADER, Bytes(4)),
"version" / Const(constants.GAMECONTROLLER_STRUCT_VERSION, Short),
"packet_number" / Byte,
"players_per_team" | / Byte,
"game_type" / Byte,
"game_state" / Enum(Byte, constants.State),
"first_half" / Byte,
"kick_of_team" / Byte,
"secondary_state" / Enum(Byte, constants.State2),
"secondary_state_info" / Bytes(4),
"drop_in_team" / Byte,
"drop_in_time" / Short,
"seconds_remaining" / Short,
"se... |
nucular/AutobahnPython | examples/twisted/websocket/echo_variants/client_reconnecting.py | Python | mit | 3,140 | 0.000318 | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... | s
from twisted.internet import reactor
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.python import log
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
class EchoClientProtocol(WebSocketClientProtocol):
def sendHello(se... | print("Text message received: {}".format(payload.decode('utf8')))
reactor.callLater(1, self.sendHello)
class EchoClientFactory(ReconnectingClientFactory, WebSocketClientFactory):
protocol = EchoClientProtocol
# http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.Reconn... |
quattor/aquilon | lib/aquilon/worker/formats/network_environment.py | Python | apache-2.0 | 1,782 | 0.000561 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2017 Contributor
#
# 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... | n.worker.formats.formatters import ObjectFormatter
class NetworkEnvironmentFormatter(ObjectFormatter):
def format_raw(self, netenv, indent="", embedded=True,
indirect_attrs=True):
details = [indent + "{0:c}: {0.name}".format(netenv)]
details.append(self.redirect_raw(netenv.dns_e... | ion:
details.append(self.redirect_raw(netenv.location, indent + " "))
if netenv.comments:
details.append(indent + " Comments: %s" % netenv.comments)
return "\n".join(details)
def fill_proto(self, netenv, skeleton, embedded=True, indirect_attrs=True):
skeleton.name ... |
nicolashainaux/mathmaker | tests/integration/mental_calculation/02_white2/test_02_white2_W03c.py | Python | gpl-3.0 | 1,240 | 0 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2018 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | r is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied w | arranty 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 Mathmaker; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-130... |
tarikgwa/nfd | newfies/mod_utils/function_def.py | Python | mpl-2.0 | 3,788 | 0.001584 | #
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The primar... | if STATUS_OF_CAMPAIGN.ABORT == id:
return '<font color="%s">%s</fo | nt>' % (STATUS_COLOR[id], _("Aborted"))
else:
return '<font color="%s">%s</font>' % (STATUS_COLOR[id], _("Stopped"))
def get_status_value(value, STATUS_LIST):
"""common function to get status value
example: get_status_value(1, EVENT_STATUS)
get_status_value(3, ALARM_STATUS)
"""
... |
opiethehokie/march-madness-predictions | ml/util.py | Python | apache-2.0 | 1,932 | 0.00207 | # Copyright 2016-2018 Michael Peters
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | sult = func(*args, **kwargs)
p.disable()
return result
finally:
p.print_stats()
return profiled_func
# annotate a function with @print_models
def print_models(func):
def printed_func(*args, **kwargs):
model = func(*args, **kwargs)
cv_keys = ('mean_tes... | ults_[cv_keys[0]][r],
model.cv_results_[cv_keys[1]][r] / 2.0,
model.cv_results_[cv_keys[2]][r]))
print('Best parameters: %s' % model.best_params_)
print('Best accuracy: %.2f' % model.best_score_)
return model
... |
jiobert/python | Velez_Felipe/Asignments/Great Number Game/server.py | Python | mit | 1,419 | 0.032417 | from flask import Flask, render_template, redirect, session, request
import random
app = Flask(__name__)
app.secret_key ="Felipe"
@app.route('/')
def index():
if not 'number_to_guess' in session:
session['hidebutton'] = 'hide'
session['number_to_guess'] = random.randrange(0,101)
print session['number_to_guess']... | t again
@app.route('/reset', methods= ['POST'])
def clear_num():
se | ssion.clear()
return redirect('/')
app.run(debug = True)
|
DirectXMan12/nova-hacking | nova/tests/virt/xenapi/test_volumeops.py | Python | apache-2.0 | 8,113 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 Citrix 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/LICE... |
volumeops.volume_utils.purge_sr('session', 'srref')
self.mox.ReplayAll()
ops.detach_volume(
dict(driver_volume_type='iscsi', data='conn_data'),
'instance_1', 'mountpoint')
self.assertEquals(
['find_sr_from_vbd', 'destroy_vbd'], registered_calls)
... | volumeops.vm_utils, 'vm_ref_or_raise')
self.mox.StubOutWithMock(volumeops.volume_utils, 'get_device_number')
connection_info = dict(driver_volume_type='iscsi', data='conn_data')
volumeops.vm_utils.vm_ref_or_raise('session', 'instance_1').AndReturn(
'vmref')
volumeops.volum... |
D4Vinci/Dr0p1t-Framework | core/color.py | Python | mit | 3,614 | 0.092418 | #Written by: Karim shoair - D4Vinci ( Dr0p1t-Framework )
import sys
from os.path import *
global G, Y, B, R, W , M , C , end
def set_colors():
global G, Y, B, R, W , M , C , end
if sys.platform.startswith('win'):
# Windows deserve coloring too :D
try:
import win_unicode_console , colorama
win_unicode_conso... | al purposes. {}
Use it only for {}work{} or {} educational purpose {} !!!'''.format(R,B,Y,R,Y,R,W)
def print_status(args):
global G | , Y, B, R, W , M , C , end
set_colors() # because of some non logical error on some users devices :3
if args.s:
c1,a = G," Loaded "
else:
c1,a = R,"Unloaded"
if args.t:
c2,b = G," Loaded "
else:
c2,b = R,"Unloaded"
if args.k:
c3,c = G," Loaded "
else:
c3,c = R,"Unloaded"
if args.b:
c4,d = G,... |
ltog/mapillary_utils | general/remove_duplicates.py | Python | gpl-3.0 | 17,416 | 0.00201 | #!/usr/bin/env python
# from https://github.com/mapillary/mapillary_tools/
# The MIT License (MIT)
#
# Copyright (c) 2014 Mapillary AB
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software withou... | self._previous = None
self._latest_text = ""
self._previous_filepath = None
self._max_speed_km_h = max_speed_km_h
self._way | _too_high_speed_km_h = way_too_high_speed_km_h
self._high_speed = False
self._too_high_speed = False
def set_verbose(self, verbose):
self.verbose = verbose
def get_latest_text(self):
return self._latest_text
def is_error(self, file_path, exif_reader):
"""
Retur... |
forrestv/myhdl | example/cookbook/bitonic/bitonic.py | Python | lgpl-2.1 | 2,041 | 0.007349 | from myhdl import *
from myhdl.conversion import analyze
DESCENDING, ASCENDING = False, True
def | compare(a1, a2, z1, z2, dir):
@always_comb
| def logic():
z1.next = a1
z2.next = a2
if dir == (a1 > a2):
z1.next = a2
z2.next = a1
return logic
def feedthru(a, z):
@always_comb
def logic():
z.next = a
return logic
def bitonicMerge(a, z, dir):
n = le... |
trcook/wto_python_scrape | wto_scraper.py | Python | mit | 1,127 | 0.017746 | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import scrapy
import os
# IN the special case of the wto disputes, we need to get the list of all disputes, so we run this script preliminarily:
execfile("./fetchjson.py")
# Now we build the scraper:
# Fir... | esponse):
dispute=WTO_Dispute()
dispute['url']= response.xpath("//a/text()").extract()
# dispute['name']= # fill in here
# dispute['description']= # fill in here
return dispute
# based on http://doc.scrapy.org/en/0.24/intro/overview.html
# to run: run $ scrapy runspider wtoscr | aper.py -o wto_disputes.json
|
ricequant/rqalpha-mod-vnpy | rqalpha_mod_vnpy/ctp/api.py | Python | apache-2.0 | 22,615 | 0.000588 | # -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, 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 ... | path
self.req_id = 0
self.connected = False
self.logged_in = False
self.authenticated = False
self.user_id = user_id
self.password = password
self.broker_id = broker_id
self.address = address
self.auth_code = auth_code
self.user_productio... | = {}
self.order_cache = {}
self.api_name = api_name
def onFrontConnected(self):
"""服务器连接"""
self.connected = True
if self.require_authentication:
self.authenticate()
else:
self.login()
def onFrontDisconnected(self, n):
"""服务器断开""... |
SoftButterfly/CongCards | CongCards/wsgi.py | Python | lgpl-3.0 | 430 | 0 | """
WSGI config for CongCards project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.en... | )
| |
marios-zindilis/musicbrainz-django-models | musicbrainz_django_models/models/area_annotation.py | Python | gpl-2.0 | 1,538 | 0 | """
.. module:: area_annotation
The **Area Annotation** Model.
PostgreSQL Definition
---------------------
The :code:`area_annotation` table is defined in the MusicBrainz Server as:
.. code-block:: sql
CREATE TABLE area_annotation ( -- replicate (verbose)
area INTEGER NOT NULL, -- PK, references... | ation.id
);
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class area_annotation(models.Model):
"""
Not all parameters are listed here, only those that present some interest
in their Django implementation.
:param a | rea: references :class:`.area`. This field is interesting because
it is both a Foreign Key to the Area model, as well as the Primary Key
for the Area Annotation model. In Django, this can be implemented as a
`OneToOneField`.
:param annotation: references :class:`.annotation`. Both the `area`... |
StratusLab/client | api/code/src/test/python/installator/OneInstallatorTest.py | Python | apache-2.0 | 1,678 | 0.001788 | import unittest
from stratuslab.ConfigHolder import ConfigHolder
from stratuslab.installator.OpenNebulaFrontend import OpenNebulaFrontend
class OneInstallatorTest(unittest.TestCase):
VNET_INFO_XML = """
<VNET>
<ID>%s</ID>
<UID>0</UID>
<GID>0</GID>
<UNAME>oneadmin</UNAME>
<GNAME>oneadmin</GNAME>
<NAME... | LEASE>
</LEASES>
</VNET>
"""
def test_getNetworkIdsFromNetworkNames(self):
ch = ConfigHolder()
ch.set('frontendSystem', 'fedora')
ch.set('oneHome', '~')
ch.set('oneUsername', 'foo')
ch.set('onePassword', 'bar')
oi = OpenNebulaFrontend(ch)
def _getVnetInfoXm... | et_name == 'local':
xml = OneInstallatorTest.VNET_INFO_XML % ('1', vnet_name)
elif vnet_name == 'private':
xml = OneInstallatorTest.VNET_INFO_XML % ('2', vnet_name)
return xml
oi._getVnetInfoXml = _getVnetInfoXml
ids = oi._getVnetIdsFromVnetNames(... |
briancousins/RecipeBook | tests/test_grocerylist.py | Python | mit | 784 | 0.003827 | from classes import wunderpy_wrapper
from classes import grocerylist
from classes import grocerystore
wp = wunderpy_wrapper.wunderpy_wrapper('../data/tokens.csv')
obj = wp.get_task_positions_obj(wp.WUNDERLIST_ | GROCERY)
grocery_store = grocerystore.groceryStore('../data/store_order_zehrs.csv', '../data/ingredient_categories.csv') # use the default zehrs store; good enough
groceries = grocerylist.groceryList(wp.WUNDERLIST_GROCERY, wp)
groceries.get_tasks()
groceries.get_category_for_element(groceries.grocery_list[0], grocer... | t_categories(grocery_store)
groceries.reorder_list(wp)
# wp.update_list_order(groceries.wunderlist_order_obj)
# TODO check reloading of a list when you enter the right sheet
# TODO sort by cat order value, not cat id.
print('done') |
fjsj/liveservererror | testsettings.py | Python | mit | 487 | 0 | DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
| 'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'liveservererror',
)
SECRET_KEY = 'abcde12345'... | _URL = '/static/'
|
mhbu50/frappe | frappe/integrations/doctype/oauth_scope/oauth_scope.py | Python | mit | 228 | 0.008772 | # -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see licen | se.txt
# import frappe
from frappe.model.document import Document
cl | ass OAuthScope(Document):
pass
|
tofumatt/fat-mirror | app.py | Python | mit | 3,143 | 0.000318 | # import datetime
import json
import os
import re
import time
import redis
import requests
from flask import Flask, render_template
APP_URL = os.environ.get('URL')
ASSET_URLS = re.compile(r'(src|href)="(.*)"')
CSS_ASSETS = re.compile(r'(url\([\'|"]?(.*)[\'|"]?\))')
app = Flask(__name__)
if os.environ.get('ENV') is... | ze_of_url(os.environ.get('URL'))
redis.rpush('fatmirror-%s' % APP_UR | L, json.dumps(sizes))
return json.dumps(sizes)
@app.route('/update', methods=['POST'])
def post_receive_hook():
"""Listen for GitHub hooks and check the app's size again."""
sizes = size_of_url(os.environ.get('URL'))
redis.rpush('fatmirror-%s' % APP_URL, json.dumps(sizes))
return json.dumps(si... |
analyst-collective/dbt | core/dbt/parser/sql.py | Python | apache-2.0 | 2,013 | 0.000497 | import os
from dataclasses import dataclass
from typing import Iterable
from db | t.contracts.graph.manifest import SourceFile
from dbt.contracts.graph.parsed import ParsedSqlNode, ParsedMacro
from dbt.contracts.graph.unparsed import UnparsedMacro
from dbt.exceptions import InternalException
from dbt.node_types import NodeType
from dbt.parser.base import SimpleSQLParser
from dbt.parser.macros import... | FileBlock
@dataclass
class SqlBlock(FileBlock):
block_name: str
@property
def name(self):
return self.block_name
class SqlBlockParser(SimpleSQLParser[ParsedSqlNode]):
def parse_from_dict(self, dct, validate=True) -> ParsedSqlNode:
if validate:
ParsedSqlNode.validate(dct... |
explosion/srsly | srsly/ruamel_yaml/nodes.py | Python | mit | 3,716 | 0.002153 | # coding: utf-8
from __future__ import print_function
import sys
from .compat import string_types
if False: # MYPY
from typing import Dict, Any, Text # NOQA
class Node(object):
__slots__ = 'tag', 'value', 'start_mark', 'end_mark', 'comment', 'anchor'
def __init__(self, tag, value, start_mark, end_ma... | self.tag, self.value
)
)
if self.comment:
| sys.stdout.write(' {}comment: {})\n'.format(' ' * indent, self.comment))
return
sys.stdout.write(
'{}{}(tag={!r})\n'.format(' ' * indent, self.__class__.__name__, self.tag)
)
if self.comment:
sys.stdout.write(' {}comment: {})\n'.format(' ... |
Maelstroms38/ecommerce | src/products/migrations/0020_product_embed_code.py | Python | mit | 433 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db impo | rt models, migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0019_remove_thumbnail_user'),
]
operations = [
migrations.AddField(
mo | del_name='product',
name='embed_code',
field=models.CharField(max_length=500, null=True, blank=True),
),
]
|
Florianboux/zds-site | zds/forum/feeds.py | Python | gpl-3.0 | 4,497 | 0.00089 | # coding: utf-8
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Atom1Feed
from django.conf import settings
from zds.utils.templatetags.emarkdown import emarkdown
from .models import Post, Topic
class LastPostsFeedRSS(Feed):
title = u'Derniers messages sur {}'.format(se... | topic__forum__pk=obj['forum'],
topic__tags__pk__in=[obj['tag']])\
.order_by('-pubdate')
elif "forum" in obj and "tag" not in obj:
posts = Post.objects.filter(topic__forum__group__isnull=True,
topic__fo... | .order_by('-pubdate')
elif "forum" not in obj and "tag" in obj:
posts = Post.objects.filter(topic__forum__group__isnull=True,
topic__tags__pk__in=[obj['tag']])\
.order_by('-pubdate')
if "forum" not in obj and "tag" not in obj:
... |
Juniper/neutron | neutron/plugins/vmware/plugins/service.py | Python | apache-2.0 | 81,232 | 0.000591 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/lic... | ice-router",
"routed-service-insertion",
"fwaas",
"lbaas",
| "vpnaas"
])
def __init__(self):
super(NsxAdvancedPlugin, self).__init__()
self._super_create_ext_gw_port = (
self._port_drivers['create'][l3_db.DEVICE_OWNER_ROUTER_GW])
self._super_delete_ext_gw_port = (
self._port_drivers['delete'][l3_db.DEVICE_O... |
OCA/vertical-isp | connector_equipment/models/maintenance_equipment.py | Python | agpl-3.0 | 1,795 | 0 | # Copyright (C) 2018 - TODAY, Open Source Integrators
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, fields, models
class MaintenanceEquipment(models.Model):
_inherit = 'maintenance.equipment'
_description = 'Maintenance Equipment'
backend_id = fields.Many2one('bac... | Equipment")
managed = fields.Boolean('Can be managed')
def update_config(self):
return True
def _connect(self, function, | serviceprofiles=None):
if function == 'update_config':
self.update_config()
elif function == 'add_service':
if serviceprofiles:
for sp_id in serviceprofiles:
self.add_service(sp_id)
elif function == 'update_service':
if ser... |
bpeng2000/SOS | src/sos/executor_utils.py | Python | gpl-3.0 | 17,163 | 0.000757 | #!/usr/bin/env python3
#
# Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center
# Distributed under the terms of the 3-clause BSD License.
#
# Utility functions used by various executors.
#
import os
import re
import sys
import traceback
from collections.abc import Sequence
from io import String... | ot defined in CONFIG['hosts']"
)
env.sos_dict["CONFIG"]["hosts"][env.sos_dict["CONFIG"]
["localhost"]] = {
"paths": {},
"address": "loca... | ",
}
env.sos_dict.set("__host__", env.sos_dict["CONFIG"]["localhost"])
else:
if "hosts" in env.sos_dict["CONFIG"]:
if "localhost" not in env.sos_dict["CONFIG"]["hosts"]:
env.logger.warning('locahost is no... |
lud4ik/txAWS | txaws/server/tests/test_call.py | Python | mit | 378 | 0 | from twisted.trial.unittest import TestCase
from txaws | .server.call import Call
class CallTestCase(TestCase):
def test_de | fault_version(self):
"""
If no version is explicitly requested, C{version} is set to
2009-11-30, which is the earliest version we support.
"""
call = Call()
self.assertEqual(call.version, "2009-11-30")
|
drussellmrichie/TATools | COGSTools/psgQ4Tester.py | Python | gpl-3.0 | 1,386 | 0.006494 | __author__ = 'russellrichie'
import nltk, re
from nltk.tree import *
from nltk.draw import tree
from random import choice
from nltk import CFG
"""
Paste the students' grammar between the quotes below. Use the site below to turn
http://textmechanic.com/Find-and-Replace-Text.html
"""
grammar = """
CP -> VP DP PP
V... | mar)
sent = 'put the box on the apple near the table'
tree = parser.parse(sent.split())
# If using NLTK 3.0, use this line. The parse method returns a generator rather than a list of parses, in true
# Python 3.0 style
tree.next().draw()
# if using NLTK | 2.x, use this next block
# need this if statement because there may be more than one tree in 'tree'
# if tree is a list of trees, then just draw the first one. Otherwise,
# draw the only tree there is!
"""
if type(tree) == list:
tree[0].draw()
else:
tree.draw()
"""
|
mtekel/digitalmarketplace-api | app/draft_utils.py | Python | mit | 1,022 | 0 | from .models import Framework
from .utils import get_json_from_request, json_has_required_keys, \
json_has_matching_id
from .validation import get_validation_errors
def validate_and_return_draft_request(draft_id=0):
json_payload = get_json_from_request()
json_has_required_keys(jso | n_payload, ['services'])
if draft_id:
json_has_matching_id(json_payload['services'], draft_id)
return json_payload['services']
def get_draft_validation_errors(draft_json, lot,
framework_id=0, slug=None, required=None):
if not slug and not framework_ | id:
raise Exception('Validation requires either framework_id or slug')
if not slug:
framework = Framework.query.filter(
Framework.id == framework_id
).first()
slug = framework.slug
errs = get_validation_errors(
"services-{0}-{1}".format(slug, lot.lower()),
... |
wiliamsouza/cars | cars/test_forms.py | Python | apache-2.0 | 837 | 0 | from .forms import RegistrationForm, LoginForm, SearchForm, CarForm
user_data = {'name': 'Jhon Doe', 'email': 'jhon@doe.com',
'password': 'jJdD | ', 'confirm': 'jJdD'}
car_data = {'year': '1938', 'manufacturer': 'Volkswagen',
'model': 'Beetle'}
"""
def test_registration_form():
form = RegistrationForm()
form.process(user_data)
form.validate()
assert form.errors == {} |
def test_login_form():
form = LoginForm()
form.process({'username': 'jhon@doe.com', 'password': 'jJdD'})
form.validate()
assert form.errors == {}
def test_search_form():
form = SearchForm()
form.process({'search': 'Beetle'})
form.validate()
assert form.errors == {}
def test_car_fo... |
pfreixes/aiohttp | aiohttp/client_proto.py | Python | apache-2.0 | 5,879 | 0 | import asyncio
import asyncio.streams
from contextlib import suppress
from .client_exceptions import (ClientOSError, ClientPayloadError,
ServerDisconnectedError)
from .http import HttpResponseParser
from .streams import EMPTY_PAYLOAD, DataQueue
class ResponseHandler(DataQueue, asyncio... | it anyway below
self.set_exception(exc)
self.transport = None
self._should_close = True
self._parser = None
self._message = None
self._payload = None
self._payload_parser = None
self._reading_paused = False
super().connection_lost(exc)
d... | self.transport.pause_reading()
except (AttributeError, NotImplementedError, RuntimeError):
pass
self._reading_paused = True
def resume_reading(self):
if self._reading_paused:
try:
self.transport.resume_reading()
except... |
morelab/weblabdeusto | server/src/weblab/core/web/configuration.py | Python | bsd-2-clause | 1,788 | 0.005596 | #!/usr/bin/env python
#-*-*- encoding: utf-8 -*-*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individual... | e_response
from weblab.core.wl import weblab_api
@weblab_api.route_web('/experiments.js')
def configuration():
clients = weblab_api.db.list_clients()
formatted = {
# 'client_id' : [
# {
| # 'experiment.name' : 'foo',
# 'experiment.category' : 'bar',
# 'other.property' : 'foobar',
# },
# {
# 'experiment.name' : 'other',
# 'experiment.category' : 'bar',
# ... |
julien6387/supvisors | supvisors/supvisorsmapper.py | Python | apache-2.0 | 12,501 | 0.00352 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ======================================================================
# Copyright 2016 Julien LE CLEACH
#
# 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 Lic... | required by applicable law or agreed to in writing, software
# distributed under the License is d | istributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ======================================================================
import re
from collections import O... |
leesdolphin/rentme | rentme/web/migrations/0024_auto_20170211_0402.py | Python | agpl-3.0 | 620 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-11 04:02
from __future__ import unicode_literals
from django.db import migrations, models
c | lass Migration(migrations.Migration):
dependencies = [
| ('web', '0023_auto_20170211_0325'),
]
operations = [
migrations.AddField(
model_name='agency',
name='branding_disable_banner',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='agencyagent',
name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.