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 |
|---|---|---|---|---|---|---|---|---|
paultag/ftp-master-doc | doc/conf.py | Python | gpl-3.0 | 7,820 | 0.007545 | # -*- coding: utf-8 -*-
#
# ftp-master-doc documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 4 21:44:03 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
... | ctories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: | etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_aut... |
andersk/zulip | zerver/lib/actions.py | Python | apache-2.0 | 325,551 | 0.001554 | import datetime
import hashlib
import itertools
import logging
import os
import time
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from operator import itemgetter
from typing import (
IO,
AbstractSet,
Any,
Callable,
Collection,
Dict,
Iterable,
List,... | er,
get_subscribed_stream_ids_for_user,
get_subscriptions_for_send_message,
get_used_colors_for_user_ids,
get_user_ids_for_streams,
num_subscribers_for_strea | m_id,
subscriber_ids_with_stream_history_access,
)
from zerver.lib.stream_topic import StreamTopicTarget
from zerver.lib.streams import (
access_stream_by_id,
access_stream_for_send_message,
can_access_stream_user_ids,
check_stream_access_based_on_stream_post_policy,
create_stream_if_needed,
... |
jvrsantacruz/XlsxWriter | xlsxwriter/test/worksheet/test_write_worksheet.py | Python | bsd-2-clause | 887 | 0.001127 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ...worksheet import Worksheet
class TestWriteWorksheet(unittest.TestCase):
"""
... | self.worksheet = Worksheet()
self.worksheet._set | _filehandle(self.fh)
def test_write_worksheet(self):
"""Test the _write_worksheet() method"""
self.worksheet._write_worksheet()
exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationship... |
596acres/django-livinglots-template | project_name/project_name/settings/base.py | Python | gpl-3.0 | 8,268 | 0.002056 | from collections import OrderedDict
import os
from os.path import abspath, dirname
from django.core.exceptions import ImproperlyConfigured
ENV_VARIABLE_PREFIX = 'LL'
def get_env_variable(var_name):
"""Get the environment variable or return exception"""
if not ENV_VARIABLE_PREFIX:
raise ImproperlyCon... | VERRIDES = {
'elephantblog.entry': elephantblog_entry_url_app,
'elephantblog.categorytranslation': elephantblog_categorytranslation_url_app,
}
SOUTH_MIGRATION_MODULES = {
'page': 'cms.migrate.page',
'medi | alibrary': 'cms.migrate.medialibrary',
}
HONEYPOT_FIELD_NAME = 'homepage_url'
HONEYPOT_VALUE = 'http://example.com/'
ADMIN_TOOLS_INDEX_DASHBOARD = '{{ project_name }}.admindashboard.LivingLotsDashboard'
LIVING_LOTS = {
'MODELS': {
'lot': 'lots.Lot',
'lotgroup': 'lots.LotGroup',
'organizer... |
zephyrplugins/zephyr | zephyr.plugin.jython/jython2.5.2rc3/Lib/test/test_xdrlib.py | Python | epl-1.0 | 30 | 0 | impo | rt xdrlib
xdrlib._te | st()
|
rigetticomputing/grove | grove/pyqaoa/maxcut_qaoa.py | Python | apache-2.0 | 4,142 | 0.002414 | ##############################################################################
# Copyright 2016-2017 Rigetti Computing
#
# 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... | maxcut_graph.add_edge(*edge)
graph = ma | xcut_graph.copy()
cost_operators = []
driver_operators = []
for i, j in graph.edges():
cost_operators.append(PauliTerm("Z", i, 0.5)*PauliTerm("Z", j) + PauliTerm("I", 0, -0.5))
for i in graph.nodes():
driver_operators.append(PauliSum([PauliTerm("X", i, -1.0)]))
if connection is Non... |
clarammdantas/Online-Jugde-Problems | online_judge_solutions/diferent_digits.py | Python | mit | 250 | 0.068 | #diferent_digits
while True:
try:
n1, n2 = map(int,raw_input( | ).split())
| n_casas = n2 - n1 + 1
n = 0
for i in range(n1, n2 + 1):
c = str(i)
c_nrep = set(c)
if len(c) != len(c_nrep):
n += 1
print n_casas - n
except: break
|
evanthebouncy/nnhmm | mnist_haar/check_data.py | Python | mit | 735 | 0.006803 | from data import *
from draw import *
img, hiden_x = get_img_class()
print img.shape
print img
d_idx = np.random.randint(0, 50)
x_x, obs_x, obs_y, o | bs_tfs, new_ob_x, new_ob_y, new_ob_tf, imgs = gen_data()
print show_dim(x_x)
print | show_dim(obs_x)
print show_dim(obs_y)
print show_dim(obs_tfs)
print show_dim(new_ob_x)
print show_dim(new_ob_y)
print show_dim(new_ob_tf)
obss = zip([np.argmax(obx[d_idx]) for obx in obs_x],
[np.argmax(oby[d_idx]) for oby in obs_y],
[obtf[d_idx] for obtf in obs_tfs])
obss = [((x[0],x[1]), x[2... |
akrzos/cfme_tests | cfme/tests/infrastructure/test_provisioning.py | Python | gpl-2.0 | 7,759 | 0.003093 | # -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme.common.provider import cleanup_vm
from cfme.provisioning import do_vm_provisioning
from cfme.services import requests
from cfme.web_ui import fill
from utils import normalize_text, testgen
from utils.blockers import BZ
from utils.log import logger
from... | =5)
cells = {'Description': 'Provision from [{}] to [{}###]'.format(template, vm_name)}
wait_for(lambda: requests.go_to_request(cells), num_sec=80, | delay=5)
if edit:
# Automatic approval after editing the request to conform
with requests.edit_request(cells) as form:
fill(form.num_vms, "1")
new_vm_name = vm_name + "_xx"
fill(form.vm_name, new_vm_name)
vm_names = [new_vm_name] # Will be just one now
... |
schnittstabil/findd | findd/cli/views.py | Python | mit | 1,481 | 0 | import logging
from shlex import quote
from findd.cli.widgets import hr
from findd.cli.widgets import ProgressBarManager
__LOG__ = logging.getLogger(__name__)
class BaseView(object):
def __init__(self, show_progressbars):
self.pbm = ProgressBarManager() if show_progressbars else None
def __enter__... | oin([quote(afile.relpath) for afile in duplicates]))
class ProcessDuplicatesView(BaseView):
def __init__(self):
BaseView.__init__(self, __LOG__.isEnabledFor(logging.INFO))
def print_subprocess_call(self, args):
__LOG__.debug(' '.join(args))
d | ef print_duplicates(self, duplicates):
if __LOG__.isEnabledFor(logging.INFO):
print(hr(' processed duplicates '))
paths = [quote(afile.relpath) for afile in duplicates]
for path in paths:
print(path)
print(hr())
|
alexsavio/aizkolari | matrans.py | Python | bsd-3-clause | 10,313 | 0.029089 | #!/usr/bin/python
#-------------------------------------------------------------------------------
#License GPL v3.0
#Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
#Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
#Universidad del Pais Vasco UPV/EHU
#Use this at your own risk!
#-----------------------... | --------------------------
#definining measure functions
def mylogm (v):
return np.reshape(logm(v.reshape(N,N)), [1,N*N])
#-------------------------------------------------------------------------------
def mydet (v):
return det(v.reshape(N,N))
# | -------------------------------------------------------------------------------
def mytrace (v):
return np.trace(v.reshape(N,N))
#-------------------------------------------------------------------------------
def myeigvals (v):
return eigvals(v.reshape(N,N)).flatten()
#-----------------------------------------... |
KryoEM/relion2 | python/star/replace_ctf.py | Python | gpl-2.0 | 2,295 | 0.031808 | # Replaces the ctf values in input star file with the values in a reference star file
import argparse
import os
from star import *
def parse_args():
parser = argparse.ArgumentParser(description="Replaces the ctf values in input star file with the values in a reference star file.")
parser.add_argument('--input', me... | r index,field in enumerate(fields_to_replace):
values[field] = mic_to_ctf[mic_root][index] or values[field]
output += makeTabbedLine(values)
return output
if __name__ == '__main__':
args = parse_args()
input_path = args.input[0]
reference_path = args.reference[0]
if args | .output:
output_path = args.output[0]
else:
root, ext = os.path.splitext(input_path)
output_path = root + '_replace_ctf' + ext
main(reference_path, input_path)
with open(output_path, 'w') as output_file:
output_file.write(output)
print "Done!"
|
andrewhead/Package-Qualifiers | migrate/0002_add_column_task_mode.py | Python | mit | 386 | 0.002591 | #! /usr/bin/env python
# | -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from playhouse.migrate import migrate
from peewee import TextField
logger = logging.getLogger('data')
def forward(migrator):
migr | ate(
migrator.add_column('task', 'mode', TextField(default='uninitialized')),
migrator.add_index('task', ('mode',), False),
)
|
kxepal/phoxpy | phoxpy/tests/modules/__init__.py | Python | bsd-3-clause | 216 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Al | exander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should ha | ve received as part of this distribution.
#
|
datacommonsorg/data | scripts/eurostat/regional_statistics_by_nuts/population_density/PopulationDensity_preprocess_gen_tmcf.py | Python | apache-2.0 | 3,311 | 0.000604 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | t_NUTS3.tmcf"
_OUTPUT_COLUMNS = [
'Date',
'GeoId',
'Count_Person_PerArea',
]
def translate_wide_to_long(data_url):
df = pd.read_csv(data_url, delimiter='\t')
assert df.head
header = list(df.columns.values)
years = header[1:]
# Pandas.melt() unpivots a DataFrame from wide format to l... | var_name='time',
value_name='value')
# Separate geo and unit columns.
new = df[header[0]].str.split(",", n=1, expand=True)
df['geo'] = new[1]
df['unit'] = new[0]
df.drop(columns=[header[0]], inplace=True)
# Remove empty rows, clean values to have all digits.
df = df[df.... |
rohe/IdPproxy | src/idpproxy/social/linkedin/__init__.py | Python | bsd-2-clause | 1,002 | 0.002994 | import json
from idpproxy.social.oauth import OAuth
import oauth2 as oauth
#from xml.etree import ElementTree as ET
import logging
logger = logging.getLogger(__name__)
__author__ = 'rohe0002'
class LinkedIn(OAuth):
def __init__(self, client_id, client_secret, **kwargs):
OAuth.__init__(self, client_id, cli... | f, info_set):
token = oauth.Token(key=info_set["oauth_token"][0],
secret=info_set["oauth_token_secret"][0])
client = oauth.Client(self.consumer, token)
resp, content = client.request(self.extra["userinfo_endpoint"], "GET")
# # content in XML :-(
# logg... | in root:
# res[child.tag] = child.text
res = json.loads(content)
logger.debug("userinfo: %s" % res)
res["user_id"] = info_set["oauth_token"]
return resp, res |
mojwang/selenium | py/test/selenium/webdriver/common/results_page.py | Python | apache-2.0 | 1,408 | 0 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | ef load(self):
raise Exception("This page shouldn't be loaded directly")
def link_contains_match_for(self, term):
result_section = self._driver.find_element_by_id("res")
elements = result_section.find_elements_by_xpath(".//*[@class='l']")
for e in elements:
if | term in e.get_text():
return True
return False
|
plotly/plotly.py | packages/python/plotly/plotly/validators/contourcarpet/colorbar/_showticklabels.py | Python | mit | 476 | 0 | import | _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="showticklabels",
parent_name="contourcarpet.colorbar",
**kwargs
):
super(ShowticklabelsValidator, self).__init__(
plo... | edit_type=kwargs.pop("edit_type", "colorbars"),
**kwargs
)
|
ludoo/wpkit | attic/wpfrontman/wp_frontman/management/commands/wpf_maintenance.py | Python | bsd-3-clause | 9,051 | 0.007071 | import os
import sys
import time
import subprocess
import select
from optparse import make_option
from django.conf import settings
from django.db import connection
from django.core.cache import cache
from django.core.management.base i | mport BaseCommand, CommandError
from wp_frontman.blog import Blog
from wp_frontman.cache import cache_timestamps
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
"--delete-revisions", action="store_true", dest="revisions", default=False,
help... | help="purge stale files from the cache"
),
make_option(
"--publish-future-posts", action="store_true", dest="future", default=False,
help="publish posts that have been scheduled for past dates"
),
make_option(
"--wp-cron", action="store_true", des... |
MDU-PHL/ngmaster | setup.py | Python | gpl-2.0 | 1,595 | 0.000627 | from setuptools import setup
from ngmaster import __version__
def readme():
with open('README.md', encoding='utf-8') as f:
return f.read()
setup(name='ngmaster',
version=__version__,
description='In silico multi-antigen sequence typing for Neisseria gonorrhoeae (NG-MAST)',
long_descri... | keywords='microbial genomics Neisseria sequence typing',
url='https://github.com/MDU-PHL/ngmaster',
| author='Jason Kwong',
author_email='kwongj@gmail.com',
license='GPLv3',
packages=['ngmaster'],
python_requires='>=3.6',
install_requires=[
'argparse',
'biopython',
'bs4',
'requests',
],
test_suite='nose.collector',
tests_require=[]... |
daringer/pyORM | tests/field_ex_test.py | Python | gpl-2.0 | 1,954 | 0.013818 | import os, sys
import time
import unittest
import operator as ops
sys.path.append("..")
from baserecord import BaseRecord
from fields import StringField, IntegerField, DateTimeField, \
OneToManyRelation, FloatField, OptionField, ManyToOneRelation, \
ManyToManyRelation
from core import Database
fro... |
class FieldExpressionTestSuite(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
| def test_simple_exp_add(self):
x, y = 1, 2
for o in [ops.add, ops.sub, ops.and_, ops.or_, ops.eq, ops.lt, ops.le]:
f1 = FieldExpression(x, y, o)
self.assertTrue(f1.eval() == o(x, y), "failed: {}, ref: {}". \
format(o.__name__, o(x, y)))
def test_partl... |
miumok98/weblate | weblate/accounts/management/commands/changesite.py | Python | gpl-3.0 | 2,417 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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, eithe... | NTY; 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/>.
#
from django.core.management.base import BaseCommand, CommandError
from django.contrib.sites.models import Site
from optparse import make_option
class Command(BaseCommand):
h... |
Distrotech/bzr | bzrlib/tests/fake_command.py | Python | gpl-2.0 | 859 | 0 | # Copyright (C) 2008 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in ... | pe 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, write to the... | treet, Fifth Floor, Boston, MA 02110-1301 USA
from bzrlib.tests import test_commands
test_commands.lazy_command_imported = True
class cmd_fake(object):
pass
|
google-coral/project-keyword-spotter | mel_features.py | Python | apache-2.0 | 9,761 | 0.004815 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | scale using HTK formula.
Args:
frequencies_hertz: Scalar or np.array of frequencies in hertz.
Returns:
Object of same size as frequencies_hertz containing corresponding values
on the mel scale.
"""
return _MEL_HIGH_FREQUENCY_Q * np.log(
1.0 + (frequencies_hertz / _MEL_BREAK_FREQUENC | Y_HERTZ))
def spectrogram_to_mel_matrix(num_mel_bins=20,
num_spectrogram_bins=129,
audio_sample_rate=8000,
lower_edge_hertz=125.0,
upper_edge_hertz=3800.0):
"""Return a matrix that can post-multip... |
codendev/rapidwsgi | src/mako/codegen.py | Python | gpl-3.0 | 39,495 | 0.007368 | # codegen.py
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""provides functionality for rendering a parsetree constructing into module source code."""... | r.writeline(
"_source_encoding=%r" % self | .compiler.source_encoding)
if self.compiler.imports:
buf = ''
for imp in self.compiler.imports:
buf += imp + "\n"
self.printer.writeline(imp)
impcode = ast.PythonCode(
buf,
source... |
marcio-curl/EPUB-plasTeX | pacotes/amsmath.py | Python | lgpl-3.0 | 2,208 | 0.018569 | #!/usr/bin/env python
from plasTeX import Command, Environment, sourceChildren
from plasTeX.Base.LaTeX.Arrays import Array
from plasTeX.Base.LaTeX.Math import EqnarrayStar, equation, eqnarray, MathEnvironment
#### Imports Added by Tim ####
from plasTeX.Base.LaTeX.Math import math
class pmatrix(Array):
pass
class... | tionStar):
macroName = 'gather*'
class falign(_AMSEquation):
pass
class FAlignStar(_AMSEquationStar):
macroName = 'falign*'
class multiline(_AMSEquation):
pass
class MultilineStar(_AMSEquationStar):
macroName = 'multiline*'
class alignat(_AMSEquation):
pass
class AlignatStar(_AMSEquationSt... |
class split(_AMSEquation):
pass
#### Added by Tim ####
class EquationStar(_AMSEquationStar):
macroName = 'equation*'
class aligned(_AMSEquation):
pass
class cases(_AMSEquation):
pass
class alignat(_AMSEquation):
args = 'column:int'
class AlignatStar(_AMSEquationStar):
args = 'column:int'
... |
yannrouillard/weboob | modules/lutim/browser.py | Python | agpl-3.0 | 1,503 | 0.000665 | # -*- coding: utf-8 -*-
# Copyright(C) 2014 Vincent A
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | ob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along... | .gnu.org/licenses/>.
from weboob.tools.browser import BaseBrowser
from StringIO import StringIO
import re
from .pages import PageAll
__all__ = ['LutimBrowser']
class LutimBrowser(BaseBrowser):
ENCODING = 'utf-8'
def __init__(self, base_url, *args, **kw):
BaseBrowser.__init__(self, *args, **kw)
... |
TomBaxter/osf.io | admin/common_auth/admin.py | Python | apache-2.0 | 2,590 | 0.001544 | from __future__ import absolute_import
from django.contrib import admin
from django.contrib.admin.models import DELETION
from django.contrib.auth.models import Permission
from django.core.urlresolvers import reverse
from django.utils.html import escape
fro | m osf.models import AdminLogEntry
from osf.models import AdminProfile
class PermissionAdmin(admin.ModelAdmin):
search_fields = ['name', 'codename']
class AdminAdmin(admin.ModelAdmin):
def permission_groups(self):
| perm_groups = ', '.join(
[perm.name for perm in self.user.groups.all()]) if self.user.groups.all() else 'No permission groups'
return u'<a href="/account/register/?id={id}">{groups}</a>'.format(id=self.user._id, groups=perm_groups)
def user_name(self):
return self.user.username
... |
baixuexue123/note | python/others/serialport/camera.py | Python | bsd-2-clause | 3,086 | 0.010313 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"debug camera"
__author__ = "baixue"
from ctypes import *
import os, sys
from time import sleep
from binascii import unhexlify
import serial
DIR_ROOT = os.getcwd()
HEADER = 'AABB'
ADDR = '01'
RELAY_NO = ['%02d' % (i+1) for i in range(16)]
# config camera info
GROUP_A... | in(DIR_ROOT, u'A组相机'.encode('gbk')),
u'第一组相机')
GROUP_B = (('03 | ', '04'),
((12461130, 'L1'), (12492601, 'R1')),
os.path.join(DIR_ROOT, u'B组相机'.encode('gbk')),
u'第二组相机')
GROUP_C = (('05',),
((12461145, 'L1'), (13020874, 'R1')),
os.path.join(DIR_ROOT, u'C组相机'.encode('gbk')),
u'第三组相机')
CAMERA = (GROUP_A, GROUP_B, GROUP_... |
dawran6/flask | tests/test_views.py | Python | bsd-3-clause | 6,085 | 0 | # -*- coding: utf-8 -*-
"""
tests.views
~~~~~~~~~~~
Pluggable views.
:copyright: (c) 2015 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import pytest
import flask
import flask.views
from werkzeug.http import parse_set_header
def common_test(app):
c = app.test_client(... | ew = Index.as_view('index')
view.view_class = Other
app.add_url_rule('/', view_func=view)
common_test(app)
def test_view_inheritance(app):
class Index(flask.views.MethodView):
def get(self):
return 'GET'
def post(self):
return 'POST'
class BetterIndex(Inde... | def delete(self):
return 'DELETE'
app.add_url_rule('/', view_func=BetterIndex.as_view('index'))
c = app.test_client()
meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])
assert sorted(meths) == ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST']
def test_view_decorators(... |
lmaycotte/quark | quark/db/migration/alembic/cli.py | Python | apache-2.0 | 7,166 | 0 | # 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... | revision = CONF.command.revision or ''
if '-' in revision:
raise SystemExit(_('Negative relative revision (downgrade) not '
'supported'))
delta = CONF.comm | and.delta
if delta:
if '+' in revision:
raise SystemExit(_('Use either --delta or relative revision, '
'not both'))
if delta < 0:
raise SystemExit(_('Negative delta (downgrade) not supported'))
revision = '%s+%d' % (revision, delta)
... |
SGenheden/Scripts | Membrane/water_leakage.py | Python | mit | 3,011 | 0.008303 | # Author: Samuel Genheden, samuel.genheden@gmail.com
"""
Program to calculate how many water molecules are leaking into the membrane
"""
import argparse
import math
import numpy as np
from sgenlib import parsing
from sgenlib import mol
def _count_water_inside(dens1, dens2, fi, li, fx, lx) :
return sum(dens1[... | ensity crosses at: %.3f %.3f"%(xv | als[li], lx_std)
print "\nNumber of leaked water: %d %d"%(_count_water_inside(
densities[args.watdens], densities[args.lipdens],
fi, li, xvals[fi], xvals[li]),
in_std)
fi, li = mol.density_intercept(densities[args.lipdens2], densities[args.lipdens])
(fx_std, lx_std),... |
adamkh/micropython | tests/basics/string_format.py | Python | mit | 4,990 | 0.001603 | # Change the following to True to get a much more comprehensive set of tests
# to run, albeit, which take considerably longer.
full_tests = False
def test(fmt, *args):
print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<')
test("}}{{")
test("{}-{}", 1, [4, 5])
test("{0}-{1}", 1, [4, 5])
test("{1}-{0}", 1, [... | h=10))
print("{text:{align}{width}}".format(text="foo", align=">", width=30))
print("{foo}/foo".format(foo="bar"))
print("{}".format(123, foo="bar"))
print("{}-{foo}".format(123, foo="bar"))
def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg):
fmt = '{'
if conv:
fmt += '!'
... | fmt += '.'
fmt += precision
fmt += type
fmt += '}'
test(fmt, arg)
if fill == '0' and alignment == '=':
fmt = '{:'
fmt += sign
fmt += prefix
fmt += width
if precision:
fmt += '.'
fmt += precision
fmt += type
f... |
synergeticsedx/deployment-wipro | lms/djangoapps/branding/tests/test_api.py | Python | agpl-3.0 | 4,864 | 0.005345 | # encoding: utf-8
"""Tests of Branding API """
from __future__ import unicode_literals
from django.test import TestCase
import mock
from branding.api import get_logo_url, get_footer
from django.test.utils import override_settings
class TestHeader(TestCase):
"""Test API end-point for retrieving the header. """
... | G": "/edx-blog",
"DONATE": "/donate",
"JOBS": "/jobs",
"SITE_MAP": "/sitemap",
"TOS_AND_HONOR": "/edx-terms-service",
"PRIVACY": "/e | dx-privacy-policy",
"ACCESSIBILITY": "/accessibility",
"MEDIA_KIT": "/media-kit",
"ENTERPRISE": "/enterprise"
})
@override_settings(PLATFORM_NAME='\xe9dX')
def test_get_footer(self):
actual_footer = get_footer(is_secure=True)
expected_footer = {
'copyright... |
liuzz1983/open_vision | openvision/facenet/align/bulk_detec_face.py | Python | mit | 9,832 | 0.00356 |
def bulk_detect_face(images, detection_window_size_ratio, model, threshold, factor):
# im: input image
# minsize: minimum of faces' size
# pnet, rnet, onet: caffemodel
# threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold [0-1]
all_scales = [None] * len(images)
images_with_b... | image_obj['onet_input'] = np.transpose(tempimg, (3, 1, 0, 2))
i += rne | t_input_count
# # # # # # # # # # # # #
# third stage - further refinement and facial landmarks positions with onet
# # # # # # # # # # # # #
bulk_onet_input = np.empty((0, 48, 48, 3))
for index, image_obj in enumerate(images_with_boxes):
if 'onet_input' in image_obj:
bulk_onet... |
Xiaofei-Zhang/NAMD_Docking_pipeline | pre_DOCKING/prepare_receptors.py | Python | mit | 1,588 | 0.015113 | # prepare_receptors.py
# Create the .pdbqt files and receptors coordinates file of receptors
# for VinaMPI Docking
# Usage:
# python prepare_receptors.py
#
# Specify the correct paths of prepare_receptor4.py pythonsh VMD
# Make sure the get_AS_grid.tcl file uses the correct residue number
# of the active sites
# Run th... | pdbqtfile +' -A hydrogens')
# Create receptors.txt f | ile
with open('receptors.txt','w') as f:
f.write('receptor size_x size_y size_z center_x center_y center_z cpu=1\n')
for pdbfile in receptor_list:
pdbid = pdbfile[:-4]
os.system('\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'get_AS_grid.tcl' + ' ' + '-args' + ' '+ pdbid)
|
pcubillos/pytips | pytips/__init__.py | Python | mit | 491 | 0.002037 | # Copyright (c) | 2015-2019 Patricio Cubillos and contributors.
# pytips is open-source software under the MIT license (see LICENSE).
from .tips import __all__
from .tips import *
# Clean up top-level namespace--delete everything that isn't in __all__
# or is a magic attribute, and that isn't a submodule of this package
for varname ... | el(varname)
|
Thortoise/Super-Snake | Blender/animation_nodes-master/nodes/boolean/invert_node.py | Python | gpl-3.0 | 368 | 0.002717 | impo | rt bpy
from ... base_types.node import AnimationNode
class InvertNode(bpy.types.Node, AnimationNode):
bl_idname = "an_InvertNode"
bl_label = "Invert Boolean"
def create(self):
self.newInput("Boolean", "Input", "input")
self.newOutput("Boolean", "Output", "output")
def getExe | cutionCode(self):
return "output = not input"
|
mfussenegger/Huluobo | base.py | Python | mit | 1,242 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from tornado.web import RequestHandler, HTTPError
from schema import Session, Feed
from jinja2.exceptions import TemplateNotFound
class Base(RequestHandler):
@property
def env(self):
return self.application.env
def get_error_html(self, status_code, *... | ls['static_url'] | = self.static_url
self.env.globals['xsrf_form_html'] = self.xsrf_form_html
self.write(template.render(kwds))
Session.close()
class NoDestinationHandler(Base):
def get(self):
raise HTTPError(404)
|
mlopes/LogBot | logbot/__init__.py | Python | mit | 147 | 0 | from l | ogbot.daemonizer import Daemonizer
from logbot.irc_client import IrcClient
from logbot.logger import Logger
from logbot.parser import Parser | |
agundy/Whiteboard | trackSchool/trackSchool/settings/common.py | Python | mit | 258 | 0.003876 | REST_FRAMEWORK = {
# Use Django's standard `d | jango.contrib.auth` permissions,
# or allow read-only ac | cess for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
} |
Gustry/inasafe | safe/gui/tools/wizard/step_kw49_inasafe_raster_default_values.py | Python | gpl-3.0 | 7,187 | 0 | # coding=utf-8
"""InaSAFE Wizard Step InaSAFE Raster Default Fields."""
# noinspection PyPackageRequirements
import logging
from parameters.qt_widgets.parameter_container import ParameterContainer
from safe import messaging as m
from safe.utilities.i18n import tr
from safe.common.parameters.default_value_parameter i... | i | f self.parameter_container:
self.default_values_grid.removeWidget(
self.parameter_container)
if self.parameters:
self.parameters = []
# Iterate through all inasafe fields
# existing_inasafe_default_values
for inasafe_field in self.inasafe_fields_... |
seishei/multiprocess | py2.6/multiprocess/forking.py | Python | bsd-3-clause | 14,448 | 0.001453 | #
# Module for starting a process object using os.fork() or CreateProcess()
#
# multiprocessing/forking.py
#
# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
#
import os
import sys
import signal
from multiprocess import util, process
__all__ = ['Popen', 'assert_spawning', 'exit', 'duplicate', 'close', 'Forki... | e = os.close
#
# We define a Popen class similar to the one from subprocess, but
# whose constructor takes a process object as its argument.
#
class Popen(object):
def __init__(self, process_obj):
| sys.stdout.flush()
sys.stderr.flush()
self.returncode = None
self.pid = os.fork()
if self.pid == 0:
if 'random' in sys.modules:
import random
random.seed()
code = process_obj._bootstrap()
... |
calendall/calendall | calendall/profiles/migrations/0004_auto_20150117_1017.py | Python | bsd-3-clause | 703 | 0.001422 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from dj | ango.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
| ('profiles', '0003_auto_20150115_1939'),
]
operations = [
migrations.AddField(
model_name='calendalluser',
name='location',
field=models.CharField(blank=True, max_length=30, verbose_name='User location'),
preserve_default=True,
),
migratio... |
zeekay/flask-uwsgi-websocket | flask_uwsgi_websocket/__init__.py | Python | mit | 1,032 | 0.012597 | '''
Flask-uWSGI-WebSocket
---------------------
High-performance WebSockets for your Flask apps powered by `uWSGI <http://uwsgi-docs.readthedocs.org/en/latest/>`_.
'''
__docformat__ = 'restructuredtext'
__version__ = '0.6.1'
__license__ = 'MIT'
__author__ = 'Zach Kelling'
import sys
from ._async import *
from ._uws... |
class GeventNotInstalled(Exception):
pass
try:
from ._gevent import *
except ImportError:
class GeventWebSocket(object):
def __init__(self, *args, **kwargs):
raise GeventNotInstalled("Gevent must be installed to use GeventWebSocket. Try: `pip install gevent`.")
class AsyncioNotAvaila... | def __init__(self, *args, **kwargs):
raise AsyncioNotAvailable("Asyncio should be enabled at uwsgi compile time. Try: `UWSGI_PROFILE=asyncio pip install uwsgi`.")
|
walkinreeds/MultiProxies | lib/EchoColor.py | Python | gpl-3.0 | 1,788 | 0.002237 | # coding=utf-8
__author__ = 'DM_'
import platform
import ctypes
import sys
USE_WINDOWS_COLOR = False
if platform.system() == "Windows":
USE_WINDOWS_COLOR = True
# #########################################
#windows color.
BLACK = 0x0
BLUE = 0x01
GREEN = 0x02
CYAN = 0x03
RED = 0x04
... | reset = False
from lib.ProxiesFunctions import isClientVerbose
from lib.ProxiesFunctions import isColor
if USE_WINDOWS_COLOR:
if color and isColor():
set_cmd_text_color(color | color | color)
reset = True
else:
if color and is... | sys.stdout.flush()
else:
print(mess)
if reset:
resetColor()
color = _echocolor() |
Lekensteyn/buildbot | master/buildbot/www/auth.py | Python | gpl-2.0 | 6,728 | 0.000297 | # This file is part of Buildbot. Buildbot 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; without eve... | = self.headerRegex.match(header)
if res is None:
raise Error(
403, 'http header does not match regex! "%s" not matching %s' %
(header, self.headerRegex.pattern))
session = request.getSession()
if session.user_info != dict(res.groupdict()):
... | request)
@implementer(IRealm)
class AuthRealm(object):
def __init__(self, master, auth):
self.auth = auth
self.master = master
def requestAvatar(self, avatarId, mind, *interfaces):
if IResource in interfaces:
return (IResource,
PreAuthenticatedLoginRes... |
fenceFoil/canopto | text.py | Python | bsd-3-clause | 3,088 | 0.038212 | #!/bin/python3
from Canopto import Canopto
import pygame
from pygame import *
from pygame.locals import *
import time
from colorsys import *
import sys
import json
import datetime
# scroll text across canopto. blocks. fg & bg are colors
def scrollText (canopto, text, fg = (0xFF, 0x33, 0xFF), bg = (0x00, 0x00, 0x00, 0... | suggests
# with open(CONFIG_PATH) as json_config:
# config = json.load(json_config)
# ACCOUNT_SID = config['twilio']['account_sid']
# AUTH_TOKEN = config['twilio']['auth_token']
# print("Successfuly read api information from config")
# client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
# processedMessages... | ow() + datetime.timedelta(hours=4)
# while (True): #display.tracker.running):
# #if tracker.frameCounter == 10:
# #tracker.resetToMotion = True
# #print "reset to motion"
# print ("hihi")
# #Because of a conflict between timezones used to represent dates cannot limit by day since messages sent after
# #... |
freedesktop-unofficial-mirror/gstreamer-sdk__cerbero | cerbero/bootstrap/__init__.py | Python | lgpl-2.1 | 1,054 | 0 | # cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; eit... | ):
self.config | = config
def start(self):
raise NotImplemented("'start' must be implemented by subclasess")
|
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/features/v2015_12_01/_feature_client.py | Python | mit | 4,057 | 0.003451 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | _client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
| self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.features = FeaturesOperations(self._client, self._config, self._serialize, self._deserialize)
def _send_request(
self,
request, ... |
Just-D/chromium-1 | tools/perf/PRESUBMIT.py | Python | bsd-3-clause | 4,403 | 0.010902 | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about th... | _api):
"""git cl upload will call this hook after the issue is created/modified.
This hook adds extra try bots list to the CL description in order to run
Telemetry benchmarks on Perf trybots in addtion to CQ trybots if the CL
contains any changes to Telemetry benchmarks.
"""
benchmarks_modified = _IsBenchm... | _EXTRA_TRYBOTS=.*', original_description, re.M | re.I):
return []
results = []
bots = [
'linux_perf_bisect',
'mac_perf_bisect',
'win_perf_bisect',
'android_nexus5_perf_bisect'
]
bots = ['tryserver.chromium.perf:%s' % s for s in bots]
bots_string = ';'.join(bots)
description = original_d... |
quintel/etmoses | scripts/power_to_heat/p2h_profile_generator.py | Python | mit | 7,575 | 0.011485 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 11:09:48 2015
@author: joris.berkhout@quintel.com & chael.kruip@quintel.com
"""
#==============================================================================
# This script can be used to generate typical domestic hot water (DHW) profiles
# for a period of one year a... | each type of event varies throughout the year (i.e.
# slightly more DHW consumption in winter), throughout the week (more in the
# weekend) and throughout the day (no DHW consumption during the night).
#
# The script returns two types of profiles:
#- use profiles: randomly generated profiles with a time resolution of... | cate how full the boiler has to be
# in order to meet future demands. The profiles are derived from the use
# profile by and are also expressed as a fraction of the maximal storage volume
#==============================================================================
import numpy as np
import pylab as plt
plt.close... |
lalitkumarj/NEXT-psych | next/database/database_backup.py | Python | apache-2.0 | 2,053 | 0.026303 | #!/usr/bin/python
"""
Every 30 minutes backs up database to S3. To recover the database, (i.e. reverse the process)
simply download the file from S3, un-tar it, and use the command:
(./)mongorestore --host {hostname} --port {port} path/to/dump/mongodump
where {hostname} and {port} are as they are below
"""
import sys... | import subprocess
import next.constants as constants
import os
NEXT_BACKEND_GLOBAL_HOST = os.environ.get('NEXT_BACKEND_GLOBAL_HOST', 'localhost')
AWS_BUCKET_NAME = os.environ.get('AWS_BUCKET_NAME','next-database-backups')
timestamp = utils.datetimeNow()
print "[ %s ] starting backup of MongoDB to S3..." % str(times... | ort} --out /dump/mongo_dump'.format( hostname=constants.MONGODB_HOST, port=constants.MONGODB_PORT ),shell=True)
try:
tar_file = sys.argv[1]
except:
tar_file = 'mongo_dump_{hostname}_{timestamp}.tar.gz'.format( hostname=NEXT_BACKEND_GLOBAL_HOST, timestamp= timestamp.strftime("%Y-%m-%d_%H:%M:%S") )
subprocess.call('... |
TribeMedia/synapse | tests/api/test_filtering.py | Python | apache-2.0 | 15,549 | 0.000064 | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | FrozenEvent(kwargs)
class FilteringTestCase(unittest.TestCase):
@defer.inlineCallbacks
def setUp(self):
self.mock_federation_resource = MockHttpResource()
self.mock_http_client = Mock(spec=[])
self.mock_http_client.put_json = DeferredMockCallable()
hs = yield setup_test_home... | handlers=None,
http_client=self.mock_http_client,
keyring=Mock(),
)
self.filtering = hs.get_filtering()
self.datastore = hs.get_datastore()
def test_definition_types_works_with_literals(self):
definition = {
"types": ["m.room.message", ... |
gizela/gizela | example/matplotlib/axis.py | Python | gpl-3.0 | 782 | 0.021739 | # set S-JTSK axes orientation
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
ax=plt.gca()
#ax.set_ylim(ax.get_ylim()[::-1])
# direction of axes
ax.invert_xaxis()
ax.invert_yaxis()
# ticks position
for tick in ax.xaxis.get_major_ticks():
tick.label1On = False
tick.label2... | ):
tick.label1On = False
tick.label2On = True
plt.plot([1,2,3,1],[3,1,2,3])
# ticks string formatter
import matplotlib.ti | cker as ticker
formatter = ticker.FormatStrFormatter('%.2f m')
ax.xaxis.set_major_formatter(formatter)
# ticks func formatter
def format(x, pos):
return "%s - %s" % (x,pos)
formatter = ticker.FuncFormatter(format)
ax.xaxis.set_major_formatter(formatter)
plt.show()
|
da1z/intellij-community | python/helpers/pydev/_pydevd_bundle/pydevd_referrers.py | Python | apache-2.0 | 8,753 | 0.005141 | import sys
from _pydevd_bundle import pydevd_xml
from os.path import basename
import traceback
try:
from urllib import quote, quote_plus, unquote, unquote_plus
except:
from urllib.parse import quote, quote_plus, unquote, unquote_plus #@Reimport @UnresolvedImport
#==============================================... | ', Value: ')
stream.write(unquote_plus(value))
stream.write(', Type: ')
stream.write(unquote_plus(val_type))
if found_as:
stream.write(', Found as: %s' % (unquote_plus(found_as),))
stream.write('\n')
#======================================================================================== | ===========
# print_referrers
#===================================================================================================
def print_referrers(obj, stream=None):
if stream is None:
stream = sys.stdout
result = get_referrer_info(obj)
from xml.dom.minidom import parseString
dom = parseStri... |
dyn888/youtube-dl | youtube_dl/extractor/aenetworks.py | Python | unlicense | 2,401 | 0.002082 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import smuggle_url
class AENetworksIE(InfoExtractor):
IE_NAME = 'aenetworks'
IE_DESC = 'A+E Networks: A&E, Lifetime, History.com, FYI Network'
_VALID_URL = r'https?://(?:www\.)?(?:(?:history|aetv|mylifetime)\.com|fyi\.... | ft-minnesota-prairie-cottage',
'only_matching': True
}, {
'url': 'http://www. | mylifetime.com/shows/project-runway-junior/video/season-1/episode-6/superstar-clients',
'only_matching': True
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
video_url_re = [
r'data-href="[^"]*/%s"[^>]... |
thiagopena/PySIGNFe | pysignfe/nfse/bhiss/v10/ConsultarSituacaoLoteRps.py | Python | lgpl-2.1 | 5,547 | 0.010817 | # -*- coding: utf-8 -*-
from pysignfe.xml_sped import *
from .Rps import IdentificacaoPrestador, IdentificacaoRps
import os
DIRNAME = os.path.dirname(__file__)
class MensagemRetorno(XMLNFe):
def __init__(self):
super(MensagemRetorno, self).__init__()
self.Codigo = TagCaracter(nome=u'Codigo', tama... | _xml(self):
xml = XMLNFe.get_xml(self)
xml += ABERTURA
xml += u'<ListaMensagemRetornoLote>'
for m in self.MensagemRetornoLote:
xml += tira_abertura(m.xml)
xml += u'</ListaMensagemRetornoLote>'
return xml
def set_xml(self, arquivo... | self.le_grupo('[nfse]//ListaMensagemRetornoLote/MensagemRetornoLote', MensagemRetornoLote)
xml = property(get_xml, set_xml)
class ListaMensagemRetorno(XMLNFe):
def __init__(self):
super(ListaMensagemRetorno, self).__init__()
self.MensagemRetorno = []
def get_xml(self):
xml = XMLNFe... |
max00xam/service.maxxam.teamwatch | lib/engineio/client.py | Python | gpl-3.0 | 25,302 | 0.00004 | import logging
try:
import queue
except ImportError: # pragma: no cover
import Queue as queue
import signal
import threading
import time
import six
from six.moves import urllib
try:
import requests
except ImportError: # pragma: no cover
requests = None
try:
import websocket
except ImportError: #... | m headers to send with the
connection request.
:param transports: The list of allowed transports. Valid transports
are ``'polling'`` and ``'websocket'``. If not
given, the polling transport is connected first,
| then an upgrade to websocket is attempted.
:param engineio_path: The endpoint where the Engine.IO server is
installed. The default value is appropriate for
most cases.
Example usage::
eio = engineio.Client()
eio.... |
aokolnychyi/spark | python/pyspark/shell.py | Python | apache-2.0 | 3,126 | 0.003199 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Versi | on 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 appl | icable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
An interactive shell.
... |
elkeschaper/tral | tral/examples/example_workflow_MBE2014.py | Python | gpl-2.0 | 4,872 | 0.001643 |
'''
Implementation of the workflow used in :
Schaper,E. et al. (2014) Deep conservation of human protein tandem repeats within the eukaryotes. Molecular Biology and Evolution. 31, 1132–1148 .
'''
import logging
import logging.config
import os
from tral.paths import config_file, PACKAGE_DIRECTORY
from tral.sequence ... | ust, T-reks, Xstream, HHrepID) are used to search the
# INSERT OWN PARAMTERS USING: test_denovo_list = test_seq.detect(denovo =
# True, **TEST_DENOVO_PARAMETERS)
test_denovo_list = test_seq.detect(denovo=True)
# When Trust is part of the detectors, the number of found repeats may
# differ between ru... | enovo_list.repeats) == 10
# De novo TRs with dTR_units (divergence) > 0.8; n_effective < 2.5; l < 10 or
# pvalue "phylo_gap01_ignore_trailing_gaps_and_coherent_deletions" > 0.01
# are discarded.
test_denovo_list = test_denovo_list.filter(
"pvalue",
TEST_SCORE_MBE_2014,
0.01)
... |
unioslo/cerebrum | Cerebrum/modules/event_publisher/event.py | Python | gpl-2.0 | 11,579 | 0 | # encoding: utf-8
#
# Copyright 2017 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your op... | blic License
# along with Cerebrum; if not, write to the Fr | ee Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
""" An abstract event that can be stored in the database. """
from __future__ import absolute_import
import datetime
import itertools
import mx.DateTime
import pytz
import cereconf
class _VerbSingleton(type):
""" A metaclass... |
scattermagic/django-wizard-builder | wizard_builder/tests/urls.py | Python | bsd-3-clause | 534 | 0 | from django.conf.urls import include, url
from | django.contrib import admin
from django.views.generic.base import RedirectView
from .. import views
urlpatterns = [
url(r'^$',
views.NewWizardView.as_view(),
),
url(r'^new/$',
views.NewWizardView.as_view(),
name='wizard_new',
),
url(r'^ste | p/(?P<step>.+)/$',
views.WizardView.as_view(),
name='wizard_update',
),
url(r'^nested_admin/', include('nested_admin.urls')),
url(r'^admin/', admin.site.urls),
]
|
skylines-project/skylines | tests/api/views/about_test.py | Python | agpl-3.0 | 664 | 0.001506 | def test_imprint(app, client):
app.config["SKYLINES_IMPRINT"] = u"foobar"
res = client.get("/imprint")
assert res.status_code == 200
assert res.json == {u"content": u"foobar"}
def test_team(client):
res = client.get("/team")
assert res.status_code == 200
content = res.json["content"]
... | license(client):
res = client.get("/license")
assert res.status | _code == 200
content = res.json["content"]
assert "GNU AFFERO GENERAL PUBLIC LICENSE" in content
|
south-coast-science/scs_dfe_eng | tests/gas/isi/elc_dsi_t1_test.py | Python | mit | 1,580 | 0 | #!/usr/bin/env python3
"""
Created on 27 May 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
import time
from scs_dfe.gas.isi.elc_dsi_t1 import ElcDSIt1
from scs_dfe.interface.interface_conf import InterfaceConf
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
# ... | rface_conf | .interface()
print(interface)
interface.power_gases(True)
ident = controller.version_ident()
print("ident:[%s]" % ident)
tag = controller.version_tag()
print("tag:[%s]" % tag)
print("-")
for _ in range(5):
controller.start_conversion()
time.sleep(0.1)
c_wrk,... |
audreyr/opencomparison | package/templatetags/package_tags.py | Python | mit | 1,974 | 0.001013 | from datetime import datetime, timedelta
from django import template
from package.models import Commit
from package.context_processors import used_packages_list
register = template.Library()
class ParticipantURLNode(template.Node):
def __init__(self, repo, participant):
self.repo = template.Variable(... | age_weeks = (now - cdate).days // 7
if age_weeks < 52:
weeks[age_weeks] += 1
return ','.join(map(str, reversed(weeks)))
@register.inclusion_tag('package/templatetags/_usage_button.html | ', takes_context=True)
def usage_button(context):
response = used_packages_list(context['request'])
response['STATIC_URL'] = context['STATIC_URL']
response['package'] = context['package']
if context['package'].pk in response['used_packages_list']:
response['usage_action'] = "remove"
resp... |
yvesalexandre/bandicoot | bandicoot/helper/tools.py | Python | mit | 8,941 | 0.000895 | # The MIT License (MIT)
#
# Copyright (c) 2015-2016 Massachusetts Institute of Technology.
#
# 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 without limitation ... | time + timedelta(seconds=r.call_duration - min_gab) >= calls[i + 1].datetime:
overlapping_calls += 1
return (float(overlapping_calls) / len(calls))
def antennas_missing_locations(user, Method=None):
"""
Return the number of antennas missing locations in the records of a given user.
""... | ntenna is not None])
return sum([1 for antenna in unique_antennas if user.antennas.get(antenna) is None])
def pairwise(iterable):
"""
Returns pairs from an interator: s -> (s0,s1), (s1,s2), (s2, s3)...
"""
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
class AutoVivificati... |
iamweilee/pylearn | cstringio-example-2.py | Python | mit | 249 | 0.012048 | '''
ΪÁËÈÃÄãµÄ´úÂ뾡¿ | ÉÄÜ¿ì, µ«Í | ¬Ê±±£Ö¤¼æÈݵͰ汾µÄ Python ,Äã¿ÉÒÔʹÓÃÒ»¸öС¼¼ÇÉÔÚ cStringIO ²»¿ÉÓÃʱÆôÓà StringIO Ä£¿é, Èç ÏÂÀý Ëùʾ.
'''
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
print StringIO |
mstiri/p3270 | setup.py | Python | gpl-3.0 | 1,698 | 0.014134 | #from distutils.core import setup
import setuptools
setuptools.setup(
name = 'p3270',
packages = ['p3270'],
version = '0.1.3',
description = 'Python library to communicate with IBM hosts',
author = 'Mossaab Stiri',
author_email = 'mossaab.stiri@gmail.com',
url = ... | : Python',
'Programming Language :: | Python :: 3',
'Programming Language :: Python :: 3 :: Only',
'Operating System :: Unix',
'Operating System :: POSIX :: Linux',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: ... |
Vaypron/ChromaPy | Example Scripts/Keypad/3. setbyRow.py | Python | mit | 370 | 0 | import ChromaPy32 as Chroma # Import the Chroma Module
from time import sleep
Keypad = Chroma.Keypad() # Initialize a new Keypad Instance
RED = (255, 0, 0) # Initialize a new color by RGB (RED,GREEN,BLUE)
Keypad.setbyRow(2, RED) # sets the whole th | ird row of the Keyboad-Grid to red
Keypad.applyGrid() # app | lies the Keypad-Grid to the connected Keypad
sleep(5)
|
utkbansal/tardis | tardis/plasma/tests/test_property_atomic.py | Python | bsd-3-clause | 836 | 0.009569 | import numpy as np
def test_levels_property(excitation_energy):
assert np.isclose(excitation_energy.ix[2].ix[0].ix[1], 3.17545416e-11)
def test_lines_property(lines):
assert np.isclose(lines.ix[564954]['wavelength'], 10833.307)
assert lines.index[124] == 564954
def test_lines_lower_level_index_property(l... | onization_data_property(ionization_data):
assert np.isclose(float(ionization_data.ix[2].ix[1]), 3.9393336e-11)
def test_zeta_data_property(ze | ta_data):
assert np.isclose(zeta_data.ix[2].ix[1][2000], 0.4012) |
EwgOskol/python_training | model/group.py | Python | apache-2.0 | 683 | 0.002928 | __author__ = 'tester'
from sys import maxsize
import re
class Group:
def __init__(self, name=None, header=None, footer=None, id=None):
self.name = name
self.h | eader = header
self.footer = footer
self.id = id
def __repr__(self):
return "%s:%s:%s:%s" % (self.id, self.name, self.header, self.footer)
def __eq__(self, other):
return (self.id is None or other.id is None or self.id == other.id) \
and re.sub(r'\s+', ' ', self.... | if (self.id):
return int(self.id)
else:
return maxsize
|
benhoff/facebook_api_script | eye_aligner.py | Python | gpl-3.0 | 1,214 | 0.004942 | import os
import cv2
from crop_pictures import CropFace
file_dir = os.path.dirname(os.path.realpath(__file__))
cropped_photos_dir = os.path.join(file_dir,
| 'cropped_photos',
'')
eye_cascade_filepath = os.path.join(file_dir, 'haarcascade_eye.xml')
eye_classifier = cv2.CascadeClassifier(eye_cascade_filepath)
all_cropped_photos = os.listdir(cropped_photos_dir)
eye_coord_list = []
for photo_filename in all_... | pped_photos:
image = cv2.imread(photo_filename)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
eyes = eye_classifier.detectMultiScale(gray_image, 1.1, 2, 0|cv2.CASCADE_SCALE_IMAGE, (30, 30))
if len(eyes) > 2:
print('More eyes than you can shake a stick at!')
if len(eyes) < 2:
p... |
Tbear1981/bitcoin-overseer | files/webcrawler.py | Python | gpl-3.0 | 705 | 0.009929 | import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = "https://thenewboston.com/videos.php?cat=98&video=20144" #+ str(page)
source_code = request.get(url)
| plain_text = source_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findAll("a", {"class": "itemname"}):
href = link.get("href")
print("href")
trade_spider(1)
def get_single_item_data(item_url):
source_code = request.get(item_url)
plain_text = source_code.... | .string)
|
f3at/feat | src/feat/test/integration/test_simulation_graph.py | Python | gpl-2.0 | 19,012 | 0.000263 | # F3AT - Flumotion Asynchronous Autonomous Agent Toolkit
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# 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 Foundation; either version... | % (
expected_kings, seen_kings, self.count_agents()))
@defer.inlineCallbacks
def start_host(self, join_shard=True):
script = format_block("""
desc = descriptor_f | actory('host_agent')
agency = spawn_agency(start_host=False)
medium = agency.start_agent(desc, run_startup=False)
agent = medium.get_agent()
""")
yield self.process(script)
agent = self.get_local('agent')
if join_shard:
yield agent.start_join_shard_... |
smartcrib/password-scrambler-ws | ScramblerTools/sc_initkey.py | Python | gpl-3.0 | 1,190 | 0.020168 | #!/usr/bin/python
"""sc_initkey.py: utility script forS-CRIB Scramble device to format initialisation key
it requires input string of 40 hex characters - project sCribManager - Python."""
'''
@author: Dan Cvrcek
@copyright: Copyright 2013-14, Smart Crib Ltd
@credits: Dan Cvrcek
@license: GPL version 3 (e.g., https:/... | data = sys.argv[1]
bindata = binascii.unhexlify(data)
hash_obj = hashlib.sha1()
hash_obj.update(bindata)
crc = hash_obj.hexdigest()[:4]
prefix = ''
byte1 = ord(bindata[1])
for i in range(4):
prefix = chr(0x31+(byte1&0x3)) + prefix
byte1 = byte1 / 4
byte0 = ord(... | x
byte0 = byte0 / 4
initkey0 = prefix + data[4:] + crc
initkey1 = initkey0.upper()
print(initkey1)
else:
print("This script must be callled with exactly one argument - 40 characters long hex string")
|
marco-lancini/Showcase | settings_private.py | Python | mit | 984 | 0.012195 | #
# PRIVATE DATA
#
SECRET_KEY = ''
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = "" |
DEFAULT_FROM_EMAIL = ""
#
# SOCIAL
#
FACEBOOK_APP_ID = ''
FACEBOOK_API_SECRET = ''
TWITTER_CONSUMER_KEY = ''
TWIT | TER_CONSUMER_SECRET = ''
LINKEDIN_CONSUMER_KEY = ''
LINKEDIN_CONSUMER_SECRET = ''
FLICKR_APP_ID = ''
FLICKR_API_SECRET = ''
TUMBLR_CONSUMER_KEY = ''
TUMBLR_CONSUMER_SECRET = ''
# GITHUB_APP_ID = ''
# GITHUB_API... |
mmanhertz/elopic | elopic/ui/central_widget.py | Python | bsd-2-clause | 1,328 | 0 | from PySide import QtGui
from PySide.QtCore import Signal
from elo_button_row import EloButtonRow
from picture_area import PictureArea
class CentralWidget(QtGui.QWidget):
left_chosen = Signal()
right_chosen = Signal()
left_deleted = Signal()
right_deleted = Signal()
def __init__(self, left_image... | age_path, parent=None):
super(CentralWidget, self).__init__(parent=parent)
self._init_ui(left_image_path, right_image_path)
self._init_signals()
def _init_ | ui(self, left_image_path, right_image_path):
vbox = QtGui.QVBoxLayout(self)
self.pic_area = PictureArea(
left_image_path,
right_image_path,
parent=self
)
self.buttons = EloButtonRow(parent=self)
vbox.addWidget(self.pic_area, stretch=100)
... |
Tactique/common | database/sql_scripts/seeders/template.py | Python | mit | 1,052 | 0.003802 | import os
import csv
import json
from tables.templates import (
ResponseTemplate
)
from seeders.base_seeder import BaseSeeder, print_delete_count
class TemplateSeeder(BaseSeeder):
def __init__(self, session):
BaseSeeder.__init__(self, session)
self.template_data = os.path.join(self.database_d... | templates = json.loads(file_.read())
for template in templates:
print("Adding template for response %s" % template)
JSONstr = json.dumps(templates[template])
new_template = ResponseTemplate(name=template, json=JSONstr)
... | elete())
|
katemsu/kate_website | kate3/utils/bitly.py | Python | mit | 6,991 | 0.013446 | #!/usr/bin/python2.4
#
# Copyright 2009 Empeeric LTD. 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 requir... | an try and catch the exception
if 'ERROR' in data or data['statusCode'] == 'ERROR':
raise BitlyError, data['errorMessage']
for key in data['results']:
if type(data['results']) is dict and type(data['results'][key]) is dict:
if 'statusCode' in data['results'][key] ... | ject):
'''A class representing the Statistics returned by the bitly api.
The Stats structure exposes the following properties:
status.user_clicks # read only
status.clicks # read only
'''
def __init__(self,user_clicks=None,total_clicks=None):
self.user_clicks = user_clicks
... |
stefanklug/psd-tools | tests/test_info.py | Python | mit | 1,195 | 0.005887 | # -*- coding: utf-8 -*-
from __future__ imp | ort absolute_import, unicode_literals
from psd_tools import PSDIm | age
from psd_tools.constants import TaggedBlock, SectionDivider, BlendMode
from .utils import decode_psd
def test_1layer_name():
psd = decode_psd('1layer.psd')
layers = psd.layer_and_mask_data.layers.layer_records
assert len(layers) == 1
layer = layers[0]
assert len(layer.tagged_blocks) == 1
... |
elifesciences/elife-tools | tests/fixtures/test_media/content_07_expected.py | Python | mit | 7,974 | 0 | # output from elife04493.xml
expected = [
{
"mime-subtype": "mov",
"mimetype": "video",
"xlink_href": "elife04493v001.mov",
"content-type": "glencoe play-in-place height-250 width-310",
"component_doi": "10.7554/eLife.04493.007",
"type": "media",
"sibling_ordi... | dinal": 4,
"position": 4,
"ordinal": 4,
},
{
"mime-subtype": "mov",
"mimetype": "video",
"xlink_href": "elife | 04493v005.mov",
"content-type": "glencoe play-in-place height-250 width-310",
"component_doi": "10.7554/eLife.04493.013",
"type": "media",
"sibling_ordinal": 5,
"position": 5,
"ordinal": 5,
},
{
"mime-subtype": "mov",
"mimetype": "video",
"... |
ardi69/pyload-0.4.10 | pyload/plugin/crypter/FiredriveCom.py | Python | gpl-3.0 | 474 | 0.012658 | # -*- coding: utf-8 -*-
from pyload.plugin.internal.DeadCrypter import DeadCrypter
class Fi | redriveCom(DeadCrypter):
__name = "FiredriveCom"
__type = "crypter"
__version = "0.03"
__pattern = r'https?://(?:www\.)?(firedrive|putlocker)\.com/share/.+'
__config = [] #@TODO | : Remove in 0.4.10
__description = """Firedrive.com folder decrypter plugin"""
__license = "GPLv3"
__authors = [("Walter Purcaro", "vuolter@gmail.com")]
|
varadarajan87/piernik | bin/generate_public.py | Python | gpl-3.0 | 1,873 | 0.003203 | #!/usr/bin/env python
imp | ort qa
import re
i | mport numpy
have_use = re.compile("^\s{1,12}use\s")
remove_warn = re.compile('''(?!.*QA_WARN .+)''', re.VERBOSE)
unwanted = re.compile("(\s|&|\n)", re.VERBOSE)
def do_magic(files, options):
name = files[0]
glob = []
temp = []
for f in files[2:]:
lines = open(f, 'r').readlines()
temp =... |
zengxs667/tiblog | asterisk/admin/__init__.py | Python | mit | 87 | 0.011494 | from flask | import Blueprint
admin = Blueprint("admin", __name__)
from . import views | |
botify-labs/moto | tests/test_sts/test_server.py | Python | apache-2.0 | 1,095 | 0 | from __future__ import unicode_literals
import sure # noqa
import moto.server as server
'''
Test the different serv | er responses
'''
def test_sts_get_session_token():
backend = server.create_backend_app("sts")
test_client = backend.test_client()
res = test_client.get('/?Action=GetSessionToken')
res.status_code.should.equal(200)
res.data.should.contain(b"SessionToken")
res.data.should.contain(b"AccessKeyId"... | res = test_client.get('/?Action=GetFederationToken&Name=Bob')
res.status_code.should.equal(200)
res.data.should.contain(b"SessionToken")
res.data.should.contain(b"AccessKeyId")
def test_sts_get_caller_identity():
backend = server.create_backend_app("sts")
test_client = backend.test_client()
... |
PW-Sat2/PWSat2OBC | integration_tests/telecommand/compile_info.py | Python | agpl-3.0 | 236 | 0.004237 | from | telecommand import Telecommand
class GetCompileInfoTelecommand(Telecommand):
def __init__(self):
Telecommand.__init__(self)
def apid(self):
return 0x27
| def payload(self):
return [] |
kapteyn-astro/kapteyn | doc/source/EXAMPLES/mu_externaldata.py | Python | bsd-3-clause | 977 | 0.0174 | from kapteyn import maputils
from matplotlib import pylab as plt
import numpy
header = {'NAXIS' : 2, 'NAXIS1': 800, 'NAXIS2': 800,
'CTYPE1' : 'RA---TAN',
'CRVAL1' : 0.0, 'CRPIX1' : 1, 'CUNIT1' : 'deg', 'CDELT1' : -0.05,
'CTYPE2' : 'DEC--TAN',
'CRVAL2' : 0.0, 'CRPIX2' : 1, 'CUNI... | = nx - sizex1
sizey1 = nx/2.0; sizey2 = nx - sizey1
x, y = numpy.mgrid[-sizex1:sizex2, -sizey1:sizey2]
edata = numpy.exp(-(x**2/float(sizex1*10)+y**2/float(sizey1*10)))
f = maputils.FITSimage(externalheader=header, externaldata=edata)
f.writetofits()
fig = plt.figure(figsize=(6,5))
frame = fig.add_axes([0.1,0.1, 0.82,... | line(color='y')
mplim.plot()
mplim.interact_toolbarinfo()
mplim.interact_imagecolors()
mplim.interact_writepos()
plt.show()
|
oskarm91/sis | sis/settings/test.py | Python | bsd-3-clause | 435 | 0 | """
This is an example settings/test.py file.
Use this settings file when running tests.
These settings overrides what's in settings/base.py
"""
from .base import *
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sql | ite3",
"NAME": ":memory:",
"USER": "",
"PASSWORD": "",
"HOST": "",
"PORT": "",
},
}
SECRET_KEY = '*k3tkxu5a*08f9ann#5sn!3qc&o2nkr-+z)0=k | mm7md9!z7=^k'
|
Azure/azure-sdk-for-python | sdk/synapse/azure-synapse-artifacts/azure/synapse/artifacts/operations/_spark_job_definition_operations.py | Python | mit | 45,127 | 0.005097 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')
return HttpRe | quest(
method="POST",
url=url,
params=query_parameters,
headers=header_parameters,
**kwargs
)
def build_rename_spark_job_definition_request_initial(
spark_job_definition_name: str,
*,
json: JSONType = None,
content: Any = None,
**kwargs: Any
) -> HttpReq... |
abadger/Bento | bento/commands/hooks.py | Python | bsd-3-clause | 3,935 | 0.00737 | import os
import sys
import re
from bento.compat \
import \
inspect as compat_inspect
from bento.commands.core \
import \
command
SAFE_MODULE_NAME = re.compile("[^a-zA-Z_]")
__HOOK_REGISTRY = {}
__PRE_HOOK_REGISTRY = {}
__POST_HOOK_REGISTRY = {}
__COMMANDS_OVERRIDE = {}
__INIT_FUNCS = {}
def... | RY[cmd_name].append(func)
def get_regist | ry_categories():
global __HOOK_REGISTRY
return __HOOK_REGISTRY.keys()
def get_registry_category(categorie):
global __HOOK_REGISTRY
return __HOOK_REGISTRY[categorie]
def get_pre_hooks(cmd_name):
global __PRE_HOOK_REGISTRY
return __PRE_HOOK_REGISTRY.get(cmd_name, [])
def get_post_hooks(cmd_na... |
stanzheng/advent-of-code | 2017/day5/main.py | Python | apache-2.0 | 5,444 | 0.004041 |
def main(i):
ins = i.split("\n")
arr = [int(i) for i in ins]
index =0
iterations = 0
while (index>=0 and index < len(arr)):
arr[index], index = arr[index] + 1, index + arr[index];
iterations = iterations+1
print(iterations)
def main2(i):
ins = i.split("\n")
arr = [int(i) for i in ins]
inde... |
-484
-969
-121
-858
-208
-618
-384
-1 | 6
-91
-662
-348
-675
-63
-713
-966
-678
-293
-827
-445
-387
-212
-763
-847
-756
-299
-443
-80
-286
-954
-521
-394
-357
-861
-530
-649
-671
-437
-884
-606
-73
-452
-354
-729
-927
-248
-2
-738
-521
-440
-435
-291
-104
-402
-375
-875
-686
-812
-539
-934
-536
-924
-924
-365"""
# i = """0
# 3
# 0
# 1
# -3"""
main(i)
main2(i... |
alpine9000/amiga_examples | tools/external/amitools/amitools/scan/FileScanner.py | Python | bsd-2-clause | 3,414 | 0.01406 | # scan a set of file
from __future__ import print_function
import os
import fnmatch
import tempfile
from ScanFile import ScanFile
class FileScanner:
def __init__(self, handler=None, ignore_filters=None, scanners=None,
error_handler=None, ram_bytes=10 * 1024 * 1024,
skip_handler=None... | r(sf)
sf.close()
return ok
def _scan_dir(self, path):
if self._is_ignored(path):
return True
for root, dirs, files in os.walk(path):
for name in files:
if not self._scan_file(os.path.join(root,name)):
return False
for name in dirs:
if not self._scan_dir(os.... | turn True
def _scan_file(self, path):
if self._is_ignored(path):
return True
# build a scan file
try:
size = os.path.getsize(path)
with open(path, "rb") as fobj:
sf = ScanFile(path, fobj, size, True, True)
return self.scan_obj(sf, False)
except IOError as e:
eh... |
knxd/pKNyX | tests/common/singleton.py | Python | gpl-3.0 | 617 | 0.006483 | # -*- coding: utf-8 -*-
from pyknyx.common.singleton import *
import unittest
# Mute logger
from pyknyx.services.logger import logging; logger = logging.getLogger(__name__)
from pyknyx.services.logger import logging
logger = logging.getLogger(__name__)
logging.getLogger("pyknyx").setLevel(logging.ERROR)
@six.add_me... | class(Singleton)
class SingletonTest(object):
pass
class SingletonTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_constructor(self):
s1 = | SingletonTest()
s2 = SingletonTest()
self.assertIs(s1, s2)
|
gboone/wedding.harmsboone.org | rsvp/migrations/0020_auto__add_field_guest_hotel.py | Python | mit | 8,280 | 0.005797 | # -*- coding: 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):
# Removing M2M table for field guests on 'Event'
db.delete_table(db.shorten_name(u'rsvp_event_guests'))
... | id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('guest', models.ForeignKey(orm[u'rsvp.guest'], null=False)),
('event', models.ForeignKey(orm[u'rsvp.event'], null=False))
))
db.create_unique(m2m_table_name, ['guest_id', 'event_id'])
# Remo... | ests on 'Table'
db.delete_table(db.shorten_name(u'rsvp_table_guests'))
# Removing M2M table for field guests on 'Hotel'
db.delete_table(db.shorten_name(u'rsvp_hotel_guests'))
# Removing M2M table for field guests on 'Room'
db.delete_table(db.shorten_name(u'rsvp_room_guests'))
... |
catapult-project/catapult | telemetry/telemetry/core/memory_cache_http_server_unittest.py | Python | bsd-3-clause | 3,837 | 0.001824 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import os
from telemetry.core import util
from telemetry.core | import memory_cache_http_server
from telemetry.testing import tab_test_case
class RequestHandler(
memory_cache_http_server.MemoryCacheDynamicHTTPRequestHandler):
def ResponseFromHandler(self, path):
content = "Hello from handler"
return self.MakeResponse(content, "text/html", False)
class MemoryCach... | ar.webm'
test_file = os.path.join(util.GetUnittestDataDir(), 'bear.webm')
self._test_file_size = os.stat(test_file).st_size
def testBasicHostingAndRangeRequests(self):
self.Navigate('blank.html')
x = self._tab.EvaluateJavaScript('document.body.innerHTML')
x = x.strip()
# Test basic html host... |
luminize/libcanopen | python/examples/canopen-dump.py | Python | bsd-3-clause | 649 | 0.001541 | #!/usr/bin/python
# ------------------------------------------------------------------------------
# Copyright (C) 2012, Robert Johansson <rob@raditex.nu>, Raditex Control AB
# All rights reserved.
#
# This file is part of the rSCADA system.
#
# rSCADA
# http://www.rSCADA.se
# info@rscada.se
# ------------------------... | pycanopen import *
canopen = CANopen()
while True:
canopen_frame = canopen.read_frame()
if canopen_frame:
print canop | en_frame
else:
print("CANopen Frame parse error")
|
arun1729/road-network | rng/__init__.py | Python | mit | 19 | 0.052632 | d | ef rng():
pass | |
mlhhu2017/identifyDigit | marc/mnist_util.py | Python | mit | 5,121 | 0.004687 | # coding: utf-8
from mnist import MNIST
import math
import numpy as np
import itertools
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from random import randint
def get_np_array(path='data'):
"""
Get images and install converter:
1. install MNIST from the command line with 'pip insta... | labels)
def show_a_num(num):
"""
Plots a single number
inputs:
num takes 1d-array with shape (784,) containing a single | image
outputs:
img matplotlib image
"""
pixels = num.reshape((28,28))
img = plt.imshow(pixels, cmap='gray')
plt.axis("off")
return img
def show_nums(data, nrow=None, xsize=15, ysize=15):
"""
Plots multiple numbers in a "grid"
inputs:
data takes 2d-array wit... |
mekolat/manachat | external/construct/lib/container.py | Python | gpl-2.0 | 6,139 | 0.00619 | """
Various containers.
"""
def recursion_lock(retval, lock_name = "__recursion_lock__"):
def decorator(func):
def wrapper(self, *args, **kw):
if getattr(self, lock_name, False):
return retval
setattr(self, lock_name, True)
try:
return fun... | ):
return list(self.iteritems())
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
@rec | ursion_lock("<...>")
def __pretty_str__(self, nesting = 1, indentation = " "):
attrs = []
ind = indentation * nesting
for k, v in self.iteritems():
if not k.startswith("_"):
text = [ind, k, " = "]
if hasattr(v, "__pretty_str__"):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.