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 |
|---|---|---|---|---|---|---|---|---|
nint8835/NintbotForDiscordV2 | NintbotForDiscord/FeatureManager.py | Python | mit | 593 | 0.001686 | from .Feature import Feature
from .BasePlugin import BasePlugin
from . imp | ort Bot
class FeatureManager(object):
def __init__(self, bot: "Bot.Bot"):
self.bot = bot
self.features = {}
def register_feature(self, owner: BasePlugin, name: str, description: str = "A feature.") -> Feature:
if name in self.features:
return self.features[name]
f... | = feature
return feature
def get_feature(self, name: str) -> Feature:
return self.features[name]
|
micahhausler/django-tour | run_tests.py | Python | mit | 1,141 | 0.002629 | """
Provides the ability to run test on a sta | ndalone Django app.
"""
import sys
from optparse import OptionParser
import django
from django.conf import settings
from settings import configure_settings
# Configure the default settings and setup django
configure_settings()
if django.VERSION[1] >= 7:
django.setup()
# Django nose must be imported here since i... | m south.management.commands import patch_for_test_db_setup
patch_for_test_db_setup()
if not test_args:
test_args = ['tour']
kwargs.setdefault('interactive', False)
test_runner = NoseTestSuiteRunner(**kwargs)
failures = test_runner.run_tests(test_args)
sys.exit(failures)
if __na... |
dennisss/sympy | sympy/ntheory/tests/test_ntheory.py | Python | bsd-3-clause | 31,774 | 0.001322 | from collections import defaultdict
from sympy import Sieve, binomial_coefficients, binomial_coefficients_list, \
multinomial_coefficients, Mul, S, Pow, sieve, Symbol, summation, Dummy, \
factorial as fac, pi, GoldenRatio as phi, sqrt
from sympy.core.numbers import Integer, igcd, Rational
from sympy.core.compat... | cycle_length
from sympy.ntheory.primetest import _mr_safe_helper, mr
from sympy.ntheory.bbp_pi import pi_hex_digits
from sympy.ntheory.modular import crt, crt1, crt2, solve_congruence
from sympy.ntheory.continued_fraction import \
(continued_fraction_periodic as cf_p,
continued_fraction_iterator as cf_i,
... | ions import Fraction
from sympy.core.add import Add
from sympy.polys.domains import ZZ
from sympy.utilities.pytest import raises
from sympy.utilities.iterables import capture
from sympy.utilities.randtest import random_complex_number
from sympy.ntheory.multinomial import multinomial_coefficients_iterator
def test_t... |
juergenhamel/cuon | cuon_server/LoadBalancer/txlb/__init__.py | Python | gpl-3.0 | 199 | 0 | name = 'txL | oadBalancer'
shortName = 'txLB'
projectURL = 'https://launchpad.net/txloadbalancer'
summary = 'txLoadBalancer - A Twisted-bas | ed TCP load balancer.'
description = summary
version = '1.1.0'
|
uptimejp/postgres-toolkit | postgres_toolkit/TcpdumpWrapper.py | Python | gpl-2.0 | 13,163 | 0.000304 | #!/usr/bin/env python
# coding: UTF-8
# TcpdumpWrapper
#
# Copyright(c) 2015-2018 Uptime Technologies, LLC.
from datetime import datetime, timedelta, date, time
import hashlib
import os
import re
import subprocess
import sys
import log
class TcpdumpPacket:
def __init__(self, ts, src, dst, bytes, debug=None):
... | :
log.debug("get_timestamp: %s" % str(self.ts))
return self.ts
def get_messages(self):
return self.messages
def parse_ip_header(self, data):
self.iph_version = (data[0] >> 4) & 0b1111
self.iph | _header_len = data[0] & 0b1111
self.iph_tos = data[1]
self.iph_dgram_len = (data[2] << 8) + data[3]
self.iph_id = (data[4] << 8) + data[5]
self.iph_dst = "%d.%d.%d.%d" % (data[12], data[13], data[14], data[15])
self.iph_src = "%d.%d.%d.%d" % (data[16], data[17], data[18], data[19... |
septicmk/MEHI | test/test_utils.py | Python | bsd-3-clause | 1,542 | 0.001297 | ############################# | ###
# Author : septicmk
# Date : 2015/07/2 | 4 19:41:26
# FileName : test_utils.py
################################
import shutil
import tempfile
import unittest
from numpy import vstack
from pyspark import SparkContext
class PySparkTestCase(unittest.TestCase):
def setUp(self):
class_name = self.__class__.__name__
self.sc = SparkContext('lo... |
tdsmith/numpy | numpy/distutils/fcompiler/gnu.py | Python | bsd-3-clause | 15,266 | 0.001834 | from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_uti... | artswith('0') or v.startswith('2') or v.startswith('3'):
# the '0' is for early g77's
return ('g | 77', v)
else:
# at some point in the 4.x series, the ' 95' was dropped
# from the version string
return ('gfortran', v)
# If still nothing, raise an error to make the problem easy to find.
err = 'A valid Fortran version was not... |
FePhyFoFum/PyPHLAWD | src/cluster_tree_wc.py | Python | gpl-2.0 | 2,115 | 0.009456 | import os
import sys
import random
from clint.textui import colored
import subprocess
from conf import DI
from conf import treemake
from conf import py
import emoticons
from logger import Logger
import tree_reader
def run_tree(infile,outfile):
cmd = "FastTree -nt -gtr "+infile+" 2>fasttree.out > "+outfile
os.... | TERING INTERNAL "+root)
tablename = [x for x in files if ".table" in x][0]
if root[-1] != "/":
root = root+"/"
cmd = py+" "+DI+"cluster_internal_wc.py "+root+ " "+root+tablename+" "+logfile+" "+rantempdir
rc = subprocess.call(cmd,shell=... | sys.exit(1)
cmd = py+" "+DI+"annotate_clusters.py "+sys.argv[1]
os.system(cmd)
cmd = py+" "+DI+"post_process_cluster_info.py "+sys.argv[1]
os.system(cmd)
|
SF-Zhou/LeetCode.Solutions | solutions/container_with_most_water_2.py | Python | mit | 480 | 0 | class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
res = 0
left, right = 0, len(height) - 1
while left < right:
if height[left] <= height[right]:
res = max(res, height[left] | * (right - left))
left += 1
else:
res = max(res, height[right] * (right - left))
right -= 1
return | res
|
Graylog2/graylog-ansible-role | molecule/ci/tests/conftest.py | Python | apache-2.0 | 650 | 0.001538 | """PyTest Fixtures."""
from __future__ import absolute_import
import os
import pytest
def pytest_runtest_setup(item): |
"""Run tests only when under molecule with testinfra installed."""
try:
import testinfra
except ImportError:
pytest.skip("Test requires testinfra", allow_module_level=True)
if "MOLECULE_INVENTORY_FILE" in os.environ:
pytest.testinfra_hosts = testinfra.utils.ansible_runner.Ansibl... | _FILE"]
).get_hosts("all")
else:
pytest.skip(
"Test should run only from inside molecule.", allow_module_level=True
)
|
tensorflow/datasets | tensorflow_datasets/question_answering/xquad_test.py | Python | apache-2.0 | 1,233 | 0.004055 | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# 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 appl... | slate-dev": "translate-dev.json",
"tra | nslate-test": "translate-test.json",
"test": "test.json",
}
SPLITS = {
"translate-train": 3,
"translate-dev": 2,
"translate-test": 3,
"test": 1,
}
if __name__ == "__main__":
testing.test_main()
|
jstacoder/modern-business-flask | app/data.py | Python | apache-2.0 | 6,480 | 0.01821 | from marshmallow import Schema, fields, pprint,utils
from faker import Factory
import pickle
import os
tmt = utils.to_marshallable_type
factory = Factory()
faker = factory.create()
f = faker
def dump_fields(meta):
for table in meta.tables.values():
print '{}'.format(table.name)
print '---------... | 'blog_id':blog_id,
}
def make_post(model,blog_id):
post = model(**post_data(blog_id))
post.save()
return post
def make_posts(model,blogs):
rtn = []
for b in blogs:
for i in range(5):
rtn.append(make_post(model,b.id))
return rtn
categorys = [
{'name... | escription':f.text()},
{'name':'another','description':f.text()},
]
def make_categorys(model):
rtn = []
for c in categorys:
tmp = model()
tmp.name = c['name']
tmp.description = c['description']
tmp.save()
rtn.append(tmp)
return rtn
def users():
return... |
babbel/floto | examples/child_workflow/decider.py | Python | mit | 1,797 | 0.006678 | import floto
import logging
from floto.specs.task import ActivityTask, ChildWorkflow
from floto.specs import DeciderSpec
import floto.decider
logger = logging.getLogger(__name__)
rs = floto.specs.retry_strategy.InstantRetry(retries=3)
domain = 'floto_test'
#Define tasks and decider of the workflow
copy_files = Activ... | in,
task_list='copy_files_task_list',
default_activity_task_list='s3_files_worker',
activity_tasks=[copy_files, child_workflow],
terminate_decider_after_completion=True)
decider = floto.decider.Decider(decider_s... | (separate_process=True)
# Define tasks and decider of the child workflow
file_length = ActivityTask(domain=domain, name='fileLength', version='1', retry_strategy=rs)
child_workflow_spec = DeciderSpec(domain=domain,
task_list='file_length_task_list',
default_activ... |
tedye/leetcode | Python/leetcode.124.binary-tree-maximum-path-sum.py | Python | mit | 704 | 0.017045 | please enter code here...
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# | self.right = None
class Solution(object):
def __init__(self):
self.res = -0x7fffffff
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
| if not root: return 0
self.helper(root)
return self.res
def helper(self,root):
l = 0
r = 0
if root.left: l = self.helper(root.left)
if root.right: r = self.helper(root.right)
self.res = max(l+r+root.val,self.res)
return max(max(l,r) + root.val,0) |
mplucinski/tex-gettext | tex_math.py | Python | bsd-2-clause | 15,267 | 0.006747 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import subprocess
import sys
import unittest
COMMAND_PREFIX = 'gettextmath'
def generate_command_call(name, prefix, *args):
return '\\' + prefix + name + '{' + '}{'.join(args) + '}'
class Parser:
class Token:
function = False
def proce... | ce(self.arg_truefalse, Parser.OperatorTernaryMiddle):
raise Exception('Operator "?" must have matching ":", but "{}" found'.format(self.arg_truefalse))
stack.append(self)
def generate(self):
return generate_command_call('ifthenelse', COMMAND_PREFIX, self.arg_condition.ge... | function = False
def consume(self, stack):
self.false = stack.pop()
self.true = stack.pop()
stack.append(self)
class OpenParenthesis(Token):
priority = 100
def process(self, stack, output):
stack.append(self)
def __str__(self):
... |
davidvon/pipa-pay-server | admin/sms/sdk.py | Python | apache-2.0 | 2,956 | 0.001691 | # -*- coding: UTF-8 -*-
import hashlib
import base64
import datetime
import urllib2
import json
class TemplateSMS:
account_sid = ''
account_token = ''
app_id = ''
server_ip = ''
server_port = ''
soft_version = ''
timestamp = ''
def set_account(self, account_sid, token):
self.a... | url = "https://" + self.server_ip + ":" + sel | f.server_port + "/" + self.soft_version + "/Accounts/" + \
self.account_sid + "/SMS/TemplateSMS?sig=" + sig
src = self.account_sid + ":" + self.timestamp
req = urllib2.Request(url)
b = '["%s","%s"]' % (random, valid_min)
body = '''{"to": "%s", "datas": %s, "templateId": "%s... |
cea-sec/ivre | ivre/tools/db2view.py | Python | gpl-3.0 | 3,806 | 0.000788 | #! /usr/bin/env python
# This file is part of IVRE.
# Copyright 2011 - 2021 Pierre LALET <pierre@droids-corp.org>
#
# IVRE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | _category)]
if args.test:
def output(host: Record) -> None:
return displayfunction_json([host], db.view)
elif args.no_merge:
output = db.view.store_host
| else:
output = db.view.store_or_merge_host
# Output results
itr = to_view(_from)
if not itr:
return
for elt in itr:
output(elt)
|
MiLk/ansible-modules-core | system/service.py | Python | gpl-3.0 | 52,336 | 0.003573 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of... | ented on target platform")
# ===========================================
# Generic methods that should be used on all platforms.
def execute_command(self, cmd, | daemonize=False):
if self.syslogging:
syslog.openlog('ansible-%s' % os.path.basename(__file__))
syslog.syslog(syslog.LOG_NOTICE, 'Command %s, daemonize %r' % (cmd, daemonize))
# Most things don't need to be daemonized
if not daemonize:
return self.module.run_... |
digitalocean/netbox | netbox/circuits/migrations/0019_nullbooleanfield_to_booleanfield.py | Python | apache-2.0 | 426 | 0 | # Generated by Django 3.1b1 on 2020-07-16 15:5 | 5
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('circuits', '0018_standardize_description'),
]
operations = [
migrations.AlterField(
model_name='circuittermination',
name='connection_status',
field=m... | ]
|
rezoo/chainer | tests/chainer_tests/functions_tests/loss_tests/test_mean_squared_error.py | Python | mit | 3,876 | 0 | import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
from chainer.utils import type_check
@testing.parameterize(
{'dtype': ... | ):
self.check_forward(self.x0, self.x1)
@attr.gpu
@condition.retry(3)
def test_forward_gpu | (self):
self.check_forward(cuda.to_gpu(self.x0), cuda.to_gpu(self.x1))
def check_backward(self, x0_data, x1_data):
gradient_check.check_backward(
functions.mean_squared_error,
(x0_data, x1_data), None, eps=1e-2, **self.backward_tols)
@condition.retry(3)
def test_bac... |
jithinbp/vLabtool-v0 | v0/templates/template_exp_standalone.py | Python | gpl-3.0 | 4,665 | 0.009861 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'exp_std.ui'
#
# Created: Sat Apr 18 15:55:49 2015
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attrib... | a = QtGui.QScrollArea(self.centralwidget)
self.scrollArea.setStyleSheet(_fromUtf8(""))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName(_fromUtf8("scrollArea"))
self.scrollAreaWidgetContents_2 = QtGui.QWidget | ()
self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 847, 452))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollAreaWi... |
imscs21/myuniv | 1학기/programming/basic/파이썬/파이썬 과제/5/5_6.py | Python | apache-2.0 | 271 | 0.060837 | def double(n):
return n * 2
def halve(n):
return n // | 2
def fastmult(m,n):
if n > 0:
if n % 2 == 0:
return fastmult(double(m),halve(n))
else:
return m+fastmult | (m,n-1)
else:
return 0
#그냥 재귀 |
cdrooom/odoo | openerp/addons/base/ir/ir_actions.py | Python | agpl-3.0 | 63,067 | 0.004678 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2014 OpenERP S.A. <http://www.openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of... | for ir_actions_report_xml in self.browse(cr, uid, ids, context=context):
if ir_actions_report_xml.ir_values_id:
try:
self.pool['ir.values'].unlink(
cr, SUPERUSER_ID, ir_actions_report_xml.ir_values_id.id, context
)
... | , name, data, context=None):
"""
Look up a report definition and render the report for the provided IDs.
"""
new_report = self._lookup_report(cr, name)
if isinstance(new_report, (str, unicode)): # Qweb report
# The only case where a QWeb report is rendered with this... |
viljoviitanen/plugin.minimal.example | addon.py | Python | unlicense | 1,556 | 0.003856 | # This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that r... | TABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
#
import xbmcgui
import xbmcplugin
import xbmcaddon
addon = xbmcaddon.Addon()
username = addon.getSetting('username') or 'nobody'
item = xbmcgui.ListItem('Hello, %... |
vmalavolta/django-pieguard | tests/test_app/models.py | Python | mit | 461 | 0 | from __future__ import unicode_literals
from datetime imp | ort datetime
from django.db import models
class Project(models.Model):
name = models.CharField(max_length=128, unique=True)
created_at = models.DateTimeFi | eld(default=datetime.now)
class Meta:
get_latest_by = 'created_at'
permissions = (
('view_project', 'View project'), # used by django-tastypie
)
def __unicode__(self):
return self.name
|
mehdy/pyeez | setup.py | Python | gpl-2.0 | 1,167 | 0 | """
This module instructs the setuptools to setpup this package properly
:copyright: (c) 2016 by Mehdy Khoshnoody.
:license: GPLv3, see LICENSE for more | details.
"""
impor | t os
from distutils.core import setup
setup(
name='pyeez',
version='0.1.0',
packages=['pyeez'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved ::... |
google-research/google-research | linear_dynamical_systems/process_mit_bih.py | Python | apache-2.0 | 3,056 | 0.009162 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | r 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.
"""Generate timeseries in 2 clusters: NS... | ure__ import print_function
import random
from absl import app
from absl import flags
import numpy as np
import wfdb
FLAGS = flags.FLAGS
flags.DEFINE_string(
'input_dir', None,
'Local input directory containing the mit-bih file that can be copied from '
'/namespace/health-research/unencrypted/reference/... |
tomato42/tlsfuzzer | scripts/test-sslv2-force-export-cipher.py | Python | gpl-2.0 | 8,593 | 0.00256 | # Author: Hubert Kario, (c) 2015
# Released under Gnu GPL v2.0, see LICENSE file for details
"""Test forcing of export ciphers in SSLv2"""
from __future__ import print_function
import traceback
import sys
import re
from random import sample
import getopt
from tlsfuzzer.runner import Runner
from tlsfuzzer.messages impo... | clude:
continue
print("{0} ...".format(c_name))
runner = Runner(conversation)
res = True
exception = None
try:
runner.run()
except Exception as exp:
exception = exp
print("Error while processing")
print(traceba... | print("")
res = False
if c_name in expected_failures:
if res:
xpass += 1
xpassed.append(c_name)
print("XPASS-expected failure but test passed\n")
else:
if expected_failures[c_name] is not None and \
... |
jibaron/q35-seabios | tools/acpi_extract.py | Python | gpl-3.0 | 11,577 | 0.008465 | #!/usr/bin/python
# Copyright (C) 2011 Red Hat, Inc., Michael S. Tsirkin <mst@redhat.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Process mixed ASL/AML listing (.lst file) produced by iasl -l
# Locate and execute ACPI_EXTRACT directives, output offset info
#
# Documentation of ACP... | in fileinput.input():
# Strip trailing newline
line = line.rstrip( | );
# line number and debug string to output in case of errors
lineno = lineno + 1
debug = "input line %d: %s" % (lineno, line)
#ASL listing: space, then line#, then ...., then code
pasl = re.compile('^\s+([0-9]+)\.\.\.\.\s*')
m = pasl.search(line)
if (m):
add_asl(lineno, pasl.sub("",... |
KirarinSnow/Google-Code-Jam | Round 1C 2010/C.py | Python | gpl-3.0 | 1,627 | 0.006146 | #!/usr/bin/python
#
# Problem: Making Chess Boards
# Language: Python
# Author: KirarinSnow
# Usage: python thisfile.py <input.in >output.out
from heapq import *
def process(r1, r2, c1, c2):
for i in range(r1, r2):
for j in range(c1, c2):
if 0 <= i < m and 0 <= j < n:
if g[i]... | s = [[1 for i in range(n)] for j in range(m)]
q = []
process(0, m, 0, n)
b = []
while q:
x, r, c = heappop(q)
if x != 0 and s[r][c] == -x:
b.append((-x, r, c))
clear(r+x+1, r+1, c+x+1, c+1)
process(r+x+... | print k, len(filter(lambda x: x[0] == k, b))
|
olivierdalang/stdm | third_party/FontTools/fontTools/t1Lib.py | Python | gpl-2.0 | 9,506 | 0.035451 | """fontTools.t1Lib.py -- Tools for PostScript Type 1 fonts
Functions for reading and writing raw Type 1 data:
read(path)
reads any Type 1 font file, returns the raw data and a type indicator:
'LWFN', 'PFB' or 'OTHER', depending on the format of the file pointed
to by 'path'.
Raises an error when the fi... | , data, dohex)
err = 0
finally:
if err and not DEBUG:
try:
os.remove(path)
except os.error:
pass
# -- internal --
LWFNCHUNKSIZE = 2000
HEXLINELENGTH = 80
def readLWFN(path, onlyHeader=0):
"""reads an LWFN font file, returns raw data"""
resRef = Res.FSOpenResFile(path, 1) # ... | i)
code = ord(res.data[0])
if ord(res.data[1]) <> 0:
raise T1Error, 'corrupt LWFN file'
if code in [1, 2]:
if onlyHeader and code == 2:
break
data.append(res.data[2:])
elif code in [3, 5]:
break
elif code == 4:
f = open(path, "rb")
data.append(f.read())
f.clo... |
speth/ember | test/reference/bdf.py | Python | mit | 3,354 | 0.002683 | #!/usr/bin/env python
"""
Simple implementations of BDF integration to generate comparisons
for unit testing.
"""
import numpy as np
from scipy import linalg
class BDFIntegrator(object):
def __init__(self, h, y, A, k):
"""
Integrator for y' = Ay + k.
Uses second-order BDF with step size h.... | np.linalg.solve(M, b)
else:
# Apply second-order BDF: y_n = 4/3* | y_(n-1) - 1/3*y_(n-2) + 2/3*h * y'_n
# by solving (I-2/3*h*A) y_n = 4/3*y_(n-1) - 1/3*y_(n-2) + (2/3)*h*k
self.yprev2 = self.yprev.copy()
self.yprev = self.y.copy()
M = np.eye(self.N) - 2.0/3.0 * self.h * self.A
b = 4.0/3.0 * self.yprev - 1.0/3.0 * self.yprev2... |
Who8MyLunch/euler | problem_001.py | Python | mit | 632 | 0.003165 |
from __future__ import division, print_function #, unicode_literals
"""
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples
of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
import numpy as np
# Setup.
nu... | :
if not i % k:
factors.append(i)
break
print('\nRange: {:d}'.format(num_max))
print('Number of factors: {:d}'.format(len(factors)))
print('The answer: {:d}'.format(np.sum(factors))) |
# Done.
|
Mifiel/python-api-client | mifiel/certificate.py | Python | mit | 120 | 0.016667 | from mifiel import Base |
class Certificate(Base):
def __init__(self, client):
Base.__init__(self, | client, 'keys')
|
dsarkozi/care4care-sdp-grp4 | Care4Care/C4CApplication/tests/OIDTest.py | Python | agpl-3.0 | 5,177 | 0.006761 | from base64 import urlsafe_b64decode
from io import StringIO
from django.http.response import HttpResponse
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
import openid2rp
from Care4Care.settings import STATICFILES_DIRS
@... | (response):
ax = 'ax' + "."
oax = 'openid.' + ax
res = {}
for k, v in response.items():
if k.startswith(oax+"type."):
k = k.rsplit('.',1)[1]
value_name = oax+"value."+k
if ax+"value."+k not in response['openid.signed']:
continue
res... | "http://axschema.org/eid/card-validity/end" : 'card_validity_end',
"http://axschema.org/person/gender" : 'gender',
"http://axschema.org/contact/postalAddress/home" : 'address',
"http://axschema.org/namePerson/first" : 'firstname',
"http://axschema.org/eid/photo" : 'photo',
... |
arnomoonens/Mussy-Robot | myservo.py | Python | mit | 2,876 | 0.019471 | import pigpio
import time
from multiprocessing import Process, Queue, Lock
#----------------------- SERVO 1 ----------------------------
speed = .1
minP = 30
maxP = 180
currentP = 90
newP = 90
q = Queue() #queue for the new position
q.put(newP)
q2 = Queue() #queue for the current position
q2.put(currentP)
l = Lock()... | oPin_2,g2q(_currentP_2))
q2_2.put(_currentP_2)
l_2.release()
pi_2.stop()
print 'Process P1 terminated.'
except:
print 'Error!!Process P1 terminated'
pi_2.sto | p()
|
onehao/opensource | pyml/crawler/minispider/SpiderFileUtils.py | Python | apache-2.0 | 610 | 0.004967 | # -*- coding:utf-8 -*-
'''
Created on 20 | 15年3月12日
@author: wanhao01
'''
import os
class SpiderFileUtils(object):
'''
deal with file related operations.
'''
def __save_page(self, data, url, outputdir):
'''
save the page content with the specific url to the local path.
'''
if(not os.path.... | 'w')
f.writelines(data)
f.close()
if __name__ == '__main__':
pass |
Titulacion-Sistemas/PracticasDjango | practicaConCarratala/manage.py | Python | gpl-2.0 | 263 | 0.003802 | #!/usr/bin/env python
import os
import sys |
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "practicaConCarratala.s | ettings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
metapolator/mutatormathtools | python_modules/lib/python/defcon/objects/glyph.py | Python | apache-2.0 | 60,725 | 0.001894 | import weakref
from warnings import warn
from fontTools.misc import arrayTools
from defcon.objects.base import BaseObject
from defcon.objects.contour import Contour
from defcon.objects.point import Point
from defcon.objects.component import Component
from defcon.objects.anchor import Anchor
from defcon.objects.lib impo... | lf._shallowLoadedContours = None
self._contours = []
self._components = []
self._anchors = []
self._guidelines = []
self._lib = None
if contourClass is None:
contourClass = Contour
if pointClass is None:
pointClass = Point
if compo... | lass is None:
componentClass = Component
if anchorClass is None:
anchorClass = Anchor
if guidelineClass is None:
guidelineClass = Guideline
if libClass is None:
libClass = Lib
if imageClass is None:
imageClass = Image
se... |
biomodels/BIOMD0000000534 | BIOMD0000000534/model.py | Python | cc0-1.0 | 427 | 0.009368 | import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000534.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def m | odule_exists(module_name):
try:
__import__(module_name)
except ImportError: |
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) |
22i/minecraft-voxel-blender-models | models/extra/blender-scripting/lib/agent.py | Python | gpl-3.0 | 1,320 | 0.018182 | import bpy
import os
# join them together ctrl+j
bpy.ops.object.join()
def get_override(area_type, region_type):
for area in bpy.context.screen.areas:
if area.type == area_type:
for region in area.regions:
if region.type == region_type: ... | ,1))
blend_file_path = bpy.data.filepath
directory = os.path.dirname(blend_file_path)
#target_f | ile = os.path.join(directory, 'agent.obj')
#target_file = os.path.join(directory, 'exported/agent.b3d')
target_file = os.path.join(directory, 'agent.b3d')
#bpy.ops.export_scene.obj(filepath=target_file)
bpy.ops.screen.b3d_export(filepath=target_file)
#bpy.ops.export_scene.obj()
#bpy.ops.screen.b3d_export()
# exits b... |
partp/gtg-services | GTG/plugins/notification_area/notification_area.py | Python | gpl-3.0 | 18,501 | 0.00027 | # -*- coding: utf-8 -*-
# Copyright (c) 2009 - Paulo Cabido <paulo.cabido@gmail.com>
# - Luca Invernizzi <invernizzi.l@gmail.com>
# - Izidor Matušov <izidor.matusov@gmail.com>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU G... | r and a status icon
"""
NORMAL_ICON = "gtg"
ATTENTION_ICON = "gtg_need_attention"
def __init__(self):
self._indicator = TheIndicator().get_indicator()
self._icon = None
self._menu = None
| self._attention = False
def activate(self, leftbtn_callback, menu):
""" Setup the icon / the indicator """
self._menu = menu
if self._indicator:
# Show the icon even when runing ./scripts/debug.sh
theme_path = os.path.join(DATA_DIR, 'icons')
self._... |
Bengt/AL-FanControl | python/fancontrol/ui/cli_util.py | Python | mit | 2,042 | 0 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
RJUST = 12
def format_fans(fans):
return format_line(prefix='fans'.rjust( | RJUST), values=fans)
def format_rpms(rpms):
return format_line(prefix='rpms'.rjust(RJUST), values=rpms)
def format_pwms(pwms):
return format_line(prefix='pwms'.rjust(RJUST), values=pwms)
def format_tmps(tmps) | :
return format_line(prefix='temps'.rjust(RJUST), values=tmps)
def format_names(names):
return format_line(prefix='names'.rjust(RJUST), values=names)
def format_ports(ports):
return format_line(prefix='ports'.rjust(RJUST), values=ports)
def format_temps(temps):
return format_line(prefix='temps'.rj... |
AnotherBobSmith/CLUZ | forms/cluz_form_remove.py | Python | gpl-2.0 | 3,682 | 0.003259 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'cluz_form_remove.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
... | QtGui.QPushButton(self.h | orizontalLayoutWidget)
self.okButton.setMinimumSize(QtCore.QSize(0, 24))
self.okButton.setObjectName(_fromUtf8("okButton"))
self.horizontalLayout.addWidget(self.okButton)
self.cancelButton = QtGui.QPushButton(self.horizontalLayoutWidget)
self.cancelButton.setMinimumSize(QtCo... |
gushaokun/AppPack | iospack/views.py | Python | mit | 1,042 | 0.002037 | # -*- coding: utf-8 -*-
from django.contrib.auth.models import User, Group
from iospack.models import App
from rest_framework import viewsets
from rest_framework import generics
from iospack.serializers import UserSerializer, GroupSerializer, AppSerializer
# Create your views here.
class UserViewSet(viewsets.ModelVie... | :
"""
允许查看和编辑user 的 API endpoint
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
允许查看和编辑group的 API endpoint
"""
| queryset = Group.objects.all()
serializer_class = GroupSerializer
class AppsViewSet(viewsets.ModelViewSet):
"""
允许查看和编辑app的 API endpoint
"""
queryset = App.objects.all()
serializer_class = AppSerializer
lookup_field = 'bundle_id'
class app(generics.RetrieveUpdateDestroyAPIView):
""... |
puttarajubr/commcare-hq | corehq/ex-submodules/couchforms/tests/test_errors.py | Python | bsd-3-clause | 3,166 | 0.000632 | from django.test import TestCase
from corehq.apps.receiverwrapper import submit_form_locally
from couchforms.models import XFormError
class CaseProcessingErrorsTest(TestCase):
def test_no_case_id(self):
"""
submit form with a case block that has no case_id
check that
- it errors
... | """<data xmlns="example.com/foo">
<meta>
<instanceID>abc-easy-as-456</instanceID>
</meta>
<case case_id="123" xmlns="http://commcarehq.org/case/transaction/v2">
<referral>
| <referral_id>456</referral_id>
<open>
<referral_types>t1 t2</referral_types>
</open>
</referral>
</case>
</data>""",
'my_very_special_domain',
)
xform_errors = XFormError.vie... |
CoderBotOrg/coderbotsrv | server/lib/cryptography/hazmat/primitives/hashes.py | Python | gpl-3.0 | 3,022 | 0 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... | elf._backend, ctx=self._ctx.copy()
)
def finalize(self):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
digest = self._ctx.finalize()
self._ctx = None
return digest
@utils.register_interface(interfaces.HashAlgorithm)
class SHA1(o... | block_size = 64
@utils.register_interface(interfaces.HashAlgorithm)
class SHA256(object):
name = "sha256"
digest_size = 32
block_size = 64
@utils.register_interface(interfaces.HashAlgorithm)
class SHA384(object):
name = "sha384"
digest_size = 48
block_size = 128
@utils.register_interface(... |
everaldo/example-code | 17-futures/crypto/arcfour_futures.py | Python | mit | 1,219 | 0.00082 | import sys
import time
from concurrent import futures
from random import randrange
from arcfour import arcfour
JOBS = 12
SIZE = 2**18
KEY = b"'Twas brillig, and the slithy toves\nDid gyre"
STATUS = '{} workers, elapsed time: {:.2f}s'
def arcfour_test(size, key):
in_text = bytearray(randrange(256) for i in range... | d(job)
for future in futures.as_completed(to_do):
| res = future.result()
print('{:.1f} KB'.format(res/2**10))
print(STATUS.format(actual_workers, time.time() - t0))
if __name__ == '__main__':
if len(sys.argv) == 2:
workers = int(sys.argv[1])
else:
workers = None
main(workers)
|
perimosocordiae/sparray | sparray/tests/test_truediv.py | Python | mit | 662 | 0.006042 | import unittest
import numpy as np
from numpy.testing import assert_array_almost_equal
from .test_base import BaseSparrayTest, dense2d
class | TestTrueDivision(BaseSparrayTest):
def test_truediv(self):
c = 3
assert_array_almost_equal(dense2d / c, (self.sp2d / c).toarray())
with np.errstate(divide='ignore'):
assert_array_almost_equal(c / dense2d, c / self.sp2d)
def test_itruediv(self):
self.sp2d /= 1
assert_array_almost_equal(d... | _equal(dense2d / b, self.sp2d.toarray())
if __name__ == '__main__':
unittest.main()
|
michigraber/neuralyzer | docker/jupyter_minimal/jupyter_notebook_config.py | Python | mit | 1,000 | 0.004 | # Copyright (c) Jupyter Development Team.
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
PEM_FILE = os.path.join(jupyter_data_dir(), 'notebook.pem')
c = get_config()
c.NotebookApp.ip = os.getenv('INTERFACE', '') or '*'
c.NotebookApp.port = int(os.getenv('PORT', '') or 8888)
c.NotebookApp.... | , 'req', '-new',
'-newkey', 'rsa:2048', '-days', '365', '-nodes', '-x509',
'-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
| '-keyout', PEM_FILE, '-out', PEM_FILE])
c.NotebookApp.certfile = PEM_FILE
# Set a password if PASSWORD is set
if 'PASSWORD' in os.environ:
from IPython.lib import passwd
c.NotebookApp.password = passwd(os.environ['PASSWORD'])
del os.environ['PASSWORD']
|
purduesigbots/pros-cli | pros/serial/devices/system_device.py | Python | mpl-2.0 | 285 | 0 | import typing
from pros.conductor import Project
class SystemDevice(object):
def upload_project(self, project: Project, **kwargs):
raise NotImplementedError
def | write_program(self, file: typing.BinaryIO, quirk: int = 0, **kwargs):
| raise NotImplementedError
|
saangel/randomcoding | QuestionShuffling.py | Python | gpl-2.0 | 678 | 0.041298 | import numpy as np
# import text file, which has a determined format
a=open("test.dat")
b=open("test2.dat","w")
f=a.read()
g=f.split("\n")
nlines=6
nquestions=16
q1=[g[nlines*i:nlines*(i+1)] for i in range(nquestions)]
# these two lines can be commented if y | ou want to shuffle last question also
last=q1[-1]
q2=q1[:-1]
np.random.shuffle(q2)
for q in q2:
alts=q[4:9]
np.random.shuffle(alts)
q=np.concatenate([q[:4],alts,q[-2:]])
for l in q:
b. | write(str(l)+"\n")
# comment this block also if you want to shuffle last question
alts=last[4:9]
np.random.shuffle(alts)
last=np.concatenate([last[:4],alts,last[-2:]])
for l in last:
b.write(str(l)+"\n")
a.close()
b.close()
|
kaushik94/sympy | sympy/functions/elementary/hyperbolic.py | Python | bsd-3-clause | 48,081 | 0.000478 | from __future__ import print_function, division
from sympy.core import S, sympify, cacheit, pi, I, Rational
from sympy.core.add import Add
from sympy.core.function import Function, ArgumentIndexError, _coeff_isneg
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.elem... | tion.
"""
return asinh
@classmethod
def eval(cls, arg):
from sympy import sin
arg = sympify(arg)
if arg.is_Number:
if arg is S.NaN:
return S.NaN
| elif arg is S.Infinity:
return S.Infinity
elif arg is S.NegativeInfinity:
return S.NegativeInfinity
elif arg.is_zero:
return S.Zero
elif arg.is_negative:
return -cls(-arg)
else:
if arg is S.... |
jessenieminen/aalto-fitness-homepage | manage.py | Python | mit | 256 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ = | = "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aalto_fitness.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| |
saghul/sipwping-django | sipwping/forms.py | Python | gpl-3.0 | 333 | 0.012012 |
from django.forms import Form, RegexField
# Naive validation of a SIP URI
_sip_uri_regex = r'^((?P<user>[a-zA-Z | 0-9 _\-\+\.\%]+)@)?(?P<host>([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6})$'
class SIPU | RIForm(Form):
uri = RegexField(label='', regex=_sip_uri_regex, error_messages={'invalid': 'Invalid SIP URI'})
|
trivoldus28/pulsarch-verilog | tools/local/bas-release/bas,3.9-SunOS-i386/lib/python/lib/python2.4/email/Generator.py | Python | gpl-2.0 | 13,450 | 0.000967 | # Copyright (C) 2001-2004 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Classes to generate plain text from a message object tree."""
import re
import sys
import time
import random
import warnings
from cStringIO import StringIO
from email.Header import Header
UNDERSCORE = '_'
... | e=h, continuation_ws='\t').encode()
# A blank line always separates headers from body
print >> self._fp
#
# Handlers for writing types and subtypes
#
def _handle_text(self, msg):
payload = msg.get_payload()
| if payload is None:
return
cset = msg.get_charset()
if cset is not None:
payload = cset.body_encode(payload)
if not isinstance(payload, basestring):
raise TypeError('string payload expected: %s' % type(payload))
if self._mangle_from_:
... |
flaviovdf/phoenix | phoenix/basic_io/__init__.py | Python | bsd-3-clause | 88 | 0.011364 | #-*- c | oding: utf8
from __future__ import division, print_function
__all__ = [ | 'parser']
|
qunying/gps | share/support/ui/pygps/notebook.py | Python | gpl-3.0 | 1,632 | 0.000613 | """ This module provides a higher-level interface to notebooks.
It relies on the pygobject package.
"""
try:
from gi.repository import Gtk, GObject
import pygps
def switch_notebook_page(notebook, label):
"""Switch to the page with the given label in the notebook.
Returns the page n... | get_notebook_pages(notebook):
"""Return the list of all visible pages for the notebook"""
pages = []
for p in range(0, notebook.get_n_pages()):
page = notebook.get_nth_page(p)
if page.get_visible():
pages.append(page | )
return pages
def get_notebook_page_labels_text(notebook):
"""Return a list containing the labels of all visible pages for the
notebook"""
return [get_notebook_page_label(notebook, p).get_label()
for p in get_notebook_pages(notebook)]
except ImportError:
pa... |
sibis-platform/ncanda-data-integration | scripts/redcap/import_mr_sessions_stroop.py | Python | bsd-3-clause | 5,597 | 0.021083 | #!/usr/bin/env python
##
## See COPYING file distr | ibuted along with the ncanda-data-integration package
## for the copyright and license terms
##
from __future__ import print_function
from builtins import str
import os
import re
import tempfile
import shutil
from sibis | py import sibislogger as slog
from sibispy import utils as sutils
#
# Check for Stroop data (ePrime log file) in given XNAT session
#
import_bindir = os.path.join( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ), 'import', 'laptops' )
bindir = os.path.dirname( os.path.abspath(__file__) )
# Check a lis... |
udoprog/python-adc | adc/parser.py | Python | bsd-3-clause | 5,221 | 0.014557 | from pyparsing import *
from .arguments import *
import string
"""
The following module is a parser based on the ADC specification version 1.0:
http://adc.sourceforge.net/ADC.html
"""
FEATURE_ADD="+"
FEATURE_REM="-"
SEPARATOR=" "
TYPE_SEP=":"
EOL="\n"
B_HEADER = ["B"];
CIH_HEADER = ["C", "I", "H"];
DE_HEADER = ["D"... | e_header | cih_message_header | d | e_message_header | f_message_header | u_message_header | message_header)
(separator parameter)*
"""
message_body = (message_header + parameters).setResultsName('message_body');
"""
message ::= message_body? eol
"""
message = Optional(message_body) + String... |
s-hertel/ansible | test/units/plugins/connection/test_ssh.py | Python | gpl-3.0 | 31,464 | 0.003564 | # -*- coding: utf-8 -*-
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (a... | )
self.assertEqual(unprocessed, b'')
self.assertFalse(conn._flags['become_prompt'])
self.assertTrue(conn._flags['become_success'])
self.assertFalse(conn._flags['become_error'])
self.assertFalse(conn._flags['become_nopasswd_error'])
# test examining outpu | t for become failure
conn._flags = dict(
become_prompt=False,
become_success=False,
become_error=False,
become_nopasswd_error=False,
)
pc.prompt = False
conn.become.prompt = False
pc.success_key = None
output, unprocessed =... |
mosquito/rest-client | setup.py | Python | mit | 1,043 | 0.000959 | #!/usr/bin/env python
# encoding: utf-8
from setuptools import setup, find_packages
import rest_client
import sys
requires = [
'tornado',
]
if sys.version_info < (3,):
requires.append('futures')
setup(
name='rest-client',
version=rest_client.__version__,
author=rest_client.__author__,
url=... | license="MIT",
description="RESTful Client for tornado",
platforms="all",
classifiers=[
'Environment :: Console',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.1',
'Programming Language :: Pyth... | anguage :: Python :: Implementation :: PyPy',
],
long_description=open('README.rst').read(),
packages=find_packages(exclude=['tests']),
install_requires=requires,
)
|
maggu/hack | tictactoe.py | Python | gpl-2.0 | 8,127 | 0.002461 | #!/usr/bin/env python3
# Copyright (C) 2019 C C Magnus Gustavsson
# Released under the GNU General Public License
"""Tic-tac-toe / noughts and crosses / Xs and Os using Pygame
Choose if each side is to be played by the computer or a human
"""
import pygame
import sys
from math import sqrt
from random import choic... | eep(0.5)
for priority in COUNT_PRIORITIES[player - 1]:
good = [r for r, c in zip(ROWS, counts) if c == priority]
if good:
diagonal = [r for r in good if r in DIAGONALS]
if diagonal:
row = choice(diagonal)
else:
row = choice(good)
... | = [s for s in squares if state[s] == 0]
if empty:
return choice(empty)
def game_over(state, keep_color):
"""Paint non-winning squares black"""
for square in [s for s in range(9) if not s in keep_color]:
draw_mark(state[square], square, color=BLACK, flip=False)
pygame.display.fl... |
shumik/skencil-c | Script/select_same_fill_color.py | Python | gpl-2.0 | 3,431 | 0.001457 | # Sketch - A Python-based interactive drawing program
# Copyright (C) 1999 by Bernhard Herzog
#
# 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; either
# version 2 of the License, or (at ... | properties object has three methods that indicate whether the
# fill-, line- or text properties are valid: HasFill(), HasLine()
# and HasFont(). Only if one of those methods returns true, can
# you safely access the respective properties. The properties are
# publicly readable attributes of ... | ct_same_fill_color(context):
doc = context.document
select = []
properties = doc.CurrentProperties()
if properties.HasFill():
color = properties.fill_pattern.Color()
layer = doc.ActiveLayer()
doc.SelectNone()
for obj in layer.GetObjects():
if obj.has_fill:
... |
matthewbauer/reddwall | setup.py | Python | mit | 447 | 0.004474 | #!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup
setup(name='ReddWall',
ve | rsion='0.2',
description='Get random wallpapers from Reddit',
author='Matthew Bauer',
author_email='mjbauer95@gmail.com',
url='http://github.com/matthewbauer/reddwall',
install_requires=['requests', 'beautifulsoup4', 'praw', 'wxpython'],
packages=['detools'],
| scripts=['reddwall.py'],
)
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/contrib/sessions/backends/cached_db.py | Python | bsd-3-clause | 1,823 | 0 | """
Cached, database-backed sessions.
"""
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import cache
KEY_PREFIX = "django.contrib.sessions.cached_db"
class SessionStore(DBStore):
"""
Implements cached, database backed sessions... | # Some backends (e.g. memcache) raise an exception on invalid
# cache keys. If this happens, reset the session. See #17810.
data = None
if data is None:
data = super(SessionStore, self).load()
cache.set(self.cache_key, data, setti | ngs.SESSION_COOKIE_AGE)
return data
def exists(self, session_key):
if (KEY_PREFIX + session_key) in cache:
return True
return super(SessionStore, self).exists(session_key)
def save(self, must_create=False):
super(SessionStore, self).save(must_create)
cache.s... |
socialplanning/opencore | opencore/interfaces/membership.py | Python | gpl-3.0 | 2,171 | 0.001382 | # @@ maybe these should go in a team.py
from zope.interface import Interface, Attribute
from zope.interface import implements
from Products.TeamSpace.interfaces.membership import ITeamMembership
class IOpenMembership(ITeamMembership):
"""
Interface provided by OpenMembership objects.
"""
class IMembershi... | ecified project.
"""
def removeInvitation(address, proj_id):
"""
Removes | the invitation registered for the specified email
address and project id.
Does nothing if the invitation doesn't exist.
"""
def removeAllInvitesForAddress(address):
"""
Removes registration of all invitations for the specified
email address.
Does nothing if... |
xuweiliang/Codelibrary | openstack_dashboard/dashboards/admin/volumes_back/cgroups/tables.py | Python | apache-2.0 | 6,186 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | xt_lazy as _
from horizon import exceptions
from horizon import tables
from ope | nstack_dashboard.api import cinder
from openstack_dashboard import policy
class CreateVolumeCGroup(policy.PolicyTargetMixin, tables.LinkAction):
name = "create"
verbose_name = _("Create Consistency Group")
url = "horizon:admin:volumes:cgroups:create"
classes = ("ajax-modal",)
icon = "plus"
pol... |
citruspi/Atlas | atlas/templating/template.py | Python | unlicense | 356 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from jinja2 import Template as Jinja2Template
from atlas.pr | oviders import providers
class Template(Jinja2Template):
def __init__(self, *args, **kwargs):
super(Template, self).__init__(*args, **kwargs)
for provider in providers:
| self.globals[provider] = providers[provider]
|
rollbar/pyrollbar | rollbar/contrib/django/utils.py | Python | mit | 122 | 0 | class MiddlewareMixin(object):
def __init__ | (self, get_response=None):
super(MiddlewareMixin, self).__init__( | )
|
francois-durand/svvamp | svvamp/rules/rule_condorcet_sum_defeats.py | Python | gpl-3.0 | 12,230 | 0.001145 | # -*- coding: utf-8 -*-
"""
Created on 4 dec. 2018, 16:00
Copyright François Durand 2014-2018
fradurand@gmail.com
This file is part of SVVAMP.
SVVAMP 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, e... | ||
|| || || ||
V V V | V
majority_favorite_c_ut_ctb (False) ==> majority_favorite_c_ut (True)
|| ||
V V
IgnMC_c_ctb (False) ==> IgnMC_c (True)
... |
jpardobl/naman | naman/core/pypelib/persistence/PersistenceEngine.py | Python | bsd-3-clause | 2,078 | 0.027911 | import os
import sys
import time
'''
@author: msune,omoya,CarolinaFernandez
@@organization: i2CAT, OFELIA FP7
Persistence engine
Implementes driver-based persistence backend selection
'''
class PersistenceEngine():
#Default Class Attributes
_defaultParser = "RegexParser"
_defaultPersistence = ... | icmethod
def save(obj, pBackend, parser=None, **kwargs):
| return PersistenceEngine._getDriver(pBackend).save(obj, parser, **kwargs)
@staticmethod
def load(tableName, pBackend, resolverMappings, parser=None, **kwargs):
return PersistenceEngine._getDriver(pBackend).load(tableName, resolverMappings, parser, **kwargs)
'''
Retrieves every Driver's PolicyRule... |
jonparrott/google-cloud-python | pubsub/google/cloud/pubsub_v1/gapic/publisher_client.py | Python | apache-2.0 | 40,328 | 0.001364 | # -*- coding: utf-8 -*-
#
# Copyright 2018 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... | ed credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constru | ctor.
kwargs: Additional arguments to pass to the constructor.
Returns:
PublisherClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(
filename)
kwargs['credentials'] = credentials
return cls(... |
remap/ndn-flow | framework/ndn_iot_python/examples/test_consuming.py | Python | lgpl-3.0 | 2,489 | 0.006027 | #!/usr/bin/python
from pyndn import Name, Interest, Data
from pyndn.util.memory_content_cache import MemoryContentCache
from pyndn.security import KeyChain
from pyndn.threadsafe_face import ThreadsafeFace
from ndn_iot_python.bootstrap.bootstrap import Bootstrap
import time
import sys
import json
import logging
try... | cio
class AppConsumer():
def __init__(self, face, certificateName, keyChain, dataPrefix):
self._keyChain = keyChain
self._defaultCertificateName = certificateName
self._fa | ce = face
self._dataPrefix = dataPrefix
return
def start(self):
interest = Interest(self._dataPrefix)
self._face.expressInterest(interest, self.onData, self.onTimeout)
print "Interest expressed " + interest.getName().toUri()
return
def onData(self, interest, dat... |
ptressel/sahana-eden-madpub | controllers/rms.py | Python | mit | 6,228 | 0.006904 | # -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Functions'... | [T("Requests"), False, URL(r=request, f="req"), [
[T("List"), False, URL(r=request, f="req")],
[T("Add"), False, URL(r=request, f="req", args="create")],
# @ToDo Sear | ch by priority, status, location
#[T("Search"), False, URL(r=request, f="req", args="search")],
]],
[T("All Requested Items"), False, URL(r=request, f="ritem")],
]
if session.rcvars:
if "hms_hospital" in session.rcvars:
hospital = db.hms_hospital
query = (hospital.id == session.rcvar... |
stygstra/keras-contrib | keras_contrib/layers/wrappers.py | Python | mit | 94 | 0 | from keras.engine | import Layer
from keras.engine import InputSpec
from .. imp | ort backend as K
|
rajul/tvb-framework | tvb/core/entities/transient/graph_structures.py | Python | gpl-2.0 | 11,862 | 0.005142 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web-UI helpful to run brain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http:/... | owing structure::
input_datatypes operation_parent
| |
| |
V V
[operation_parent] | [output_datatypes] * Currently Selected node
| |
| |
V V
output_datatypes in_operations
"""
input_datatypes = []
operation_parent = []
out... |
danielhanchen/sciblox | sciblox (v1)/sciblox.py | Python | mit | 74,277 | 0.041816 | #------------- Daniel Han-Chen 2017
#------------- https://github.com/danielhanchen/sciblox
#------------- SciBlox v0.02
#-------------
maxcats = 15
import warnings
warnings.filterwarnings("ignore")
true = True; TRUE = True
false = False; FALSE = False
import pip
def install(package): pip.main(['install', package])
#... | else:
if len(x) > n: return x[:n]
else: return x
def tail(x, n = 5):
if istable(x)==1: return x.tail(n)
else:
if len(x) > n: return x[-n: | ]
else: return x
#-----------------------------
def sample(x, n = 5, ordered = False):
if n > len(x): g = len(x)
else: g = n
if istable(x)==1:
if ordered == False: return x.sample(g)
else: return x.iloc[[int(y*(len(x)/g)) for y in range(g)]]
else:
if orde... |
bearstech/ansible | lib/ansible/modules/database/proxysql/proxysql_global_variables.py | Python | gpl-3.0 | 9,148 | 0.000656 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: proxysql_global_variables
... | iable, cursor)
manage_config(variable,
save_to_disk,
load_to_runtime,
| cursor,
|
vienin/vlaunch | tools/createvm.py | Python | gpl-2.0 | 5,196 | 0.013857 | #!/usr/bin/env python
# UFO-launcher - A multi-platform virtual machine launcher for the UFO OS
#
# Copyright (c) 2008-2009 Agorabox, Inc.
#
# This 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... | ge setextradata global "GUI/Input/AutoCapture" "true"')
os.system('VBoxManage setextradata global "GUI/SuppressMessages" ",remindAboutAutoCapture,confirmInputCapture,remindAboutMouseIntegrationOn,remindAboutMouseIntegrationOff,remindAboutInaccessibleMedia,remindAboutWrongColorDepth,confirmGoingFullscreen"')
os.system('... | Manage setextradata global "GUI/UpdateCheckCount" "2"')
os.system('VBoxManage setextradata global "GUI/UpdateDate" "never"')
# setting virtual machine extradatas
os.system('VBoxManage setextradata ' + options.vm + ' "GUI/SaveMountedAtRuntime" "false"')
os.system('VBoxManage setextradata ' + options.vm + ' "GUI/Fullscr... |
tdickers/mitmproxy | mitmproxy/console/grideditor.py | Python | mit | 19,995 | 0.002001 | from __future__ import absolute_import, print_function, division
import copy
import os
import re
import urwid
from mitmproxy import filt
from mitmproxy import script
from mitmproxy import utils
from mitmproxy.console import common
from mitmproxy.console import signals
from netlib.http import cookies
from netlib.http... | g, subeditor):
self.heading = heading
self.subeditor = subeditor
def text(self, obj):
p = cookies._format_pairs(obj, sep="\n")
| return urwid.Text(p)
def blank(self):
return []
def keypress(self, key, editor):
if key in "rRe":
signals.status_message.send(
self,
message = "Press enter to edit this field.",
expire = 1000
)
return
e... |
aakechin/BRCA-analyzer | install.py | Python | gpl-3.0 | 2,506 | 0.034318 | # This script configurates BRCA-analyzer
import argparse,os
import subprocess as sp
thisDir=os.path.dirname(os.path.realpath(__file__))+'/'
par=argparse.ArgumentParser(description='This script configures BRCA-analyzer')
par.add_argument('--bwa','-bwa',dest='bwaDir',type=str,help='destination of BWA. If it can be sta... | arDir+='/'
if args.cutprimersDir and args.cutprimersDir[-1]!='/':
args.cutprimersDir+='/'
file=open(thisDir+'config.txt','w')
##file.write('\n'.join([args | .bwaDir,args.samDir,args.bcfDir,args.picardDir,args.gatkDir,args.snpeffDir,args.annovarDir]))
file.write('\n'.join([args.bwaDir,args.samDir,args.picardDir,args.gatkDir,args.snpeffDir,args.annovarDir,args.cutprimersDir]))
file.close()
|
schleichdi2/OpenNfr_E2_Gui-6.0 | lib/python/Screens/EpgSelection.py | Python | gpl-2.0 | 58,072 | 0.026708 | from time import localtime, time, strftime, mktime
from enigma import eServiceReference, eTimer, eServiceCenter, ePoint
from Screen import Screen
from Screens.HelpMenu import HelpableScreen
from Components.About import about
from Components.ActionMap import HelpableActionMap, HelpableNumberActionMap
from Components.B... | lf
self['epgcursoractions'] = HelpableActionMap(self, 'DirectionActions',
{
'left': (self.prevService, _('Goto previous channel')),
'right': (self.nextService, _('Goto next channel')),
| 'up': (self.moveUp, _('Goto previous channel')),
'down': (self.moveDown, _('Goto next channel'))
}, -1)
self['epgcursoractions'].csel = self
elif self.type == EPG_TYPE_ENHANCED:
self['epgactions'] = HelpableActionMap(self, 'EPGSelectActions',
{
'nextBouquet': (self.nextBouquet, _('Got... |
SELO77/seloPython | 3.X/ex/timeEx.py | Python | mit | 198 | 0.030303 | from time | import time
timeShow = time()
print(timeShow)
print(type(range(0,5)))
# for item in range(0,5):
# print(item)
for index,item in enumerate(range(0,5)):
print(index)
print(item)
| |
LovingYoung/xdom-mn | xdommn/data.py | Python | mit | 1,135 | 0.000881 | class SingletonType(type):
def __call__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(SingletonType, cls).__call__(
*args, **kwargs)
return cls.__instance
class Data(object):
__metaclass__ = S... | controlle | rs=None):
if controllers is not None:
self.controllers = controllers
else:
self.controllers = dict()
self.name_map = dict()
self.reverse_name_map = dict()
self.name_map_index = 1
def getNextName(self, node_name, prefix):
name = "%s%d" % (prefi... |
hasura/quickstart-docker-git | python-flask/app/conf/gunicorn_config.py | Python | mit | 275 | 0.003636 | impo | rt os
import multiprocessing
bind = "0.0.0.0:8080"
workers = (multiprocessing.cpu_count() * 2) + 1
accesslog = "-"
access_log_format = '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'
loglevel = "debug"
capture_output = True
enable_stdio_inheritan | ce = True
|
lucienfostier/gaffer | python/GafferUI/ScrolledContainer.py | Python | bsd-3-clause | 5,893 | 0.034787 | ##########################################################################
#
# Copyright (c) 2011, John Haddon. All rights reserved.
# Copyright (c) 2011-2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... | talScrollBarPolicy( GafferUI.ScrollMode._toQt( mode ) )
def getHorizontalMode( self ) :
p = self._qtWidget().horizontalScrollBarPolicy()
return GafferUI.ScrollMode._fromQt( p[0] )
def setVerticalMode( self, mode ) :
self._qtWidget().setVerticalScrollBarP | olicy( GafferUI.ScrollMode._toQt( mode ) )
def getVerticalMode( self ) :
p = self._qtWidget().verticalScrollBarPolicy()
return GafferUI.ScrollMode._fromQt( p[1] )
def _revealDescendant( self, descendant ) :
self._qtWidget().ensureWidgetVisible( descendant._qtWidget() )
# Private implementation - a QScrollA... |
igemsoftware/SYSU-Software2013 | project/Python27_32/web/encrypt.py | Python | mit | 2,590 | 0.028958 | #coding=utf-8
##
# @file encrypt.py
# @brief tools for encrypting
# @author Jiexin Guo
# @version 1.0
# @date 2013-07-28
# @copyright 2013 SYSU-Software. All rights reserved.
# This project is released under MIT License.
import rsa
import os,sys
import binascii
import hashlib
base = [str(x) for x in range(10)] + [ ch... | ide RSA method
# ----------------------------------------------------------------------------
class Encrypt:
def __init__ (self):
(pub_key, priv_key) = rsa.newkeys(1024)
self.publicKey=pub_key
self.privateKey=priv_key
# ---------- | ----------------------------------------------------------------
##
# @brief get the public key
#
# @param self
#
# @returns return the public key
#
# --------------------------------------------------------------------------
def getPublicKey(self):
return self.publicKey
# ----------------------------... |
ahaym/eden | languages/km.py | Python | mit | 359,695 | 0.019014 | # -*- coding: utf-8 -*-
{
"A location that specifies the geographic area for this region. This can be a location from the location hierarchy, or a 'group location', or a location that has a boundary for the area.": "ទីតាំងដែលបញ្ជាក់ផ្ទៃភូមិសាស្ត្រសម្រាប់តំបន់នេះ ។ វាអាចជាទីតាំងមកពីឋានានុក្រមទីតាំង ឬ 'ក្រុមទ... | ន្ថែមសហគមន៍ថ្មីដោយចុចលើតំណ 'បន្ថែមសហគមន៍' ។",
"If you don't see the location in the list, you can add a new one by clicking link 'Create Location'.": "ប្រសិនបើអ្នកមិនឃើញទីតាំងនៅក្នុងបញ្ជីនេះទេ អ្នកអាចបន្ថែមប | ញ្ជីថ្មីដោយចុចលើតំណ 'បន្ថែមទីតាំង' ។",
"If you don't see the milestone in the list, you can add a new one by clicking link 'Create Milestone'.": "ប្រសិនបើអ្នកមិនឃើញគោលវាស់វែងនៅក្នុងបញ្ជីនេះទេ អ្នកអាចបន្ថែមគោលវាស់វែងថ្មីដោយចុចលើតំណ 'បន្ថែមគោលវាស់វែង' ។",
"If you don't see the project in the list, you ... |
Oisota/Breakout | setup.py | Python | gpl-3.0 | 2,098 | 0.029075 | """
Setup Module
This module is used to make a distribution of
the game using distutils.
"""
from distutils.core import setup
setup(
name = 'Breakout',
version = '1.0',
description = 'A remake of the classic video game',
author = 'Derek Morey',
author_email = 'dman... | Pygame',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'License :: OSI Appr | oved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Games/Entertainment',
'Topic :: Games/Entertainment :: Arcade'],
long_description =
"""
Breakout
--------
Th... |
WayneDW/Sentiment-Analysis-in-Event-Driven-Stock-Price-Movement-Prediction | archived/preprocessing_v2.py | Python | mit | 8,714 | 0.009066 | #!/usr/bin/python
import os
import en
import nltk
import json
import numpy as np
import operator
import datetime
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import reuters
from keras.preprocessing import sequence
from crawler_reuters import news_Reuters
# def gen_financial_top_words(... | oad(data_file)
# step 2, build feature matrix for training data
loc = './input/'
input_files = [f for f in | os.listdir(loc) if f.startswith('news_reuters.csv')]
word2idx = {'START': 0, 'END': 1}
idx2word = ['START', 'END']
current_idx = 2
word_idx_cnt = {0: float('inf'), 1: float('inf')}
dp = {} # only consider one news for a company everyday
cnt = 0
testDates = dateGenerator(100)
stopWords = ... |
lms-io/lms | src/user.py | Python | mit | 2,311 | 0.028992 | from bottle import route,request
from cassandra.cluster import Cluster
import uuid, collections, traceback, redis, thread, bcrypt, configparser, requests, sys, jsonpickle, random, os, zipfile, shutil, appcontext, permission
config = configparser.ConfigParser()
config.read('config. | ini')
def redis():
return appcontext.redis()
def db():
return appcontext.db()
def exists(username, password):
usr = appcontext.db().execute('SELECT username, password, organization_uid from user_by_organization where username=%s', (username,)) | [0]
match = usr.password == bcrypt.hashpw(password.encode('utf-8'), usr.password.encode('utf-8'))
if match:
return usr.organization_uid
return None
def create(organization_uid, username, password, firstName="", lastName=""):
ins = "INSERT INTO user_by_organization (organization_uid, username, password) VA... |
MRN-Code/pl2mind | tools/rois.py | Python | gpl-2.0 | 11,580 | 0.008031 | """
This module is designed for using afni to find regions of interest from a nifti file.
"""
__author__ = "Devon Hjelm"
__copyright__ = "Copyright 2014, Mind Research Network"
__credits__ = ["Devon Hjelm"]
__licence__ = "3-clause BSD"
__email__ = "dhjelm@mrn.org"
__maintainer__ = "Devon Hjelm"
import argparse
import... |
cm = tuple([cs[x] for x in [1, 2, 3]])
coords = tuple([cs[x] for x in [7, 8, 9]])
rois = find_region_names(coords)
# grey_value = check_grey(coords)
| cluster_dict[c] = dict(
coords = coords,
volume = cs[0],
cm = |
Geoportail-Luxembourg/qgis-pag-plugin | resources.py | Python | mit | 78,761 | 0.000063 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created: mer. 14. sept. 10:51:53 2016
# by: The Resource Compiler for PyQt (Qt v4.8.5)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x07\xea\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x... | \x61\x70\x2f\x31\x2e\x30\x2f\
\x6d\x6d\x2f\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x73\x74\x52\x65\x66\
\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x6e\x73\x2e\x61\x64\x6f\x62\
\x65\x2e\x63\x6f\x6d\x2f\x78\x61\x70\x2f\x31\x2e\x30\x2f\x73\x54\
\x7 | 9\x70\x65\x2f\x52\x65\x73\x6f\x75\x72\x63\x65\x52\x65\x66\x23\
\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6d\x70\x3d\x22\x68\x74\x74\
\x70\x3a\x2f\x2f\x6e\x73\x2e\x61\x64\x6f\x62\x65\x2e\x63\x6f\x6d\
\x2f\x78\x61\x70\x2f\x31\x2e\x30\x2f\x22\x20\x78\x6d\x70\x4d\x4d\
\x3a\x4f\x72\x69\x67\x69\x6e\x61\x6c\x44\x6f\x63\x75\x6d\x6... |
Mhynlo/SickRage | sickbeard/webapi.py | Python | gpl-3.0 | 114,568 | 0.002889 | # coding=utf-8
# Author: Dennis Lutter <lad1337@gmail.com>
# Author: Jonathon Saine <thezoggy@gmail.com>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | e, sort_keys=True)
callback = self.get_query_argument('callback', None) or self.get_query_argument('jsonp', None)
if callback:
out = callback + '(' + out + ');' # wrap with | JSONP call if requested
except Exception as e: # if we fail to generate the output fake an error
logger.log(u"API :: " + traceback.format_exc(), logger.DEBUG)
out = '{{"result": "{0}", "message": "error while composing output: {1}"}}'.format(result_type_map[RESULT_ERROR], ex(e))
... |
faush01/MBCon | default.py | Python | gpl-2.0 | 296 | 0 | # Gnu General Public License - see LICENSE.TXT
from resources.lib.simple_logging import SimpleLogging
from resources.lib.functi | ons import mainEntryPoint
log = SimpleLogging('default')
log.debug("About to enter mainEntryPoint()")
mainEntryPoint()
| # clear done and exit.
# sys.modules.clear()
|
subeax/grab | test/case/spider_task.py | Python | mit | 8,629 | 0.011589 | from unittest import TestCase
#try:
# import cPickle as pickle
#except ImportError:
# import pickle
import grab.spider.base
from grab import Grab
from grab.spider import Spider, Task, Data, SpiderMisuseError, NoTaskHandler
from test.server import SERVER
class SimpleSpider(Spider):
base_url = 'http://google... | RVER.BASE_URL, callback=func))
bot.run()
self.assertEqual(['0_handler', '1_func', '1_func', '1_func'],
sorted(tokens))
#def test_task_callback_serialization(self): |
# 8-(
# FIX: pickling the spider instance completely does not work
# 8-(
#class FuncWithState(object):
#def __init__(self, tokens):
#self.tokens = tokens
#def __call__(self, grab, task):
#self.tokens.append('func')
#toke... |
gagneurlab/concise | docs/autogen.py | Python | mit | 12,495 | 0.00032 | # -*- coding: utf-8 -*-
'''
General documentation architecture:
Home
Index
- Getting started
Getting started to concise
Layers
- Preprocessing
Genomic Sequence Preprocessing
RNA Structure Preprocessing
Spline-position Preprocessing
- Data
Encode
Attract
Losses
Metrics
Eval metrics
Optimizer... | def | process_function_docstring(docstring):
docstring = re.sub(r'\n # (.*)\n',
r'\n __\1__\n\n',
docstring)
docstring = re.sub(r'\n # (.*)\n',
r'\n __\1__\n\n',
docstring)
docstring = re.sub(r' ([... |
maseaver/todomaker | todomaker.py | Python | mit | 13,220 | 0.004992 | import sys
import json
from tkinter import filedialog
def getFiles(failedargs):
newfiles = []
if failedargs:
if failedargs == -1:
answer = input("""\
You didn't specify any files as input, would you like to continue? y/n
>""")
if answer in ["n", ""]:
raise S... | t is
unsuccessful, you can either try again, do it fr | om scratch, or quit the script.
> """.format(file, default))
if answer not in ["y", "Y", "n", "N", "d", "D", "s", "S"]:
answer = "n"
print("Didn't get that, so I'll assume \"no.\"")
formatList.append(default)
elif answer in "yY":
wh... |
tchx84/social-sugar | extensions/web/twitter/twitter/twr_status.py | Python | gpl-2.0 | 7,122 | 0.009267 | #!/usr/bin/env python
#
# Copyright (c) 2013 Martin Abente Lahaye. - tch@sugarlabs.org
#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 the righ... | ed_cb, completed_data)
object.connect('transfer-failed', failed_cb, failed_data)
object.request('POST', url, params, filepath)
def __completed_cb(self, object, data, signal):
try:
info = json.loads(data)
if 'err | ors' in info.keys():
raise twr_error.TwrStatusError(str(info['errors']))
if self._status_id is None and 'id_str' in info.keys():
self._status_id = str(info['id_str'])
self.emit(signal, info)
except Exception, e:
print '__completed_cb crashed ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.