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 |
|---|---|---|---|---|---|---|---|---|
RexFuzzle/sfepy | sfepy/terms/terms_basic.py | Python | bsd-3-clause | 12,864 | 0.003887 | import numpy as nm
from sfepy.base.base import assert_
from sfepy.linalg import dot_sequences
from sfepy.terms.terms import Term, terms
class IntegrateVolumeTerm(Term):
r"""
Evaluate (weighted) variable in a volume region.
Depending on evaluation mode, integrate a variable over a volume region
('eval... | finition:
.. math::
\int_\Gamma y \mbox{ , } \int_\Gamma \ul{y}
\mbox{ , } \int_\Gamma \ul{y} \cdot \ul{n} \\
\int_\Gamma c y \mbox{ , } \int_\Gamma c \ul{y}
\mbox{ , } \int_\Gamma c \ul{y} \cdot \ul{n} \mbox{ flux }
.. math::
\mbox{vector for } K \from \Ical_h:
... | nt_{T_K} 1 \\
\mbox{vector for } K \from \Ical_h:
\int_{T_K} c y / \int_{T_K} 1 \mbox{ , }
\int_{T_K} c \ul{y} / \int_{T_K} 1 \mbox{ , }
\int_{T_K} (c \ul{y} \cdot \ul{n}) / \int_{T_K} 1
.. math::
y|_{qp} \mbox{ , } \ul{y}|_{qp}
\mbox{ , } (\ul{y} \cdot \ul{n})|_{qp}... |
saltstack/salt | tests/unit/test_fileserver.py | Python | apache-2.0 | 2,610 | 0.000766 | """
:codeauthor: Joao Mesquita <jmesquita@sangoma.com>
"""
import datetime
import os
import time
import salt.utils.files
from salt import fileserve | r
from tests.support.helpers import with_tempdir
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase
class MapDiffTestCase(TestCase):
def test_diff_with_diffent_keys(self):
"""
Test that different maps are indeed reported different
"""
map... | = {"file1": 1234}
map2 = {"file2": 1234}
assert fileserver.diff_mtime_map(map1, map2) is True
def test_diff_with_diffent_values(self):
"""
Test that different maps are indeed reported different
"""
map1 = {"file1": 12345}
map2 = {"file1": 1234}
asser... |
rosegun38/LintCode | Two_Strings_Are_Anagrams/Solution.py | Python | gpl-3.0 | 307 | 0 | class Solution:
"""
@param s: The first string
@param b: The second string
@return true or false
"""
# Time: is equal to sorted O(nlogn)
# Space: O(1)
def anagram(self, s, t):
# write y | our code here
| s = sorted(s)
t = sorted(t)
return s == t
|
yaolei313/python-study | base/test.py | Python | gpl-2.0 | 365 | 0.00554 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
sql_template0 = " | ""alter table _shadow_orders_{0}_ modify fingerprint text DEFAULT '' COMMENT '下单fingerprint';"" | "
if __name__ == '__main__':
for index in range(0, 50):
print(sql_template0.format(index))
print("------")
for index in range(50, 100):
print(sql_template0.format(index)) |
SublimeText/VintageEx | plat/__init__.py | Python | mit | 109 | 0 | import subl | ime
HOST_PLATFORM = sublime.platform()
WINDOWS = 'windows'
LINUX = 'linux'
OSX = 'osx' | |
camradal/ansible | lib/ansible/module_utils/lxd.py | Python | gpl-3.0 | 6,180 | 0.004045 | # -*- coding: utf-8 -*-
# (c) 2016, Hiroaki Nakamura <hnakamur@gmail.com>
#
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to th... | imeout=timeout)
if resp_json['type'] == 'async':
url = '{0}/wait'.format(resp_json['operation'])
resp_json = self._send_request('GET', url)
if resp_json['metadata']['status'] != 'Success':
| self._raise_err_from_json(resp_json)
return resp_json
def authenticate(self, trust_password):
body_json = {'type': 'client', 'password': trust_password}
return self._send_request('POST', '/1.0/certificates', body_json=body_json)
def _send_request(self, method, url, body_json=None, ... |
htimko/ArcPIC | pic2d/tests/rngtestAna.py | Python | gpl-3.0 | 571 | 0.019264 | #!/usr/bin/env python
import matplotlib.pyplot a | s plt
import os
import math as m
import numpy as np
def Gaus(v,mu,sigma):
"Gaus | sian distribution"
return np.exp(-0.5*((v-mu)/sigma)**2)/(sigma*m.sqrt(2*m.pi))
mu = 0.5;
sigma = 1.5;
print "reading file..."
gausFile = open("gausRandom.out", 'r')
gausNums = map(float,gausFile.read().split())
gausFile.close()
gausBins = np.linspace(mu-5*sigma, mu+5*sigma);
gausPoints = gausBins[:-1] - np.diff... |
BechtelCIRT/pivoteer | pivoteer/__init__.py | Python | mit | 74 | 0 | from | pivoteer import *
from pivotEngine import *
from pivotUtils import *
| |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/application_gateway_backend_address_pool.py | Python | mit | 2,589 | 0.001545 | # 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 ... | e type: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguratio | n]'},
'backend_addresses': {'key': 'properties.backendAddresses', 'type': '[ApplicationGatewayBackendAddress]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {... |
matt-jordan/mjmud | lib/transports/ws_receiver.py | Python | mit | 1,886 | 0 | #
# mjmud - The neverending MUD project
#
# Copyright (c) 2014, Matt Jordan
#
# See https://github.com/matt-jordan/mjmud for more information about the
# project. Please do not contact the maintainers of the project for information
# or assistance. The project uses Github for these purposes.
#
# This program is free so... | -- the peer that connected
"""
def on_closed(protocol, was_clean, code, reason):
"""Called when a connection is closed
Keyword Arguments:
protocol -- the websocket protocol that dis | connected
was_clean -- true if the handshake occurred; false otherwise
code -- numeric code describing the disconnection
reason -- why the disconnection occurred
"""
class IWebSocketClientReceiver(Interface):
def on_connection_failed(protocol, connector, reason):
"... |
nriley/NewsBlur | apps/rss_feeds/views.py | Python | mit | 21,500 | 0.005302 | import datetime
from urlparse import urlparse
from utils import log as logging
from django.shortcuts import get_object_or_404, render_to_response
from django.views.decorators.http import condition
from django.http import HttpResponseForbidden, HttpResponseRedirect, HttpResponse, Http404
from django.conf import settings... | if feed.is_push:
try:
stats['push_expires'] = localtime_for_timezone(feed.push.lease_expires,
| timezone).strftime("%Y-%m-%d %H:%M:%S")
except PushSubscription.DoesNotExist:
stats['push_expires'] = 'Missing push'
feed.is_push = False
feed.save()
# Minutes between updates
update_interval_minutes = feed.get_next_scheduled_update(force=True, verbose=False)
... |
ScholarTools/pypub | pypub/entry_functions.py | Python | mit | 1,300 | 0.009231 | import pypub.publishers.pub_resolve as pub_r | esolve
from pypub.paper_info import PaperInfo
def get_paper_info(doi=None, url=None):
"""
Parameters
----------
doi :
url :
Returns
-------
Errors
------
UnsupportedPublisherError : Retriev | al of information from this publisher is not yet available
"""
if doi is not None:
publisher = pub_resolve.publisher_from_doi(doi)
paper_info = publisher.get_paper_info(doi=doi)
elif url is not None:
publisher = pub_resolve.publisher_from_url(url)
paper_info = publisher... |
bouk/redshift_sqlalchemy | redshift_sqlalchemy/dialect.py | Python | mit | 34,694 | 0.000461 | from collections import defaultdict
import numbers
import pkg_resources
import re
import sqlalchemy as sa
from sqlalchemy import schema, exc, inspect, Column
from sqlalchemy.dialects.postgresql.base import PGDDLCompiler, PGCompiler
from sqlalchemy.dialects.postgresql.psycopg2 import PGDialect_psycopg2
from sqlalchemy.... | (key):
if '.' not in key:
return (None, key)
identifiers = SQL_IDENTIFIER_RE.findall(key)
if len(identifiers) == 1:
return (None, key)
elif len(identifiers) == 2:
return identifiers
raise ValueError("%s does not look like a valid relation identifier")
def unquoted(key):
... | y* with one level of double quotes removed.
Redshift stores some identifiers without quotes in internal tables,
even though the name must be quoted elsewhere.
In particular, this happens for tables named as a keyword.
"""
if key.startswith('"') and key.endswith('"'):
return key[1:-1]
re... |
ppiotr/Bibedit-some-refactoring | modules/webjournal/lib/widgets/bfe_webjournal_widget_latestPhoto.py | Python | gpl-2.0 | 3,928 | 0.005855 | # -*- coding: utf-8 -*-
##
## This file is part of CDS Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN.
##
## CDS Invenio 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 versio... | oundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
WebJournal widget - display photos from given collections
"""
from invenio.bibformat_engine import BibFormatObject
from invenio.search_engine import perform_request_search
from inven | io.config import CFG_CERN_SITE, CFG_SITE_URL
def format(bfo, collections, max_photos="3", separator="<br/>"):
"""
Display the latest pictures from the given collection(s)
@param collections: comma-separated list of collection form which photos have to be fetched
@param max_photos: maximum number of ph... |
TheMasterGhost/CorpBot | Cogs/Time.py | Python | mit | 8,457 | 0.03299 | import asyncio
import discord
import datetime
import pytz
from discord.ext import commands
from Cogs import FuzzySearch
from Cogs import Settings
from Cogs import DisplayName
from Cogs import Message
from Cogs import Nullify
class Time:
# Init with the bot reference, and a reference to the s... | = member
member = DisplayName.memberForName(memberName, ctx.message.guild)
if not member:
msg = 'Couldn\'t find user *{}*.'.format(memberName)
| # Check for suppress
if suppress:
msg = Nullify.clean(msg)
await ctx.channel.send(msg)
return
# We got one
timezone = self.settings.getGlobalUserStat(member, "TimeZone")
if timezone == None:
msg = '*{}* hasn\'t set their TimeZone yet - they can do so with the `{}settz [Region/City... |
donspaulding/adspygoogle | examples/adspygoogle/dfp/v201302/inventory_service/get_ad_unit_hierarchy.py | Python | apache-2.0 | 3,490 | 0.010029 | #!/usr/bin/python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | root_ad_unit: dict the root ad unit to build the tree under.
all_ad_units: list the list of all ad units to build the tree with.
"""
tree = {}
for ad_unit in all_ad_units:
if 'parentId' in ad_unit:
if ad_unit['parentId'] not in tree:
tree[ad_unit['parentId']] = []
tree[ad_unit['pare... | dfp_client = DfpClient(path=os.path.join('..', '..', '..', '..', '..'))
main(dfp_client)
|
apache/incubator-airflow | tests/providers/google/cloud/hooks/test_vision.py | Python | apache-2.0 | 38,031 | 0.003523 | #
# 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, Version 2.0 (the
# "License"); you may not... | ': [{'type': enums.Feature.Type.LOGO_DETECTION}],
}
BATCH_ANNOTATE_IMAGE_REQUEST = [
{
'image': {'source': {'image_uri': "gs://bucket-name/object-name"}},
'features': [{'type': enums.Feature.Type.LOGO_DETECTION}],
},
{
'image': {'source': {'image_uri': "gs://bucket-name/object-name"}... | ms.Feature.Type.LOGO_DETECTION}],
},
]
REFERENCE_IMAGE_NAME_TEST = (
f"projects/{PROJECT_ID_TEST}/locations/{LOC_ID_TEST}/products/"
f"{PRODUCTSET_ID_TEST}/referenceImages/{REFERENCE_IMAGE_ID_TEST}"
)
REFERENCE_IMAGE_TEST = ReferenceImage(name=REFERENCE_IMAGE_GEN_ID_TEST)
REFERENCE_IMAGE_WITHOUT_ID_NAME = R... |
JoyTeam/metagam3d | python/metagam3d/objects.py | Python | lgpl-3.0 | 3,360 | 0.004762 | im | port _metagam3d
from _metagam3d import AxisAlignment, AlignmentType
from metagam3d.channels import blocking
from metagam3d.scripts import m3d_expr
from concurrence import Tasklet
class LoadError(Exception):
pass
class Object(_metagam3d.Object):
def __init__(self, objid):
_metagam3d.Object | .__init__(self, objid)
self._params = {}
def param(self, paramid):
"Get parameter object for given parameter id"
try:
return self._params[paramid]
except KeyError:
pass
param = ObjectParam(self, paramid)
self._params[paramid] = param
r... |
danithaca/berrypicking | django/advanced/crop/migrations/0002_auto_20150123_1831.py | Python | gpl-2.0 | 628 | 0.001592 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('crop', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile... | d=False, allow_fullsize=False),
preserve_default=True,
| ),
]
|
mediaburst/clockwork-python | tests/clockwork_tests.py | Python | mit | 3,369 | 0.004808 | # -*- coding: utf-8 -*-
import unittest
from clockwork import clockwork
from clockwork import clockwork_exceptions
class ApiTests(unittest.TestCase):
api_key = "YOUR_API_KEY_HERE"
def test_should_send_single_message(self):
"""Sending a single SMS with the minimum detail and no errors should work"""
... | 'pqrstuvwxyzäöñüà'''
u'''€[\]^{|}~'''
,long=True)
response = api.send(sms)
self.assertTrue(response.success)
def test_should_fail_with_no_message(self):
"""Sending a single SMS with no message should fail"""
api = clockwork.API(self.api_key)
s... | test_should_fail_with_no_to(self):
"""Sending a single SMS with no message should fail"""
api = clockwork.API(self.api_key)
sms = clockwork.SMS(to="", message="This is a test message")
response = api.send(sms)
self.assertFalse(response.success)
def test_should_send_multiple_... |
jinzekid/codehub | python/数据分析/func_lambda_test.py | Python | gpl-3.0 | 150 | 0.02 | from math import log
def make_logarithmic_function(base):
return lambda x: log(x, b | ase)
My_LF = make_logarithmic_function(3)
print(My_LF(9))
| |
extsui/7SegFinger | test_8digit.py | Python | mit | 4,304 | 0.035431 | # -*- coding: utf-8 -*-
import spidev
import math
def reverse_bit_order(x):
x_reversed = 0x00
if (x & 0x80):
x_reversed |= 0x01
if (x & 0x40):
x_reversed |= 0x02
if (x & 0x20):
x_reversed |= 0x04
if (x & 0x10):
x_reversed |= 0x08
if (x & 0x08):
x_reversed |= 0x10
if (x & 0x04):
x_... | 要がある。
# [参考URL] http://tightdev.net/Spi | Dev_Doc.pdf
#
xfer_data = map(reverse_bit_order, xfer_data)
print xfer_data
# フレーム送信
spi.writebytes(xfer_data)
import os
os.system('sleep 1')
num_to_pattern = [
0xfc, # 0
0x60, # 1
0xda, # 2
0xf2, # 3
0x66, # 4
0xb6, # 5
0xbe, # 6
0xe4, # 7
0xfe, # 8
0xf6, # 9
]
rad = 0.0
... |
vlegoff/tsunami | src/secondaires/navigation/equipage/controle.py | Python | bsd-3-clause | 5,105 | 0.001191 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | contrôles actifs sur le même navire, l'un |
de type 'vitesse' précisant que le navire doit aller à 1,7 noeuds
et l'autre de type 'direction' précisant que le navire doit maintenir
ce cap.
"""
cle = None
logger = type(importeur).man_logs.get_logger("ordres")
def __init__(self, equipage, *args):
BaseObj.__init__(self)
... |
TL4/deploy | run.py | Python | mit | 92 | 0.032609 | # coding: utf-8
from deploy import app
if | __name__ == '__main__':
ap | p.run(debug = True) |
winstonf88/pyjobs | pyjobs/app.py | Python | gpl-2.0 | 750 | 0.001333 | import logging
import os
import sys
from tornado import | ioloop
from tornado import web
from pyjobs import handlers
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger(__name__)
STATIC_PATH = os.path.join(os.path.dirname(__file__), 'static/')
url_patterns = [
web.url('/', handlers.HomeHandler, name='home'),
web.url('/ws', han | dlers.WebSocketHandler),
web.url('/static/(.*)', web.StaticFileHandler, {'path': STATIC_PATH}),
]
settings = {
'compiled_template_cache': False,
}
def server():
logger.info('Serving on port 8888')
application = web.Application(url_patterns, **settings)
application.listen(8888)
ioloop.IOLoop.c... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_08_01/aio/operations/_network_interfaces_operations.py | Python | mit | 72,800 | 0.004973 | # 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 ... | source_group_name: The name of the re | source group.
:type resource_group_name: str
:param network_interface_name: The name of the network interface.
:type network_interface_name: str
:param expand: Expands referenced resources.
:type expand: str
:keyword callable cls |
ARM-software/CMSIS_5 | CMSIS/DSP/cmsisdsp/sdf/nodes/host/message.py | Python | apache-2.0 | 3,886 | 0.022131 | # --------------------------------------------------------------------------
# Copyright (c) 2020-2022 Arm Limited (or its affiliates). All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the License); you may
# not use this file except in compliance with t... | o_bytes(l):
return(b"".join([x.to_bytes(INTSIZE,byteorder=sys.byteorder,signed=True) for x in l]))
# Convert a bytestream to a list | of Q15
def bytes_to_list(l):
res=[]
i = 0
while(i<len(l)):
res.append(int.from_bytes(l[i:i+INTSIZE],byteorder=sys.byteorder,signed=True))
i = i+INTSIZE
return(res)
# Send a list of Q15
def sendIntList(conn,l):
data = list_to_bytes(l)
sendBytes(conn,data)
# Receive a list of Q... |
darren-rogan/CouchPotatoServer | libs/flask/views.py | Python | gpl-3.0 | 5,629 | 0 | # -*- coding: utf-8 -*-
"""
flask.views
~~~~~~~~~~~
This module provides class-based views inspired by the ones in Django.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from .globals import request
http_method_funcs = frozenset(['get', 'post', 'head', '... | ot introduce new methods).
if methods:
rv.methods = sorted(methods)
return rv
class MethodView(View):
"""Like a regular class-based view but that dispatches requests to
particular methods. For instance if you implement a method called
:meth:`get` it means you will resp... | se to ``'GET'`` requests and
the :meth:`dispatch_request` implementation will automatically
forward your request to that. Also :attr:`options` is set for you
automatically::
class CounterAPI(MethodView):
def get(self):
return session.get('counter', 0)
def ... |
driftyco/ionitron-issues | tests/test_close_old_issue.py | Python | mit | 3,578 | 0.006149 | # python -m unittest discover
import unittest
from datetime import datetime
from tasks import old_issues as c
class TestCloseOldIssue(unittest.TestCase):
def test_is_closed_issue(self):
self.assertEquals(c.is_closed({'closed_at': None}), False)
self.assertEquals(c.is_closed({'closed_at': "2014-1... | ing_close(None), False)
self.assertEquals(c.has_events_preventing_close([
{ 'event': 'c | losed' },
{ 'event': 'labeled' }
]), False)
self.assertEquals(c.has_events_preventing_close([
{ 'event': 'closed' },
{ 'event': 'referenced' }
]), True)
|
zfrenchee/pandas | asv_bench/benchmarks/offset.py | Python | bsd-3-clause | 3,276 | 0 | # -*- coding: utf-8 -*-
from datetime import datetime
import numpy as np
import pandas as pd
try:
import pandas.tseries.holiday # noqa
except ImportError:
pass
hcal = pd.tseries.holiday.USFederalHolidayCalendar()
# These offests currently raise a NotImplimentedError with .apply_index()
non_apply = [pd.offset... | fset']
def setup(self, offset):
N = 1000
self.data = pd.date_range(start='1/1/2000', periods=N, freq=' | T')
def time_add_offset(self, offset):
self.data + offset
class OffestDatetimeArithmetic(object):
goal_time = 0.2
params = offsets
param_names = ['offset']
def setup(self, offset):
self.date = datetime(2011, 1, 1)
self.dt64 = np.datetime64('2011-01-01 09:00Z')
def t... |
pebble/spacel-provision | src/spacel/provision/app/db/base.py | Python | mit | 874 | 0 | import logging
from spacel.provision.app.base_decorator import BaseTemplateDecorator
logger = logging.getLogger('spacel.provision.app.db')
class BaseDbTemplateDecorator(BaseTemplateDecorator):
def __init__(self, ingress):
sup | er(BaseDbTemplateDecorator, self).__init__()
self._ingress = ingress
def _add_client_resources(self, resources, app_region, port, params,
sg_ref):
clients = params.get('clients', ())
| ingress_resources = self._ingress.ingress_resources(app_region,
port,
clients,
sg_ref=sg_ref)
logger.debug('Adding %s ingress... |
czpython/django-cms | cms/tests/test_permmod.py | Python | bsd-3-clause | 44,347 | 0.001804 | # -*- coding: utf-8 -*-
from djangocms_text_ckeditor.models import Text
from django.contrib.admin.sites import site
from django.contrib.admin.utils import unquote
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, Group, Permission
from django.contrib.sites.models impor... | - published page
- master can do anything on its subpages, but not on home!
2. `master`:
- published page
- created by super
- `master` | can do anything on it and its descendants
- subpages:
3. `slave-home`:
- not published
- assigned slave user which can add/change/delete/
move/publish this page and its descendants
- `master` user want to moder... |
lukeolson/crappy | utils.py | Python | bsd-3-clause | 5,160 | 0.00155 | import re
import numpy as np
def identify_templates(hfile):
"""
Parameters
----------
hfile : string
.h header file to be parsed
Returns
-------
tdict : dictionary
dictionary of lists
each dictionary is a function
each list identifies the arglist
Notes... | temp_iter = re.finditer('template\s*\<', text)
temp_start = [m.start(0) for m in temp_iter]
docst_iter = re.finditer(r'//\s*begin{docstring}', text)
docst_start = [m.start(0) for m in docst_iter]
docst_iter = re.finditer(r'//\s*end{docstring}', text)
docst_end = [m.start(0) for m in docst_iter]
... | f len(docst_start) != len(docst_end):
raise ValueError('Problem with docstring begin{docstring} ' +
'or end{docstring}')
# each docstring is associated with some template
# each template is not associated with some docstring
# associate the templates with docstring if possi... |
GETLIMS/LIMS-Backend | lims/projects/migrations/0011_auto_20160822_1527.py | Python | mit | 415 | 0 | # -*- cod | ing: utf-8 -*-
from __future__ import unicode_literals
from | django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0010_product_design_format'),
]
operations = [
migrations.AlterField(
model_name='product',
name='design',
field=models.TextField(null=True, blan... |
kratman/psi4public | psi4/header.py | Python | gpl-2.0 | 2,628 | 0.003425 | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | ov,
R. Di Remigio, R. M. Richard, J. F. Gonthier, A. M. James,
H. R. McAlexander, A. Kumar, M. Saitow, X. Wang, B. P | . Pritchard,
P. Verma, H. F. Schaefer III, K. Patkowski, R. A. King, E. F. Valeev,
F. A. Evangelista, J. M. Turney, T. D. Crawford, and C. D. Sherrill,
submitted.
-----------------------------------------------------------------------
Psi4 started on: %s
Process ID: %6d
PSIDATADIR: %s
... |
mbranko/kartonpmv | osnovni/views.py | Python | mit | 9,507 | 0.001367 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from dateutil import relativedelta
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.db.models import Q, Count
from django_tables2 import RequestConfig
from osnovni.forms import PredmetForm,... | else:
form = Predmet | Form(instance=pred)
if request.user.radnik.uloga.id > 2:
context['predmet'] = pred
context['titleinfo'] = u'Pregled podataka u kartonu inv.br. ' + str(pred.inv_broj)
template = 'osnovni/predmet_view.html'
istorija = IstorijaIzmenaPredmeta.objects.filter(predmet=pred).ord... |
cristicalin/setwall | junk/test_copy.py | Python | gpl-3.0 | 181 | 0.005525 | import copy
from wpm.filelist import *
f = filelist()
f.load("/home/kman/bin/wpm")
f.get_list()
p = copy.copy(f)
p.sort()
f.randomize()
p.get | _list()
f.get_list()
p.close()
f. | close() |
jenix21/DarunGrim | Src/Scripts/FileManagement/setup.py | Python | bsd-3-clause | 361 | 0.108033 | from distutils.core import setup, Extension
setup | (name = "win32ver",
version = "1.0",
maintainer = "Jeong Wook Oh",
maintainer_email = "oh.jeongwook@gmail.com",
description = "Win32 Version Information Retriever",
ext_modules = | [ Extension('win32ver',
sources = ['win32ver.cpp'],
libraries = ['version'],
platforms='x86' ) ]
)
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.2/Lib/test/test_contextlib.py | Python | mit | 10,109 | 0.002968 | """Unit tests for contextlib.py, and other context managers."""
import sys
import tempfile
import unittest
from contextlib import * # Tests __all__
from test import support
try:
import threading
except ImportError:
threading = None
class ContextManagerTestCase(unittest.TestCase):
def test_contextmanage... |
x = C()
self.assertEqual(state, [])
with closing(x) as y:
self.assertEqual(x, y)
self.assertEqual(state, [1])
def test_closing_error(self):
state = []
class C:
def cl | ose(self):
state.append(1)
x = C()
self.assertEqual(state, [])
with self.assertRaises(ZeroDivisionError):
with closing(x) as y:
self.assertEqual(x, y)
1 / 0
self.assertEqual(state, [1])
class FileContextTestCase(unittest.TestCa... |
cloudera/hue | desktop/libs/notebook/src/notebook/management/commands/samples_setup.py | Python | apache-2.0 | 2,309 | 0.003465 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | by applicable law or agreed to in writing, | software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
from django.core.management.base impo... |
AMOboxTV/AMOBox.LegoBuild | plugin.video.salts/salts_lib/srt_scraper.py | Python | gpl-2.0 | 9,410 | 0.004145 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | L)
try:
body = self.__http_get_with_retry(url, req)
body = body.decode('utf-8')
| parser = HTMLParser.HTMLParser()
body = parser.unescape(body)
except Exception as e:
kodi.notify(msg='Failed to connect to URL: %s' % (url), duration=5000)
log_utils.log('Failed to connect to URL %s: (%s)' % (url, e), log_utils.LOGERROR)
return ''
self.... |
ultimatepritam/HelloWeb | DoraTheExplorer.py | Python | gpl-3.0 | 7,919 | 0.011491 | #This script is built as a prototype during Mozilla HelloWeb Hackathon Kolkata 2016
#An Interactive Artificial Intelligence with a friendly personality to teach 5 year olds about HTML and WEB
#Copyright Protected Under GPL3 License | Follow the License | Send Pull Requests
import re
import py
import requests
imp... | big texts her | e!")
#IMAGE IMPORT IN HTML
speak("Oho! Everything is great but you don't have to be naked for that. Lets dress up, shall we?")
speak("Now lets again check that stupid file with lots of bla bla texts in it")
os.system('atom KeepCalm.html')
... |
odoo-brazil/l10n-brazil-wip | l10n_br_financial/constantes.py | Python | agpl-3.0 | 388 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 KMEE
# License AGPL-3.0 or later (h | ttp://www.gnu.org/licenses/agpl).
from __future__ import division, print_function, unicode_literals
TIPO_COBRANCA = (
('0', u'Carteira'),
('1', u'Cheque'),
('2', u'CNAB'),
)
TIPO_COBRANCA_SPED = (
('0', u'Duplicata'),
('1', u'Cheque'),
('2', u'Promissória'),
('3', u'Rec | ibo'),
)
|
gitterHQ/ansible | v2/ansible/parsing/yaml/composer.py | Python | gpl-3.0 | 1,212 | 0.00495 | from yaml.composer import Composer
from yaml.nodes import MappingNode
class AnsibleComposer(Composer):
def __init__(self):
self.__mapping_starts = []
super(Composer, self).__init__()
def compose_node(self, parent, index):
# the line number where the previous token has ended (plus empty ... | rn node
def compose_mapping_node(self, anchor):
# the column here will point at the position in the file immediately
# after the first key is found, which could be a space or a newline.
# We could back this up to find the beginning of the key, but this
# should be good enough to dete... | + 1))
return Composer.compose_mapping_node(self, anchor)
|
westernx/sgfs | sgfs/commands/rv.py | Python | bsd-3-clause | 2,458 | 0.004475 | import os
from subprocess import call, Popen, PIPE
import sys
from . import Command
from . import utils
class OpenSequenceInRV(Command):
"""%prog [options] [paths]
Open the latest version for each given entity.
"""
def run(self, sgfs, opts, args):
# Parse them all.... | rg] = path
movies = [arg_to_movie[arg] for arg in args]
print 'Opening:'
print '\t' + '\n\t'.join(movies)
rvlink = Popen(['rv', '-bakeURL'] + movies, stderr=PIPE).communicate()[1].strip().split()[-1]
self.open(rvlink)
|
def open(self, x):
if sys.platform.startswith('darwin'):
call(['open', x])
else:
call(['xdg-open', x])
run = OpenSequenceInRV()
|
chadoneba/django-planfix | planfix/classes.py | Python | apache-2.0 | 6,136 | 0.009452 | import requests
from hashlib import md5
from xml.etree import ElementTree
from django.core.cache import cache
from functools import cmp_to_key
# class Cache(object):
# params = {}
#
# def get(self,key):
# if key in self.params:
# return self.params[key]
# else:
# return N... | **kwargs))
elif tmp_val == 'customValue':
res = self.get_value(tmp_key, **kwargs)
if not res == '' and isinstance(res, list):
result_list.append("".join(["".join([str(i[0]),str(i[1])]) for i in res]))
el... | result_list.append(self.get_value(tmp_val, **kwargs))
else:
result_list.append(self.string_by_schemefileds(tmp_val, **kwargs))
return "".join(result_list)
def get_value(self,value, **kwargs):
if value in kwargs:
return kwargs.get(value)
... |
oknalv/piollo | loggersingleton.py | Python | gpl-2.0 | 1,004 | 0.001992 | class LoggerSingleton:
_instance = None
@staticmethod
def get_instance(console_log=False):
if LoggerSingleton._instance is None:
LoggerSingleton._instance = LoggerSingleton._Logger()
if console_log:
LoggerSingleton._instance.set_next(LoggerSingleton._ConsoleL... | on._Logger.__init__(self)
def log(self, message):
print message
LoggerSingleton._Logg | er.log(self, message)
|
ogazitt/stackalytics | tests/unit/test_mps.py | Python | apache-2.0 | 1,964 | 0 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | ns</strong></div>
<div class="span-7 last">
<div>
| <b>Rackspace</b> From (Current)
</div>
</div>
<div class="span-3"><strong>Statement of Interest </strong></div>
<div class="span-7 last">
<p>contribute logic and evangelize openstack</p>
</div>
<p> </p>'''
match = re.search(mps.NAME_AND_DATE_PATTERN, content)
self.assertTrue(match... |
sixfeetup/cloud-custodian | tools/c7n_logexporter/c7n_logexporter/exporter.py | Python | apache-2.0 | 26,318 | 0.00057 | # Copyright 2017 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | onfig(level=logging.INFO)
logging.getLogger('c7n.worker').setLevel(logging.DEBUG)
logging.getLogger('botocore').setLevel(logging.WARNING)
log = logging.getLogger('c7n-log-exporter')
CONFIG_SCHEMA = {
'$schema': 'http://json-schema.org/schema#',
| 'id': 'http://schema.cloudcustodian.io/v0/logexporter.json',
'definitions': {
'destination': {
'type': 'object',
'additionalProperties': False,
'required': ['bucket'],
'properties': {
'bucket': {'type': 'string'},
'prefix': {'ty... |
tinloaf/home-assistant | homeassistant/components/light/mqtt/schema_template.py | Python | apache-2.0 | 16,276 | 0 | """
Support for MQTT Template lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.mqtt_template/
"""
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components import mqtt
from homeassistant.co... | es[CONF_GREEN_TEMPLATE] is not None and
self._templates[CONF_BLUE_TEMPLATE] is not None):
se | lf._hs = [0, 0]
else:
self._hs = None
self._effect = None
async def _subscribe_topics(self):
"""(Re)Subscribe to topics."""
for tpl in self._templates.values():
if tpl is not None:
tpl.hass = self.hass
last_state = await self.async_ge... |
cee1/cerbero-mac | test/test_cerbero_packages_wix.py | Python | lgpl-2.1 | 8,020 | 0.006733 | # 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... | .exe" Source="z:\\\\\\test\\\\bin\\\\test.exe"/>
</Component>
<Component Guid="1" Id="_test2 | .exe">
<File Id="_test2exe" Name="test2.exe" Source="z:\\\\\\test\\\\bin\\\\test2.exe"/>
</Component>
<Component Guid="1" Id="_test3.exe">
<File Id="_test3exe" Name="test3.exe" Source="z:\\\\\\test\\\\bin\\\\test3.exe"/>
</Component>
</Directory>
<Directory Id="_lib" Name="lib">
<Directo... |
noslenfa/tdjangorest | uw/lib/python2.7/site-packages/generate_scaffold/management/verbosity.py | Python | apache-2.0 | 1,463 | 0 | import os
from django.core.management.color import supports_color
from django.utils import termcolors
class VerboseCommandMixin(object):
| def __init__ | (self, *args, **kwargs):
super(VerboseCommandMixin, self).__init__(*args, **kwargs)
self.dry_run = False
if supports_color():
opts = ('bold',)
self.style.EXISTS = \
termcolors.make_style(fg='blue', opts=opts)
self.style.APPEND = \
... |
xroot88/rax_ansible | library/rax_security_group.py | Python | apache-2.0 | 3,554 | 0.002532 | """Dummy module to create rax security groups"""
#!/usr/bin/env python
import pyrax
from ansible.module_utils.basic import *
uri_sgs = 'https://dfw.networks.api.rackspacecloud.com/v2.0/security-groups'
def get_sg(cnw, name):
try:
result, sgs = cnw.identity.method_get(uri_sgs)
if result.status_co... | ax.set_credential_file('rax.py')
pyrax.set_setting('region', module.params['region'])
is_error, has_changed, result = \
choice_map.get(module.params['state'])(module.params)
if not is_error:
module.exit_json(changed=has_changed, security_group=result)
else:
| module.fail_json(msg='Error', security_group=result)
if __name__ == '__main__':
main()
|
GaZ3ll3/numba | numba/cuda/tests/cudadrv/test_inline_ptx.py | Python | bsd-2-clause | 1,302 | 0 | from __future__ import print_function, division, absolute_import
from llvmlite.llvmpy.core import Module, Type, Builder, InlineAsm
from llvmlite import binding as ll
from numba.cuda.cudadrv import nvvm
from numba.cuda.testing import unittest, CUDATestCase
from numba.cuda.testing import skip_on_cudasim
@skip_on_cudasi... | ))
if __ | name__ == '__main__':
unittest.main()
|
NicovincX2/Python-3.5 | Divers/draw_a_clock_vpython.py | Python | gpl-3.0 | 6,444 | 0.001552 | # -*- coding: utf-8 -*-
import os
"""Clock for VPython - Complex (cx@cx.hu) 2003. - Licence: Python
Usage:
from visual import *
from cxvp_clock import *
clk=Clock3D()
while 1:
rate(1)
clk.update()
See doc strings for more.
Run this module to test clocks.
TODO: More types of clocks, such as 3D digital,
ch... | box(frame=self.frame, pos=(0.99, 0, 0), length=0.14, height=h,
width=0.12, color=c).rotate(angle=a, axis=(0, 0, 1), origin= | (0, 0, 0))
t = text(pos=(0.8 * sin(a), 0.8 * cos(a) - 0.06, 0), axis=(1, 0, 0), height=0.12,
string=str(j + 12 * (not j)), color=self.number_color, depth=0.02, justify='center')
for o in t.objects:
o.frame.frame = self.frame
else:
... |
apruden/mica2 | mica-python-client/src/main/python/mica/access_harmonization_dataset.py | Python | gpl-3.0 | 1,215 | 0.004115 | """
Apply access on a harmonization dataset.
"""
import sys
import mica.core
import mica.access
def add_arguments(parser):
"""
Add command specific options
"""
mica.access.add_permission_arguments(parser, True)
parser.add_argument('id', help='Harmonization dataset ID')
def do_command(args):
"... | t
except Exception, e:
print e
sys.exit(2)
except pycurl.error, error:
er | rno, errstr = error
print >> sys.stderr, 'An error occurred: ', errstr
sys.exit(2)
|
cloudify-cosmo/cloudify-manager | tests/integration_tests/resources/dsl/deployment_update/modify_relationship_operation/modification/custom_workflow.py | Python | apache-2.0 | 304 | 0 |
from cloudify.workflows import ctx, parameters
ctx.logger.info(parameters.node_id)
instance = [n for n in ctx.node_instances
if n.node_id == parameters.node_id][0]
for relationship in instance.relationship | s:
relationship.e | xecute_source_operation('custom_lifecycle.custom_operation')
|
safwanrahman/kuma | kuma/attachments/tests/test_views.py | Python | mpl-2.0 | 9,771 | 0 | import datetime
import json
from constance.test import override_config
from django.conf import settings
from django.core.files.base import ContentFile
from django.db import transaction
from django.utils.http import parse_http_date_safe
from kuma.core.urlresolvers import reverse
from kuma.users.tests import UserTestCa... | (
content='A file for testing intermediate attachment model.')
p | ost_data = {
'title': 'Intermediate test file',
'description': 'Intermediate test file',
'comment': 'Initial upload',
'file': file_for_upload,
}
files_url = reverse('attachments.edit_attachment',
kwargs={'document_path': doc.slu... |
Agent007/deepchem | examples/tox21/tox21_graphcnn.py | Python | mit | 1,211 | 0.003303 | """
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import json
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet im... | ata_dir)
print(valid_dataset.data_dir)
# Fit models
metric = dc.metrics.Metric(
dc.metrics.roc_auc_score, np.mean, mode="classification")
# Batch size of models
batch_size = 128
model = PetroskiSuchModel(
len(tox21_tasks), batch_size=batch_size, mode='classification')
model.fit(train_dataset, nb_epoch=10)
... | e(train_dataset, [metric], transformers)
valid_scores = model.evaluate(valid_dataset, [metric], transformers)
print("Train scores")
print(train_scores)
print("Validation scores")
print(valid_scores)
|
Azure/azure-sdk-for-python | sdk/graphrbac/azure-graphrbac/azure/graphrbac/models/domain_py3.py | Python | mit | 2,154 | 0.000464 | # 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 ... | es: dict[str, object]
:ivar authentication_type: the type of the authentication into the domain.
:vartype authentication_type: str
:ivar is_default: if this is the default domain in the tenant.
:vartype is_default: bool
:ivar is_verified: if this domain's ownership is verified.
:vartype is_verif... | d: bool
:param name: Required. the domain name.
:type name: str
"""
_validation = {
'authentication_type': {'readonly': True},
'is_default': {'readonly': True},
'is_verified': {'readonly': True},
'name': {'required': True},
}
_attribute_map = {
'addition... |
jimcarreer/hpack | test/test_hpack_integration.py | Python | mit | 2,084 | 0.001919 | # -*- coding: utf-8 -*-
"""
This module defines substantial HPACK integration tests. These can take a very
long time to run, so they're outside the main test suite, but they need to be
run before every change to HPACK.
"""
from hpack.hpack import Decoder, Encoder
from binascii import unhexlify
from pytest import skip
... | ing.
| input_headers = [(item[0], item[1]) for header in case['headers'] for item in header.items()]
encoded = e.encode(input_headers, huffman=True)
decoded_headers = d.decode(encoded)
assert input_headers == decoded_headers
|
asutherland/opc-reviewboard | setup.py | Python | mit | 4,082 | 0.002695 | #!/usr/bin/env python
#
# Setup script for Review Board.
#
# A big thanks to Django project for some of the fixes used in here for
# MacOS X and data files installation.
import os
import shutil
import sys
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
from setuptools... | nstall_data, which is why we roll our own
# install_data class.
def finalize_options(self):
# By the time finalize_options is called, install.install_lib is
# set to the fixed directory, so we set the installdir to install_lib.
# The # install_data class uses ('install_data', 'install_d... | ib', 'install_dir'))
install_data.finalize_options(self)
if sys.platform == "darwin":
cmdclasses = {'install_data': osx_install_data}
else:
cmdclasses = {'install_data': install_data}
PACKAGE_NAME = 'ReviewBoard'
if is_release():
download_url = 'http://downloads.reviewboard.org/releases/%s/%s.%... |
dragondjf/PFramer | qframer/ftablewidget.py | Python | gpl-3.0 | 7,960 | 0.000126 | #!/usr/bin/python
# -*- cod | ing: utf-8 -*-
from PySide2.QtCore import *
| from PySide2.QtGui import *
from PySide2.QtWidgets import *
class FDragRowsTableWidget(QTableWidget):
def __init__(self, rows=0, cloumns=2, parent=None):
super(FDragRowsTableWidget, self).__init__(rows, cloumns, parent)
self.parent = parent
self.setEditTriggers(self.NoEditTriggers)
... |
OpenLD/enigma2-wetek | lib/python/Screens/ScanSetup.py | Python | gpl-2.0 | 68,521 | 0.030093 | from Screen import Screen
from ServiceScan import ServiceScan
from Components.config import config, ConfigSubsection, ConfigSelection, ConfigYesNo, ConfigInteger, getConfigListEntry, ConfigSlider, ConfigEnableDisable
from Components.ActionMap import NumberActionMap, ActionMap
from Components.ConfigList import ConfigLis... | try:
device_id = GetDeviceId('TT3L10', nim_idx)
device_id = "--device=%s" % (device_id)
| except Exception, err:
print "GetCommand ->", err
device_id = "--device=0"
# print nim_idx, nim_name, cable_autoscan_nimtype[nim_name], device_id
command = "%s %s" % (cable_autoscan_nimtype[nim_name], device_id)
return command
except Exception, err:
print "GetCommand ->", err
r... |
Kimi-Arthur/Pimix | deploy.py | Python | mit | 805 | 0 | import os
import re
import shutil
destination = 'C:/Software/Pimix/'
apps = [
'fileutil',
'jobutil'
]
include_patterns = [
r'\.exe',
| r'\.exe\.config',
r'\.dll',
r'\.pdb'
]
exclude_patterns = [
'FSharp',
'vshost'
]
os.makedirs(destination, exist_ok=T | rue)
for app in apps:
for entry in os.scandir('src/{}/bin/Release/'.format(app)):
to_copy = False
for p in include_patterns:
if re.search(p, entry.path):
to_copy = True
break
if not to_copy:
continue
for p in exclude_patterns:
... |
uclouvain/osis | education_group/auth/predicates.py | Python | agpl-3.0 | 12,243 | 0.003921 | from typing import Union
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _, pgettext
from rules import predicate
from base.models.academic_year import current_academic_year
from base.models.education_group_year import EducationGroupYear... | ducationGroupYear, GroupYear] = None
):
if obj:
user_entity_ids = self.context['role_qs'].get_entities_ids()
return obj.management_entity_id in user_entity_ids
return obj
# FIXME: Move to business logic because it's not a predicate
@predicate(bind=True)
@predicate_failed_msg(message=_("You mus... | pk', None))
def is_element_only_inside_standard_program(
self,
user: User,
education_group_year: Union[EducationGroupYear, GroupYear] = None
):
from program_management.ddd.repositories import program_tree_version
if isinstance(education_group_year, GroupYear):
element_id = Elemen... |
Widiot/simpleblog | venv/lib/python3.5/site-packages/cffi/backend_ctypes.py | Python | mit | 42,086 | 0.001022 | import ctypes, ctypes.util, operator, sys
from . import model
if sys.version_info < (3,):
bytechr = chr
else:
unicode = str
long = int
xrange = range
bytechr = lambda num: bytes([num])
class CTypesType(type):
pass
class CTypesData(object):
__metaclass__ = CTypesType
__slots__ = ['__we... | me__ = '<cdata>'
def __init__(self, *args):
raise TypeError("cannot instantiate %r" % (self.__class__,))
@classmethod
def _newp(cls, init):
raise TypeError("expected a pointer or array ctype, got ' | %s'"
% (cls._get_c_name(),))
@staticmethod
def _to_ctypes(value):
raise TypeError
@classmethod
def _arg_to_ctypes(cls, *value):
try:
ctype = cls._ctype
except AttributeError:
raise TypeError("cannot create an instance of %r" % (cl... |
restless/mezzanine-slider-revolution | slider_revolution/admin.py | Python | mit | 1,323 | 0.002268 | from __future__ import unicode_literals
from django.contrib import admin
from django.core import urlresolvers
from mezzanine.core.admin import TabularDynamicInlineAdmin, StackedDynamicInlineAdmin
from .models import Slider, SlideCaption, Slide
class SlideI | nline(TabularDynamicInlineAdmin):
template = "slider_revolution/admin/slide_dynamic_inline_tabular.htm | l"
model = Slide
extra = 1
def changeform_link(self, instance):
if instance.id:
changeform_url = urlresolvers.reverse('admin:slider_revolution_slide_change', args=(instance.id,))
return '<a href="{}">Details</a>'.format(changeform_url)
else:
addform_url =... |
yiplee/ltc-huobi | ltc_huobi/settings.py | Python | mit | 3,262 | 0.001226 | """
Django settings for ltc_huobi project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import ... | eep the secret key used in production secret!
SECRET_KEY = '6t$e^bg18g6u)((0gvfb(dnfh5y&=0_lz&5*-6hrs=mc&u1j#t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = [
'ltc.apps.LtcConfig',
'django.co | ntrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middl... |
Urumasi/Flask-Bones | app/tasks.py | Python | mit | 874 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import render_template
from app.extensions import celery, mail
from app.data import db
from celery.signals import task_postrun
from flask_mail imp | ort Message
@celery.task
def send_registration_email(user, token):
msg = Message(
'User Registration',
sender='admin@flask-bones.com',
recipients=[user.email]
)
msg.body = render_template(
'mail/registration.mail',
user=user,
token=token
)
mail.send(... | SQLAlchemy will automatically create new sessions for you from
# a scoped session factory, given that we are maintaining the same app
# context, this ensures tasks have a fresh session (e.g. session errors
# won't propagate across tasks)
db.session.remove()
|
drvinceknight/sklDj | sklDj/implementations/__init__.py | Python | mit | 59 | 0 | from implementation import *
from implement | ations i | mport *
|
curiburn/pso2_grind_optimizer | py/main.py | Python | gpl-3.0 | 2,887 | 0.011304 | import sys
import argparse
import time
sys.path.append('./bin/moabc')
import optimizer
#引数の処理
#parserの初期化
parser = argparse.ArgumentParser(description='This script optimizes bayesian network graph structure by MOABC')
#強化成功率表
parser.add_argument("infile_pt", type=str)
#一回の強化費用
parser.add_argument("-pg","--pricegri... | s['n']
op.weight_h = args['alpha']
op.proc = args['num_proc']
op.num_average = args['num_average']
#パラメータを適用
op.gen.calculate_weights()
#学習の処理
d | ir_save_progress = ''
if save_progress:
dir_save_progress = out_dir
start = time.time()
op.learn(out_dirname=dir_save_progress)
end = time.time()
#経過時間の出力
str_time = "time: ", "{0}".format(end - start)
print(str_time)
f = open('%s/time.log' % out_dir, 'w')
f.writelines(str_time)
f.close()
#学習結果の出力
op.save_result(... |
klinstifen/rpi.mar13 | mar13.py | Python | lgpl-3.0 | 6,451 | 0.014106 | #!/usr/bin/python
import serial
import RPi.GPIO as GPIO
import time
import math
from RPIO import PWM
import logging
from math import *
from hmc5883l import hmc5883l
import sys
import os
# -----------------------------------------
# ----- begin declare variables
# -----------------------------------------
# log file... | it(',')
if (NMEAdata[0] == "$GPRMC"):
# make sure we have GPS lock
if NMEAdata[2] == "V": continue
GPS[0] = round(getDegrees(NMEAdata[3],NMEAdata[4]),6) # lat
GPS[1] = NMEAdata[4] # n/s
GPS[2] = round(getDegrees(NMEAdata[5],NMEAdata[6]),6) # long
... | = NMEAdata[6] # e/w
GPS[4] = NMEAdata[8] # heading
GPSFound = 1
return GPS
def getBearing(lat1, long1, lat2, long2):
long1, lat1, long2, lat2 = map(radians, [long1, lat1, long2, lat2])
dLon = long2 - long1
y = sin(dLon) * cos(lat2)
x = cos(lat1) * sin(lat2) \
- sin(... |
krishna11888/ai | third_party/pattern/examples/05-vector/01-document.py | Python | gpl-2.0 | 3,205 | 0.007488 | import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import codecs
from pattern.vector import Document, PORTER, LEMMA
# A Document is a "bag-of-words" that splits a string into words and counts them.
# A list of words or dictionary of (word, count)-items can also be given.
# Words ... | can be used to compare docu | ments. The word count in a document is normalized
# between 0.0-1.0 so that shorted documents can be compared to longer documents.
# Words can be stemmed or lemmatized before counting them.
# The purpose of stemming is to bring variant forms a word together.
# For example, "conspiracy" and "conspired" are both stemmed... |
redvox/Eliza | docs/conf.py | Python | apache-2.0 | 9,460 | 0.006237 | # -*- coding: utf-8 -*-
#
# Core documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 12 12:49:48 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... | of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = No | ne
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied... |
ekaakurniawan/Bioinformatics-Tools | plot_conservation/plot_conservation.py | Python | gpl-2.0 | 2,539 | 0.002363 | # Copyright (C) 2012 by Eka A. Kurniawan
# eka.a.kurniawan(ta)gmail(tod)com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hop... | ']]
conservations = []
totalFile = len(files)
for file in | files:
inFile = open(file[0], 'r')
conservations.append(np.array(inFile.read().split(',')[:-1], \
dtype = np.float))
inFile.close()
plot.boxplot([np.asarray(cs) for cs in conservations])
plot.title('Conservation Box Plot of Different Viruses')
plot.ylabel('Score (0 to 11)'... |
pernici/sympy | sympy/solvers/tests/test_solvers.py | Python | bsd-3-clause | 13,913 | 0.016172 | from sympy import (Matrix, Symbol, solve, exp, log, cos, acos, Rational, Eq,
sqrt, oo, LambertW, pi, I, sin, asin, Function, diff, Derivative, symbols,
S, sympify, var, simplify, Integral, sstr, Wild, solve_linear, Interval,
And, Or, Lt, Gt, Assume, Q, re, im, expand, zoo)
from sympy.solvers import solve_l... | TIONAL_CV_1
def test_guess_transcendental():
x, y, a, b = symbols('x,y,a,b')
#transcendental functions
assert guess_solve_strategy( exp(x) + 1, x ) == GS_TRANSCENDENTAL
assert guess_solve_strategy( 2*cos(x)-y, x ) == GS_TRANSCENDENTAL
assert guess_solve_strategy( exp(x) + exp(-x) - y, x ) == GS_TRA... | e_strategy(a*x**b-y, x) == GS_TRANSCENDENTAL
def test_solve_args():
x, y = symbols('x,y')
#implicit symbol to solve for
assert set(int(tmp) for tmp in solve(x**2-4)) == set([2,-2])
assert solve([x+y-3,x-y-5]) == {x: 4, y: -1}
#no symbol to solve for
assert solve(42) == []
assert solve([1,2]... |
shadghost/Auto-Backdoor | the-backdoor-factory/payloadtests.py | Python | gpl-3.0 | 6,022 | 0.001993 | #!/usr/bin/env python
'''
Copyright (c) 2013-2015, Joshua Pitts
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this li... | \xfe', '\xca\xfe\xba\xbe',
'\xce\xfa\xed\xfe',
]
testBinary = open(FILE, 'rb')
header = testBinary.read(4)
testBinary.close()
if 'MZ' in header:
return 'PE'
elif 'E | LF' in header:
return 'ELF'
elif header in macho_supported:
return "MACHO"
else:
'Only support ELF, PE, and MACH-O file formats'
return None
if __name__ == "__main__":
'''
Will create patched binaries for each payload for the type of binary provid... |
prometheanfire/portage | bin/dohtml.py | Python | gpl-2.0 | 6,987 | 0.025619 | #!/usr/bin/python
# Copyright 1999-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
#
# Typical usage:
# dohtml -r docs/*
# - put all files and directories in docs into /usr/share/doc/${PF}/html
# dohtml foo.html
# - put foo.html into /usr/share/doc/${PF}/html
#
#
# Detailed ... | alues
| else:
args.append(sys.argv[x])
x += 1
return (options, args)
def main():
(options, args) = parse_args()
if options.verbose:
print("Allowed extensions:", options.allowed_exts)
print("Document prefix : '" + options.doc_prefix + "'")
print("Allowed files :", options.allowed_files)
success = False
ends... |
Jgarcia-IAS/Fidelizacion_odoo | openerp/addons/sale_stock/sale_stock.py | Python | agpl-3.0 | 24,595 | 0.005733 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | ither be a in a list or in a form
view, if there is only one delivery order to show.
'''
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
result = mod_obj.get_object_reference(cr, uid, 'stock', 'action_p | icking_tree_all')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
#compute the number of delivery orders to display
pick_ids = []
for so in self.browse(cr, uid, ids, context=context):
pick_ids += [picking.id for picking in ... |
gmimano/commcaretest | corehq/apps/hqadmin/tasks.py | Python | bsd-3-clause | 98 | 0.020408 | from celery.task import task
import time
@task
def sleep(duration=10):
ti | me.sleep(duration)
| |
google/objax | objax/util/check.py | Python | apache-2.0 | 2,313 | 0.003891 | # 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 writi | ng, 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.
__all__ = ['assert_assigned_type_and_shape_match']
import j... |
erik/translate | translate/client/exceptions.py | Python | gpl-3.0 | 5,955 | 0 | # -*- coding: utf-8 -*-
# This file is part of translate.
#
# translate is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# translate ... | not available, doesn't respond, etc.)
"""
pass
class RateLimitException(TranslateException):
"""Exception raised when a client goes over the rate | limit."""
def __init__(self, limit, per, reset):
self.limit = limit
self.per = per
self.reset = reset
@classmethod
def from_json(cls, obj):
try:
details = obj.get('details', {})
return cls(limit=details['limit'], per=details['per'],
... |
SevenW/Plugwise-2-py | devtools/Join-2.py | Python | gpl-3.0 | 58,244 | 0.009546 | #!/usr/bin/env python3
# Copyright (C) 2012,2013,2014,2015,2016,2017,2018,2019,2020 Seven Watt <info@sevenwatt.com>
# <http://www.sevenwatt.com>
#
# This file is part of Plugwise-2-py.
#
# Plugwise-2-py is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | on.
#
# Plugwise-2-py is distributed in the hope that it will be useful,
# but WI | THOUT 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 Plugwise-2-py. If not, see <http://www.gnu.org/licenses/>.
#
# The pr... |
paulburkinshaw/mopidy-radio-pi | mopidy_radio_pi/static/MyHandler.py | Python | apache-2.0 | 11,919 | 0.043544 | import SimpleHTTPServer
import sqlite3 as lite
import sys
import urlparse
import datetime
import json
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class TrackListHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
self.send_response(200)
self.send_header('application/json; charset=utf... | ']
self.getTrackRating(trackUriString)
elif('likeTrack' in typeString):
trackUriString = queryParsed['trackUri']
trackNameString = queryPa | rsed['trackname']
trackArtistString = queryParsed['artist']
trackAlbumString = queryParsed['album']
self.likeTrack(trackUriString, trackNameString, trackArtistString, trackAlbumString)
elif('voteToSkipTrack' in typeString):
trackUriString = queryParsed['trackUri']
trackNameString = queryParsed['t... |
streamcorpus/streamcorpus-filter | py/src/streamcorpus_filter/_filter.py | Python | mit | 8,706 | 0.005628 | '''python example of filtering through strings from a
streamcorpus.StreamItem to find names from a FilterName
'''
from __future__ import absolute_import
import logging
import os
import sys
from cStringIO import StringIO
## import the thrift library
from thrift import Thrift
from thrift.transport.TTransport import T... | er_names.name_to_target_ids[name].append(target_id)
print('%d names, %d target_ids' % (len(self.filter_names.name_to_target_ids),
len(self.filter_names.target_id_to_names)))
def compile_filters(self):
if not self.filter_names:
raise Exception... | or this simple example, all we do is convert the utf-8
## from FilterNames into unicode
self._names = dict()
for name in self.filter_names.name_to_target_ids:
self._names[name.decode('utf8')] = self.filter_names.name_to_target_ids[name]
def register_token_boundary_char(self, ch... |
plus1s/shadowsocks-py-mu | shadowsocks/asyncdns.py | Python | apache-2.0 | 17,651 | 0.00017 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014-2015 clowwindy
#
# 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 r... | + 4, (name, None, record_type, record_class, None, None)
def parse_header(data):
if len(data) >= 12:
header = struct.unpack('!HBBHHHH', data[:12])
res_id = header[0]
res_qr = header[1] & 128
res_tc = header[1] & 2
res_ra = header[2] & 128
| res_rcode = header[2] & 15
# assert res_tc == 0
# assert res_rcode in [0, 3]
res_qdcount = header[3]
res_ancount = header[4]
res_nscount = header[5]
res_arcount = header[6]
return (res_id, res_qr, res_tc, res_ra, res_rcode, res_qdcount,
res_anco... |
thoas/django-sequere | sequere/contrib/timeline/signals.py | Python | mit | 279 | 0 | from django.dispatch import Signal
pre_save = Signal(providing_args=['instance', 'action', ])
post_save = Signal(providing_a | rgs=['instance', 'action', ])
pre_delete = Signal(providing_args=['instance', 'action', ] | )
post_delete = Signal(providing_args=['instance', 'action', ])
|
okfn/brand-manager | manager/apps/brand/notifications.py | Python | mit | 1,306 | 0 | from django.core.mail import send_mail
from django.core.urlresolvers import reverse
class EmailNotification:
msg_from = 'OKFN team <noreply@okfn.org>'
def __init__(self, msg_to, msg_from=None):
self.msg_to = msg_to
if msg_from:
self.msg_from = msg_from
def send_mail(self, su... | e):
send_mail(subject, message, self.msg_from, [self.msg_to],
fail_silently=True)
def create_notification(self, brand_nm, bsin):
brand_url = reverse('brand', args=(bsin,))
subject = "%s added to the OKFN brand repository" % brand_nm
message | = """Dear contributor,
Your brand %s was added to the OKFN brand respository under BSIN %s.
More details at http://product.okfn.org%s .
Thank you for your contribution.
Regards,
OKFN brand manager team""" % (brand_nm, bsin, brand_url)
self.send_mail(subject, message)
def delete_notification(self, bran... |
Beeblio/django | tests/dispatch/tests/test_saferef.py | Python | bsd-3-clause | 1,886 | 0 | import unittest
from django.dispatch.saferef import safeRef
from django.utils.six.moves import xrange
class Test1(object):
def x(self):
pass
def test2(obj):
pass
class Test2(object):
def __call__(self, obj):
pass
class SaferefTests(unittest.TestCase):
def setUp(self):
ts... | ss
self.closureCount = 0
def tearDown(self):
del self.ts
del self.ss
def testIn(self):
"""Test the "in" operator for safe references (cmp)"""
for t in self.ts[:50]:
self.assertTrue(safeRef(t.x) in self.ss)
def testValid(self): |
"""Test that the references are valid (return instance methods)"""
for s in self.ss:
self.assertTrue(s())
def testShortCircuit(self):
"""Test that creation short-circuits to reuse existing references"""
sd = {}
for s in self.ss:
sd[s] = 1
for... |
DLR-SC/F2x | src/F2x/template/ctypes_noerr/lib/glue.py | Python | apache-2.0 | 17,616 | 0.0021 | # Copyright 2018 German Aerospace Center (DLR)
#
# 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 a... | :
cptr = ctypes.c_char_p(0)
cfunc(ctypes.byref(cptr))
return cptr.value.decode('utf-8').rstrip()
return _get
else:
cfunc.argtypes = []
cfunc.restype = ctype
return cfunc
def _ | global_setter(ctype, cfunc, strlen=None):
if cfunc is None:
return None
elif ctype == ctypes.c_char_p:
cfunc.argtypes = [ctypes.POINTER(ctype)]
cfunc.restype = None
def _set(value):
cstring = ctypes.create_string_buffer(value.encode('utf-8'), strlen)
cva... |
kymbert/behave | behave/formatter/html.py | Python | bsd-2-clause | 15,092 | 0.001789 | # -*- coding: utf-8 -*-
"""
Creates a very basic one-page html file for reporting a test run.
"""
from __future__ import absolute_import
from behave.formatter.base import Formatter
from behave.formatter.css import BasicTheme
from behave.compat.collections import Counter
import xml.etree.ElementTree as ET
import base64... | ormatter):
"""
Provides a single-page HTML formatter that writes the result of a test run.
"""
name = 'html'
description = 'Basic HTML formatter'
title = u"Behave Test Report"
def __init__(self, stream_opener, config):
super(HTMLFormatter, self).__init__(stream_opener, | config)
# -- XXX-JE-PREPARED-BUT-DISABLED:
# XXX Seldom changed value.
# XXX Should only be in configuration-file in own section "behave.formatter.html" ?!?
# XXX Config support must be provided.
# XXX REASON: Don't clutter behave config-space w/ formatter/plugin related config ... |
zack-bitcoin/forumcoin | networking.py | Python | gpl-3.0 | 1,788 | 0.009508 | import socket, subprocess, re, tools, custom
#This file explains how sockets work for networking.
MAX_MESSAGE_SIZE = 60000
def kill_processes_using_ports(ports):
popen = subprocess.Popen(['netstat', '-lpn'],
shell=False,
stdout=subprocess.PIPE)
(data, er... | data=tools.unpackage(data)
| client.send(tools.package(message_handler_func(data, queue)))
except: pass
def connect(msg, host, port):
if len(msg)<1 or len(msg)>MAX_MESSAGE_SIZE:
print('wrong sized message')
return
s = socket.socket()
try:
s.settimeout(4)
s.connect((str(host), int(port)))
... |
sosiouxme/openshift-ansible | roles/lib_openshift/library/oc_scale.py | Python | apache-2.0 | 66,630 | 0.001291 | #!/usr/bin/env python
# pylint: disable=missing-docstring
# flake8: noqa: T001
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ ... | h the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is d | istributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
'''
OpenShiftCLI class that wraps the o... |
Valentijn1995/Kn0ckKn0ck | Kn0ckKn0ckTestSuite.py | Python | mit | 1,092 | 0.000916 | from unittest import TestLoader, TextTestRunner, TestSuite
from UnitTests.TableTest import TestTable
from UnitTests.DestinationTest import TestDestination
from UnitTests.CSVReaderTest import TestCSVReader
from UnitTests.ProxyExtractorTest import TestProxyExtractor
from UnitTests.NoProtocolTest import TestNoProtocol
fro... | uite_list.append(TestLoader().loadTestsFromTestCase(TestCSVReader))
suite_list.append(TestLoader().loadTestsFromTestCase(TestProxyE | xtractor))
suite_list.append(TestLoader().loadTestsFromTestCase(TestNoProtocol))
suite_list.append(TestLoader().loadTestsFromTestCase(TestHttpProtocol))
suite_list.append(TestLoader().loadTestsFromTestCase(TestProxy))
suite = TestSuite(suite_list)
TextTestRunner(verbosity=2).run(suite)
if __name_... |
rakeshmi/cinder | cinder/tests/unit/test_volume_types_extra_specs.py | Python | apache-2.0 | 5,074 | 0 | # Copyright (c) 2011 Zadara Storage Inc.
# Copyright (c) 2011 OpenStack Foundation
# Copyright 2011 University of Southern California
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
... | are
# 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 govern | ing permissions and limitations
# under the License.
"""
Unit Tests for volume types extra specs code
"""
from cinder import context
from cinder import db
from cinder import test
class VolumeTypeExtraSpecsTestCase(test.TestCase):
def setUp(self):
super(VolumeTypeExtraSpecsTestCase, self).setUp()
... |
ktnyt/chainer | chainer/distributions/pareto.py | Python | mit | 3,069 | 0 | import chainer
from chainer.backends import cuda
from chainer import distribution
from chainer.functions.array import where
from chainer.functions.math import exponential
from chainer import utils
class Pareto(distribution.Distribution):
"""Pareto Distribution.
.. math::
f(x) = \\alpha x_m^{\\alpha}... | def event_shape(self):
return ()
@property
def _is_gpu(self):
return isinstance(self.scale.data, cuda.ndarray)
def log_prob(self, x):
x = chainer.as_variable(x)
logp = exponential.log(self.alpha) \
+ self.alpha * exponential.log | (self.scale) \
- (self.alpha + 1) * exponential.log(x)
xp = logp.xp
return where.where(
utils.force_array(x.data >= self.scale.data),
logp, xp.array(-xp.inf, logp.dtype))
@property
def mean(self):
mean = (self.alpha * self.scale / (self.alpha - 1))
... |
SafeW3rd/Ciphers | password.py | Python | mit | 179 | 0.005587 | print('What is the password?' | )
password = input()
if password == 'rosebud':
print('Access granted.')
if password != 'rosebud':
p | rint('Access denied.')
print('Done.') |
sunj1/my_pyforms | pyforms/Utils/timeit.py | Python | mit | 694 | 0.034582 | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Ricardo Ribeiro"
__credits__ = ["Ricardo Ribeiro"]
__license__ = "MIT"
__version__ = "0.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ricardojvr@gmail.com"
__status__ = "Development"
|
import time
from datetime import datetime, timedelta
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
time_elapsed = datetime(1,1,1) + timedelta(seconds=(te-ts) )
print("%s: %d:%d:%d:%d;%d" % (method.__name__, time_elapsed.day-1, time_elapsed.hour... | lt
return timed |
clancia/TASEP | Sequential_TASEP/LinRegCTvsSize.py | Python | gpl-2.0 | 2,328 | 0.018041 | import matplotlib.pyplot as plt
import numpy as np
from glob import glob
from scipy import stats
#p = 0.5
e = 0.1
qth = [25,50,75,90]
nomefile = './N*' + '_B*' + '_p=1su2L_e0.0.npy'
nomefile = glob(nomefile)
data = []
N = []
medie = []
mediane = []
massimi = []
perc = []
nomefile.sort(key=lambda x:int(x.split('_')... | intercept
Mline = Mslope*xi + Mintercept
ax.plot(N,Eline,'r-',N,med | ie,'o')
ax.set_ylabel('Mean of Coalescence Times', fontsize=15)
ax.set_xlabel('Number of Sites of the Ring')
ax.text(15,35, 'Slope = %f \nIntercept = %f' %(Eslope, Eintercept), fontsize=16)
bx.plot(N,MEDline,'r-',N,mediane,'x')
bx.set_ylabel('Median of Coalescence Times', fontsize=15)
bx.set_xlabel('Number of Sites of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.