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 |
|---|---|---|---|---|---|---|---|---|
yahoo/lopq | python/lopq/search.py | Python | apache-2.0 | 11,638 | 0.001461 | # Copyright 2015, Yahoo Inc.
# Licensed under the terms of the Apache License, Version 2.0. See the LICENSE file associated with the project for terms.
import heapq
from collections import defaultdict, namedtuple
from itertools import count
import numpy as np
import array
from .utils import iterate_splits, compute_code... | ist_for_cell(cell):
return sum([cluster_dists[s][i] for s, i in enumerate(cell)])
def inds_in_range(inds):
for i in inds:
if i >= V:
return False
return True
# Initialize priority queue
h = []
traversed = set()
start_inds = tuple(0 for _ in xrang... | ppush(h, (start_dist, start_inds))
# Traverse cells
while len(h):
d, inds = heapq.heappop(h)
yield d, cell_for_inds(inds)
traversed.add(inds)
# Add neighboring cells to queue
if inds[1] == 0 or (inds[0] + 1, inds[1] - 1) in traversed:
c = (inds[0] + 1, inds[... |
vinhqdang/spice | torch-rnn/spice/p4/spectral_original.py | Python | gpl-3.0 | 6,288 | 0.004453 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 10:47:00 2016
@author: Remi Eyraud
Tested with Python 2.7 and Python 3.4
"""
# State the problem number
problem_number = '4'
# and the user id (given during registration)
user_id = '42'
train_file = problem_number + ".spice.train"
prefix_file = problem_number + ".s... | name = "v510"
def learn(train_file, parameter):
""" Learn a weighted automaton using spectral approach
parameter is the rank
"""
# Import the SPiCe spectral learning toolbox
import sp2learn.learning as LC
from sp2learn.sample import Sample
# Get the learning sample in needed dicti... | Create a learning instance
S_app = LC.Learning(sample_instance=pT)
# Learn an automaton (see documentation for other possible parameters)
A = S_app.LearnAutomaton(rank=parameter, lrows=lrows,
lcolumns=lcolumns, version=version,
parti... |
aaronfang/personal_scripts | af_scripts/tmp/setPivotToFace.py | Python | mit | 1,729 | 0.05321 | import pymel.core as pm
def set_pivot_to_selected_face(face):
cur_sel = pm.select(face,r=1)
if cur_sel and len(cur_sel) == 1 and cur_sel.split(:
pm.mel.eval("setToolTo Move;")
piv = pm.manipMoveContext("Move",q=1,p=1)
mesh = pm.listRelatives(pm.listRelatives(face,p=1)[0],p=1)
vt... |
pm.mel.eval("snap3PointsTo3Points(0);")
pm.parent(mesh,planeA)
pm.xform(planeA,ws=1,piv=(piv[0],piv[1],piv[2]))
cur_plane_pos = pm.xform(pla | neA,q=True,ws=True,piv=True)[0:3]
cur_plane_rot = pm.xform(planeA,q=True,ws=True,ro=True)
pm.parent(mesh,w=1)
pm.select(mesh,planeA,r=1)
pm.makeIdentity(a=1,t=1,r=0,s=0,n=0)
pm.parent(mesh,planeA)
pm.xform(planeA,ws=True,t=(-cur_plane_pos[0],-cur... |
pennlabs/penn-sdk-python | penn/calendar3year.py | Python | mit | 1,735 | 0.002305 | import requests
import datetime
BASE_URL = "https://www.stanza.co/api/schedules/almanacacademiccalendar/"
class Calendar(object):
def __init__(self):
pass
def pull_3year(self):
"""Returns a list (in JSON format) containing all the events from the Penn iCal Calendar.
List contains e... | raw_date = line.split(":")[1][0:8]
start_date = datetime.datetime.strptime(raw_date, '%Y%m%d').date()
| d['start'] = start_date.strftime('%Y-%m-%d')
elif line.startswith("DTEND"):
raw_date = line.split(":")[1][0:8]
end_date = datetime.datetime.strptime(raw_date, '%Y%m%d').date()
d['end'] = end_date.strftime('%Y-%m-%d')
elif l... |
playpauseandstop/rororo | src/rororo/openapi/annotations.py | Python | bsd-3-clause | 311 | 0 | from typing im | port Any, Dict, List, Union
from ..annotations import TypedDict
SecurityDict = Dict[str, List[str]]
c | lass ValidateEmailKwargsDict(TypedDict, total=False):
allow_smtputf8: bool
allow_empty_local: bool
check_deliverability: bool
timeout: Union[int, float]
dns_resolver: Any
|
cccs-web/mezzanine | mezzanine/core/models.py | Python | bsd-2-clause | 17,835 | 0.000785 | from __future__ import unicode_literals
from future.builtins import str
from future.utils import with_metaclass
from json import loads
try:
from urllib.request import urlopen
from urllib.parse import urlencode
except ImportError:
from urllib import urlopen, urlencode
from django.contrib.contenttypes.gener... | ass Displayable(Slugged, MetaData, TimeStamped):
"""
Abstract model that provides features of a visible page on the
website such as publishing fields. Basis of Mezzanine pages,
blog posts, | and Cartridge products.
"""
status = models.IntegerField(_("Status"),
choices=CONTENT_STATUS_CHOICES, default=CONTENT_STATUS_PUBLISHED,
help_text=_("With Draft chosen, will only be shown for admin users "
"on the site."))
publish_date = models.DateTimeField(_("Published from"),... |
vpikulik/lymph | lymph/core/monitoring/aggregator.py | Python | apache-2.0 | 509 | 0.001965 | from lymph.core.monitoring.metrics import Aggregate
fro | m lymph.core.monitoring.global_metrics import RUsageMetrics, GeventMetrics, GarbageCollectionMetrics, ProcessMetrics
class Aggregator(Aggregate):
@classmethod
def from_config(cls, co | nfig):
tags = config.get_raw('tags', {})
# FIXME: move default metrics out
return cls([
RUsageMetrics(),
GarbageCollectionMetrics(),
GeventMetrics(),
ProcessMetrics(),
], tags=tags)
|
mario21ic/python_curso | session1/9_iterativos.py | Python | apache-2.0 | 356 | 0.002809 | # -*- | coding: utf-8 -*-
print "#"*3 +" Iterativos "+"#"*3
print "while:"
x = 0
while x <= 5:
print x
x += 1
print "\nfor-in:"
for x in range(5):
print x
print "\nbreak:"
for x in range(5):
if x == 2:
break
print x
print | "\ncontinue:"
nuevo = ""
for x in "abac":
if x != "a":
continue
nuevo += x
print nuevo
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/utilities/tests/test_codegen.py | Python | agpl-3.0 | 39,167 | 0.004366 | from StringIO import StringIO
from sympy.core import symbols, Eq, pi, Catalan, Lambda, Dummy
from sympy.utilities.codegen import CCodeGen, Routine, InputArgument, Result, \
CodeGenError, FCodeGen, codegen, CodeGenArgumentListError, OutputArgument, \
InOutArgument
from sympy.utilities.pytest import XFAIL, raise... | mport (acos, asin, atan, ceiling, cos, cosh, floor, log, ln,
sin, sinh, sqrt, tan, tanh, N, Abs)
x = symbols('x')
name_expr = [
| ("test_fabs", Abs(x)),
("test_acos", acos(x)),
("test_asin", asin(x)),
("test_atan", atan(x)),
("test_ceil", ceiling(x)),
("test_cos", cos(x)),
("test_cosh", cosh(x)),
("test_floor", floor(x)),
("test_log", log(x)),
("test_ln", ln(x)),
("te... |
tiagoprn/experiments | django/drf_book/gamesapi/gamesapi/settings.py | Python | mit | 5,648 | 0.001948 | """
Django settings for gamesapi project.
Generated by 'django-admin st | artproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs | .djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/depl... |
tmhorne/simplewiki | tools/extract_translator_comments.py | Python | gpl-2.0 | 1,702 | 0.036428 | #!/usr/bin/python
import re
source_files = {}
comment_re = re.compile(r'\s+#\s+T:\s+(.+)\s*$')
def get_file(file):
if not file in source_files:
#~ print 'Extracting comments from', file
source_files[file] = open(file).readlines()
source_files[file].append('')
return source_files[file]
def extract_comment(f... | _re.search(lines[i])
if match:
return match.group(1)
i += 1
return None
def extract_comments(sources):
| sources = [s.split(':') for s in sources]
comments = []
for file, line in sources:
comment = extract_comment(file, int(line))
if comment and comment not in comments:
comments.append(comment)
if comments:
return ' | \n'.join(['#. '+c for c in comments])+'\n'
else:
print 'No translator comment for:'
for ... |
gravitylow/OpenCourse | orientation/urls.py | Python | apache-2.0 | 201 | 0.004975 | from d | jango.conf.urls import patterns, url
from orientation import views
urlpatterns = patterns('',
url(r'^$', views.search, name='search'),
url | (r'^majors/$', views.majors, name='majors'),
)
|
gppezzi/easybuild-framework | easybuild/tools/utilities.py | Python | gpl-2.0 | 11,107 | 0.002791 | # #
# Copyright 2012-2019 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (... | _name])
_log.debug("importing module %s", modpath)
try:
mod = __import__(modpath, globals(), locals(), [''])
except ImportError as err:
raise EasyBuildError("i | mport_available_modules: Failed to import %s: %s", modpath, err)
if mod not in modules:
modules.append(mod)
return modules
def only_if_module_is_available(modnames, pkgname=None, url=None):
"""Decorator to guard functions/methods against missing required module with speci... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/pip/status_codes.py | Python | mit | 116 | 0 | SUCCESS = 0
ERROR = 1
UNKNOWN_ERROR = 2
VIRT | UALENV_NOT_FOUND = 3
PREVIOUS_BUILD_DIR_ERROR = 4
NO_MAT | CHES_FOUND = 23
|
Jrius/PyPRP | PyPRP/prp_CamClasses.py | Python | gpl-2.0 | 32,164 | 0.018126 | # Copyright (C) 2008 Guild of Writers PyPRP Project Team
# See the file AUTHORS for more info about the team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of... | ipt(self,script):
self.fAccel = float(FindInDict(script,"accel",self.fAccel))
self.fD | ecel = float(FindInDict(script,"decel",self.fDecel))
self.fVelocity = float(FindInDict(script,"velocity",self.fVelocity))
self.fPOAAccel = float(FindInDict(script,"poaaccel",self.fPOAAccel))
self.fPOADecel = float(FindInDict(script,"poadecel",self.fPOADecel))
self.fPOCVelocity = float(Fi... |
caseywstark/colab | colab/apps/ajax_select/fields.py | Python | mit | 9,217 | 0.010741 |
from ajax_select import get_lookup
from django import forms
from django.core.urlresolvers import reverse
from django.forms.util import flatatt
from django.template.defaultfilters import escapejs
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.translat... |
""" | widget to select a model """
add_link = None
def __init__(self,
channel,
help_text='',
*args, **kw):
super(forms.widgets.TextInput, self).__init__(*args, **kw)
self.channel = channel
self.help_text = help_text
def render... |
kartikgupta0909/build-mozharness | scripts/desktop_l10n.py | Python | mpl-2.0 | 44,931 | 0.000801 | #!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# 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/.
# ***** END LICENSE BLOCK *****
"""desktop_l10n.py
This script m... | zharness.mozilla.updates.balrog import BalrogMixin
try:
import simplejson as json
assert json
except ImportError:
import | json
# needed by summarize
SUCCESS = 0
FAILURE = 1
# when running get_output_form_command, pymake has some extra output
# that needs to be filtered out
PyMakeIgnoreList = [
re.compile(r'''.*make\.py(?:\[\d+\])?: Entering directory'''),
re.compile(r'''.*make\.py(?:\[\d+\])?: Leaving directory'''),
]
# mand... |
ChandranshuRao14/AlertMe | setup.py | Python | mit | 444 | 0.027027 | from distutils.core import setup
setup(
name='alertme',
description='Pyt | hon command line tool that sends email when your script finishes running or has an erro | r',
version='0.1.0',
url='http://github.com/ChandranshuRao14/AlertMe/',
packages=['alertme'],
scripts=['bin/alertme'],
author='Chandranshu Rao',
author_email='chandranshu.rao@gmail.com',
license='MIT',
long_description=open('README.txt').read(),
keywords='alert alertme'
)
|
HKuz/Test_Code | CodeFights/weakNumbers.py | Python | mit | 1,030 | 0 | #!/usr/local/bin/python
# Code Fights Weak Numbers Problem
def weakNumbers(n):
def get_divisors(n):
divs = []
for i in range(1, n + 1):
count = 0
for d in range(1, i + 1):
if i % d == 0:
count += 1
divs.append(count)
r... | enumerate(divs)]
return [max(weaks), weaks.count(max(weaks))]
def main():
tests = [
[9, [2, 2]],
[1, [0, 1]],
[2, [0, 2]],
[7, [2, 1]],
[500, [403, 1]],
[4, [0, 4]]
]
for t in tests:
res = weakNumbers(t[0])
ans = t[1]
if ans == ... | rned {}"
.format(t[0], res))
else:
print("FAILED: weakNumbers({}) returned {}, answer: {}"
.format(t[0], res, ans))
if __name__ == '__main__':
main()
|
sympy/scipy-2017-codegen-tutorial | notebooks/exercise_lambdify_jac.py | Python | bsd-3-clause | 114 | 0 | J = sym.Matrix(ydot). | jacobian(y) # EXERCISE: jacobian
J_cb = sym.lambdify((y, t) + | k, J) # EXERCISE: (y, t) + k
|
YedaAnna/work_scripts | list_ligand_id.py | Python | mit | 294 | 0.006803 | #! usr/bin/python3
impo | rt os
for fn in os.listdir():
if ".pdb" in fn:
#sub = {}
with open(fn, 'r') as f:
for line in f:
c = line.split()
if len(c) > 5 and c[0] == "HET":
ligand= c[1]
print(fn, l | igand)
|
ntoll/uflash | docs/conf.py | Python | mit | 11,491 | 0.000522 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# uFlash documentation build configuration file, created by
# sphinx-quickstart on Thu Dec 17 19:01:47 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
# aut... | ets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These f... | sing the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates th... |
cordis/pycloudia | pycloudia/activities/facades/streams_impl/protocol.py | Python | mit | 132 | 0 | from pycloudia.activities.facades.interfaces import IClient
class Pr | otocol(IClient):
def __init__(self | , server):
pass
|
gahoo/SNAP | core/db.py | Python | mit | 14,857 | 0.011846 | import os
import pdb
import functools
import glob
from core import models
from core.ali.oss import BUCKET, oss2key, is_object_exists, is_size_differ_and_newer, is_source_newer, is_md5_differ
from core.misc import *
from colorMessage import dyeWARNING, dyeFAIL
from sqlalchemy import create_engine, UniqueConstraint
from ... | sion.commit()
def mkSampleTaskDepends(app, module, dep_app, dep_module):
def mkEachSampleTaskDepends(sample_name):
tasks = getSampleTask(app, module, sample_name)
dep_tasks = getSampleTask(dep_app, dep_module, sample_name)
mkCombTaskDepends(tasks, dep... | tasks)
map(mkEachSampleTaskDepends, [sample['sample_name'] for sample in self.parameters['Samples']])
def mkAppDepends(app, module_name, depends):
for dep_appname in depends[app.name]['depends']:
if dep_appname not in apps_in_param:
print dyeWARNING(... |
rynkowsg/hamster | src/hamster/tray.py | Python | gpl-3.0 | 16,295 | 0.004235 | # coding: utf-8
#from hamster indicator
import gtk
import datetime as dt
import gobject
from hamster.lib import Fact, stuff
from hamster.configuration import dialogs, runtime, conf
from collections import OrderedDict
have_appindicator = True
try:
import appindicator
except:
have_appindicator = False
def ... | ction="Quit"/>
</menu>
</menubar>
</ui>
'''
actions = [
| ('Menu', None, 'Menu'),
('Quit', gtk.STOCK_QUIT, '_Quit...', None, 'Quit Time Tracker', self.on_quit)]
ag = gtk.ActionGroup('Actions')
ag.add_actions(actions)
self.manager = gtk.UIManager()
self.manager.insert_action_group(ag, 0)
self.manager.add_ui_from_string(menu)... |
mraue/pyfact | examples/write_fits_arf.py | Python | bsd-3-clause | 4,522 | 0.005971 | #===========================================================================
# Copyright (c) 2011-2012, the PyFACT developers
# All rights reserved.
#
# LICENSE
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * R... | ----------------------------- | ---------------------
|
cjaymes/pyscap | src/scap/model/xccdf_1_2/UriRefType.py | Python | gpl-3.0 | 932 | 0.001073 | # Copyright 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 the GNU General Public License as published by
# the Free Software Foundation, either versi | on 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 ev | en 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 PySCAP. If not, see <http://www.gnu.org/licenses/>.
import logging
from scap.model.xs.StringType... |
GunGame-Dev-Team/GunGame-SP | addons/source-python/plugins/gungame/core/messages/hooks.py | Python | gpl-3.0 | 1,705 | 0 | # ../gungame/core/messages/hooks.py
"""Provides a way to hook GunGame messages."""
# =============================================================================
# >> IMPORTS
# =============================================================================
# Source.Python
from core import AutoUnload
# GunGame
from .m... | =========================================================
# >> CLASSES
# =============================================================================
class MessageHook(AutoUnload):
"""Decorator used to register message hooks.""" |
def __init__(self, message_name):
"""Store the message name."""
self.message_name = message_name
self.callback = None
def __call__(self, callback):
"""Store the callback and register the hook."""
self.callback = callback
message_manager.hook_message(self.messag... |
mezz64/home-assistant | tests/components/cert_expiry/test_sensors.py | Python | apache-2.0 | 7,132 | 0.001262 | """Tests for the Cert Expiry sensors."""
from datetime import timedelta
import socket
import ssl
from unittest.mock import patch
from homeassistant.components.cert_expiry.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PORT, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import CoreState
... | (hass, utcnow() + timedelta(hours | =48))
await hass.async_block_till_done()
state = hass.states.get("sensor.cert_expiry_timestamp_example_com")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == timestamp.isoformat()
assert state.attributes.get("error") == "None"
... |
Kniyl/mezzanine | mezzanine/utils/conf.py | Python | bsd-2-clause | 11,932 | 0.000587 | from __future__ import unicode_literals
import os
import sys
from warnings import warn
from django import VERSION
from django.conf import global_settings as defaults
from django.template.base import add_to_builtins
from mezzanine.utils.importing import path_for_import
from mezzanine.utils.timezone import get_best_lo... | lt("SOUTH_MIGRATION_MODULES", {})
for app in s["INSTALLED_APPS"]:
# We need to verify the path to the custom migrations
# package exists for each app. We can't simply try
# and import it, for some apps this causes side effects,
# so we need to import something hig... | e the actual app either,
# side effects again, but we can generally import the
# top-level package for apps that are contained within
# one, which covers Mezzanine, Cartridge, Drum.
if "." not in app:
continue
migrations = "%s.migrations.south"... |
larsbutler/zpa | publish/store.py | Python | apache-2.0 | 399 | 0 | import sys
if __name__ == '__main__':
with open('/dev/input') as input_fp:
with open('/dev/output', 'a') as output_fp:
output_fp.write(input_fp.read())
msg = 'Zapp registered!'
resp = """\
HTTP/1.1 201 Created
Content-Type: message/http
Content-Length: %(msg_len)s
%(m... |
resp %= dict(msg=msg, msg_len=len(msg))
sys.std | out.write(resp)
|
simontakite/sysadmin | pythonscripts/learningPython/prop-person-deco.py | Python | gpl-2.0 | 954 | 0.001048 | class Person:
def __init__(self, name):
self._name = name
@property
def name(self): # | name = property(name)
"name property docs"
print('fetch...')
return self._name
@name.setter
def name(self, value): # name = name.setter(name)
print('change...')
self._name = value
@name.deleter
def name(self): # name = name.de... | uns name getter (name 1)
bob.name = 'Robert Smith' # Runs name setter (name 2)
print(bob.name)
del bob.name # Runs name deleter (name 3)
print('-'*20)
sue = Person('Sue Jones') # sue inherits property too
print(sue.name)
print(Person.name.__doc__) # Or help(P... |
viksvampire19/Twigle | authomatic-master/tests/functional_tests/config-template.py | Python | mit | 6,344 | 0 | # -*- coding: utf-8 -*-
import datetime
import constants
# Choose and configure the browser of your choice
def get_browser():
return webdriver.Chrome()
# The host and port where the tested ap shoud listen.
HOST = '127.0.0.1'
PORT = 8080
# The host alias set in the /etc/hosts file.
# The actual tests will navi... | er-Agent header in every request.
'user_picture': '??????????',
'user_phone': PHONE_INTERNATIONAL,
},
'paypal': {
'consumer_key': '##########',
'consumer_secret': '##########',
},
'reddit': {
'consumer_key': '##########',
'cons | umer_secret': '##########',
'user_login': USERNAME,
'user_id': '??????????',
'access_headers': {'User-Agent': ('Authomatic.py Automated Functional '
'Tests')}
},
# Viadeo doesn't support access to its API
# http://dev.viadeo.com/documentation... |
SquirrelMajik/flask_rest4 | flask_rest4/response.py | Python | mit | 2,232 | 0.000448 | '''Rest4 response helpers
Response helper functions for Rest4
'''
import functools
import json
from flask import current_app, make_response, request
from . import settings
def output_json(func):
@functools.wraps(func)
def decorate(*args, **kwargs):
result = func(*args, **kwargs)
data, sta... | settings.CORS_HEADERS_ALLOW_HEADERS)
allow_methods = settings.CORS_HEADERS_ALLOW_METHODS
allowed_origins = settings.CORS_HEADERS_ALLOW_ORIGIN
if '*' in allowed_origins | :
allowed_origins = '*'
elif request.headers.get('Origin') in allowed_origins:
allowed_origins = request.headers['Origin']
allow_credentials = str(settings.CORS_HEADERS_ALLOW_CREDENTIALS).lower()
max_age = settings.CORS_HEADERS_MAX_AGE
return {
"Access-Control-Allow-Headers": al... |
woodbridge/life | game.py | Python | mit | 4,698 | 0.009791 | import pyglet
import random
from pyglet.gl import *
from pyglet.window import key as keys
WIDTH = 500
HEIGHT = 500
rows = 100
columns = 100
RUNNING = False
cell_width = float(WIDTH) / rows
cell_height = float(HEIGHT) / columns
INITAL_POPULATION = 10
ACTIVE_TILE_INDEX = 0
STATE = []
win = pyglet.window.Window(w... | - rows) + 1
to_check = [
top_left, mid_left, top_right,
left, right,
bot_left, bot_mid, bot_right
| ]
alive = STATE[i] == 1
num_alive = 0
for cell in to_check:
try:
if STATE[cell] == 1: num_alive += 1
except: pass
return num_alive
@win.event
def on_mouse_motion(x, y, dx, dy):
global ACTIVE_TILE_INDEX
row = int(y / float(cell_height)) - 1 # TODO:... |
prkumar/uplink | uplink/interfaces.py | Python | mit | 3,372 | 0 | class AnnotationMeta(type):
def __call__(cls, *args, **kwargs):
if cls._can_be_static and cls._is_static_call(*args, **kwargs):
self = super(AnnotationMeta, cls).__call__()
self(args[0])
return args[0]
else:
return super(AnnotationMeta, cls).__call__(*... | listener is not None:
self.__listener(annotation)
def is_done(self):
return True
def build(self):
raise NotImplementedError
class AnnotationHandler(object):
@property
def annotations(self):
raise NotImplementedError
class UriDefinitionBuilder(object):
@prope... | raise NotImplementedError
@is_dynamic.setter
def is_dynamic(self, is_dynamic):
raise NotImplementedError
def add_variable(self, name):
raise NotImplementedError
@property
def remaining_variables(self):
raise NotImplementedError
def build(self):
raise NotI... |
filias/django | tests/model_options/test_tablespaces.py | Python | bsd-3-clause | 5,370 | 0.000186 | from __future__ import unicode_literals
from django.apps import apps
from django.conf import settings
from django.db import connection
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models.tablespaces import (
Article, ArticleRef, Authors, Reviewers, Scientist, ScientistRef,
)
def ... | xed_field(self):
# No tablespace-related SQL
self.assertEqual(sql_for_table(Article),
sql_for_table(ArticleRef))
@skipUnlessDBFeature('supports_tablespaces')
def test_tablespace_for_many_to_many_field(self):
sql = sql_for_table(Authors).lower()
# The joi... | yToManyField goes to the model's tablespace,
# and its indexes too, unless DEFAULT_INDEX_TABLESPACE is set.
if settings.DEFAULT_INDEX_TABLESPACE:
# 1 for the table
self.assertNumContains(sql, 'tbl_tbsp', 1)
# 1 for the primary key
self.assertNumContains(sq... |
eHanseJoerg/learning-machine-learning | 00 python basics/threadingexample.py | Python | gpl-2.0 | 513 | 0.001953 | import threading
class BuckysMessenger(threading.Thread):
def run(self):
for _ in range(10000) | :
print(threading.current_thread().getName() + str(_))
# Diese Klasse kann also gethreaded werden, d.h. mehrere Objekt | e davon
# können zur gleichen Zeit laufen!
x = BuckysMessenger(name='Sender')
y = BuckysMessenger(name='Reveive')
# Immer wenn man einen Thread kreiert, muss man die START - Funktion aufrufen:
# (start selbst such in der Klasse nach der run - Methode
x.start()
y.start() |
TitasNandi/Summer_Project | yodaqa/data/ml/fbpath/evaluate_queries_results.py | Python | apache-2.0 | 9,017 | 0.010092 | #!/usr/bin/python -u
#
# Evaluate fbpath-based query performance (on gold standard and as predicted)
#
# Usage: evaluate_queries_results.py traindata.json valdata.json
#
# A model is trained on traindata and then its performance is measured
# on valdata. (FIXME: Duplicate code with fbpath_train_logistic, instead
# of ... | ndata: %d questions, %d features, %d fbpaths' % (
np.size(traindata.X, axis=0), np.size(tra | indata.X, axis=1), np.size(traindata.Y, axis=1)))
sys.stdout.flush()
t_start = time.clock()
cfier = OneVsRestClassifier(LogisticRegression(penalty='l1'), n_jobs=4)
cfier.fit(traindata.X, traindata.Y)
with open(sys.argv[2]) as f:
full = json.load(f)
full_data = VectorizedData(full,... |
gcr/robots | client_py/patrol.py | Python | bsd-3-clause | 1,048 | 0.000954 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Patrols the edges of the map going clockwise. Just drives around in circles,
taking pains not to hit a wall.
When we see a wall, turn right a little.
"""
from courier import RoboLink
robot = RoboLink.connect(name="Patroller", scanner=2, engine=5)
# ... | # Should probably be handled by RoboLink.connect, but whatever.
if not robot: |
print "Error connecting"
exit(1)
# The below will be changed to 'while not robot.dead:' just as soon as I
# implement that.
while True:
# Full speed ahead! Doing this every tic just in case we hit a wall or stop
# or something. Setting the throttle doesn't take very long.
robot.throttle = 100
... |
activitycentral/statistics-consolidation | stats_consolidation/db.py | Python | gpl-3.0 | 18,505 | 0.004864 | import logging
from datet | ime import datetime
import time
import sqlalchemy as sa
from sqlalchemy.sql import func
import os.path
log = logging.getLogger("stats-consolidation")
def _to_url(dialect, **kwargs):
""" From keywords to a database URL.
>>> _to_url(dialect='sqlite', db_name='/tmp/database')
'sqlite:////tmp/database'
... | db_name='database', db_user='user', db_pass='secret')
'postgres://user:secret@localhost/database'
"""
if dialect == 'sqlite':
path_to_file = os.path.abspath(kwargs['db_name'])
url = "sqlite:///" + path_to_file
else:
url = "{dialect}://{db_user}:{db_pass}@localhost/{db_name}"
... |
Nickolaim/nick_toy_car | src/test_joystick_axes_to_degree.py | Python | mit | 779 | 0 | from unittest import TestCase
fro | m joy_to_command_translation import joystick | _axes_to_degree
class TestJoystick_axes_to_degree(TestCase):
def test_joystick_axes_to_degree(self):
self.assertEqual(None, joystick_axes_to_degree(0, 0))
self.assertAlmostEqual(-90, joystick_axes_to_degree(32767, 0), 2)
self.assertAlmostEqual(-45, joystick_axes_to_degree(16767, -16767), 2... |
CampfireBros/Fitness-Tracker | app/utils/validators.py | Python | mit | 540 | 0.003704 | from cerberus import Validator
# validators for various field
class MyValidator(Validator):
# constructor for the class
def __init__(self, *args, **kwargs):
if 'addition | al_context' in kwargs:
self.additional_context = kwargs['additional_context']
super(MyValidator, self).__init__(*args, **kwargs)
# method to validate an object id
def _validate_type_objectid(self, field, value):
if not re.match('[a-f0-9]{24}', value):
s | elf._error(field, ERROR_BAD_TYPE.format('ObjectId')) |
Vhati/CompileSubs | lib/parsers/tabbed_text.py | Python | gpl-2.0 | 4,034 | 0.012395 | from datetime import datetime, timedelta
import contextlib
import logging
import re
import sys
import time
import urllib2
from lib import arginfo
from lib import common
from lib import global_config
# Namespace for options.
ns = "tabbed_text."
# Names of lib.subsystem modules that should be set up i... | tern/replacement tuples to strip reply topic from comments.
reply_regexes = []
if (ns+"reply_name" in options and options[ns+"reply_name"]):
reply_name_escaped = re.escape(options[ns+"reply_name"])
| reply_regexes = [(re.compile(" +@"+ reply_name_escaped +" +", re.IGNORECASE), " "),
(re.compile(" *@"+ reply_name_escaped +" *", re.IGNORECASE), "")]
start_date = None
snarks = []
lines = []
try:
with contextlib.closing(urllib2.urlopen(src_path)) as snark_file:
whil... |
andresriancho/HTTPretty | tests/functional/test_requests.py | Python | mit | 32,623 | 0.001962 | # #!/usr/bin/env python
# -*- coding: utf-8 -*-
# <HTTPretty - HTTP client mock for Python>
# Copyright (C) <2011-2018> Gabriel Falcão <gabriel@nacaolivre.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to ... | retty.register_uri(HTTPretty.GET, "http://github.com/foo",
body="this is supposed to be the response",
adding_headers={
'Server': 'Apache',
| 'Content-Length': '27',
'Content-Type': 'application/json',
})
response = requests.get('http://github.com/foo')
expect(dict(response.headers)).to.equal({
'content-type': 'application/json',
'connection': 'close'... |
michaupl/braincloud | brainindex/api.py | Python | apache-2.0 | 422 | 0 | # coding: utf-8
from core.base_api import BaseResource
from .index import search_in_title_and_tags
class TextThoughtAjaxResource(BaseResource):
class Meta:
resource_name | = 'livesearch'
def post_list(self, request, **kwargs):
phrase = request.POST.get('q')
if phrase:
th | oughts = search_in_title_and_tags(1, phrase)
return self.create_response(request, thoughts)
|
mhugent/Quantum-GIS | python/plugins/processing/modeler/ModelerAlgorithm.py | Python | gpl-2.0 | 32,306 | 0.000836 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ModelerAlgorithm.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**********************... | This is just a
# list of dependencies not set by outputs and inputs but
# explicitly entered instead, meaning that an algorithm must
# 'wait' for another to finish. Each entry is a list with
# algorithm indexes
self.dependencies = []
# Outputs of Geoalgorithms in self.a... | # intermediate output
self.algOutputs = []
# Hardcoded parameter values entered by the user when defining
# the model. Keys are value names.
self.paramValues = {}
# Position of items in canvas
self.algPos = []
self.paramPos = []
self.outputPos = [] #... |
xiaokangwang/KKUniCtrlConsole_Core | ControlerInterface_AMQP.py | Python | gpl-3.0 | 13,751 | 0.018835 | #!/usr/bin/env python3
import uuid
import pika
import threading
import json
import time
import os
import kecsl
import base64
import logging
LOGGER = logging.getLogger(__name__)
"""ControlerInterface:AMQP Progresser"""
WorkMode={
'WorkNode', #Accetpt Control
'ControlConsole' #Connect to Server Accept Control
}
class... |
datatosendW=self.ALL_Wrapencdata(datatosend,'Data')
chann | el=self.Runtimevar['AQMP_channel']
channel.basic_publish(routing_key=conn['name'],body=datatosendW)
def WorkNode_makeCtrlConn(self,Req):
ctrlqueue=self.Runtimevar['AQMP_channel'].queue_declare(exclusive=True)#Wrong! concurrent poll() invocation
ctrlqueuename = ctrlqueu... |
CloCkWeRX/rabbitvcs-svn-mirror | rabbitvcs/vcs/git/gittyup/client.py | Python | gpl-2.0 | 63,317 | 0.006839 | #
# client.py
#
import os
import os.path
import re
import shutil
import fnmatch
import time
from string import ascii_letters, digits
from datetime import datetime
from mimetypes import guess_type
import subprocess
import dulwich.errors
import dulwich.repo
import dulwich.objects
from dulwich.pack import Pack
from dul... | e ignored
"""
for pattern in patterns:
if fnmatch.fnmatch(filename, pattern) and not pattern.startswith("!"):
return True
return False
def _read_di | rectory_tree(self, path, show_ignored_files=False):
files = []
directories = []
for root, dirs, filenames in os.walk(path, topdown=True):
try:
dirs.remove(".git")
removed_git_dir = True
except ValueError:
pass
#... |
MasAval/django_pipedrive | pipedrive/views.py | Python | bsd-3-clause | 3,721 | 0.000269 | import json
import logging
from django.views.decorators.csrf import csrf_exempt
from django.db import IntegrityError
from django.http import HttpResponse
from pipedrive.models import Deal
from pipedrive.models import Person
from pipedrive.models import Organization
from pipedrive.models import Note
from pipedrive.mod... | commands
# source: https://github.com/djangonauts/django-hstore/issues/141
from django.db import connection
from psycopg2.extras import register_hstore
# And then in `def handle`
register_hstore(connection.cursor(), globally=True, | unicode=True)
def handle_v1(json_data):
meta = json_data[u'meta']
object_type = meta[u'object']
action = meta[u'action']
external_id = meta[u'id']
model = map_models(object_type)
# previous = json_data[u'previous']
current = json_data[u'current']
try:
if action == 'updat... |
GunGame-Dev-Team/GunGame-SP | addons/source-python/plugins/gungame/plugins/included/gg_reload/info.py | Python | gpl-3.0 | 538 | 0 | # ../gungame/plugins/included/gg_reload/info.py
"""Contains plugin inf | ormation."""
# =============================================================================
# >> IMPORTS
# =============================================================================
# GunGame
from gungame.core.plugins.info import GunGamePluginInfo
# ===============================================================... | fo = GunGamePluginInfo(__name__)
|
aureooms/mupi | linext.py | Python | agpl-3.0 | 2,203 | 0.088062 | from matrix import mat , show , subscripts , parse
from information import comparator
def grid ( m , n ) :
e = mat( m + 1 , n + 1 , [ ] )
e[0][0] = [ [ ] ]
for i in range ( 1 , m + 1 ) :
e[i][0] = [ [ "a[%d]" % k for k in range( 1 , i + 1 ) ] ]
for j in range ( 1 , n + 1 ) :
e[0][j] = [ [ "b[%d]" % k fo... | 2 ) )
4
>>> compare = comparator( [ [ 0 , -1 ] , [ 1 , 1 ] ] )
>>> e = grid( 2 , 2 )
>>> len( gen( compare , e , 2 , 2 ) )
2
>>> compare = comparator( | [ [ -1 , -1 ] , [ 1 , 0 ] ] )
>>> e = grid( 2 , 2 )
>>> len( gen( compare , e , 2 , 2 ) )
2
"""
if not e[i][j] :
result = compare( i - 1 , j - 1 )
if result > 0 :
e[i][j] = [ ext + [ "a[%d]" % i ] for ext in gen( compare , e , i - 1 , j ) ]
elif result < 0 :
e[i][j] = [ ext + [ "b[%d]" % j ]... |
bayesimpact/bob-emploi | frontend/server/test/auth_google_test.py | Python | gpl-3.0 | 11,110 | 0.00162 | """Tests for the Google authentication."""
import unittest
from unittest import mock
from bob_emploi.frontend.server import server
from bob_emploi.frontend.server.test import base_test
@mock.patch(server.__name__ + '.auth.id_token.verify_oauth2_token')
class AuthenticateEndpointGoogleTestCase(base_test.ServerTestC... | '12345',
}
response = self.app.post(
'/api/user/authenticate', data='{"googleTokenId": "my-token"}',
content_type='application/json')
auth_response = self.json_from_response(response)
user_id = auth_response['authenticatedUser']['userId']
auth_token = aut... | f'{{"userId": "{user_id}", "googleId": "12345", '
'"profile": {"email": "used@email.fr"}}',
content_type='application/json',
headers={'Authorization': 'Bearer ' + auth_token})
self.assertEqual(403, response.status_code)
def test_update_no_email_change(self, mock_verify_o... |
ageorge/beets-bandcamp | beetsplug/bandcamp.py | Python | mit | 13,653 | 0.001978 | # Copyright (C) 2015 Ariel George
#
# 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; version 2.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; wit... | onfig['art']:
for plugin in plugins.find_plugins():
if isinstance(plugin, fet | chart.FetchArtPlugin):
plugin.sources = [BandcampAlbumArt(plugin._log, self.config)] + plugin.sources
fetchart.ART_SOURCES['bandcamp'] = BandcampAlbumArt
fetchart.SOURCE_NAMES[BandcampAlbumArt] = 'bandcamp'
break
def album_distance(sel... |
mlperf/inference_results_v0.7 | closed/Intel/code/resnet/resnet-ov/py-bindings/_nlp_common.py | Python | apache-2.0 | 10,322 | 0.001841 | import unicodedata
try:
import sentencepiece as spm
except ImportError:
spm = None
#from ..config import ConfigError
#from ..utils import contains_all
SPIECE_UNDERLINE = '\N{LOWER ONE EIGHTH BLOCK}'
SEG_ID_A = 0
SEG_ID_B = 1
SEG_ID_CLS = 2
SEG_ID_SEP = 3
SEG_ID_PAD = 4
special_symbols = {
"<unk>": 0,
... | sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append("[UNK]")
else:
output_tokens.extend(sub_tokens)
return output_tokens
def tokenize(self, text):
tokens = []
for token in self.basic_tokenizer(t... | |
TuftsBCB/pybcb | pybcb/sabmark.py | Python | mit | 1,530 | 0.001307 | import csv
import os
import os.path
import sys
import pybcb.flags as flags
__TWILIGHT = 'twi_fp'
__SUPERFAMILY = 'sup_fp'
def join(*args):
flags.assert_flag('sabmark-dir')
flags.assert_flag('sabmark-set')
if flags.config.sabmark_set == 'twilight':
return os.path.join(flags.config.sabmark_dir, _... | , 'pdb', sabid + '.ent')
def group(group_num):
'''
`group_num` is the group number in the alignment set of the context.
(The alignment set is discovered through the `sabmark-set` flag.)
Returns a tuple of lists, where the first is a list of true positive
SCOP identifiers and the second is a list ... | not exist in %s' \
% (group_num, flags.config.sabmark_set)
sys.exit(1)
tps, fps = [], []
gsummary = open(join('group%d' % group_num, 'group.summary'))
for row in csv.DictReader(gsummary, delimiter='\t'):
if row['True pos'].strip() == '1':
tps.append(row['Name'].stri... |
felipechaulet/mailcollector | lwc/src/lwc/urls.py | Python | gpl-2.0 | 294 | 0.006803 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'joins.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^ | admin/', include(a | dmin.site.urls)),
)
|
zzzzzzzlmy/MyLeetCode | 217. Contains Duplicate.py | Python | unlicense | 524 | 0.01145 | '''
Given an array of integers, find if the array contains | any duplicates. Your function should return true if any value
appears at least twice in the array, and it should return false if every element is distinct.
'''
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
... | |
maxmalysh/tiny-py-interpreter | tinypy/runtime/Errors.py | Python | mit | 685 | 0.008759 |
class BaseRuntimeExcep | tion(BaseException):
def __init__(self, message):
super().__init__(message)
class MemoryError(BaseRuntimeException):
pass
class NameError(MemoryError):
pass
class TypeError(BaseRuntimeException):
pass
class ArithmeticError(BaseRuntimeException):
pass
class ZeroDivisionError(ArithmeticEr... | on):
pass
class KeyError(BaseRuntimeException):
pass
class IndexError(BaseRuntimeException):
pass
class NotImplementedError(BaseRuntimeException):
pass
|
mahak/neutron | neutron/services/trunk/rpc/agent.py | Python | apache-2.0 | 4,441 | 0 | # Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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... | le subports event."""
# if common logic may be extracted out, consider making a base
# version of this method that can be overridden by the inherited
# skeleton.
# NOTE: If the subport belongs to a trunk which the agent does not
# manage, the notification should be ignored.
cla... | proxy code for agent->server communication."""
# API HISTORY
# 1.0 - initial version
VERSION = '1.0'
def __init__(self):
self.stub = resources_rpc.ResourcesPullRpcApi()
target = oslo_messaging.Target(
topic=trunk_consts.TRUNK_BASE_TOPIC,
version=self.VERSION,
... |
0verchenko/Addressbook | test/test_add_group.py | Python | apache-2.0 | 638 | 0.00627 | # -*- coding: utf-8 -*-
from model.group import Group
imp | ort pytest
def test_add_group(app, db, json_groups):
group = json_groups
with pytest.allure.step('Take existing group list from db'):
old_groups = db.get_group_list()
with pytest.allure.step('Create new group %s' %group):
app.group.create(group)
with pytest.allure.step('Take existing gr... | llure.step('Compare groups lists'):
assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
|
algarecu/tbwd | src/Louvain/utility.py | Python | gpl-3.0 | 25,180 | 0.117355 |
def edges_all():
edges = [('sd_10','as_1'),
('sd_27','as_1'),
('sd_19','as_1'),
('sd_1','as_2'),
('sd_29','as_2'),
('sd_30','as_2'),
('sd_5','as_3'),
('sd_18','as_3'),
('sd_3','as_3'),
('sd_6','as_3'),
('sd_4','as_3'),
('sd_8','as_3'),
('sd_10','as_3'),
('sd_7','as_3'),
('sd_31','as_4'),
('sd_24','as_5'),
('sd_26... | ,
('sd_1','dp_85'),
('sd_28','dp_85'),
('sd_9','dp_85'),
('sd_21','dp_88'),
('sd_6','dp_88'),
('sd_6','dp_90'),
('sd_11','dp_90'),
('sd_17','dp_90'),
('sd_12','dp_90'),
('sd_5','d | p_90'),
('sd_13','dp_90'),
('sd_25','dp_90'),
('sd_16','dp_90'),
('sd_6','dp_95'),
('sd_11','dp_95'),
('sd_17','dp_95'),
('sd_11','dp_97'),
('sd_5','dp_97'),
('sd_24','dp_97'),
('sd_2','dp_97'),
('sd_4','dp_100'),
('sd_7','dp_100'),
('sd_8','dp_100'),
('sd_25','dp_100'),
('sd_1','dp_100'),
('sd_27','dp_100'),
('sd_17',... |
xmikos/qopenvpn | qopenvpn/stun.py | Python | gpl-3.0 | 4,389 | 0.001139 | #!/usr/bin/env python
"""Simple STUN client for getting external IP address.
Based on stun.py from https://github.com/myers/html5_udp_to_server,
but heavily simplified (dropped Twisted dependency, only supports old RFC 3489)
"""
import os, socket, str | uct, math
BINDING_REQUEST = 0x0001
BINDING_RESPONSE = 0x0101
MAPPED_ADDRESS = 0x0001
FAMILY_IPV4 = 0x01
STUN_SERVERS = [
("stun.l.google.com", 19302),
("stun1.l.google.com", 19302),
("stun2.l.google.com", 19302),
("stun3.l.google.com", 19302),
("stun4.l.google.com", 19302),
("stun.iptel.org", ... | elf, timeout=5, attempts=3):
self._timeout = timeout
self._attempts = attempts
self._transaction_id = b""
def get_ip(self, stun_host="", stun_port=3478, source_address="", source_port=54320):
"""Get external IP address and port"""
if stun_host:
stun_servers = [(s... |
idaholab/raven | tests/framework/aliasSystemTests/externalModel/lorentzAttractor.py | Python | apache-2.0 | 1,994 | 0.021565 | # Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file exc | ept in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ... | |
ktan2020/legacy-automation | win/Lib/idlelib/TreeWidget.py | Python | mit | 15,708 | 0.001273 | # XXX TO DO:
# - popup menu
# - support partial or total redisplay
# - key bindings (instead of quick-n-dirty bindings on Canvas):
# - up/down arrow keys to move focus around
# - ditto for page up/down, home/end
# - left/right arrows to expand/collapse & move out/in
# - more doc strings
# - add icons for ... | le_top and height <= visible_height:
fraction = top + height - visible_height
else:
fraction = top
fraction = float(fracti | on) / y1
self.canvas.yview_moveto(fraction)
def lastvisiblechild(self):
if self.children and self.state == 'expanded':
return self.children[-1].lastvisiblechild()
else:
return self
def update(self):
if self.parent:
self.parent.upda... |
KatiRG/wms-pyferret | pyferretWMS_flask.py | Python | mit | 14,186 | 0.012195 | #!/usr/bin/env python
from __future__ import print_function
import multiprocessing
import gunicorn.app.base
from gunicorn.six import iteritems
import os, sys
import re
import shutil
import tempfile
import pyferret
from paste.request import parse_formvars
import subprocess
from jinja2 import Template
import itertoo... | variable, 'dset': dset, 'postvar': postvar})
nbMaps = len(session['cart']) #len(cmdArray)
listSynchroMapsToSet = list(itertools.permutations(range(1,nbMaps+1), 2))
return render_template('showmaps.html', cmdArray=session['cart'], listSynchroMapsToSet=listSynch | roMapsToSet)
@app.route('/showmaps_resource', methods=['POST','GET'])
def api_calcmaps():
DSET = str(request.args.get('DSET'))
POSTVAR = str(request.args.get('POSTVAR'))
COMMAND = str(request.args.get('COMMAND'))
VARIABLE = str(request.args.get('VARIABLE'))
tmpname = tempfile.NamedTemporaryF... |
vivek8943/django-chartit | chartit/chartdata.py | Python | bsd-2-clause | 27,318 | 0.009151 | import copy
from collections import defaultdict
from itertools import groupby, chain, islice
from operator import itemgetter
# use SortedDict instead of native OrderedDict for Python 2.6 compatibility
from django.utils.datastructures import SortedDict
from validation import clean_dps, clean_pdps
from chartit.val... | s2
def _get_data(self):
for tk_td_tuples, vqs in self._generate_vqs():
vqs_list = list(vqs)
for tk, td in tk_td_tuples:
# everything has a reference to the same list
self.series[tk]['_data'] = vqs_list
class PivotDataPool(DataPool):
... | def __init__(self, series, top_n_term=None, top_n=None, pareto_term=None,
sortf_mapf_mts=None):
""" Creates a PivotDataPool object.
:Arguments:
- **series** (**required**) - a list of dicts that specifies the what
data to retrieve, wher... |
santa4nt/django-gravatar | django_gravatar/templatetags/gravatar_tags.py | Python | mit | 4,346 | 0.002761 | import re
import urllib
import hashlib
from django import template
from django.conf import settings
URL_RE = re.compile(r'^https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?',
re.IGNORECASE)
EMAIL_RE = re.compile(r'^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$',
re.IGNORECASE)
GRAVATAR_URL_PREFIX = 'http... | ing': ('r', 'g'), # | 'pg', 'r', or 'x'
'default': ('d', ''), # 'identicon', 'monsterid', 'wavatar', '404', or escaped URI
}
register = template.Library()
def _build_gravatar_url(email, params):
"""Generate a Gravatar URL.
"""
# step 1: get a hex hash of the email address
email = email.strip().lower().... |
Kryz/sentry | src/sentry/utils/strings.py | Python | bsd-3-clause | 978 | 0 | """
sentry.utils.strings
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import base64
import zlib
from django.utils.encoding import smart_unicode
def truncatechars(value, arg):
... | press(value):
return zlib.decompress(base64.b64decode(value))
def gunzip(value):
return zlib.decompress(value, 16 + zlib.MAX_WBITS)
def strip(value):
if not value:
| return ''
return smart_unicode(value).strip()
|
shakamunyi/neutron-vrrp | neutron/agent/metadata/namespace_proxy.py | Python | apache-2.0 | 6,335 | 0.001421 | # Copyright 2012 New Dream Network, LLC (DreamHost)
#
# 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 a... | ,
| help=_('Run as daemon.')),
cfg.IntOpt('metadata_port',
default=9697,
help=_("TCP Port to listen for metadata server "
"requests.")),
cfg.StrOpt('metadata_proxy_socket',
default='$state_path/metadata_proxy'... |
bkendzior/scipy | scipy/signal/signaltools.py | Python | bsd-3-clause | 116,017 | 0.000086 | # Author: Travis Oliphant
# 1999 -- 2002
from __future__ import division, print_function, absolute_import
import warnings
import threading
import sys
import timeit
from . import sigtools, dlti
from ._upfirdn import upfirdn, _UpFIRDn, _output_len
from scipy._lib.six import callable
from scipy._lib._version import Num... | ule, where the larger array input needs to come
before the smaller array input when operating in this mode.
Note that if the mode provided is not 'valid', False is immediately
returned.
"""
if mode == 'valid':
ok1, ok2 = True, True
for d1, d2 in zip(shape1, shape2):
if ... | ok2 = False
if not (ok1 or ok2):
raise ValueError("For 'valid' mode, one must be at least "
"as large as the other in every dimension")
return not ok1
return False
def correlate(in1, in2, mode='full', method='auto'):
"""
Cross-correlate two N... |
shail2810/nova | nova/tests/functional/api_sample_tests/test_scheduler_hints.py | Python | apache-2.0 | 1,979 | 0 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | subs)
| self._verify_response('scheduler-hints-post-resp', subs, response, 202)
|
IvanMalison/okcupyd | tests/xpath_test.py | Python | mit | 1,572 | 0 | from lxml import etree
from okcupyd import xpath
def test_selected_attribute():
node = xpath.XPathNode(element='element', selected_attribute='value')
assert node.xpath == '//element/@value'
tree = etree.XML("<top><container><element value='1'>"
"</element><element value='2'></elemen... | tribute_contains():
tree = etree.XML("<top><elem a='complete'></elem></top>")
assert xpath.xpb.elem.attribute_contains('a', 'complet').apply_(tree) != []
def test_text_contains():
element_text = "cool stuff44"
tree = etree.XML("<top><elem>{0}</elem><elem></elem>"
"<elem>other thin... | result = xpath.xpb.elem.text_contains_("stuff").text_.apply_(tree)
result_text, = result
assert result_text == element_text
result = xpath.xpb.elem.text_contains_("afdsafdsa").text_.apply_(tree)
assert result == []
|
RichardLitt/wyrd-django-dev | django/contrib/comments/models.py | Python | bsd-3-clause | 7,766 | 0.005022 | from django.conf import settings
from django.contrib.comments.managers import CommentManager
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core import urlresolvers
from django.db import models
from djan... | erinfo.__doc__)
def _get_name(self):
return self.userinfo["name"]
def _set_name(self, val):
if self.user_id:
raise AttributeError(_("This comment | was posted by an authenticated "\
"user and thus the name is read-only."))
self.user_name = val
name = property(_get_name, _set_name, doc="The name of the user who posted this comment")
def _get_email(self):
return self.userinfo["email"]
def _set_email(s... |
slonak79/MBDreamers | bios/models.py | Python | gpl-2.0 | 443 | 0.011287 | from django.db import models
# Create your models here.
class Author(models.Model):
first_name = models.CharField(max_lengt | h = 100)
last_name = models.CharField(max_length = 100)
date_of_birth = models.DateField()
profile_photo = models.ImageField(upload_to="media")
linkedin_link = models.URLField(max_length=250)
personal_website_link = models.URLField(max_length=250, blank=True)
bio = models.Text | Field()
|
justasabc/python_tutorials | tutorial/gui/pygtk2/layout/6_vbox.py | Python | gpl-3.0 | 621 | 0.028986 | #!/usr/bin/env pytho | n
import gtk
class PyApp(gtk.Window):
def __init__(self):
super(PyApp,self).__init__()
self.set_title('vbox')
self.set_default_size(200, 100)
vbox = gtk.VBox(False, 5)
button1 = gtk.Button("Button 1")
button2 = gtk.Button("Button 2")
button3 = gtk.Button("Button 3")
... | button3,False,False,0)
self.add(vbox)
self.connect("destroy", lambda w: gtk.main_quit())
self.show_all()
PyApp()
gtk.main()
|
Manu343726/siplasplas | src/reflection/parser/utility/namespace.py | Python | mit | 752 | 0.007979 |
class Namespace(object):
SCOPE_OPERATOR = '::'
def __init | __(self, string = '', splitted = []):
if string and not splitted:
self._string = string
self._splitted = string.split(Namespace.SCOPE_OPERATOR)
else:
self._splitted = splitted
self._string = Namespace.SCOPE_OPERATOR.join(splitted)
@property
def pa... | def child(self, namespace):
return Namespace(splitted = self._splitted + [namespace])
def get_text(self):
return self._string
@staticmethod
def global_namespace():
return Namespace()
|
kalev/anaconda | pyanaconda/gui.py | Python | gpl-2.0 | 50,515 | 0.006117 | #
# gui.py - Graphical front end for anaconda
#
# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
# Red Hat, Inc. All rights reserved.
#
# 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 F... | that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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/>.
#
# Author(s): Matt Wilson <msw@redhat.com>
# Michael Fulbright <msf@redhat.com>
#
import os
from flags import flags
os.environ["GNOME_DISABLE_CRASH_DIALOG"] = "1"
import string
import time
impor... |
hpparvi/PyTransit | pytransit/contamination/__init__.py | Python | gpl-2.0 | 1,603 | 0.003119 | # PyTransit: fast and easy exoplanet transit modelling in Python.
# Copyright (C) 2010-2019 Hannu Parviainen
#
# 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... | it will be useful,
# but WITHOUT ANY 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 <https://... | ination, BBContamination, contaminate_light_curve
from .filter import DeltaFilter, BoxcarFilter, TabulatedFilter, sdss_z, sdss_i, sdss_r, sdss_g
def true_radius_ratio(apparent_k: float, contamination: float) -> float:
return apparent_k / sqrt(1 - contamination)
def apparent_radius_ratio(true_k: float, contamina... |
JshWright/home-assistant | homeassistant/components/device_tracker/fritz.py | Python | apache-2.0 | 3,308 | 0 | """
Support for FRITZ!Box routers.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.fritz/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.c... | """Initialize the scanner."""
self.last_results = []
self.host = config[CONF_HOST]
self.username = config[CONF_USERNAME]
self.password = config[CONF_PASSWORD]
self.success_init = True
# pylint: disable=import-error
import fritzconnection as fc
# ... | (ValueError, TypeError):
self.fritz_box = None
# At this point it is difficult to tell if a connection is established.
# So just check for null objects.
if self.fritz_box is None or not self.fritz_box.modelname:
self.success_init = False
if self.success_init:
... |
ajayaa/keystone | keystone/tests/unit/test_v3_credential.py | Python | apache-2.0 | 19,309 | 0 | # Copyright 2013 OpenStack Foundation
#
# Lice | nsed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lic... | lied. See the
# License for the specific language governing permissions and limitations
# under the License.
import hashlib
import json
import uuid
from keystoneclient.contrib.ec2 import utils as ec2_utils
from oslo_config import cfg
from six.moves import http_client
from testtools import matchers
from keystone impo... |
drmaize/ThermoAlign | TA_codes/UOD.py | Python | gpl-3.0 | 23,672 | 0.02522 | ### UOD: Unique Oligonucleotide Design algorithm; a part of Thermo-Align tool for the design of template specific hybridization and priming oligonucleotides
### Version 1.0.0: 06/28/2016
### Authors: Felix Francis (felixfrancier@gmail.com); Randall J. Wisser (rjw@udel.edu)
############################################... | ts, filter_GC_clamp= filter_GC_clamp) #+ strand
elif (i+primer_size) >= target_stop_pos:
primer = input_seq[i:i+primer_size].upper()
rev_comp_primer = rev_complement(primer)
primer_filter (rev_comp_primer, minTm, maxTm, GC_range... | i_si_repeats, filter_GC_clamp= filter_GC_clamp) # - strand
else:
primer = input_seq[i:i+primer_size].upper()
rev_comp_primer = rev_complement(primer)
primer_filter (primer, minTm, maxTm, GC_range_min,GC_range_max, self_Tmdiff, filter_AT_3prime, primer_dict, i=... |
hackerspace-ntnu/website | news/migrations/0005_auto_20180723_1631.py | Python | mit | 730 | 0.002743 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-23 16:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0004_auto_20180213_1839'),
]
operations = [
migrations.AlterField(... | e_name='Lenke for ekstern påmelding'),
),
migrations.AlterField(
model_name='event', |
name='ingress_content',
field=models.CharField(blank=True, max_length=30, verbose_name='Ingress'),
),
]
|
PysKa-Ratzinger/personal_project_euler_solutions | solutions/076-100/77/.ycm_extra_conf.py | Python | mit | 4,697 | 0.018948 | # Generated by YCM Generator at 2019-06-21 11:57:11.711058
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publis... | ORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
import os
import ycm_core
flags = [
'-x',
'c++',
'-I../../utils/',
]
# Set this to the absolute path to the folder... |
# You can get CMake to generate this file for you by adding:
# set( CMAKE_EXPORT_COMPILE_COMMANDS 1 )
# to your CMakeLists.txt file.
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_fo... |
GoogleCloudPlatform/healthcare-deid | deid_app/backend/server.py | Python | apache-2.0 | 29,411 | 0.008024 | # Copyright 2018 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 ... | common import unicodecsv
from deid_app.backend impor | t config
from deid_app.backend import model
from dlp import run_deid_lib
from eval import run_pipeline_lib as eval_lib
import jsonschema
from google.cloud import bigquery
from google.cloud import storage
from google.cloud.exceptions import exceptions
logging.getLogger().setLevel(logging.INFO)
app = flask.Flask(__na... |
kmatzen/nyc3dcars-toolkit | test.py | Python | bsd-3-clause | 1,777 | 0.001125 | #!/usr/bin/env python
"""Runs the testing protocol for a given dataset, model, and NMS methods.
Can either run as a single process or distributed using celery."""
import celery
from nyc3dcars import SESSION, Photo, Model
import scores
import logging
import argparse
from detect import detect
from geo_rescore im... | .rollback()
raise
finally:
session.close()
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
PARSER = argparse.ArgumentParser()
PARSER.add_argument('--model', required=True)
PARSER.add_argument('--methods', nargs='+', default=scores.METHODS.keys())
PARSER.add_... | e=int)
PARSER.add_argument('--remote', action='store_true')
ARGS = PARSER.parse_args()
test(
model=ARGS.model,
remote=ARGS.remote,
methods=ARGS.methods,
dataset_id=ARGS.dataset_id,
)
|
protojour/aux | aux/protocol/http/mime.py | Python | bsd-3-clause | 1,004 | 0.003984 | import os
import re
#TODO: use mimeparse but keep factory pattern
class DefaultController(object):
def __init__(self, disposition, raw_body):
self.data = raw_body
def handle(self):
return sel | f.data
class ZIPController(object):
def __init__(self, disposition, raw_body):
sel | f.disposition = disposition
self.data = raw_body
def handle(self):
re_filename = re.compile(r'attachment;\s?filename="(.*\.zip)"')
tmp_dir = "/tmp/aux"
filename = re_filename.findall(self.disposition)[0]
filepath = os.path.join(tmp_dir, filename)
if not os.path.exist... |
snswa/swsites | zipcodes/migrations/0004_rename_intermediate_team_models.py | Python | apache-2.0 | 7,503 | 0.007864 | # 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):
db.rename_table('zipcodes_countyteam', 'zipcodes_teamcounty')
db.rename_table('zipcodes_zipcodeteam', 'zipcodes_tea... | ame']", 'object_name': 'Team'},
'auto_join': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_private': ('django.db.models.fi | elds.BooleanField', [], {'default': 'False'}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'through': "orm['teams.Member']", 'symmetrical': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
... |
pyk/rojak | rojak-pantau/rojak_pantau/i18n/i18n.py | Python | bsd-3-clause | 1,202 | 0 | class i18n(object):
def __init__(self):
# Default domain
self._domain = 'idn'
def domain(self, country):
self._domain = country
def translate(self, domain):
dic = {}
dic['idn'] = {
# Month
'Januari': 'January',
'Februari': 'Febru... | 'Okt': 'Oct',
'Nov': 'Nov',
'Des': 'Dec',
}
return dic[dom | ain] if domain in dic else {}
def __call__(self, string):
t = self.translate(self._domain)
if string in t:
return t[string]
return string
|
samuelcolvin/MonQL | MonQL/Inspect/__init__.py | Python | mit | 146 | 0.006849 | from MonQL.Inspect._sql import MySQL, SQLite, PostgreSQL
from MonQL.Inspect._ | mong | o import MongoDB
from MonQL.Inspect._utils import ConnectionError |
jwilson64/Facebook-Bot | sender.py | Python | mit | 501 | 0.00998 | import urllib2
# Made an api class in case more integration is needed in the future.
# This will be far more useful as the bot is built out.
class Api:
def post(self,data,url,headers={'Content-type': 'application/json'}):
requ | est = urllib2.Request(url,data,headers)
try:
respon | se = urllib2.urlopen(request)
print response
except urllib2.HTTPError as e:
print "Fatal error log info: " + url
print data
print e
|
stefanheule/putil | putil/util.py | Python | apache-2.0 | 378 | 0.010582 | # ------------------------------------------------------------------------------
#
# Various helpers.
#
# Author: Stefan Heule <stefanheule@gmail.com>
#
# ------------------------------------------------------------------------------
import time
def | get_time_str():
"""
Returns a string of the current time.
"""
retu | rn time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) |
kvendingoldo/Import-SSU-schedule-to-Google-Calendar | src/python/importer/main.py | Python | mit | 547 | 0.001828 | #!/usr/bin/python3.5
# -*- coding: utf-8 -*-
# @Author: Alexander Sharov
from entity import config as cfg
from entity import calendar as cal
from generator import schedule as sch
def main | ():
config = cfg.Config()
calendar = cal.Calendar(configuration=config)
schedule = sch.generate('http://www.sgu.ru/schedule/%s/%s/%s' % (
| config.data['department'], config.data['study_mode'], config.data['group']))
# calendar.clear(config.data['calendarId'])
calendar.put_week(schedule)
if __name__ == '__main__':
main()
|
pyblish/pyblish-softimage | pyblish_softimage/__init__.py | Python | lgpl-3.0 | 176 | 0 | from vers | ion import *
from lib import (
show,
setup,
regist | er_plugins,
register_host,
add_to_filemenu,
# Utility functions
maintained_selection
)
|
MFry/pyAlgoDataStructures | Cracking the Coding Interview/Linked_Lists/question2.py | Python | mit | 941 | 0.002125 | """
Algorithm that finds kth to last element in a singly linked list
"""
from linkedlist import LinkedList
def findKelementh(list, k):
"""
:param list:
:type list: LinkedList
:param k:
:type k: int
:return:
"""
i = 0
node = list.head
kth_node = None
while node is not None:... | k:
kth_node = list.head
return kth_node
def main():
test = LinkedList()
for i in range(20):
test.add(i)
print(test)
print('Find the node before last', findKelementh(test, 2))
print('Find the last node', findKelementh(test, 1))
print('Findi | ng 12th to last Node: ', findKelementh(test, 12))
if __name__ == '__main__':
main()
|
robcza/intelmq | intelmq/bots/collectors/blueliv/collector_crimeserver.py | Python | agpl-3.0 | 1,233 | 0 | # -*- coding: utf-8 -*-
import json
import logging
import sys
from intelmq.lib.bot import Bot
from intelmq.lib.message import Report
from sdk.blueliv_api import BluelivAPI
class BluelivCrimeserverCollectorBot(Bot):
def process(self):
| self.logger.info("Downloading report through API")
http_proxy = getattr(self.parameters, 'http_proxy', None)
https_proxy = getattr(self.parameters, 'http_ssl_proxy', None)
proxy = None
if http_proxy and https_proxy:
proxy = {'http': http_proxy,
'https':... | ng.INFO,
proxy=proxy)
response = api.crime_servers.online()
self.logger.info("Report downloaded.")
report = Report()
report.add("raw", json.dumps([item for item in response.items]))
report.add("feed.name", self.parameters.feed)
report.add("feed.... |
RandolphVI/CNN-Text-Classification | CRNN/test_crnn.py | Python | apache-2.0 | 6,213 | 0.004346 | # -*- coding:utf-8 -*-
__author__ = 'Randolph'
import os
import sys
import time
import logging
import numpy as np
sys.path.append('../')
logging.getLogger('tensorflow').disabled = True
import tensorflow as tf
from utils import checkmate as cm
from utils import data_helpers as dh
from utils import param_parser as par... | EL = dh.get_model_name()
logger = dh.logger_fn("tflog", "logs/Test-{0}.log".format(time.asctime()))
CPT_DIR = 'runs/' + MODEL + '/checkpoints/'
BEST_CPT_DIR = 'runs/' + MODEL + '/bestcheckpoints/'
SAVE_DIR = | 'output/' + MODEL
def create_input_data(data: dict):
return zip(data['f_pad_seqs'], data['b_pad_seqs'], data['onehot_labels'])
def test_crnn():
"""Test CRNN model."""
# Print parameters used for the model
dh.tab_printer(args, logger)
# Load word2vec model
word2idx, embedding_matrix = dh.loa... |
mxtthias/mcomix | mcomix/library/collection_area.py | Python | gpl-2.0 | 20,879 | 0.002203 | """library_collection_area.py - Comic book library window that displays the collections."""
from xml.sax.saxutils import escape as xmlescape
import gtk
import gobject
from mcomix.preferences import prefs
from mcomix import constants
from mcomix import i18n
from mcomix import status
from mcomix import file_chooser_lib... | eturn the collection ID for the currently selected collection,
or None if no collection is selected.
"""
cursor = self._treeview.get_cursor()
if cursor is None:
return
| return self._get_collection_at_path(cursor[0])
def display_collections(self):
"""Display the library collections by redrawing them from the
backend data. Should be called on startup or when the collections
hierarchy has been changed (e.g. after moving, adding, renaming).
Any ro... |
crobby/sahara | sahara/tests/unit/conductor/manager/test_clusters.py | Python | apache-2.0 | 13,755 | 0 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | self.api.node_group_remove(ctx, ng_id)
def _add_instance(self, ctx, ng_id):
instance = {
"instance_name": "additional_vm"
}
return self.api.instance_add(ctx, ng_id, instance)
def _add_instance_ipv6(self, ctx, ng_id, instance_name):
instance = {
... | "management_ip": "FE80:0000:0000:0000:0202:B3FF:FE1E:8329"
}
return self.api.instance_add(ctx, ng_id, instance)
def test_add_instance(self):
ctx = context.ctx()
cluster_db_obj = self.api.cluster_create(ctx, SAMPLE_CLUSTER)
_i |
climu/openstudyroom | home/models.py | Python | gpl-3.0 | 10,376 | 0.001542 | from __future__ import absolute_import, unicode_literals
import random
import reque | sts
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.db.models import Count, Case, IntegerField, When
from django.db.models.functions import TruncMonth
from django.dispatch import receiver
from django.template.loader import render_to_string
from dj... | ils import timezone
from django import forms
from django.urls import reverse
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField, StreamField
from wagtail.snippets.models import register_snippet
from wagtail.snippets.blocks import SnippetChooserBlock
from wagtail.admin.edit_handlers impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.