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 |
|---|---|---|---|---|---|---|---|---|
google/nitroml | nitroml/automl/autodata/subpipeline_test.py | Python | apache-2.0 | 2,314 | 0.001729 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | eprocessor())
self.run_pipeline(components=task.components + autodata.components)
self.assertComponentSucceeded("ImportExampleGen")
self.assertComponentSucceeded("Sche | maGen.AutoData")
if ignore_features:
self.assertComponentSucceeded("annotate_schema.AutoData")
self.assertComponentSucceeded("StatisticsGen.AutoData")
self.assertComponentSucceeded("Transform.AutoData")
if __name__ == "__main__":
e2etest.main()
|
naver/hubblemon | memcached_mon/memcached_view.py | Python | apache-2.0 | 2,728 | 0.023094 |
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... | hed_cloud_map
global last_ts
ts = time.time()
if ts - last_ts >= 300:
memcached_cloud_map_tmp = {}
entity_list = common.core.get_entity_lis | t()
for entity in entity_list:
instance_list = common.core.get_table_list_of_entity(entity, 'memcached_')
if len(instance_list) > 0:
new_list = []
for instance in instance_list:
if not instance.startswith('memcached_prefix_'): # skip prefix
new_list.append(instance)
memcached_cloud_map... |
vlegoff/tsunami | src/secondaires/cuisine/types/__init__.py | Python | bsd-3-clause | 1,775 | 0 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 NOEL-BARON Léo
# 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
# ... | ; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERR | UPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Package contenant les types d'objets propres à la cuisine."""
from ... |
reinforceio/tensorforce | tensorforce/core/optimizers/linesearch_step.py | Python | apache-2.0 | 4,502 | 0.003332 | # Copyright 2020 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | nts.append(variable.assign_add(de | lta=delta, read_value=False))
with tf.control_dependencies(control_inputs=assignments):
return fn_loss(**arguments.to_kwargs())
_deltas = self.line_search.solve(
arguments=arguments, x_init=_deltas, base_value=loss_before,
... |
VirrageS/io-kawiarnie | caffe/stencils/migrations/0004_stencil_caffe.py | Python | mit | 591 | 0.001692 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-06-18 05:57
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('caffe', '0001_initial'),
('stenc | ils', '0003_auto_20160521_1743'),
]
operations = [
migrations.AddField(
model_name='stencil',
name='caffe',
field=models.ForeignKey(default=None | , null=True, on_delete=django.db.models.deletion.CASCADE, to='caffe.Caffe'),
),
]
|
hzlf/openbroadcast.org | website/apps/alibrary/forms/playlistforms.py | Python | gpl-3.0 | 9,088 | 0.00154 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import date
from ac_tagging.widgets import TagAutocompleteTagIt
from alibrary import settings as alibrary_settings
from alibrary.models import Playlist
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper... | t_duration"].widget.attrs["disabled"] = "disabled"
if self.instance.type == "playlist":
self.fields["d_tags | "].required = True
base_layout = Fieldset(
_("General"),
Field("name", css_class="input-xlarge"),
Div(Field("target_duration"), css_class="target-duration"),
Field("description", css_class="input-xlarge"),
"main_image",
css_class="base",
... |
liuwenf/moose | python/chigger/filters/__init__.py | Python | lgpl-2.1 | 1,914 | 0.00209 | #pylint: disable=missing-docstring
#################################################################
# DO NOT MODIFY THIS HEADER #
# MOOSE - Multiphysics Object Oriented Simulation Environment #
# #
# (c) 2010... | Filter import TubeFilter
from ClipperFilterBase import ClipperFilterBase
from PlaneClipper import PlaneClipper
from BoxClipper import BoxClipper
from ChiggerFilterBase import ChiggerFilterBase
def create_basic_filter(vtkfilter_type):
"""
Function for creating meta filter objects.
"""
class ChiggerMeta... | objects.
"""
def __init__(self, **kwargs):
super(ChiggerMetaFilter, self).__init__(vtkfilter_type=vtkfilter_type, **kwargs)
return ChiggerMetaFilter
GeometryFilter = create_basic_filter(vtk.vtkCompositeDataGeometryFilter)
IdFilter = create_basic_filter(vtk.vtkIdFilter)
CellCenters = cr... |
CaymanUnterborn/burnman | burnman/model.py | Python | gpl-2.0 | 6,155 | 0.000812 | # This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for the Earth and Planetary Sciences
# Copyright (C) 2012 - 2017 by the BurnMan team, released under the GNU
# GPL v2 or later.
from __future__ import absolute_import
import numpy as np
from .material import Material
from .averaging_schemes im... | if self.alpha is None:
self.calc_moduli_()
n_pressures = len(self.p)
self.alpha = np.zeros(n_pressures)
for idx in range(n_pressures):
V = np.array([m['V'] for m in self.moduli[idx]])
alpha = np.array([m['alpha'] for m in self.moduli[id... |
return self.alpha
def heat_capacity_p(self):
self.calc_heat_capacities_()
return self.c_p
def heat_capacity_v(self):
self.calc_heat_capacities_()
return self.c_v
def calc_moduli_(self):
"""
Internal function to compute the moduli if necessary.
... |
alfredoavanzosc/odoo-addons | partner_student_course/models/partner.py | Python | agpl-3.0 | 1,523 | 0 | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.multi
def _compute_student_course(self):
course_obj = self.env[... | partner.student_age = 0
partner.student_course = False
today = fields.Date.context_today(self)
today_month = fields.Date.from_string(today).month
partner.student_age = (
| fields.Date.from_string(today).year -
fields.Date.from_string(partner.birthdate_date).year)
if today_month < 9:
partner.student_age -= 1
if partner.student_repeated_courses:
partner.student_age -= partner.student_repeated_courses
... |
NZRS/content-analysis | example_usage.py | Python | agpl-3.0 | 246 | 0.004065 | import pickle
from content_stats import Compare_regions
from content_sta | ts import Title_stats
# load saved dictionaries
nz_titles = pickle.load(open('nz/all_movies_dict.p', 'rb'))
us_titles = pickle.load(open('nz/all_movies_ | dict.p', 'rb'))
|
lez/pyxl3 | tests/test_basic.py | Python | apache-2.0 | 5,433 | 0.028529 | # coding: pyxl
import unittest2
from pyxl import html
from pyxl.base import PyxlException, x_base
from pyxl.element import x_element
class PyxlTests(unittest2.TestCase):
def test_basics(self):
self.assertEqual(<div />.to_string(), '<div></div>')
self.assertEqual(<img src="blah" />.to_string(), '<i... | ')
self.assertEqual(<div class="c"></div>.to_string(), '<div class="c"></div>')
self.assertEqual(<div><span></span></div>.to_string(), '<div><span></span></div>')
self.assertEqual(<frag><span /><span /></ | frag>.to_string(), '<span></span><span></span>')
def test_escaping(self):
self.assertEqual(<div class="&">&{'&'}</div>.to_string(), '<div class="&">&&</div>')
self.assertEqual(<div>{html.rawhtml('&')}</div>.to_string(), '<div>&</div>')
def test_comments(self):
pyxl = (
... |
takeshineshiro/keystone | keystone/endpoint_policy/__init__.py | Python | apache-2.0 | 651 | 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... |
# License for the specific language governing permissions and limitations
# under the License.
from keystone.endpoint_policy.core import * # noqa
from keystone.endpoint_policy imp | ort routers # noqa
|
asciidisco/plugin.video.netflix | resources/test/test_Navigation.py | Python | mit | 301 | 0.003322 | # -*- coding: utf-8 -*-
# Module: Navigation
# Author: asciidisco
# Created on: 11.10.2017
# License: MIT https://goo. | gl/5bMj3H
"""Tests for the `Navigation` module"""
import unittest
import mock
from resources.lib.Navigation import Navigation
clas | s NavigationTestCase(unittest.TestCase):
pass
|
mganeva/mantid | scripts/SANS/sans/algorithm_detail/xml_shapes.py | Python | gpl-3.0 | 8,072 | 0.007433 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | ) + '" />' + \
'<radius val="' + str(radius) + '" /></infinite-cylinder>\n'
def finite_cylinder(centre, radius, height, axis, shape_id='shape'):
"""
Generates xml code for an infintely long cylinder
:param centre: a tuple for a point on the axis
:param radius: cylinder radius
... | ht
:param axis: cylinder orientation
:param shape_id: a string to refer to the shape by
:return the xml string
"""
return '<cylinder id="' + str(shape_id) + '">' + \
'<centre-of-bottom-base x="' + str(centre[0]) + '" y="' + str(centre[1]) + '" z="' + str(centre[2]) + \
... |
abirafdirp/blog-wagtail | about/models.py | Python | bsd-3-clause | 785 | 0 | from __future__ import unicode_literals
from django.db import models
from mo | delcluster.fields import ParentalKey
from wagtail.wagtailcore.models import Page
from | wagtail.wagtailcore import fields
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.edit_handlers import InlinePanel
from wagtail.wagtailimages.edit_handlers import ImageChooserPanel
class AboutPage(Page):
content = fields.RichTextField()
picture = models.ForeignKey(
... |
USGSDenverPychron/pychron | pychron/experiment/tasks/experiment_plugin.py | Python | apache-2.0 | 10,029 | 0.000997 | # ===============================================================================
# Copyright 2013 Jake Ross
#
# 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... | return SignalCalculator()
def _sens_selector_factory(self, *args, **kw):
return SensitivitySelector()
def _run_history_factory(self, *args, **kw):
dvc = self.application.get_service("pychron.dvc.dvc.DVC")
rhm = RunHistoryModel(dvc=dvc)
rhm.load()
rh = RunHistoryView... | id="pychron.experiment.task",
factory=self._task_factory,
name="Experiment",
image="applications-science",
task_group="experiment",
)
]
def _task_factory(self):
return ExperimentEditorTask(
application=self.... |
yuanchima/Activation-Visualization-Histogram | util.py | Python | mit | 1,077 | 0.003714 | """ Utilities """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Logging
# =======
import logging
import os, os.path
from colorlog import ColoredFormatter
ch = logging.StreamHandl | er()
ch.setLevel(logging.DEBUG)
formatter = ColoredFormatter(
"%(log_color)s[%(asctime)s] %(message)s",
# datefmt='%H:%M:%S.%f',
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'white,bold',
'INFOV': 'cyan,bold',
'WARNING': 'yellow',
... | d',
'CRITICAL': 'red,bg_white',
},
secondary_log_colors={},
style='%'
)
ch.setFormatter(formatter)
log = logging.getLogger('AVH')
log.setLevel(logging.DEBUG)
log.handlers = [] # No duplicated handlers
log.propagate = False # workaround for duplicated logs in ipython
log.addHandler(ch)
logg... |
jarno83/digigems | contrib/wallettools/walletunlock.py | Python | mit | 158 | 0 | from jsonrpc import | ServiceProxy
access = ServiceProxy("http://127.0.0.1:5332")
pwd = raw_input("Enter wallet passphrase: ")
access.walletpass | phrase(pwd, 60)
|
YuhanLin1105/Multi-User-Blog | handlers/login.py | Python | mit | 489 | 0 | from handlers import Handler
from mod | els import User
# Login handler
class Login(Handler):
def get(self):
self.render('login-form.html')
def post(self):
username = self.request.get('username')
password = self.request.get('password')
u = User.login(username, password)
if u:
self.login(u)
... | |
BirkbeckCTP/janeway | src/repository/migrations/0001_squashed_0019_auto_20201030_1423.py | Python | agpl-3.0 | 25,155 | 0.004095 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-11-10 13:37
from __future__ import unicode_literals
import core.file_system
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import repository.models
class Migration(mi... | ('date_published', models.DateTimeField(blank=True, null=True)),
('date_updated', models.DateTi | meField(blank=True, null=True)),
('current_step', models.IntegerField(default=1)),
],
),
migrations.CreateModel(
name='PreprintAccess',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name=... |
cevap/ion | test/functional/interface_http.py | Python | mit | 4,781 | 0.010458 | #!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the RPC HTTP basics."""
from test_framework.test_framework import BitcoinTestFramework
from test_... | ir)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
out1 = conn.getresponse().read()
assert(b'"error":null' in out1)
assert(conn.sock!=None) #according to http/1.1 connection m... |
out1 = conn.getresponse().read()
assert(b'"error":null' in out1) #must also response with a correct json-rpc message
assert(conn.sock!=None) #according to http/1.1 connection must still be open!
conn.close()
#same should be if we add keep-alive because this should be the std. b... |
gem/oq-hazardlib | openquake/hazardlib/tests/__init__.py | Python | agpl-3.0 | 1,329 | 0 | # The Hazard Library
# Copyright (C) 2012-2017 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#... | kle.loads(pickle.dumps(obj)).assert_equal(obj)
class IndependenceTestCase(unittest.TestCase):
def test(self):
assert_independent('openquake.baselib', 'openquake.hazardlib')
assert_independent('openquake.h | azardlib', 'openquake.hmtk')
|
mfeit-internet2/pscheduler-dev | python-pscheduler/pscheduler/pscheduler/sinumber.py | Python | apache-2.0 | 5,585 | 0.000358 | """
Functions for converting numbers with SI units to integers
"""
import copy
import re
si_multipliers = {
None: 1,
'': 1,
'k': 1000 ** 1,
'm': 1000 ** 2,
'g': 1000 ** 3,
't': 1000 ** 4,
'p': 1000 ** 5,
'e': 1000 ** 6,
'z': 1000 ** 7,
'y': 1000 ** 8,
'ki': 1024 ** 1,
... | hing doesn't make sense.
"""
if type(value) in [int, str, unicode]:
result = si_as_number(value)
return {"lower": result, "upper": result}
if type(default_lower) != int:
raise ValueError("Default lower value must be integer")
# TODO: Complain about anything else in the input?... | y(value)
vrange["lower"] = default_lower
value = vrange
for member in ["lower", "upper"]:
try:
result[member] = si_as_number(value[member])
except KeyError:
raise ValueError("Missing '%s' in input" % member)
if result['lower'] > result['upper']:
... |
vitaliykomarov/NEUCOGAR | nest/appraisal/property.py | Python | gpl-2.0 | 936 | 0.003205 | rate = 100
first_generator = 1.0 * rate
second_generator = 1.5 * rate
third_generator = 2.0 * rate
print first_generator, second_generator, third_generator
# keys for connection type
GABA = 0
Glu = 1
ACh = 2
DA_ex = 3
D | A_in = 4
|
# Quality of graphics
dpi_n = 120
k_IDs = 'IDs'
k_name = 'Name'
k_NN = 'NN'
k_model = 'Model'
# general settings
T = 40.
dt = T
# neurons number for spike detector
N_detect = 100
# neurons number for multimeter
N_volt = 3
w_Glu = 3.
w_GABA = -w_Glu * 2
w_ACh = 8.
# Volume transmission
w_DA_ex = 13.
w_DA_in = -w_... |
MaxTyutyunnikov/lino | obsolete/demo/vor/__init__.py | Python | gpl-3.0 | 118 | 0.042373 | #coding: latin1
label = 'Pr | ototyp einer Homepage für den V.O.R.'
def populate(db):
import vor1
vo | r1.populate(db)
|
Azure/azure-sdk-for-python | sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/operations/_labs_operations.py | Python | mit | 45,851 | 0.004907 | # 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 ... | g im | port ARMPolling
from msrest import Serializer
from .. import models as _models
from .._vendor import _convert_request, _format_url_section
T = TypeVar('T')
JSONType = Any
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
_SERIALIZER = Serializer()
_SERIALIZER.client_s... |
vollov/i18n-django-api | page/migrations/0001_initial.py | Python | mit | 723 | 0.002766 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Page',
fields=[
('id', models.AutoField(verbose... | dels.SlugField(unique=True, max_length=150)),
('posted', models.DateTimeField(auto_now_add=True, db_index=True)),
],
options= | {
},
bases=(models.Model,),
),
]
|
NazlyOlmos/TDD-KATA02 | polls/urls.py | Python | mit | 733 | 0.001364 | from django.conf.urls import url
from . import views
urlpatterns = [
u | rl(r'^$', views.index, name='index'),
url(r'^editar/(?P<idTrabajador>\d+)$', views.e | ditar_perfil, name='editar'),
url(r'^login$', views.login),
url(r'^register', views.register),
url(r'^logout$', views.logout),
url(r'^trabajador/(?P<pk>\d+)$', views.detail),
url(r'^detail', views.detalle_trabajador),
url(r'^addComment', views.add_comment),
url(r'^mostrarComentarios/(?P<idTr... |
chenchiyuan/hawaii | hawaii/apps/weixin/states.py | Python | bsd-3-clause | 1,561 | 0.000641 | # -*- coding: utf-8 -*-
# __author__ = chenchiyuan
from __future__ import division, unicode_literals, print_function
from hawaii.apps.weixin.models import App
from hawaii.apps.weixin.response import MessageResponse, EventResponse
from hawaii.apps.weixin.weixin.interface import StateInterface
class NoCacheState(State... | response = EventResponse.response(input)
return self.response_articles(response)
class SubscribeEventState | (NoCacheState):
def to_xml(self, input):
app = App.only_one()
rule = app.subscribe_rule
if not rule:
return self._to_wx_text("")
response = EventResponse.response(rule.id)
return self.response_articles(response) |
jwren/intellij-community | plugins/hg4idea/testData/bin/mercurial/discovery.py | Python | apache-2.0 | 22,739 | 0.000352 | # discovery.py - protocol changeset discovery functions
#
# Copyright 2010 Olivia Mackall <olivia@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import functools
from .i18n im... | issing and exclude secret stuff
sets = repo.changelog.findcommonmissing(og.commonheads, onlyheads)
og._common, allmissing = sets
og._missing = missing = []
og.excluded = excluded = []
for node in allmissing:
ctx = repo[node]
if ctx.ph | ase() >= phases.secret or ctx.extinct():
excluded.append(node)
else:
missing.append(node)
if len(missing) == len(allmissing):
ancestorsof = onlyheads
else: # update missing heads
ancestorsof = phases.newheads(repo, onlyheads, excluded)... |
parrt/dtreeviz | testing/gen_samples.py | Python | mit | 13,771 | 0.000509 | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import graphviz
import graphviz.backend
from numpy.distutils.system_info import f2py_info
from sklearn import tree
from sklearn.datasets import load_boston, load_iris, load_wine, load_digits, load_breast_cancer, load_diabetes, fetch_mldata
from matplotlib.f... | ame="Arial"):
diabetes = load_diabetes()
regr = tree.DecisionTreeRegressor(
max_depth=max_depth, random_state=random_state)
regr.fit(diabetes.data, diabetes.target)
X = None
if pickX:
X = diabetes.data[np.random.randint(0, len(diabetes.data)), :]
viz = dtreeviz(regr,
... | t,
target_name='progr',
feature_names=diabetes.feature_names,
orientation=orientation,
fancy=fancy,
X=X,
label_fontsize=label_fontsize,
ticks_fontsize=ticks_fontsize,
f... |
airelil/pywinauto-64 | pywinauto/controls/HwndWrapper.py | Python | lgpl-2.1 | 65,743 | 0.008062 | # GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your opti... | __ import unicode_literals
from __future__ import absolute_import
from __future__ imp | ort print_function
__revision__ = "$Revision$"
# pylint: disable-msg=W0611
import sys
import time
import re
import ctypes
import win32api
import win32gui
import pywintypes
import traceback, inspect
# the wrappers may be used in an environment that does not need
# the actions - as such I don't want to require sendk... |
activityworkshop/Murmeli | murmeli/pages/contacts.py | Python | gpl-2.0 | 16,404 | 0.005304 | '''Module for the contacts pageset'''
from datetime import datetime
from murmeli.pages.base import PageSet, Bean
from murmeli.pagetemplate import PageTemplate
from murmeli import dbutils
from murmeli.fingerprints import FingerprintChecker
from murmeli.contactmgr import ContactManager
from murmeli import cryptoutils
... | gerprint":
contents = self.make_checkfinger_page(commands[1], params.get('lang'))
elif commands[0] == "checkedfingerprint":
given_answer = self.get_param_as_int(params, "answer", -1)
fingers = self._make_fingerprint_checker(userid)
# Compare with expected answer, ... | pto, self.get_config()).key_fingerprint_checked( \
userid, pending_referrals)
print("Pending referrals:", pending_referrals)
for msg in pending_referrals:
self.system.invoke_call(self.system.COMPNAME_MSG_HANDLER, "receive", msg=msg)
#... |
moreati/django | tests/custom_pk/fields.py | Python | bsd-3-clause | 1,731 | 0.000578 | import random
import string
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class MyWrapper(object):
def __init__(self, value):
self.value = value
def __repr__(self):
return "<%s: %s>" % (sel... | instance(value, MyWrapper):
return six.text_type(v | alue)
return value
def get_db_prep_value(self, value, connection, prepared=False):
if not value:
return
if isinstance(value, MyWrapper):
return six.text_type(value)
return value
|
facebookresearch/ParlAI | parlai/scripts/verify_data.py | Python | mit | 5,106 | 0.000979 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Verify data doesn't have basic mistakes, like empty text fields or empty label
candidates.
## Examples
```shell
par... | if is_label_cand[c] is True:
warn(
"warning: label mentioned twice in candidate_labels:\n",
act,
opt,
| )
is_label_cand[c] = True
for _, has in is_label_cand.items():
if has is False:
warn("warning: label missing in candidate_labels:\n", act, opt)
counts['label_candidates_with_missing_label'] += 1
... |
Endeios/javascripts | src/main/python/functions.py | Python | lgpl-3.0 | 863 | 0.059096 | from io.endeios.example.javascripts import ABean, TestInterface
from java.lang import Long
def myecho(a):
return a
def greet():
return "Hello Python"
class MyClass(TestInterface):
def __init__(self):
pass
def getBean(self):
retVal =ABean()
retVal.setName("python" | )
retVal.setNumber(101)
retVal.setReady(True)
return retVal
|
def isActive(self):
return True
def getNum(self):
# NOTE Long.parseLong("101") returns a java.math.BigIntger on java side...
return Long(101)
def serviceableResult(self):
listOfStrings = service.getStrings()
print("List is "+listOfStrings.toString()+"\n")
retString = ""
for part in ... |
polltooh/traffic_video_analysis | nn_script/save_func.py | Python | apache-2.0 | 2,186 | 0.016468 | import tensorflow as tf
import time
FLAGS = tf.app.flags.FLAGS
def add_train_var():
""" add all trainable variable to summary"""
for var in tf.trainable_variables():
tf.histogram_summary(var.op.name, var)
def add_loss(loss_scope = 'losses'):
""" add all losses to summary """
for l in tf.... | .model_dir)
if ckpt and ckpt.all_model_checkpoint_paths[-1]:
print("restore " + ckpt.all_model_checkpoint_paths[-1])
saver.restore(sess, ckpt.all_model_checkpoint_paths[-1])
else:
print('no check point')
else:
print("res... | curr_time = time.strftime("%Y%m%d_%H%M")
model_name = model_dir + '/' + curr_time + \
'_iter_' + str(iteration) + '_model.ckpt'
saver.save(sess, model_name)
def add_value_sum(summary_writer, value, name):
""" add python value to tensorboard """
return tf.Summary(value = [tf... |
bioscience-data-platform/bdpindex | bdpindex/searchengine/management/commands/indexdata.py | Python | mit | 1,066 | 0.000938 | from django.core.management.base import BaseCommand, CommandError
from bdpindex.searchengine import search
from bdpindex.searchengine import models
import logging
logger = logging.getLogger(__name__)
class Command(BaseCommand):
args = '<source_url source_url ...>'
help = 'Indexes public MyTardis data'
d... | ardis_urls = self.get_all_source_url()
else:
for arg in args:
mytardis_urls.append('http://' + str(arg))
logger.debug('mytardis_urls=%s' % mytardis_urls)
for url in mytardis_urls:
records = search.pull_data(str(url))
search.index_data(records)
... | ile.objects.all()
mytardis_urls = []
for profile in mytaris_profiles:
mytardis_urls.append(profile.url)
return mytardis_urls
|
anokata/pythonPetProjects | exercises/word_count.py | Python | mit | 1,764 | 0.005669 | import unittest
# procedural
def word_count(s):
if s == '':
return 0
words = 0
in_word = False
for c in s:
if c != ' ':
if in_word:
pass
else:
in_word = True
else | :
if in_word:
words += 1
in_word | = False
else:
pass
if in_word:
words += 1
#test
print(s, words)
return words
def word_count_func(s):
def wd(s, char, in_word, words):
print('fun>', s, "'", char,"'", ord(char), in_word, words)
if s == '' and in_word:
return words + 1
... |
omermahgoub/MigTool | settings/settings.py | Python | gpl-3.0 | 424 | 0.011792 | __author__ = 'OmerMahgoub'
#!/usr/bin/env python
import os
import yaml
class StackSettings:
def ServiceSettings(self,ServiceName):
basepath = os.path.dirname(__file__)
keypairs = os.path.abspath(os.path.join(basepath, "config.yml"))
with open(keypairs,'r') as f:
| doc = yaml.load(f)
cfgServic | eSettings = doc[ServiceName]
return cfgServiceSettings
|
gypogypo/plugin.video.sneek | checkbad.py | Python | gpl-3.0 | 3,056 | 0.008181 | '''
This check has been put in place to stop the inclusion of TVA (and friends) addons in builds
from build makers that publicly insult or slander TVA's developers and friends. If your build is
impacted by this check, you can have it removed by publicly apologizing for your previous statements
via youtube and twitt... | = False
for path, bad_md5 in bad_md5s:
f = xbmcvfs.File(path)
md5 = hashlib.md5(f.read()).hexdigest()
if md5 == bad_md5:
found_md5 = True
break
has_bad_addon = any(xbmc.getCondVisibility('System.HasAddon(%s)' % (addon)) for addon in bad_addons)
if h... | ui
import sys
line2 = 'Press OK to uninstall this addon' if uninstall else 'Press OK to exit this addon'
xbmcgui.Dialog().ok('Incompatible System', 'This addon will not work with Brettus, whitedevil, thespecialist repo or the build you have installed', line2)
if uninstall:
... |
AstromechZA/VISProject_Cape2Rio | py_scripts/daily_extrapolator.py | Python | mit | 3,050 | 0.008525 | import os
import re
import json
import math
def bearing(lat1,lng1,lat2,lng2):
return 90-math.atan2(lng2-lng1, lat2-lat1) * 180.0 / math.pi
def bearing2(c1, c2):
return bearing(c1[0], c1[1], c2[0], c2[1])
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points... | 0], 0, 0]]
for i in xrange(1,num):
last = points[-1][1]
current = hourly_points[i]
distance = round(haversine(last[0], last[1], current[0], current[1]),2)
angle = (round(bearing(last[1], last[0], current[1], current[0])) if (distance > 0.01) else points[-1][2])
points += [[i... | , angle, distance]]
output_boat_data = {}
output_boat_data['yacht_name'] = boatdata[data['name']]['prettyname']
output_boat_data['race_class'] = boatdata[data['name']]['class']
output_boat_data['colour_string'] = colours[colour_index]
output_boat_data['points'] = points
output += [output_boat_... |
nzlosh/st2 | st2common/st2common/models/utils/action_param_utils.py | Python | apache-2.0 | 6,217 | 0.002091 | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... | date(action_parameters_schema)
# cast each param individually
for k, v in six.iteritems(params):
parameter_schema = parameters_schema.get(k, None)
if not parameter_schema:
LOG.debug("Will skip cast of param[name: %s, value: %s]. No schema.", k, v)
continue
paramet... | e: %s]. No type.", k, v)
continue
# Pick up cast from teh override and then from the system suppied ones.
cast = cast_overrides.get(parameter_type, None) if cast_overrides else None
if not cast:
cast = get_cast(cast_type=parameter_type)
if not cast:
LO... |
input-share/input-share | core.py | Python | gpl-3.0 | 783 | 0.001277 | # This Python file uses the following encoding: utf-8
# This file is part of InputShare
#
# Copyright © 2015 Patrick VanDusen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Soft | ware Foundation, either version 3 of the License, or
# (at your option | ) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU A... |
vgrem/Office365-REST-Python-Client | office365/sharepoint/portal/group_site_info.py | Python | mit | 315 | 0 | from office365.runtime.client_value import Cli | entValue
class GroupSiteInfo(ClientValue):
def __init__(self):
super(GroupSiteInfo, self).__init__()
self.SiteStatus = None
self.SiteUrl = None
self.DocumentsUrl = None
self.ErrorMessage = None
self.G | roupId = None
|
DmitriyNeurov/python_training_mantis | model/project.py | Python | apache-2.0 | 470 | 0.008511 | from sys import maxsize
class Project:
def __init__(self, id=None, name=None):
| self.name = name
self.id = id
def __repr__(self):
return "%s:%s" % (self.id, self.name)
def __eq__(self, other):
return (self.id is None or other.id is None or self.id == other.id) and self.name == other.name
def id_or_max(self):
if self.id:
retur... | else:
return maxsize |
rickerc/neutron_audit | neutron/tests/unit/metaplugin/test_metaplugin.py | Python | apache-2.0 | 13,882 | 0.000072 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Nachi Ueno, NTT MCL, Inc.
# All Rights Reserved | .
#
# Licensed under the Apache License, Version 2.0 (th | e "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS I... |
iulian787/spack | var/spack/repos/builtin/packages/kaldi/package.py | Python | lgpl-2.1 | 4,698 | 0.000213 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
from os.path import join
from fnmatch import fnmatch
import os
class Kaldi(Package): # Does not u... | igure_args.append('--mkl-threading=iomp')
if '+cuda' in spec:
configure_args.append('--use-cuda=yes')
| configure_args.append('--cudatk-dir=' + spec['cuda'].prefix)
if spec.satisfies('@2019-07-29:'):
configure_args.append('--cub-root=' + spec['cub'].prefix.include)
with working_dir("src"):
configure(*configure_args)
make()
mkdirp(prefix.bin)
... |
michaelbausor/api-client-staging | generated/python/grpc-google-iam-v1/google/iam/v1/policy_pb2.py | Python | bsd-3-clause | 4,654 | 0.006016 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/iam/v1/policy.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflect... | 5\x12(\n\x08\x62indings\x18\x04 \x03(\x0b\x32\x16.google.iam.v1.Binding\x12\x0c\n\x04\x65tag\x18\x03 \x01(\x0c\"(\n\x07\x42inding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\tB%\n\x11\x63om.google.iam.v1B\x0bPolicyProtoP\x01\xf8\x01\x01\x62\x06proto3')
)
_sym_db.RegisterFileDescriptor(DESCRIPTO... | file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='version', full_name='google.iam.v1.Policy.version', index=0,
number=1, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
... |
dartino/dart-sdk | tools/bots/ddc_tests.py | Python | bsd-3-clause | 1,384 | 0 | #!/usr/bin/env python
#
# Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import os.path
import shutil
import sys
import subprocess
import bot
im... | 'dartdevc_test'
])
with bot.BuildStep('Run tests'):
(bot_name, _) = bot.GetBotName()
system = bot_utils.GetSystemFromName(bot_name)
if system == 'linux':
bot.RunProcess([
'xvfb-run', sys.executable, './tools/test.py', '--strong',
'-mrele... | ress=buildbot',
'--write-result-log'
] + TARGETS)
else:
info = bot.BuildInfo(
'dartdevc',
'chrome',
'release',
system,
arch='x64',
checked=True)
bot.RunTest('dartde... |
Debetux/sr.ht | alembic/versions/3a704a54392_add_rejected_column.py | Python | mit | 607 | 0.009885 | """Add rejected column
Revision ID: 3a704a54392
Revises: 1371a0c98ad
Create Date: 2015-06-09 12:30:56.039052
"""
# revision identifiers, used | by Alembic.
revision = '3a704a54392'
down_revision = '1371a0c98ad'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('user', sa.Column('rejected', sa.Boolean(), nullable=True))
### end Alembic commands ###
def downgr... |
### commands auto generated by Alembic - please adjust! ###
op.drop_column('user', 'rejected')
### end Alembic commands ###
|
birdsarah/bokeh-miscellany | old/Scrolling/scrolling_page_of_plots.py | Python | gpl-2.0 | 3,808 | 0.00709 | # coding: utf-8
import pandas as pd
from contextlib import contextmanager
from bokeh.io import vplot, output_file, show
from bokeh.models import (
Plot, Patch, Patches, Line, MultiLine,
ColumnDataSource, Range1d, LinearAxis,
HoverTool, WheelZoomTool
)
from bokeh.palettes import Spectral3, Spectral4
from nu... | ', fill_color='value', fill_alpha=0.8, line_color | ='#CCCCCC', line_alpha=0.8)
plot.add_glyph(source, glyph)
return plot
def make_multiline_plot(x_range, y_range, source):
with make_plot(x_range, y_range, source) as plot:
glyph = MultiLine(xs='xs', ys='ys', line_color='value', line_width=5, line_alpha=0.8)
plot.add_glyph(source, glyph)... |
google-coral/edgetpu | tests/multiple_tpus_test.py | Python | apache-2.0 | 3,359 | 0.00774 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | asicEngine(model_path, edge_tpus[0])
self.assertEqual(edge_tpus[0], basic_engine.device_path())
def test_run_classification_and_detection_engine(self):
def classification_task(num_inferences):
tid = threading.get_ident()
print('Thread: %d, %d inferences for classific | ation task' %
(tid, num_inferences))
labels = test_utils.read_label_file(
test_utils.test_data_path('imagenet_labels.txt'))
model_name = 'mobilenet_v1_1.0_224_quant_edgetpu.tflite'
engine = ClassificationEngine(test_utils.test_data_path(model_name))
print('Thread: %d, using... |
Gysco/SSWD | pyment/execute.py | Python | gpl-3.0 | 13,004 | 0 | # coding=utf-8
"""
Program start here.
To python soon.
"""
# @Author: Zackary BEAUGELIN <gysco>
# @Date: 2017-04-10T15:43:09+02:00
# @Email: zackary.beaugelin@epitech.eu
# @Project: SSWD
# @Filename: execute.py
# @Last modified by: gysco
# @Last modified time: 2017-06-19T16:15:30+02:00
from statistics import (c... | ar ordre croissant des
concentrations dans nom_feuille_res
"""
sort_collection(data_co, 7, 1)
ecrire_titre(titre_data[1], nom_feuille_res + feuilles_res[i],
lig_data - 1, col_data2)
ecrire_data_co(data_co, | nom_colonne, lig_data, col_data2,
nom_feuille_res + feuilles_res[i], True, iproc)
i += 1
"""loi empirique"""
if dist[0] is True:
loi = 1
"""Ca |
MDAnalysis/mdanalysis | testsuite/MDAnalysisTests/coordinates/base.py | Python | gpl-2.0 | 29,451 | 0.002954 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#... | ame "
"readers)")
def test_frame_index_0(self):
self.universe.trajectory[0]
assert_equal(self.universe.trajectory.ts.frame, 0,
"frame number for frame index 0 should be 0")
def test_frame_index_1_raises_IndexError(self):
def go_to_2(traj=self.universe.t... | ytest.raises(IndexError):
go_to_2()
def test_dt(self):
"""testing that accessing universe.trajectory.dt gives 1.0
(the default)"""
assert_equal(1.0, self.universe.trajectory.dt)
def test_coordinates(self):
A10CA = self.universe.select_atoms('name CA')[10]
# ... |
RockingRolli/pylcdui | lcdui/ui/frame.py | Python | gpl-2.0 | 7,655 | 0.013063 | from collections import deque
from lcdui import common
from lcdui.ui import widget
import array
import time
class Frame(object):
def __init__(self, ui):
self._ui = ui
self._widgets = {}
self._position = {}
self._span = {}
self._screen_buffer = ScreenBuffer(self.rows(), self.cols())
self.onI... | get.LineWidget, row=i+1, col=0)
self._item_widgets.append(w)
self._rebuildMenu()
def showBack(self, enable):
self._show_back = enable
self._rebuildMenu()
def addItem(self, key, value):
self._items.append((key, value))
self._rebuildMenu()
def scrollUp(self):
if self._cursor_pos == ... | eturn
self._cursor_pos += 1
self._updateWindowPos()
self._rebuildMenu()
def _rebuildMenu(self):
items = self._items[self._window_pos:self._window_pos+self._window_size]
num_blank = self._window_size - len(items)
symbol_up = self._ui.GetSymbol(common.SYMBOL.MENU_LIST_UP)
symbol_down = self... |
DavidLutton/EngineeringProject | labtoolkit/SignalGenerator/Wiltron360SS69.py | Python | mit | 1,322 | 0 | from ..GenericInstrument import GenericInstrument
from .helper import SignalGenerator, amplitudelimiter
class Wiltron360SS69(GenericInstrument, SignalGenerator):
"""Wiltron 360SS69 10e6, 40e9.
.. figure:: images/SignalGenerator/Wiltron360SS69.jpg
"""
def __init__(self, instrument):
"""."""
... | ""."""
return(self.query("OL0"))
@amplitude.setter
@amplitudelimiter
def amplitude(self, amplitude):
self.write(f"L0{amplitude:.2f}DM")
'''@property
def output(self):
if self.query("OUTPut:STATe?") == "1":
return(True)
else:
return(False)
... | ''
|
JulyKikuAkita/PythonPrac | cs15211/MaximalSquare.py | Python | apache-2.0 | 6,103 | 0.002786 | __source__ = 'https://leetcode.com/problems/maximal-square/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/maximal-square.py
# Time: O(n^2)
# Space: O(n)
#
# Description: Leetcode # 221. Maximal Square
#
# Given a 2D binary matrix filled with 0's and 1's,
# find the largest square containing all 1's and re... | st w such that (i, j) to (i, j + w - 1) are feasible.
if matrix[i][j] == '1':
h, w = 1, 1
if i + 1 < len(matrix):
h = table[i+1][j][H] + 1
if j + 1 < len(matrix[i]):
w = table[i][j+1][W] + 1
... | the length of largest square for each (i, j).
s = [[0 for j in xrange(len(matrix[0]))] for i in xrange(len(matrix))]
max_square_area = 0
for i in reversed(xrange(len(matrix))):
for j in reversed(xrange(len(matrix[i]))):
side = min(table[i][j][H], table[i][j][W])
... |
wingerjc/onedeefive | src/python/onedeefive.py | Python | bsd-3-clause | 3,580 | 0.013408 | ## @package onedeefive
#
# @brief The main executable package for 1D5
#
# This package holds the main executable section of the program.
# It is basically an interactive console that can be run with i/o redirection
# from specified script files.
#
import sys
import re
import LangDef
from Script import Script,setOut... | These arguments
# allow you to set an input script file, an output text file, or ask for the
# cli help string to be printed | .
#
def main():
VERSION = '1.0.0/0213'
if len(sys.argv) == 1 :
consoleMode()
else :
outFile = None
inFile = None
for i in xrange(1,len(sys.argv)) :
if sys.argv[i] == '-i' :
inFile = Script(sys.argv[i+1],True)
elif sys.argv[i] == '-o' :
... |
short-edition/syntaxnet-wrapper | syntaxnet_wrapper/src/parser_eval.py | Python | apache-2.0 | 8,901 | 0.008988 | #
# Heavily inspired from https://github.com/IINemo/docker-syntaxnet_rus://github.com/IINemo/docker-syntaxnet_rus
# itself inspired from https://github.com/tensorflow/models/blob/master/syntaxnet/syntaxnet/parser_eval.py
# just modified to be able to call wrapper several time for the same process
#
"""A program to ann... | _sess.run(se | lf._parser.inits.values())
self._parser.saver.restore(self._sess, self._pg.model_path)
def parse(self, raw_bytes):
with stdout_redirected(self.stdout_file_path):
if os.stat(self._pg.custom_file).st_size > self._pg.max_tmp_size:
# Cleaning input file at each new call... |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/magics/osm.py | Python | lgpl-3.0 | 25,771 | 0.002755 | """Implementation of magic functions for interaction with the OS.
Note: this module is named 'osm' instead of 'os' to avoid a collision with the
builtin.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
# Distributed under the ter... | tem calls using ! or !!
do: all expressions prefixed with '$' get expanded. For details of
the semantic rules, see PEP-215:
http://www.python.org/peps/pep-0215.html. This is the library used by
IPython for variable expansion. If you want to access a true shell
variable, an ext... | ssary to prevent its expansion by
IPython::
In [6]: alias show echo
In [7]: PATH='A Python string'
In [8]: show $PATH
A Python string
In [9]: show $$PATH
/usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
You can use the alias fac... |
rupertnash/subgrid | python/dqTools/binner.py | Python | mit | 4,769 | 0.008178 | import numpy as N
class Binner(object):
"""Class to perform averages of arbitary variables over some bin
(i.e. range) of a coordinate.
An example:
r, u = calculateVelocitiesAtPositions()
# r is nx X ny X nz X 3 array of positions
# v is the same but for velocities at the corresp... |
the range are ignored, while those above the range are tallied
in the | rightmost bin.
weights : array_like, optional
An array of weights, of the same shape as `a`. Each value in `a`
only contributes its associated weight towards the bin count
(instead of 1). If `normed` is True, the weights are normalized,
so that the integral of ... |
GoogleCloudPlatform/PerfKitExplorer | server/perfkit/test_util.py | Python | apache-2.0 | 2,349 | 0.005109 | """Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by ap | plicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BA | SIS,
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.
Basic helper methods."""
__author__ = 'joemu@google.com (Joe Allan Muharsky)'
from datetime import datetime
import os
from perfkit.common i... |
zackee12/command-line-chess | board/location.py | Python | mit | 4,278 | 0.001169 | from util.enums import Color
class Location:
"""
Location on a chessboard
"""
ROWS = [1, 2, 3, 4, 5, 6, 7, 8] # RANKS
COLS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # FILES
def __init__(self, row, col):
""" initializer
:param row: integer
:param col: str
:r... | l = self._col + cols
row = self._row + rows
if 0 <= col < | len(self.COLS) and 0 <= row < len(self.ROWS):
return Location(self.ROWS[row], self.COLS[col])
return None
@property
def end_of_row(self):
""" Check if the current location is on the top or bottom row of the board
:return: boolean
"""
return self.row == self... |
Angakkuit/asiaq-aws | disco_aws_automation/disco_route53.py | Python | bsd-2-clause | 3,686 | 0.001899 | """
Some code to manage Route53.
Route53 manages our domains and DNS records.
"""
import logging
from boto.route53 import Route53Connection
from boto.route53.record import Record
class DiscoRoute53(object):
"""
A simple class to manage Route53
"""
def __init__(self):
self.route53 = Route53Co... | omain of the Hosted Zone
record_name (str): the name of the record
record_type (str): the type of record (A, AAAA, CNAME, etc)
"""
zone = self.route53.get_zone(hosted_zone_name)
records = self.route53.get_all_rrsets(zone.id)
# Needs a default None, to prevent Sto... | t((record for record in records
if record.name == record_name and record.type == record_type), None)
if not selected_record:
logging.info("Record '%s' in '%s' hosted zone does not exist. Nothing to delete",
record_name, hosted_zone_name)
... |
Cabalist/Comix | src/cursor.py | Python | gpl-2.0 | 2,337 | 0 | # coding=utf-8
"""cursor.py - Cursor handler."""
from __future__ import absolute_import
import gobject
import gtk
NORMAL, GRAB, WAIT = range(3)
class CursorHandler(object):
def __init__(self, window):
self._window = window
self._timer_id = None
self._auto_hide = False
self._curre... | :
self._kill_timer()
def auto_hide_on(self):
"""Signal that the cursor should auto-hide from now on (e.g. that
we are entering fullscreen).
"""
self._auto_hide = True
if self._current_cursor == NORMAL:
self._set_hide_timer()
def auto_hide_off... | ide from now on."""
self._auto_hide = False
self._kill_timer()
if self._current_cursor == NORMAL:
self.set_cursor_type(NORMAL)
def refresh(self):
"""Refresh the current cursor (i.e. display it and set a new timer in
fullscreen). Used when we move the cursor.
... |
marco-hoyer/replicator | src/main/python/replicator/actionmanager.py | Python | gpl-2.0 | 6,373 | 0.005963 | '''
Created on 29.07.2013
@author: mhoyer
'''
from mysqldb import MysqlDB
from local_system import LocalSystem
from remote_system import RemoteSystem
from entities import Application
import logging
import util
class Actionmanager():
'''
classdocs
'''
def __init__(self, config):
self.logger = ... | self.logg | er.debug("saving database: %s" % database)
self.db.dump_database(database, util.path_append([db_temp_path ,database + ".sql"]))
if app.files:
for afile in app.files:
self.logger.debug("saving file: %s" % afile)
self.system.mkdir(uti... |
david81brs/seaport | 5.py | Python | gpl-2.0 | 122 | 0.02459 | x = 2
cont = 0
while x >= 0:
y = 0
while y <= 4:
print(y)#comando qualquer
y = y - 1
x = | x | - 1 |
vervacity/ggr-project | scripts/data_qc/summarize_chipseq_qc.py | Python | mit | 4,085 | 0.004896 |
import gzip
import glob
import numpy as np
import pandas as pd
from scipy.stats import pearsonr
from scipy.stats import spearmanr
def get_num_lines_gz(filename):
num_lines = 0
with gzip.open(filename, "r") as fp:
for line in fp:
num_lines += 1
return num_lines
def main():
... | }/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format(
DATA_DIR, day, mark, rep))[0]
| num_macs2 = get_num_lines_gz(macs2_peaks)
results["num_macs2_peaks"].append(num_macs2)
if "CTCF" in mark:
idr_peaks = glob.glob(
"{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format(
DAT... |
AHAPX/dark-chess | src/consts.py | Python | gpl-3.0 | 2,048 | 0.008789 | UNKNOWN = 0
# kinds of figures
PAWN = 1
ROOK = 2
KNIGHT = 3
BISHOP = 4
QUEEN = 5
KING = 6
FIGURES = {
PAWN: 'pawn',
ROOK: 'rook',
KNIGHT: 'knight',
BISHOP: 'bishop',
QUEEN: 'queen',
KING: 'king',
}
# colors of figures
WHITE = 1
BLACK = 2
COLORS = {
WHITE: 'white',
BLACK:... | )] for k, v in d.i | tems()}
# end reasons
END_CHECKMATE = 1
END_DRAW = 2
END_RESIGN = 3
END_TIME = 4
|
nickdibari/pydate | tests.py | Python | mit | 1,632 | 0.037377 | #* PYTHON EMAIL PROJECT *#
#* tests.py *#
#* Fordham CSS September 25 *#
#* ------------------------------------ *#
#* Unit tests for PyDate program *#
from Email_Object import Email
from Get_Emails import Set_Priority
import unittest
# Unit Tests for Set_Priorit... | mportant', '', '')
EMAILS = [email]
hi,lo = Set_Priority(EMAILS)
self.assertEqual(len(hi),1)
self.assertFalse(lo)
# Test default
def test_low_default(self):
email = Email('test@test.com', '', 'None', '', '')
EMAILS = [email]
hi,lo = Set_Priority(EMAILS)
self.assertE... | = Email('test@fordham.edu', '', 'Blah', '', '')
#Important by subject
email_subject = Email('test@test.com', '', 'Important', '', '')
#Not Important
email_lo = Email('test@test.com', '', 'None', '', '')
EMAILS = [email_sender, email_subject, email_lo]
hi,lo = Set_Priority(... |
thinkopensolutions/l10n-brazil | sped_stock/models/inherited_stock_picking.py | Python | agpl-3.0 | 5,609 | 0.000896 | # -*- coding: utf-8 -*-
# Copyright 2017 KMEE
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from __future__ import division, print_function, unicode_literals
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.addons.sped_imposto.models.sped_calculo_imposto impor... | entações de estoque '
'concluídas!')
elif picking.state == 'cancel':
raise UserError(
| 'Você não pode excluir movimentações de estoque '
'canceladas!')
return super(StockPicking, self).unlink()
def action_cancel(self):
res = super(StockPicking, self).action_cancel()
for picking in self:
if not picking.group_id:
... |
Root-Fang/HTTP_Proxy | Proxy/Proxy.py | Python | apache-2.0 | 4,474 | 0.00827 | # -*- coding: utf-8 -*-
from eventlet import wsgi, api
import eventlet
import webob.dec
from webob import Request, Response
from multiprocessing import cpu_count
from StringIO import StringIO
import httplib
import socket
class proxy(object):
chunk_length = 32768
def __init__(self, time_out = None, lo... | url = req.path_qs.lstrip("http://").lstrip(req.host)
except Exception, e:
conn.close()
return
i_headers = {}
for tmp in req.headers:
i_headers[tmp] = req.headers[tmp]
if req.is_body_readable:
body = req.body_file_seek... | ret = conn.getresponse()
except Exception, e:
#conn.close()
return
resp = Response()
resp.status = ret.status
for tmp in ret.getheaders():
if tmp[0] == "content-type":
resp.content_type = tmp[1]
elif tmp[0] == "... |
therewillbecode/ichnaea | ichnaea/data/tasks.py | Python | apache-2.0 | 6,387 | 0.000313 | from ichnaea.async.app import celery_app
from ichnaea.async.task import BaseTask
from ichnaea.data import area
from ichnaea.data import export
from ichnaea.data.internal import InternalUploader
from ichnaea.data.mapstat import MapStatUpdater
from | ichnaea.data import monitor
from ichnaea.data import ocid
from ichnaea.data.report import ReportQueue
from ichnaea.data.score import ScoreUpdater
from ichnaea.data import station
from ichnaea.data.stats import StatCounterUpdater
from ichnaea.models import ApiKey
@celery_app.task(base=BaseTask, bind=True, queue='cele | ry_ocid')
def export_modified_cells(self, hourly=True, _bucket=None): # pragma: no cover
# BBB
ocid.CellExport(self)(hourly=True, _bucket=_bucket)
@celery_app.task(base=BaseTask, bind=True, queue='celery_ocid')
def import_latest_ocid_cells(self, diff=True): # pragma: no cover
# BBB
ocid.ImportExtern... |
mathiasertl/django-ca | ca/django_ca/migrations/0020_auto_20201213_2014.py | Python | gpl-3.0 | 7,726 | 0.004401 | # Generated by Django 3.1.4 on 2020-12-13 20:14
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import django_ca.models
class Migration(migrations.Migration):
dependencies = [
('django_ca', '0019_certificate_autogenerat... | ('created', models.DateTimeField(default=django.utils.timezone.now)),
('updated', models.DateTimeField(auto_now=True)),
('pem', models.TextField(unique=True, validators=[django_ca.models.pem_validator], verbose_name='Public key')),
('thumbprint', models.CharField(m... | |
nathanbjenx/cairis | cairis/gui/TemplateAssetsDialog.py | Python | apache-2.0 | 3,069 | 0.026067 | # 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... | wById(TEMPLATEASSETS_ASSETLIST_ID)
listCtrl.SetColumnWidth(0,150)
listCtrl.SetColumnWidth(1,150)
def addObjectRow(self,assetListCtrl,listRow,asset):
assetListCtrl.InsertStringItem(listRow,asset.name())
assetListCtrl.SetStringItem(listRow,1,asset.type())
def onAdd(self,evt):
try:
addPara... | rue)
self.addObject(addParameters)
except ARMException,errorText:
dlg = wx.MessageDialog(self,str(errorText),'Add template asset',wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
def onUpdate(self,evt):
selectedObjt = self.objts[self.selectedLabel]
assetId = selec... |
amir-zeldes/rstWeb | modules/pathutils.py | Python | mit | 19,405 | 0.005669 | # -*- coding: utf-8 -*-
# 2005/12/06
# Version 0.2.4
# pathutils.py
# Functions useful for working with files and paths.
# http://www.voidspace.org.uk/python/recipebook.shtml#utils
# Copyright Michael Foord 2004
# Released subject to the BSD License
# Please see http://www.voidspace.org.uk/python/license.shtml
# For ... | True`` - If set, instead of outputting
``1 Mbytes, 307 Kbytes, 478 bytes`` it outputs using only the largest
denominator - e.g. ``1.3 Mbytes`` or ``17.2 Kbytes``
* ``kiloname = 'Kbytes'`` - The string to use for kilobytes
* ``meganame = 'Mbytes'`` - The string to use for... | ts ``1Mbytes, 307Kbytes``,
notice there is no space.
Example outputs : ::
19Mbytes, 75Kbytes, 255bytes
2Kbytes, 0bytes
23.8Mbytes
.. note::
It currently uses the |
kyle8998/Practice-Coding-Questions | leetcode/218-Hard-The-Skyline-Problem/answer.py | Python | unlicense | 2,601 | 0.009612 | #!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Solution
# Find critical points, store in a max heap using min heap properties (-height)
#-------------------------------------------------------------------------------
import heapq
class Solution:
def getSk... | st existing building at this moment
h = -live[0][0] if live else 0
addsky(t, h)
return sky[1:]
#-------------------------------------------------------------------------------
# This does not pass test cases (Memory inefficient)
#----------- | --------------------------------------------------------------------
class Solution:
def getSkyline(self, buildings):
"""
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
if not buildings:
return []
if len(buildings) == 1:
l, r, h ... |
jayme-github/CouchPotatoServer | couchpotato/core/_base/clientscript/main.py | Python | gpl-3.0 | 1,521 | 0.00526 | from couchpotato.core.event import addEvent
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
log = CPLog(__name__)
class ClientScript(Plugin):
urls = {
'style': {},
'script': {},
}
html = {
'style': '<link rel="stylesheet" href="%s" type... | on = 'head'):
data = '' if as_html else []
try:
return self.urls[type][location]
except Exception, e:
log.error(e)
return data
def registerStyle(self, path, position = 'head'):
self.register(path, 'style', position)
def | registerScript(self, path, position = 'head'):
self.register(path, 'script', position)
def register(self, filepath, type, location):
if not self.urls[type].get(location):
self.urls[type][location] = []
filePath = filepath
self.urls[type][location].append(filePath)
|
saltastro/salt-data-quality-site | app/main/pages/instrument/rss/straylight/__init__.py | Python | mit | 422 | 0.00237 | im | port datetime
from app.main.data_quality import default_data_quality_content_for_date_range
def title():
return 'Robert Stobie Spectrograph'
def content():
return default_data_quality_content_for_date_range(__package__,
datetime.date.today() - datetime... | datetime.date.today())
|
spulec/moto | tests/test_dynamodb2/test_dynamodb_consumedcapacity.py | Python | apache-2.0 | 5,333 | 0.00225 | import boto3
import pytest
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ClientError
from moto import mock_dynamodb2
@mock_dynamodb2
def test_error_on_wrong_value_for_consumed_capacity():
resource = boto3.resource("dynamodb", region_name="ap-northeast-3")
client = boto3.... | e, value=0.5)
# SCAN
args = {"TableName": "jobs"}
if capacity:
args["ReturnConsumedCapacity"] = capacity
response = client.scan(**args)
validate_response(response, should_have_capacity, should_have_table)
# SCAN_INDEX
args["IndexName"] = "job_name-index"
response = client.scan(... | sponse, should_have_capacity, should_have_table, is_index=True)
# QUERY
args = {
"TableName": "jobs",
"KeyConditionExpression": "job_id = :id",
"ExpressionAttributeValues": {":id": {"S": "asdasdasd"}},
}
if capacity:
args["ReturnConsumedCapacity"] = capacity
response... |
sgala/gajim | src/lastfm.py | Python | gpl-3.0 | 6,006 | 0.029637 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
## src/lastfm.py
##
## Copyright (C) 2007 Olivier Mehani <shtrom AT ssji.net>
## Yann Leboulanger <asterix AT lagaule.org>
## Copyright (C) 2007-2008 Jean-Marie Traissard <jim AT lapin.org>
##
## This file is part of Gajim.
##
## Gajim is free software; yo... | n the last played song as a tuple of (ARTIST, SONG, ALBUM, TIME).
"""
if len(self.lastSongs) < 1:
return None
return self.lastSongs[0]
def getLastScrobbledTime(self):
"""
Return the Unix time the last song was played.
"""
if len(self.lastSongs) < 1:
return 0
return self.lastSongs[0][self.TIME]
... | """
Return the time in seconds since the last song has been scrobbled.
lst, the Unix time at which a song has been scrobbled, defaults to that
of the last song
"""
if lst is None:
lst = self.getLastScrobbledTime()
return int(time()) - lst
def lastSongIsRecent(self, delay=None):
"""
Return a boole... |
nanditav/15712-TensorFlow | tensorflow/contrib/learn/python/learn/utils/checkpoints.py | Python | apache-2.0 | 2,001 | 0.004498 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e License.
# ============== | ================================================================
"""Tools to work with checkpoints."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework.python.framework im... |
niwinz/django-greenqueue | version.py | Python | bsd-3-clause | 60 | 0 | # -*- coding: | utf-8 -*-
__version__ = (0, 1, 0, ' | final', 0)
|
Artemkaaas/indy-sdk | wrappers/python/indy/pool.py | Python | apache-2.0 | 8,064 | 0.002232 | from .libindy import do_call, create_cb
from typing import Optional
from ctypes import *
import json
import logging
async def create_pool_ledger_config(config_name: str,
config: Optional[str]) -> None:
"""
Creates a new local pool ledger configuration that can be used lat... | d nodes connections and | frees allocated resources.
:param handle: pool handle returned by indy_open_pool_ledger.
:return: Error code
"""
logger = logging.getLogger(__name__)
logger.debug("close_pool_ledger: >>> config_name: %r",
handle)
if not hasattr(close_pool_ledger, "cb"):
logger.debug(... |
KEggensperger/SurrogateBenchmarks | scripts/extract.py | Python | gpl-3.0 | 14,732 | 0.001901 | from argparse import ArgumentParser
import cPickle
import os
import csv
from sklearn.preprocessing import OneHotEncoder
import numpy as np
np.random.seed(1)
import Surrogates.DataExtraction.configuration_space
import Surrogates.DataExtraction.pcs_parser
import Surrogates.DataExtraction.handle_configurations
def bu... | ta[row]]))
print "..."
if args.save is not None:
fn = args.save + '_fastrf_results.csv'
print "Save to %s" % fn
with open(fn, 'wb') as csvfile:
result_writer = csv.writer(csvfile, delimiter=',', quotechar='|',
quoting=csv.QUOTE_MINIMAL)... | der])
for row in range(results.shape[0]):
line = ["%s" % str(i) for i in param_data[row]]
result_writer.writerow(line)
# Now replace cat params with numbers
for row_idx, row in enumerate(param_data):
for p_idx, p in enumerate(header):
if type_hea... |
martinjrobins/RD_3D | scripts/simpleReact_moving_interface.py | Python | lgpl-3.0 | 311 | 0.028939 | #!/usr/bin/python
import subprocess
code_dir = "."
subprocess.call([code_dir+"/release/simpleReact_moving_interface.out","10000","0.1"])
subprocess.call(["gnuplot",code_dir+"/scripts/simpleR | eact_moving_interface.gnu"])
subprocess.call(["cp",code_dir+"/simpleReact_moving_interfac | e.eps",code_dir+"/plots/"])
|
Dubrzr/golb | users/models.py | Python | mit | 1,432 | 0 | from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser
from django.db import models
class UserManager(BaseUserManager):
def create_user(self, **user_data):
user = self.model()
print(dict(user_data))
user.set_password(user_data.pop('password'))
for key, value in... | name'
REQUIRED_FIELDS = ['first_name', 'last_name', 'email', 'is_admin']
first_name = models.CharField(max_length=254)
last_name = models.CharField(max_length=254)
username = models.CharField(max_length=254, unique=True)
| email = models.EmailField(max_length=254, unique=True)
date_joined = models.DateTimeField(auto_now=True)
is_admin = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if not self.pk:
self.is_superuser = self.is_admin
self.is_staff = self.is_admin
... |
eranroz/heocr | image_extractor.py | Python | gpl-2.0 | 2,439 | 0.00697 | __author__ = 'eran'
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
from scipy.signal import convolve2d
def down_sample(img_data):
img_data = img_data[:img_data.shape[0]-img_data.shape[0] % 2, :img_data.shape[1]-img_data.shape[1] % 2, :]
img_data = img_data[::2, ::2, :]
return... | 2d(imgf[:, :, i], scharr2, boundary='symm', mode='same') for i in np.arange(3)]
grad = np.sum(np.abs(grad), 0, dtype=np.uint8)
imgf[ndimage.gaussian_filter(grad/np.mean(grad), 3) < 1] = 0
threshold = np.mean(imgf)
mask = np.any(imgf > threshold, -1)
labeled, nr_objects = ndimage.label(mask)
# la... | ch each pixel of object i is given index i
sizes = ndimage.sum(mask, labeled, range(nr_objects + 1))
#plt.title('objects are colored')
#plt.imshow(labeled)
#plt.show()
labeled[(sizes < 1000)[labeled]] = 0 # filter noise
label_im = np.searchsorted(np.unique(labeled), labeled)
# TODO: can we... |
actuaryzhang/spark | python/pyspark/ml/feature.py | Python | apache-2.0 | 155,266 | 0.003265 | #
# 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 us... | will transform the data;
if the :py:attr:`outputCol` exists, it will use that. This allows caching of the
transformed data when necessary.
:param datasetA: One of the datasets to join.
:param datasetB: Another dataset to join.
:param threshold: The threshold for the distance of... | "distCol" as default value if it's not specified.
:return: A joined dataset containing pairs of rows. The original rows are in columns
"datasetA" and "datasetB", and a column "distCol" is added to show the distance
between each pair.
"""
threshold = TypeCo... |
dkamotsky/program-y | src/test/parser/pattern/nodes/test_topic.py | Python | mit | 1,693 | 0.002363 | from test.parser.pattern.nodes.base import PatternTestBaseClass
from programy.parser.exceptions import ParserException
from programy.parser.patter | n.nodes.topic import PatternTopicNode
from programy.parser.pattern.nodes.root import PatternRootNode
class PatternTopicNodeTes | ts(PatternTestBaseClass):
def test_init(self):
node = PatternTopicNode()
self.assertIsNotNone(node)
self.assertFalse(node.is_root())
self.assertFalse(node.is_priority())
self.assertFalse(node.is_wildcard())
self.assertFalse(node.is_zero_or_more())
self.asser... |
JoeJasinski/evesch | evesch/egroup/forms.py | Python | gpl-2.0 | 1,123 | 0.026714 | from django import forms
from evesch.egroup.models import UserGroup
class UserGroupForm(forms.ModelForm):
group_desc = forms.CharField(
widget=forms.Textarea(attrs = {'cols': '30', 'rows': '5'}))
class Meta:
model = UserGroup
exclude = ['org_name','group_removable','group_hash','meta'... | attrs={'value':'group_edit'}))
class Meta:
model = UserGroup
exclude = ['org_name','group_hash','group_removable','meta']
class GroupAddMemberForm(forms.Form):
user_list = forms.CharField(required=False, max_length=512,
widget=forms.Textarea(attrs = {'cols': '45', 'rows': '5','id':'add... | iddenInput(attrs={'value':'group_member_add'}))
def clean_user_list(self):
user_string = self.cleaned_data['user_list']
user_string = user_string.strip().strip(',').strip()
return user_string
|
martinp/flask-swagger | flask_swagger/__init__.py | Python | mit | 5,769 | 0.000693 | #!/usr/bin/env python
import re
from inspect import getdoc
from urlparse import urlparse
def parse_doc(lines):
"""Create a data structure from a Sphinx-style docstring"""
doc = {}
for line in lines:
m = re.match(r'^(:\w+) ([^:]*)(?:: ?)?(.*)$', line)
if m is None:
continue
... | builder = APIBuilder(app, resource_path)
return {
'apiVersion': api_version,
'swaggerVersion': swagger_version,
'basePath': base_path,
'resourcePath': resource_path,
'apis | ': builder.make_apis(description)
}
|
conceptric/pyinvest | pyinvest/stock.py | Python | mit | 1,365 | 0.005861 | import numpy as np
class Stock:
"""
Class to represent the data and ratios of a stock.
"""
def __init__(self, eps, dps, roe=0):
'''
eps: earnings per share.
dps: dividends per share.
roe: fractional return on equity, default to 0.
'''
self.eps = n... | (1 - pa | yout ratio)^cost of equity
Returns the fractional expected growth rate numpy array.
'''
ones = np.ones_like(self.roe)
return (ones - self.payout_ratio()) * self.roe
|
StackPointCloud/ansible-modules-extras | cloud/openstack/os_project.py | Python | gpl-3.0 | 6,372 | 0.002668 | #!/usr/bin/python
# Copyright (c) 2015 IBM Corporation
#
# This module 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.
#
# This softwar... | t_spec,
supports_check_mode=True,
**module_kwargs
)
if not HAS_SHADE:
module.fail_json(msg='shade is required for this module')
name = module.params['name']
description = module.params['description']
domain = module.params.pop('domain_id')
enabled = modu | le.params['enabled']
state = module.params['state']
try:
if domain:
opcloud = shade.operator_cloud(**module.params)
try:
# We assume admin is passing domain id
dom = opcloud.get_domain(domain)['id']
domain = dom
except:... |
KennethNielsen/SoCo | tests/test_data_structures_entry_integration.py | Python | mit | 3,930 | 0.000509 | """Integration test data_structures_entry"""
import pytest
from soco.data_structures_entry import from_didl_string
from soco.data_structures import (
DidlMusicTrack,
DidlMusicArtist,
DidlMusicGenre,
DidlContainer,
DidlPlaylistContainer,
DidlMusicAlbum,
DidlPerson,
DidlAudioBroadcast,
)... | omposer.json"),
),
(
"DidlAlbumList",
DidlContainer,
DATA_LOADER.load_xml("album_list.xml"),
DATA_LOADER.load_json("share.json"),
),
(
"DidlSameArtist",
DidlPlaylistContainer,
DATA_LOADER.load_xml("same_a | rtist.xml"),
DATA_LOADER.load_json("playlist.json"),
),
(
"DidlPlaylistContainerFavorite",
DidlPlaylistContainer,
DATA_LOADER.load_xml("playlist_favorite.xml"),
DATA_LOADER.load_json("playlist.json"),
),
(
"DidlPlaylistContainerTracklist",
DidlPlay... |
Etraud123/PyCheckmarx | APICheckmarx.py | Python | mit | 2,559 | 0.02032 | #!usr/bin/python
###############################
# > Author: Duarte Monteiro
# > Version: 1.0
# > Vendor: www.checkmarx.com
# > Notes: RESTAPI for PyCheckMarx
###############################
# Python Dependencies
from flask import Flask, jsonify, request
app = Flask(__name__)
# Import PyCheckMarx
import PyCheckmarx
... | :
return pyC.getProjectScannedDisplayData()
else:
return pyC.filterProjectScannedDisplayData(projectID)
except Exception as e:
return launchError(e.message)
#
# getProjectsDisplayData
#
@app.route('/APICX/getProjectsDisplayData/', methods=["GET"])
@app.route('/APICX/getProjectsDisplayData/<int:projectID>', ... | ojectID=None):
try:
if projectID == None:
return pyC.getProjectsDisplayData()
else:
return pyC.filterProjectsDisplayData(projectID)
except Exception as e:
return launchError(e.message)
#
# getScanInfoForAllProjects
#
@app.route('/APICX/getScanInfoForAllProjects/', methods=["GET"])
@app.route('/APICX/getS... |
plum-umd/java-sketch | jskparser/ast/importdeclaration.py | Python | mit | 1,973 | 0.005575 | #!/usr/bin/env python
from node import Node
from . import _import
from .type.classorinterfacetype import ClassOrInterfaceType
class ImportDeclaration(Node):
def __init__(self, kwargs={}):
super(ImportDeclaration, self).__init__(kwargs)
locs = _import()
# NameExpr name;
... | lf.add_as_parent([self.name])
@property
def static(self): return self._static
@static.setter
def static(self, v): self._static = v
@property
def asterisk(self): return self._asterisk
@asterisk.setter
def asterisk(self, v): self._asterisk = v
@property
def isEmptyDeclaratio... | def isEmptyDeclaration(self, v): self._isEmptyDeclaration = v
@property
def implicit(self): return self._implicit
@implicit.setter
def implicit(self, v): self._implicit = v
@property
def typee(self):
return ClassOrInterfaceType({u'@t':u'ClassOrInterfaceType',
... |
TylerMoeller/fail2ban | fail2ban/exceptions.py | Python | gpl-2.0 | 1,164 | 0.004296 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
"""Fail2Ban exceptions used by both client and server
"""
# This file is part of Fail2Ban.
#
# Fail2Ban is free software; you can redistribute it and/or modif | y
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTAB... | ITY 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 Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
__author__ =... |
LCAS/spqrel_tools | actions/extracttasks.py | Python | mit | 3,145 | 0.004452 | ### register the utterance from the operator and interpret it with lu4r ###
import qi
import argparse
import sys
import time
import threading
import re
import action_base
from action_base import *
actionName = "extracttasks"
def actionThread_exec (params):
global response, lu4r_command
t = threading.current... | ter[end_fi:]
if frame == "and":
ops = rest.split("\n" + "\t"*depth + ":op")[1:]
frame_ops_list = []
for op in ops:
frame_ops_list.append(generateDict(op, depth+1))
frames_dict.update({frame: frame_ops_list})
else:
args = rest.split("\n" + "\t"*depth + ":")[1... | arg_name, arg_value = arg[:end_ani], arg[start_avi:]
if ":mod" in arg_value:
splitted = arg_value.split("\t"*(depth+1) + ":mod")
print splitted, arg_value
arg_value = splitted[0][:splitted[0].find("\n")]
mod_list = []
for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.