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 |
|---|---|---|---|---|---|---|---|---|
sigdeletras/dxf2gmlcatastro | ejemplo/catastroqgis.py | Python | gpl-3.0 | 383 | 0.007853 | # -*- coding: utf-8 -*-.
import dxf2gmlcatastro
# carpeta de trabajo
path = '/carpeta/archivos/'
# define archivos
dxf = 'parcelacad.dxf'
gml = 'catastrogml.gml'
#Define variables
dxffile = path | + dxf
gmlfile = path + gml
src = '25 | 830'
# Crea GML
dxf2gmlcatastro.crea_gml(dxffile, gmlfile, src)
#Añade capa GML a QGIS
layer = iface.addVectorLayer(gmlfile, "gmlcatastro", "ogr") |
GrognardsFromHell/TemplePlus | tpdatasrc/tpgamefiles/rules/char_class/class029_loremaster.py | Python | mit | 2,110 | 0.030806 | from toee import *
import char_class_utils
###################################################
def GetConditionName():
return "Loremaster"
def GetSpellCasterCond | itionName():
return "Loremaster Spellcasting"
def GetCategory():
return "Core 3.5 Ed Prestige Classes"
def GetClassDefinitionFlags():
return CDF_CoreClass
def GetClassHelpTopic():
return "TAG_LOREMASTERS"
classEnum = stat_level_loremaster
###################################################
class_feat | s = {
}
class_skills = (skill_alchemy, skill_appraise, skill_concentration, skill_alchemy, skill_decipher_script, skill_gather_information, skill_handle_animal, skill_heal, skill_knowledge_all, skill_perform, skill_profession, skill_spellcraft, skill_use_magic_device)
def IsEnabled():
return 0
def GetHitDieType():
... |
kalev/anaconda | scripts/getlangnames.py | Python | gpl-2.0 | 1,386 | 0.002886 | #
# getlangnames.py
#
# Copyright (C) 2007 Red Hat, Inc. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later... | rogram. If not, see <http://www.gnu.org/licenses/>.
#
import sys
sys.path.append("..")
import localeinfo
import gettext
localeInfo = localeinfo.get("en_US.UTF-8")
names = {}
for k in localeInfo.keys():
found = False
for l in localeinfo.expandLangs(k):
try:
f = open("../po/%s.gmo" %(l,))
... | set("utf-8")
names[localeInfo[k][0]] = cat.lgettext(localeInfo[k][0])
found = True
break
if not found:
names[localeInfo[k][0]] = localeInfo[k][0]
nameList = names.keys()
nameList.sort()
for k in nameList:
print("%s\t%s" % (k, names[k]))
|
tupes/School | CS175/Asn2/Reversi/model.py | Python | gpl-3.0 | 5,899 | 0.003051 |
class ReversiLogic(object):
def __init__(self):
self.turn = 'b'
self.board = Board()
# Check if the current self.turn can play. If not, change to the other
# player. If he can't play either, return None (game over).
def get_whose_turn(self):
if self.can_play():
... |
self.col = str(col)
# UTILITY FUNCTIONS
def get_key(row, col):
return str(row) + str(col)
def switch(color):
if color | == 'b': return 'w'
elif color == 'w': return 'b'
|
cloudify-cosmo/cloudify-manager | rest-service/manager_rest/test/endpoints/test_filters.py | Python | apache-2.0 | 22,691 | 0 | from cloudify.models_states import VisibilityState
from cloudify_rest_client.exceptions import CloudifyClientError
from manager_rest.test import base_test
from manager_rest.utils import get_formatted_timestamp
from manager_rest.manager_exceptions import BadFilterRule
from manager_rest.storage import models, get_storag... | 'attribute'),
FilterRule('state', ['uploaded'], AttrsOperator.NOT_CONTAINS, 'attribute'),
FilterRule('s | tate', ['uploaded', 'invalid'], AttrsOperator.NOT_CONTAINS,
'attribute'),
FilterRule('state', ['uploaded'], AttrsOperator.STARTS_WITH, 'attribute'),
FilterRule('state', ['uploaded', 'invalid'], AttrsOperator.STARTS_WITH,
'attribute'),
FilterRule('state', ['uploaded'], AttrsOper... |
kfdm/django-simplestats | quickstats/urls.py | Python | mit | 1,550 | 0.006452 | from . import views
from django.urls import path
urlpatterns = [
path("", views.PublicWidgets.as_view(), n | ame="home"),
path("create/widget", views.WidgetCreate.as_view(), name="widget-create"),
path("subscription/<pk>/delete", views.S | ubscriptionDelete.as_view(), name="subscription-delete"),
path("user/<username>/subscriptions", views.SubscriptionListView.as_view(), name="subscriptions"),
path("user/<username>/widgets", views.UserWidgets.as_view(), name="widget-user"),
# Widget Views
path("widget", views.WidgetListView.as_view(), nam... |
fxia22/ASM_xf | PythonD/site_python/twisted/internet/stdio.py | Python | gpl-2.0 | 3,287 | 0.003347 | # Twisted, the Framework of Your Internet
# Copyright (C) 2001 Matthew W. Lefkowitz
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in t... | s
import sys, os, select, errno
# Sibling Imports
import abstract, fdesc, protocol
from main import CONNECTION_LOST
_stdio_in_use = 0
class StandardIOWriter(abstract.FileDescriptor):
connected = 1
ic = 0
def __init__(self):
abstract.FileDescriptor.__init__(self)
self.fileno = sys.__std... | g(self.fileno())
def writeSomeData(self, data):
try:
return os.write(self.fileno(), data)
return rv
except IOError, io:
if io.args[0] == errno.EAGAIN:
return 0
elif io.args[0] == errno.EPERM:
return 0
re... |
MTgeophysics/mtpy | legacy/modem_data_to_phase_tensor.py | Python | gpl-3.0 | 919 | 0.007617 | #!/bin/env python
# -*- coding: utf-8 -*-
"""
Description:
Compute Phase Tensors from ModEM Dat File and output to CSV files
Usage Examples:
python scripts/mode | m_data_to_phase_tensor.py examples/data/ModEM_files/Modular_MPI_NLCG_028.dat [OutDir]
python scripts/modem_data_to_phas | e_tensor.py /e/MTPY2_Outputs/GA_UA_edited_10s-10000s_modem_inputs/ModEM_Data.dat [OutDir]
Developer: fei.zhang@ga.gov.au
LastUpdate: 08/09/2017
LastUpdate: 05/12/2017 FZ moved the function into the module mtpy.modeling.modem.Data
LastUpdate: 21/02/2018 Added command for running the script
"""
import... |
minhphung171093/GreenERP_V9 | openerp/addons/account/report/account_invoice_report.py | Python | gpl-3.0 | 9,959 | 0.004719 | # -*- coding: utf-8 -*-
from openerp import tools
from openerp import models, fields, api
class AccountInvoiceReport(models.Model):
_name = "account.invoice.report"
_description = "Invoices Statistics"
_auto = False
_rec_name = 'date'
@api.multi
@api.depends('currency_id', 'date', 'price_tot... | voice AS date,
ail.product_id, ai.partner_id, ai.payment_term_id, ail.account_analytic_id,
u2.name AS uom_name,
ai.currency_id, ai.journal_id, ai.fiscal_position_id, ai.user_id, ai.company_id,
count(ail.*) AS nbr,
ai.typ... | .state, pt.categ_id, ai.date_due, ai.account_id, ail.account_id AS account_line_id,
ai.partner_bank_id,
SUM(CASE
WHEN ai.type::text = ANY (ARRAY['out_refund'::character varying::text, 'in_invoice'::character varying::text])
THE... |
erigones/esdc-ce | pdns/migrations/0001_initial.py | Python | apache-2.0 | 9,038 | 0.003098 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Domain',
fields=[
('id', models.AutoField(help_... | LTER TABLE domains ADD CONSTRAINT c_lowercase_name CHECK (((name)::TEXT = lower((name)::TEXT)));
ALTER TABLE domains ALTER COLUMN "access" SET DEFAULT 3;
ALTER TABLE domains ALTER COLUMN "desc" SET DEFAULT '';
ALTER TABLE domains ALTER COLUMN "user" SET DEFAULT 1;
GRANT ALL ON domains TO pdns;
GRANT... | """),
# Update records table
migrations.RunSQL("""
ALTER TABLE records ADD CONSTRAINT c_lowercase_name CHECK (((name)::TEXT = lower((name)::TEXT)));
ALTER TABLE records ADD CONSTRAINT domain_exists FOREIGN KEY(domain_id) REFERENCES domains(id) ON DELETE CASCADE;
ALTER TABLE recor... |
hzlf/openbroadcast | website/djangoratings/forms.py | Python | gpl-3.0 | 100 | 0.02 | from django im | port forms
__all__ = ('RatingField',)
cl | ass RatingField(forms.ChoiceField):
pass |
passalis/sef | examples/supervised_reduction.py | Python | mit | 2,019 | 0.005448 | # License: MIT License https://github.com/passalis/sef/blob/master/LICENSE.txt
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import sklearn
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sef_dr.classification import evaluate_svm
from se... | :], target_labels=train_labels[:n_train], epochs=50,
target='supervised', batch_size=128, regularizer_weight=1, learning_rate=0.001, verbose=True)
elif method == 's-lda-2x':
# SEF output dimensions are not limited
proj = LinearSEF(train_data.shape[1], | output_dimensionality=2 * (n_classes - 1))
proj.cuda()
loss = proj.fit(data=train_data[:n_train, :], target_labels=train_labels[:n_train], epochs=50,
target='supervised', batch_size=128, regularizer_weight=1, learning_rate=0.001, verbose=True)
acc = evaluate_svm(proj.transf... |
neutrons/FastGR | addie/processing/mantid/master_table/table_tree_handler.py | Python | mit | 66,023 | 0.001287 | from __future__ import (absolute_import, division, print_function)
from collections import OrderedDict
import numpy as np
import os
import pickle
from qtpy.QtWidgets import QDialog, QTreeWidgetItem, QTableWidgetItem, QMenu, QFileDialog, QApplication
from addie.utilities import load_ui
from qtpy import QtCore, QtGui
... | import pyoncat # noqa
ONCAT_ENABLED = True
except ImportError:
print('pyoncat module not found. Functionality disabled')
ONCAT_ENABLED = False
class TableInitialization:
default_width = COLUMN_DEFAULT_WIDTH
table_headers = {}
table_width = {}
def __init__(self, main_window=None):
... | elf.parent = parent
# self.parent_ui = parent.processing_ui
self.tree_dict = TREE_DICT
def init_master_table(self):
# set h1, h2 and h3 headers
self.init_headers()
self.init_table_header(
table_ui=self.main_window.processing_ui.h1_table,
list_items=se... |
bnewbold/diffoscope | tests/comparators/test_debian.py | Python | gpl-3.0 | 5,786 | 0.004842 | # -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
#
# diffoscope 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 Foundati... | are_non_existing(monkeypatch, dot_dsc1):
monkeypatch.setattr(Config.general, 'new_file', True)
difference = dot_dsc1.compare(NonExistingFile('/nonexisting', dot_dsc1))
output_text(difference, print_func=pri | nt)
assert difference.source2 == '/nonexisting'
assert difference.details[-1].source2 == '/dev/null'
|
mtskelton/huawei-4g-stats | stats/migrations/0001_initial.py | Python | mit | 718 | 0.001393 | # -*- coding: utf-8 -*-
from __ | future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Stat',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, au... | ('up', models.BigIntegerField()),
('down', models.BigIntegerField()),
('live_time', models.BigIntegerField()),
],
options={
},
bases=(models.Model,),
),
]
|
benley/Mathics | mathics/builtin/files.py | Python | gpl-3.0 | 138,763 | 0.000649 | # -*- coding: utf8 -*-
"""
File Operations
"""
from __future__ import with_statement
import os
import io
import shutil
import hashlib
import zlib
import base64
import tempfile
import time
import struct
import sympy
import mpmath
import math
from mathics.core.expression import (Expression, Real, Complex, String, Symb... | t.m
if result is not None and os.path.isdir(result):
for ext in [os.path.join('Kernel', 'init.m'), 'init.m']:
tmp = os.path.join(result, ext)
if os.path.isfile(tmp):
| return tmp
return result
def count():
n = 0
while True:
yield n
n += 1
NSTREAMS = count() # use next(NSTREAMS)
STREAMS = []
def _channel_to_stream(channel, mode='r'):
if isinstance(channel, String):
name = channel.get_string_value()
opener = mathics_op... |
CINPLA/expipe-dev | python-neo/doc/source/images/generate_diagram.py | Python | gpl-3.0 | 7,653 | 0.000523 | # -*- coding: utf-8 -*-
"""
This generate diagram in .png and .svg from neo.core
Author: sgarcia
"""
from datetime import datetime
import numpy as np
import quantities as pq
from matplotlib import pyplot
from matplotlib.patches import Rectangle, ArrowStyle, FancyArrowPatch
from matplotlib.font_manager import FontP... | y2 >= y1:
connectionstyle = "arc3,rad=0.7"
else:
connectionstyle = "arc3,rad=-0.7"
annotate( | ax=ax, coord1=(x1, y1), coord2=(x2, y2),
connectionstyle=connectionstyle,
color=color[r], alpha=alpha[r])
# draw boxes
for name, pos in rect_pos.items():
htotal = all_h[name]
obj = objs[name]
allrelationship = (list(getattr(obj, '_child_... |
CLCMacTeam/AutoPkgBESEngine | Code/BESTemplater.py | Python | gpl-2.0 | 2,795 | 0.003936 | #!/usr/local/autopkg/python
# encoding: utf-8
#
# Copyright 2015 The Pennsylvania State University.
#
"""
BESTemplater.py
Created by Matt Hansen (mah60@psu.edu) on 2015-04-30.
AutoPkg Processor for importing tasks using the BigFix RESTAPI
Updated by Rusty Myers (rzm102@psu.edu) on 2020-02-21.
Work in progress. Does... | et_template(template_name)
# print jinja_env.list_templates()
rendered_task = template_task.render(**self.env)
# Write Final BES File to D | isk
outputfile_handle = open("%s/Deploy %s %s.bes" %
(self.env.get("RECIPE_CACHE_DIR"),
name, version), "wb")
outputfile_handle.write(rendered_task)
outputfile_handle.close()
self.env['bes_file'] = outputfile_handle.nam... |
brianspeir/Vanilla | vendor/bootstrap-vz/common/phases.py | Python | bsd-3-clause | 1,251 | 0.005596 | from base import Phase
preparation = Phase('Preparation', 'Initializing connections, fetching data etc.')
volume_creation = Phase('Volume creation', 'Creating the volume to bootstrap onto')
volume_preparation = Phase('Volume preparation', 'Formatting the bootstrap volume')
volume_mounting = Phase('Volume mounting', 'M... | s and other leftovers')
volume_unmounting = Phase('Volume unmounting', 'Unmounting the bootstrap volume')
image_registration = Phase('Image registration', 'Uploading/Registering with the provider') |
cleaning = Phase('Cleaning', 'Removing temporary files')
order = [preparation,
volume_creation,
volume_preparation,
volume_mounting,
os_installation,
package_installation,
system_modification,
system_cleaning,
volume_unmounting,
image_re... |
dominicrodger/django-tinycontent | tinycontent/migrations/0001_initial.py | Python | bsd-3-clause | 570 | 0.001754 | from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='TinyContent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_ke... | ('name', models.CharField(uniqu | e=True, max_length=100)),
('content', models.TextField()),
],
options={
'verbose_name': 'Content block',
},
),
]
|
UnrememberMe/pants | src/python/pants/engine/isolated_process.py | Python | apache-2.0 | 2,261 | 0.008403 | # coding=utf-8
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
from... | pants.engine.selectors import Select
from pants.util.objects import datatype
logger = logging.getLogger(__name__)
class ExecuteProcessRequest(datatype('ExecuteProcessRequest', ['argv', 'env', 'input_files_digest', 'digest_length'])) | :
"""Request for execution with args and snapshots to extract."""
@classmethod
def create_from_snapshot(cls, argv, env, snapshot):
return ExecuteProcessRequest(
argv=argv,
env=env,
input_files_digest=snapshot.fingerprint,
digest_length=snapshot.digest_length,
)
@classmethod
d... |
Jozhogg/iris | lib/iris/tests/unit/fileformats/grib/test_GribWrapper.py | Python | lgpl-3.0 | 6,115 | 0 | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any later ve... | warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Unit tests for the `iris.fileformats.grib.Gr... | rting anything else.
import iris.tests as tests
from biggus import NumpyArrayAdapter
import mock
import numpy as np
from iris.fileformats.grib import GribWrapper, GribDataProxy
_message_length = 1000
def _mock_grib_get_long(grib_message, key):
lookup = dict(totalLength=_message_length,
number... |
cherokee/webserver | admin/Handler.py | Python | gpl-2.0 | 1,775 | 0.007324 | # -*- coding: utf-8 -*-
#
# Cherokee-admin
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2001-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free S... | that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Pu | blic License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
import CTK
import Cherokee
import validations
URL_APPLY = '/plugin/handler/apply'
NOTE_DOCUMENT_ROOT = N_('Allows to specify an alternative Document Root pat... |
GaloMALDONADO/motorg | motorog/filterKinematics.py | Python | gpl-3.0 | 2,952 | 0.013211 | import numpy as np
from bmtools.filters import filtfilt_butter
def derivatefilterQ(model, q, t, cutoff, fs, filter_order=4):
'''
Differentiate data using backwards finite differences and
butterworth low pass filter. Takes care of quaternions
Inputs: ... | oat64(t[frame+1]-t[frame])
| q1 = q[frame,:]
q2 = q[frame+1,:]
diff = se3.differentiate(model, q1, q2)/dt
dq[frame,:] = diff.A1
dq[-1,:] = dq[-2,:]
# Filter
dq_prime = np.empty((len(t), model.nv))
for i in xrange(model.nv):
filtered = filtfilt_butter(dq[:,i], cutoff, fs, filter_order)
... |
Jumpscale/play7 | gogsclient/gogsclient.py | Python | apache-2.0 | 4,050 | 0.010123 | import requests
import json
from JumpScale import j
from mongoengine import *
ENTRY_POINT =""
TOKEN=""
class ModelGogsRepo(j.core.models.getBaseModel()):
name = StringField(default='')
description = StringField(default='')
private = BoolField(default=False)
readme = StringField(default='Default')
... | 'firstname': 'Mark',
'lastname': 'Green',
'role': ['copy', 'author'],
'location': {'address': '4925 Lacross Road', 'city': 'New York'},
'born': 'Sat, 23 Feb 1985 12:00:00 GMT'
},
{
'firstname': 'Julia'... | ': 'San Francisco'},
'born': 'Sun, 20 Jul 1980 11:00:00 GMT'
},
{
'firstname': 'Anne',
'lastname': 'White',
'role': ['contributor', 'copy'],
'location': {'address': '32 Joseph Street', 'city': 'Ashfield'},
... |
tinkerinestudio/Tinkerine-Suite | TinkerineSuite/Cura/cura_sf/skeinforge_application/skeinforge_plugins/craft_plugins/stretch.py | Python | agpl-3.0 | 21,092 | 0.022331 | """
This page is in the table of contents.
Stretch is very important Skeinforge plugin that allows you to partially compensate for the fact that extruded holes are smaller then they should be. It stretches the threads to partially compensate for filament shrinkage when extruded.
The stretch manual page is at:
http://... | dth' ratio.
==Examples==
The following examples stretch the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holde | r Bottom.stl and stretch.py.
> python stretch.py
This brings up the stretch dialog.
> python stretch.py Screw Holder Bottom.stl
The stretch tool is parsing the file:
Screw Holder Bottom.stl
..
The stretch tool has created the file:
.. Screw Holder Bottom_stretch.gcode
"""
from __future__ import absolute_import
fro... |
MjAbuz/flask | flask/ctx.py | Python | bsd-3-clause | 14,399 | 0.000625 | # -*- coding | : utf-8 -*-
"""
flask.ctx
~~~~~~~~~
Implements the objects required to keep the context.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import with_statement
import sys
from functo | ols import update_wrapper
from werkzeug.exceptions import HTTPException
from .globals import _request_ctx_stack, _app_ctx_stack
from .module import blueprint_is_module
from .signals import appcontext_pushed, appcontext_popped
class _AppCtxGlobals(object):
"""A plain object."""
def get(self, name, default=N... |
zack3241/incubator-airflow | airflow/sensors/base_sensor_operator.py | Python | apache-2.0 | 2,492 | 0 | # -*- coding: utf-8 -*-
#
# 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
... | s
class BaseSensorOperator(BaseOperator):
"""
Sensor operators are derived from this class an inherit these attributes.
Sensor operators keep executing at a time interval and succeed when
a criteria is met and fail if and when they time out.
:param soft_fail: Set to true to mark the task as ... | poke_interval: int
:param timeout: Time, in seconds before the task times out and fails.
:type timeout: int
"""
ui_color = '#e6f1f2'
@apply_defaults
def __init__(self,
poke_interval=60,
timeout=60 * 60 * 24 * 7,
soft_fail=False,
... |
Bismarrck/pymatgen | pymatgen/optimization/__init__.py | Python | mit | 229 | 0.026201 | # coding: utf-8
# Copyright (c) | Pymatgen Development Team.
<<<<<<< HEAD
# Distributed under the terms of the MIT License.
=======
# Distributed under the terms of the MIT | License.
>>>>>>> a41cc069c865a5d0f35d0731f92c547467395b1b
|
TravelModellingGroup/TMGToolbox | TMGToolbox/src/XTMF_internal/import_function_batch_file.py | Python | gpl-3.0 | 2,153 | 0.010218 | '''
Copyright 2021 Travel Modelling Group, Department of Civil Engineering, University of Toronto
This file is part of the TMG Toolbox.
The TMG Toolbox 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 Fou... | . See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the TMG Toolbox. If not, see <http://www.gnu.org/licenses/>.
'''
#---METADATA---------------------
' | ''
Copy Scenario
Authors: JamesVaughan
Latest revision by: JamesVaughan
This tool will allow XTMF to be able to execute a vdf batch file into
an EMME Databank.
'''
#---VERSION HISTORY
'''
0.0.1 Created on 2021-01-20 by JamesVaughan
'''
import inro.modeller as _m
import... |
ScottWales/rose | lib/python/rose/config_editor/data_helper.py | Python | gpl-3.0 | 21,509 | 0.000372 | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-5 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | }, "variables": {}}
config_name = self.util.split_full_ns(self.data, ns)[0]
config_data = self.data.config[config_name]
for sect, sect_data in config_data.sections.now.items():
sect_ns = sect_data.metadata["full_ns"]
if sect_ns.startswith(ns):
sub_data["se... | if variable.metadata["full_ns"].startswith(ns):
sub_data["variables"].setdefault(sect, |
skilstak/code-dot-org-python | codestudio/artist.py | Python | unlicense | 10,452 | 0.00995 | """Artist puzzles from <http://code.org> built on `tkinter` only.
Artist is similar to the great `turtle` standard module for teaching
programming but builds on a foundation of puzzle and solution, (which
`turtle` does not):
- Subset of basic Python turtle commands (all needed for puzzles).
- Puzzles created by stu... | = proto.theme
self.x = proto.x
self.y = proto.y
self.direction = proto.start_direction
self.startx = proto.startx
self.starty = proto.starty
self.lastx = proto.lastx
self.lasty = proto.lasty
self.last_direction = proto.di... | else:
self.canvas = Canvas()
self.puzzle = []
self.log = []
self.uid = None
self.type = 'artist'
self.theme = 'default'
self.x = self.startx
self.y = self.starty
self.direction = self.start_direction
... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.4.3/Lib/email/Message.py | Python | mit | 31,201 | 0.000609 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Basic message object for the email package object model."""
import re
import uu
import binascii
import warnings
from cStringIO import StringIO
# Intrapackage imports
from email import Utils
from email impor... | ), sfp, quiet=True)
payload = sfp.getvalue()
except uu.Error:
# Some decoding problem
return payload
# Everything else, including encodings with 8bit or 7bit are returned
# unchanged.
return payload
def s | et_payload(self, payload, charset=None):
"""Set the payload to the given value.
Optional charset sets the message's default character set. See
set_charset() for details.
"""
self._payload = payload
if charset is not None:
self.set_charset(charset)
def s... |
tongwang01/tensorflow | tensorflow/python/ops/array_ops.py | Python | apache-2.0 | 86,939 | 0.004911 | # Copyright 2015 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... | ther_nd
@@unique_with_counts
@@scatter_nd
@@dynamic_partition
@@dynamic_stitch
@@boolean_mask
@@one_hot
@@sequence_mask
@@dequantize
@@quantize_v2
@@quantized_concat
@@setdiff1d
## Fake quantization
Operations used to help train for better quantization accuracy.
@@fake_quan | t_with_min_max_args
@@fake_quant_with_min_max_args_gradient
@@fake_quant_with_min_max_vars
@@fake_quant_with_min_max_vars_gradient
@@fake_quant_with_min_max_vars_per_channel
@@fake_quant_with_min_max_vars_per_channel_gradient
"""
from __future__ import absolute_import
from __future__ import division
from __future__ imp... |
alibozorgkhan/utils | utils/fileoo.py | Python | mit | 1,696 | 0 | # -*- coding: utf-8 -*-
import csv
import os
impo | rt gzip
class File:
def read(self, path, **kwargs):
path = os.path.join(kwargs.get('root_path', ''), path)
content_type = kwargs.get('content_type', 'txt')
if content_type == 'txt':
with file(path, 'r') as f:
content = f.read()
yield content
... | eld content
elif content_type == 'csv':
with open(path, 'rU') as f:
reader = csv.reader(f)
for line in reader:
yield line
else:
raise Exception('Bad file type')
def write(self, path, content, **kwargs):
path = os.pa... |
unioslo/cerebrum | Cerebrum/modules/virthome/base.py | Python | gpl-2.0 | 29,202 | 0.001609 | # -*- encoding: utf-8 -*-
#
# Copyright 2013-2021 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
... | unt import BaseVirtHomeAccount, FEDAccount, VirtAccount
# TODO: Is this okay? Shou | ld we just have one class in stead? There's no real
# reason to keep two classes...
# They have been split up here in order to separate between methods that
# should be visible (imported) in other modules. All the methods in
# VirthomeUtils should only be used here. However, they DO need to be
#... |
razzius/PyClassLessons | instructors/course-2015/functions_gens_and_ducks/examples/in_class/parsetext_trade_2015.py | Python | mit | 2,835 | 0.018342 | # -*- coding: utf-8 -*-
#above helps to declare what encoding we want to use in the module
#note this is copied from | the first json lab
#above is used to set the encoding for this module, (unfortunately didn't help that much)
#used for seeing our data in nicest string format possible
import pprint
#again idiom for reading in a file, relative path given
with open('../pres_on_trade.txt', 'r') as fp:
all_text = fp.read()
#str.... | s on any white space, easy... nice
#sorted built-in function will only sort alphbetically here
all_words = sorted(all_text.split())
#begin preparation of words for a reasonable word frequency count
#we need to change our words from str to unicode
#unicode_words = [unicode(word) for word in all_words if unicode(word... |
bsmr-eve/Pyfa | eos/effects/shipheavymissileexpdmgpiratecruiser.py | Python | gpl-3.0 | 309 | 0.006472 | # shipHeavyMissileExpDmgPirateCruiser
#
# Used | by:
# Ship: Gnosis
type = "passive"
def handler(fit, ship, context):
fit.modules.filteredChargeBoost(lambda mod: mod.charge.requiresSkill("Heavy Missiles"),
| "explosiveDamage", ship.getModifiedItemAttr("shipBonusRole7"))
|
pbombnz/IRCBot | modules/whatPulse.py | Python | gpl-2.0 | 4,737 | 0.004222 | import urllib.request
import json
from modules import userDatabase
def get_what_pulse_url(param: str):
return "http://api.whatpulse.org/user.php?user=" + str(param) + "&formatted=yes&format=json"
# noinspection PyUnusedLocal
def on_channel_pm(irc, user_mask, user, channel, message):
command = message.split(... | )")
irc.send_private_message(channel, "USAGE: !setw[hat]p[ulse] (WhatPulse ID)")
return
elif len(command) == 2:
command = message.split(' ', 1)
param = str(command[1])
if command[1].lo | wer() in irc.user_info:
if irc.user_infoData[command[1].lower()]['whatpulse'] != "":
param = str(irc.userData[command[1].lower()]['whatpulse'])
try:
response = urllib.request.urlopen(get_what_pulse_url(param))
html_source = response.read().decode('utf... |
ContinuumIO/blaze | blaze/index.py | Python | bsd-3-clause | 1,644 | 0.001217 | from .dispatch import dispatch
from .compatibility import basestring
from blaze.expr.literal import BoundSymbol, data as bz_data
@dispatch(object, (basestring, list, tuple))
def create_index(t, column_name_or_names, name=None):
"""Create an index on a column.
Parameters
----------
o : table-like
... | to index on, or a list or tuple for a composite index
Examples
--------
>>> # Using SQLite
>>> from blaze import SQL
>>> # create a table called 'tb', i | n memory
>>> sql = SQL('sqlite:///:memory:', 'tb',
... schema='{id: int64, value: float64, categ: string}')
>>> dta = [(1, 2.0, 'a'), (2, 3.0, 'b'), (3, 4.0, 'c')]
>>> sql.extend(dta)
>>> # create an index on the 'id' column (for SQL we must provide a name)
>>> sql.table.indexes
se... |
jsha/letsencrypt | certbot-apache/certbot_apache/parser.py | Python | apache-2.0 | 27,616 | 0.000036 | """ApacheParser is a member object of the ApacheConfigurator class."""
import copy
import fnmatch
import logging
import os
import re
import subprocess
import sys
import six
from certbot import errors
from certbot_apache import constants
logger = logging.getLogger(__name__)
class ApacheParser(object):
"""Class... | "Error parsing Apache runtime | variables")
parts = match.partition("=")
variables[parts[0]] = parts[2]
self.variables = variables
def _get_runtime_cfg(self): # pylint: disable=no-self-use
"""Get runtime configuration info.
:returns: stdout from DUMP_RUN_CFG
"""
try:
... |
mesoscloud/events | 0.5.6/docker.py | Python | mit | 1,100 | 0.002727 | """docker"""
import http.client
import json
import socket
__all__ = ['HTTPConnection', 'HTTPError', 'get']
class HTTPConnection(http.client.HTTPConnection):
def __init__(self):
http.client.HTTPConnection.__init__(self, 'localhost')
def connect(self):
sock = socket.socket(socket.AF_UNIX, so... | eason = reason
def get(path, async=False):
conn = HTTPConnection()
try:
conn.request('GET', path)
resp = conn.getresponse()
if resp.status != 200:
raise HTTPError(resp.status, resp.reason)
except Exception:
conn.close()
raise
try:
if async:... | de('utf-8'))
else:
return resp.read()
finally:
if not async:
conn.close()
|
frederick623/wat | date_transform.py | Python | apache-2.0 | 2,296 | 0.037021 | import csv
import os
import sys
import traceback
import sqlite3
import fnmatch
import decimal
import datetime
def valid_dt(dt):
try:
datetime.datetime.strptime(dt, "%m/%d/%Y")
return True
except:
return False
def adapt_decimal(d):
return str(d)
def convert_decimal(s):
return decimal.Decimal(s)
def db_cur(... | arr[0])
arr = arr[start:]
return header, arr
else:
return arr[start:]
return
def arr_to_csv(file_name, header, data_arr):
csv_file = open(file_name, 'wb')
wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
wr.writerow(header.split(','))
for data_row in data_arr:
line = []
for ele in data_row:
line.a... | .csv")
print arr[0]
|
winhamwr/django-attendance | django_attendance/models.py | Python | bsd-3-clause | 1,202 | 0.000832 | import datetime
from django.db import models
f | rom django.utils.translation import ugettext, ugettext_lazy as _
from django.contrib.auth.models import User
from django.contrib import admin
from schedule.models import Occurrence
from django_attendance.conf import settings as attendance_settings
class EventAttendance(models.Model):
'''
The attendance statu... | ld(User)
class Meta:
verbose_name = _('attendance')
verbose_name_plural = _('attendances')
def __unicode__(self):
return "Attendance for %s-%s" % (self.occurrence.title,
self.occurrence.start)
def duration(self):
"""
Get the... |
sandow-digital/django-filebrowser-no-grappelli-sandow | filebrowser/views.py | Python | bsd-3-clause | 19,288 | 0.005081 | # coding: utf-8
# general imports
import os, re
from time import gmtime, strftime
# django imports
from django.shortcuts import render_to_response, HttpResponse
from django.template import RequestContext as Context
from django.http import HttpResponseRedirect
from django.contrib.admin.views.decorators import staff_me... | LUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
filtered = file.startswith('.')
for re_prefix in filter_r | e:
if re_prefix.search(file):
filtered = True
if filtered:
continue
results_var['results_total'] += 1
# CREATE FILEOBJECT
fileobject = FileObject(os.path.join(DIRECTORY, path, file))
# FILTER / SEARCH
append = Fals... |
AAorris/search | src/bing/runtime.py | Python | mit | 523 | 0.003824 | """
Provides a more structured call to the nodejs bing
"""
import os
impo | rt sys
import argparse
import subprocess
def main():
parser = argparse.ArgumentParser(description="Use Bing's API services")
parser.add_argument("query", nargs="*", help="Query string")
parser.add_argument("-s", "--service", default="Web", choices=["Web", "Image", "News"])
args = parser.parse_args()
... | (args.service, query))
if __name__ == '__main__':
main()
|
brettcs/diffoscope | tests/comparators/test_macho.py | Python | gpl-3.0 | 2,299 | 0.003486 | # -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2015 Jérémy Bobbio <lunar@debian.org>
# Copyright © 2015 Clemens Lang <cal@macports.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public L... | est1.macho')
obj2 = load_fixture('test2.macho')
def test_obj_identification(obj1):
assert isinstance(obj1, MachoFile)
def test_obj_no_differences(obj1):
difference = obj1.compare(obj1)
assert difference is None
@pytest.fixture
def obj_differences(obj1, obj2) | :
return obj1.compare(obj2).details
@skip_unless_tools_exist('otool', 'lipo')
def test_obj_compare_non_existing(monkeypatch, obj1):
monkeypatch.setattr(Config(), 'new_file', True)
difference = obj1.compare(MissingFile('/nonexisting', obj1))
assert difference.source2 == '/nonexisting'
assert len(dif... |
vonderborch/CS355 | sps - working/sps.py | Python | mit | 9,305 | 0.013649 | #!/usr/bin/python3
import re
import sys
######## Global Variables
# Stacks
dictionary = []
execution = []
operand = []
# Sept 21, 2011 -- fixed the handling of }{ -- each brace should be a separate token
# A regular expression that matches postscript each different kind of postscript token
pattern = '/?[a-zA-Z][a-zA-... | return True
######## Stack Control
def DictionaryPushItem(t,value):
x = {t:value}
dictionary[len(dictionary)].append(x)
def DictionaryPush(t):
dictionary.append(t)
def DictionaryPop():
return dictionary.pop()
def ExecutionPush(t):
execution.append(t)
def ExecutionPop():
if len(execution) >... | dPush(t):
operand.append(t)
return t
def OperandPushPosition(t,p):
operand.insert(p,t)
return t
def OperandPop():
return operand.pop()
######## File Reader
# Given a string, return the tokens it contains
def parse(s):
tokens = re.findall(pattern, s)
return tokens
# Given an open file, return... |
SELO77/seloPython | 3.X/ex/strFormat.py | Python | mit | 217 | 0.004608 | # testStr = "Hello {n | ame}, How long have you bean?. I'm {myName}"
#
# testStr = testStr.format(name="Leo", myName="Serim")
#
# print(testStr)
limit = None
hello = str(limit, "")
print(hello)
# print( " | 4" in "3.5")
|
leechy9/Vigilante | vigilante.py | Python | gpl-3.0 | 5,186 | 0.016969 | '''
Reads scrambled Vigenere Cipher text from stdin and attempts to decrypt it.
Written for Python 2.7.
Copyright (C) 2014 leechy9
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 ... | etters = [l for l in string.uppercase if l not in count]
for l in unfound_letters: count[l] = 0
total_letters = 0.0
for l,c in count.most_common(): total_letters += c
# Try to find the smallest difference between actual and expected frequencies
differences = defaultdict(float)
# Try shifting through every c... | unt[rotated]/total_letters)
# The smallest difference is most likely the shift value
smallest = 0
for s,d in differences.iteritems():
if differences[s] < differences[smallest]:
smallest = s
return smallest
def vigenere_shift(text, shift_values):
'''Rotates text by the shift_values given. Returns sh... |
plasmodic/hippodraw | examples/run_examples.py | Python | gpl-2.0 | 1,052 | 0.004753 | """
Run example scripts.
@author J. Chiang <jchiang@slac.stanford.edu>
@author Paul F. Kunz <Paul_Kunz@slac.stanford.edu>
"""
#$Id: run_examples.py,v 1.13 2006/10/03 20:02:20 pfkeb Exp $
import sys
from load_hippo import app, canvas
prompt = 1
scripts = []
scripts.append('static_vs_dynamic')
scripts.append('loglo... | y')
scripts.append('cuts_complex')
scripts.append('function_ntuple')
scripts.append('fitting')
scripts.append('fitting2')
scripts.append('simple_xyplot')
scripts.append('mainpage')
scripts.append('fft')
scripts.append('displays')
def prompt(prompt = None):
if (prompt):
sys.stderr.write(prompt)
| else:
sys.stderr.write("Hit return to continue: ")
x = sys.stdin.readline()
return x
print "Hit return to run named script"
for name in scripts :
prompt("Run %s: " % name)
canvas.clear()
command = 'import ' + name
exec(command)
print "All done. Enjoy!"
|
ivandm/django-geopositionmap | geopositionmap/geoWidgets.py | Python | mit | 2,620 | 0.003817 | # -*- coding: ISO-8859-1 -*-
"""
Form Widget classes specific to the geoSite admin site.
"""
# A class that corresponds to an HTML form widget,
# e.g. <input type="text"> or <textarea>.
# This handles rendering of the widget as HTML.
import json
from django.template.loader import render_to_string
from .conf import ... | eturn [None,None]
def format_output(self, rendered_widgets):
return render_to_string('geopositionmap/widgets/geopositionmap.html', {
'latitude': {
| 'html': rendered_widgets[0],
'label': _("latitude"),
},
'longitude': {
'html': rendered_widgets[1],
'label': _("longitude"),
},
'config': {
'map_widget_height': settings.GEOPOSITIONMAP_MAP_WIDGET_HEIGHT,
... |
whosken/reversedict | reversedict/__init__.py | Python | mit | 1,266 | 0.014218 | import elastic
import nlp
def lookup(description, synonyms=None):
'''
Look up words by their definitions
using the indexed terms and their synonyms.
'''
description = nlp.correct(description)
query = {'bool':{'must':get_definition_query(description)}}
synonym_query = get_synonym_query(descr... | nyms=None):
query = {'match':{'definitions':{'query':unicode(description),
'cutoff_frequency':0.001}}}
| return query
def get_synonym_query(description, synonyms=None):
tokens = nlp.tokenize(description) + (synonyms or [])
if not tokens:
return None
return {'match':{'synonyms':{'query':tokens, 'operator':'or'}}}
def parse_results(results):
print 'found', results['hits'].get('total')
return... |
carsongee/edx-platform | common/djangoapps/edxmako/__init__.py | Python | agpl-3.0 | 676 | 0.001479 | # Copyright (c) 2008 Mikeal Rogers
#
# 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 the License is distributed on an "AS IS... | Y KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
LOOKUP = {}
from .paths import add_lookup, lookup_template, clear_lookups
|
muneebalam/scrapenhl | scrapenhl/scrape_season.py | Python | mit | 13,272 | 0.008137 | import scrapenhl_globals
import scrape_game
def scrape_games(season, games, force_overwrite = False, pause = 1, marker = 10):
"""
Scrapes the specified games.
Parameters
-----------
season : int
The season of the game. 2007-08 would be 2007.
games : iterable of ints (e.g. list)
... | 21230 for regular season, and 30111 to 30417 for playoffs.
The preseason, all-star game, Olympics, and World Cup also have game IDs that can be provided.
force_overwrite : bool
If | True, will overwrite previously raw html files. If False, will not scrape if files already found.
pause : float or int
The time to pause between requests to the NHL API. Defaults to 1 second
marker : float or int
The number of times to print progress. 10 will print every 10%; 20 every 5%.
"... |
Thortoise/Super-Snake | Blender/animation_nodes-master/nodes/vector/combine_vector.py | Python | gpl-3.0 | 729 | 0.002743 | import bpy
from ... base_types.node import AnimationNode
class CombineVectorNode(bpy.types.Node, AnimationNode):
bl_idname = "an_CombineVectorNode"
bl_label = "Combine Vector"
dynamicLabelType = "HIDDEN_ONLY"
def create(self):
self.newInput("Float", "X", "x")
self.newInput("Float", "Y"... | self.newInput("Float", "Z", "z")
self.newOutput("Vector", "Vector", "vector")
def drawLabel(self):
label = "<X, Y, Z>"
for axis in "XYZ":
if self.inputs[axis].isUnlinked:
label = label.replace(axis, str(round(self.inputs[axis].value, 4)))
return label
... | (x, y, z))"
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractRumorsBlock.py | Python | bsd-3-clause | 393 | 0.022901 | def | extractRumorsBlock(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if "Rumor's Block" in item['tags'] and 'chapter' in item['title'].lower():
return buildReleaseMessageWithType(item, "Rumor's Block... | rn False
|
kamcpp/tensorflow | tensorflow/contrib/rnn/python/ops/lstm_ops.py | Python | apache-2.0 | 23,693 | 0.005149 | # 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... | if cell_size is None:
raise ValueError("cell_size from `cs_prev` should not be None.")
wci = array_ops.constant(0, dtype=dtypes.float32, shape=[cell_size])
wco = wci
wcf = wci
# pylint: disable=protected-access
return _lstm_ops_so.lstm_block_cell(
x=x,
cs_prev=cs_ | prev,
h_prev=h_prev,
w=w,
wci=wci,
wco=wco,
wcf=wcf,
b=b,
forget_bias=forget_bias,
cell_clip=cell_clip,
use_peephole=use_peephole,
name=name)
# pylint: enable=protected-access
def _block_lstm(seq_len_max,
x,
w,
... |
PuzzleboxIO/orbit-python | Puzzlebox/Orbit/__init__.py | Python | agpl-3.0 | 229 | 0 | # -*- coding: utf-8 -*-
__doc__ = """\
Copyright Puzzlebox Productions, LLC (2010)
This code is released under t | he GNU Pulic License (GPL) version 2
For more information please refer to http://www.gnu.org/cop | yleft/gpl.html
"""
|
ArseniyK/Sunflower | application/gui/input_dialog.py | Python | gpl-3.0 | 60,030 | 0.023755 | import os
import gtk
import time
import locale
import fnmatch
import user
from plugin_base.provider import FileType, Support as ProviderSupport
from common import get_user_directory, UserDirectory
from widgets.completion_entry import PathCompletionEntry
from queue import OperationQueue
# constants
class OverwriteOpt... | mission_group_read, 1, 2, 1, 2)
self._permission_group_write = gtk.CheckButton(_('Write'))
self._permission_group_write.connect('toggled', self._update_octal, (1 << 1) * 10)
table.attach(self._permission_group_write, 2, 3, 1, 2)
| self._permission_group_execute = gtk.CheckButton(_('Execute'))
self._permission_group_execute.connect('toggled', self._update_octal, (1 << 0) * 10)
table.attach(self._permission_group_execute, 3, 4, 1, 2)
# others checkboxes
self._permission_others_read = gtk.CheckButton(_('Read'))
self._permission_others_re... |
kiip/statsite | tests/unit/test_collector.py | Python | bsd-3-clause | 2,419 | 0.000827 | """
Contains tests for the collector base class.
"""
import pytest
from tests.base import TestBase
from statsite.metrics import Counter, KeyValue, Timer
from statsite.collector import Collector
class TestCollector(TestBase):
def test_stores_aggregator(self):
"""
Tests that collectors will store ag... | :
"""
Tests that parsing metrics succeeds and returns an array
of proper metric objects.
"""
message = "\n".join(["k:1|kv", "j:27|ms"])
results = Collector(None)._parse_metrics(message)
assert isinstance(results[0], KeyValue)
assert isinstance(results[1],... | f requested.
"""
message = "k:1|nope"
results = Collector(None)._parse_metrics(message)
assert 0 == len(results)
def test_parse_metrics_keeps_good_metrics(self, aggregator):
"""
Tests that parse_metrics will keep the good metrics in the face
of an error.
... |
SCORE42/nodeshot | nodeshot/community/participation/serializers.py | Python | gpl-3.0 | 2,237 | 0.001788 | from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework import serializers
from nodeshot.core.base.serializers import ModelValidationSerializer
from nodeshot.community.profiles.serializers import ProfileRelationSerializer
from .models import Comment, Vote, Rating, NodeRatingCount
... | at extend NodeRelationViewMixin
"""
def validate(self, data):
data['node'] = self.context['view'].node
return super(AutoNodeMixin, self).valida | te(data)
class CommentSerializer(AutoNodeMixin, ModelValidationSerializer):
""" Comment serializer """
node = serializers.ReadOnlyField(source='node.name')
username = serializers.ReadOnlyField(source='user.username')
class Meta:
model = Comment
fields = ('node', 'username', 'text', 'a... |
deo1/deo1 | Legacy/PythonTutorial/18InnerClasses.py | Python | mit | 630 | 0.006349 | __author__ = | 'jbowman'
# https://pythonspot.com/inner-classes/
class Human:
def __init__(self, name):
self.name = name
self.head = self.Head()
def addhead(self):
self.head2 = self.Head()
class Head:
def __init__(self):
self.brain = self.Brain()
def talk(self):
... | talking...'
class Brain:
def think(self):
return 'thinking...'
if __name__ == '__main__': # execute only if run as a script directly
joey = Human('Joey')
print(joey.name)
print(joey.head.talk())
print(joey.head.brain.think()) |
PabloVallejo/docker-django | manage.py | Python | mit | 249 | 0 | #!/usr/bin/env python3.5
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJ | ANGO_SETTINGS_MODULE", "app.settings")
from django.core.management import execute_from_command_l | ine
execute_from_command_line(sys.argv)
|
zhiwliu/openshift-ansible | roles/openshift_aws/filter_plugins/openshift_aws_filters.py | Python | apache-2.0 | 2,484 | 0.003221 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Custom filters for use in openshift_aws
'''
from ansible import errors
class FilterModule(object):
''' Custom ansible filters for use by openshift_aws role'''
@staticmethod
def scale_groups_serial(scale_group_info, upgrade=False):
''' This function w... | sterid,
'kubern | etes.io/cluster/{}'.format(clusterid): clusterid}
return tags
def filters(self):
''' returns a mapping of filters to methods '''
return {'build_instance_tags': self.build_instance_tags,
'scale_groups_match_capacity': self.scale_groups_match_capacity,
'scale_... |
pathespe/MarkerBot | tests/resources/session_6.py | Python | mit | 2,838 | 0.015856 | def get_attendance_records(file_path):
attendance_file = open(file_path,'r')
lines = attendance_file.readlines()
attendance_file.close()
header = lines[0]
attendance_records = lines[1:]
return attendance_records
def convert_attendance_record_to_bools(sessions):
sessions_bool = []
for... | ust', 'more', 'not', 'of', 'on', 'or', 'our',
'over', 'than', 'that', 'the', 'their', 'these', 'they', 'this', 'those',
'to', 'up', 'we', 'with'
}
def build_word_counter(file_path):
with open(file_path, 'r') as f:
speech = f.read()
chars_to_remove = list(string.punctuation) + ['\n'] + list(... | ctions.Counter(w.lower() for w in speech.split() if w not in IGNORE)
def common_words(file_path):
word_counter = build_word_counter(file_path)
return sorted(w.decode('utf-8') for w in word_counter if word_counter[w] > 10)
def most_used_words(file_path):
word_counter = build_word_counter(file_path)
wor... |
xorpaul/shinken | shinken/objects/checkmodulation.py | Python | agpl-3.0 | 4,462 | 0.00381 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redis... | lass = CheckModulation
def linkify(self, timeperiods, commands):
| self.linkify_with_timeperiods(timeperiods, 'check_period')
self.linkify_one_command_with_commands(commands, 'check_command')
def new_inner_member(self, name=None, params={}):
if name is None:
name = CheckModulation.id
params['checkmodulation_name'] = name
#print... |
wasserfeder/lomap | lomap/algorithms/__init__.py | Python | gpl-2.0 | 765 | 0.003922 | # Copyright (C) 2012-2015, Alphan Ulusoy (alphan@bu.edu)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This pr... | icense along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110- | 1301 USA.
|
krafczyk/spack | lib/spack/spack/test/cmd/test_compiler_cmd.py | Python | lgpl-2.1 | 3,159 | 0 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | iler
import spack.compilers
import spack.spec
import spack.util.pattern
from spack.version import Version
test_version = '4.5-spacktest'
@pytest.fixture()
def mock_compiler_dir(tmpdir):
"""Return a directory containing a fake, but detectable compiler."""
tmpdir.ensure('bin', dir=True)
bin_dir = | tmpdir.join('bin')
gcc_path = bin_dir.join('gcc')
gxx_path = bin_dir.join('g++')
gfortran_path = bin_dir.join('gfortran')
gcc_path.write("""\
#!/bin/sh
for arg in "$@"; do
if [ "$arg" = -dumpversion ]; then
echo '%s'
fi
done
""" % test_version)
# Create some mock compilers in the... |
0x00ach/zer0m0n | signatures/network_irc.py | Python | gpl-3.0 | 1,128 | 0.000887 | # Copyright (C) 2013 Claudio "nex" Guarnieri (@botherder)
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even t | he implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from lib.cuckoo.common.abstracts import Sig... |
joeedh/gameblendjs | blender/dm/node_types.py | Python | mit | 4,508 | 0.00488 | from . import utils
import bpy
from bpy.types import NodeTree, Node, NodeSocket
# Implementation of custom nodes from Python
# Derived from the NodeTree base ty | pe, similar to Menu, Operator, Panel, etc.
class GameGraph(NodeTree):
# Description string
'''A custom node tree type that will show up in the node editor header'''
# Optional identifier string. If not explicitly defined, the python class name is used.
bl_idname = 'GameG | raphType'
# Label for nice name display
bl_label = 'Game Graph'
# Icon identifier
bl_icon = 'NODETREE'
# Custom socket types
class ReadySocket(NodeSocket):
def __new__(self):
self.link_limit = 500
print("set link limit!")
# Description string
'''Custom node sock... |
arthurdejong/python-stdnum | stdnum/lu/__init__.py | Python | lgpl-2.1 | 954 | 0 | # __init__.py - collection of Luxembourgian numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# 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 option) any later version.
#
# This library 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
# L | esser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
"""Collection of Luxembourgian numbers."""
# provid... |
chipaca/snapcraft | snapcraft/internal/db/datastore.py | Python | gpl-3.0 | 4,171 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | cked storage for TinyDB."""
def __init__(self, path: str):
self.path = pathlib.Path(path)
logger. | debug(f"_YAMLStorage init {self.path}")
def read(self) -> Dict[str, Any]:
"""Read database from file."""
logger.debug(f"_YAMLStorage read: {self.path}")
try:
with self.path.open() as fd:
db_data = yaml.safe_load(fd)
except FileNotFoundError:
r... |
mzdaniel/oh-mainline | vendor/packages/Django/tests/regressiontests/fixtures_regress/models.py | Python | agpl-3.0 | 5,411 | 0.000185 | from django.db import models, DEFAULT_DB_ALIAS, connection
from django.contrib.auth.models import User
from django.conf import settings
class Animal(models.Model):
name = models.CharField(max_length=150)
latin_name = models.CharField(max_length=150)
count = models.IntegerField()
weight = models.FloatF... | :
return self.name
class WidgetProxy(Widget):
class Meta:
proxy = True
# Check for forward references in FKs and M2Ms with natural keys
class TestManager(models.Manager):
def get_by_natural_key(self, key):
return self.get(name=key)
class Store(models.Model):
objects = TestManag... |
return (self.name,)
class Person(models.Model):
objects = TestManager()
name = models.CharField(max_length=255)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
# Person doesn't actually have a dependency on store, but we need to define
# one... |
sheanmassey/django-audit-trails | django_audit/apps.py | Python | unlicense | 89 | 0 | from django.apps import AppConfig
|
class AuditorConfig( | AppConfig):
name = 'auditor'
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractFeelinthedarkWordpressCom.py | Python | bsd-3-clause | 566 | 0.033569 |
def extractFeelinthedarkWordpressCom(item):
'''
Parser for 'feelinthedark.wordpress.com'
'''
vol, chp, frag, postfix = | extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterou | s', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
jomyhuang/sdwle | SDWLE/cards_copy/minions/warlock.py | Python | mit | 8,778 | 0.005354 | from SDWLE.cards.base import MinionCard
from SDWLE.cards.heroes import Jaraxxus
from SDWLE.cards.weapons.warlock import BloodFury
from SDWLE.constants import CHARACTER_CLASS, CARD_RARITY, MINION_TYPE
from SDWLE.game_objects import Minion
from SDWLE.tags.action import Summon, Kill, Damage, Discard, DestroyManaCrystal, G... | ler", 4, CHARACTER_CLASS.WARLOCK, CARD_RARITY.COMMON, minion_type=MINION_TYPE.DEMON)
def create_minion(self, player):
return Minion(3, 4, deathrattle=Deathrattle(Summon(HandSource(FriendlyPlayer(), [IsType(MINION_TYPE.DEMON)])),
PlayerSelector()))
class... | super().__init__("Anima Golem", 6, CHARACTER_CLASS.WARLOCK, CARD_RARITY.EPIC, minion_type=MINION_TYPE.MECH)
def create_minion(self, player):
return Minion(9, 9, effects=[Effect(TurnEnded(MinionCountIs(1), BothPlayer()),
ActionTag(Kill(), SelfSelector()))])
cla... |
openstack/octavia | octavia/tests/unit/controller/worker/v1/flows/test_amphora_flows.py | Python | apache-2.0 | 20,294 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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... | rk_driver')
class TestAmphoraFlows(base.TestCase):
def setUp(self):
super().setUp()
self.conf = self.useFixture(oslo_fixture.Config(cfg.CONF))
self.conf.config(
group="controller_worker",
amphora_driver='amphora_haproxy_rest_driver')
self.conf.config(group="n... | 2 = data_models.Amphora(id=2)
self.amp3 = data_models.Amphora(id=3, status=constants.DELETED)
self.amp4 = data_models.Amphora(id=uuidutils.generate_uuid())
self.lb = data_models.LoadBalancer(
id=4, amphorae=[self.amp1, self.amp2, self.amp3])
def test_get_create_amphora_flow(self... |
cbears/octoform | ocr/findBarcode.py | Python | gpl-3.0 | 15,096 | 0.036235 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Code128 Barcode Detection & Analysis
(c) Charles Shiflett 2011
Finds Code128 barcodes in documents scanned in Grayscale at 300 dpi.
Usage:
Each page of the PDF must be converted to a grayscale PNG image, and should
be ordered as follows:
1001/1001-... | elf, f, filt )
if type(filt) == type(False):
raise ValueError("Error: filter %s was not found in filter.py" % f)
return convolve( self.im, filt, reshape )
def findBarcode( self ):
results = self.applyFilter("scaledFilter", reshape=False)
list = [ (x[1], int(x[0] % sel | f.stride), int(x[0] / self.stride)) for x in enumerate(results) if x[1] > 1000 ]
list.sort(reverse=True)
return list[0:20]
def unAlias(s):
"Remove dithering. "
#s.im= ss.convolve2d( s.im, unAliasFilter, mode="same" )
s.im=convolve( s.im, unAliasFilter, reshape=True )
s.im=numpy.piecewise(s.im... |
Rio517/pledgeservice | lib/stripe/http_client.py | Python | apache-2.0 | 10,566 | 0 | import os
import sys
import textwrap
import warnings
from stripe import error, util
# - Requests is the preferred HTTP library
# - Google App Engine has urlfetch
# - Use Pycurl if it's there (at least it verifies SSL certs)
# - Fall back to urllib2 with a warning if needed
try:
import urllib2
except ImportError:... | msg = ("There was a problem rec | eiving all of your data from "
"Stripe. This is likely due to a bug in Stripe. "
"Please let us know at support@stripe.com.")
else:
msg = ("Unexpected error communicating with Stripe. If this "
"problem persists, let us know at support@stripe... |
setphen/Donsol | tests/test_card.py | Python | mit | 860 | 0.005814 | from game.models import (Card,
HEART,
SPADE,
CLUB,
DIAMOND)
def test_card_creation_without_name():
c = Card('heart', 5)
assert c.name | == 'heart'
assert c.suit == 'heart'
assert c.value == 5
|
def test_card_creation_with_name():
c = Card('spade', 5, name='jabberwock')
assert c.name == 'jabberwock'
assert c.suit == 'spade'
assert c.value == 5
def test_card_spade_is_monster():
c = Card(SPADE, 5)
assert c.is_monster() == True
def test_card_club_is_monster():
c = Card(CLUB, 5)
... |
omartrinidad/schiffsdiebe | schiffsdiebe/datasets/__init__.py | Python | mit | 2,327 | 0.008595 | import numpy as np
import os
__location__ = os.path.realpath(
os.path.join(os.getcwd(),
os.path.dirname(__file__))
) + "/"
class Dataset():
"""
I want to create a similar object to that one existing in R: Dataframe
"""
def __init__(self, tra... | kip_header = 1
)[:,0:-1]
# test labels set
self.test_labels = np.genfromtxt(
test_file, dtype=float,
delimiter=',', skip_header = 1
| )[:,-1:].ravel()
# attributes
if header:
self.attributes = np.genfromtxt(
test_file, dtype=str,
delimiter=',', max_rows = 1
)
else:
ncols = range(self.training_labels.shape[0])
self.att... |
Galarius/gann-square | gann.py | Python | mit | 3,346 | 0.003586 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getopt
from datetime import datetime
import math
from gann import *
def print_usage():
print """
classic Gann square: gann.py -o <output file name> -s <square size>
Gann square based on date: gann.py -o <output file name> -a <base date... | datetime.strptime(arg, date_format)
elif opt in ("-b", "--b_date"):
date_b = datetime.strptime(arg, date_format)
elif opt in ("-m", "--mfile"):
marks_fil | e_name = arg
elif opt in ("-r", "--rect"):
rect = arg.split(';')
try:
left, bot, right, up = int(rect[0]), int(rect[1]), int(rect[2]), int(rect[3])
except ValueError as e:
print 'Failed to parse range!'
if output_file_name == '':
p... |
goodwinnk/intellij-community | python/testData/pyi/inspections/hiddenPyiImports/HiddenPyiImports.py | Python | apache-2.0 | 347 | 0.048991 | from m1 import <er | ror descr="Cannot find reference 'foo' in 'm1.pyi'">foo</error>
from m1 import <error descr="Cannot find reference 'bar' in 'm1.pyi'">bar</error>
from m1 import bar_imported
from m1 import <error descr="Cannot find reference 'm2' in 'm1.pyi'">m2</error>
from m1 import m2_imported
print( | foo, bar, bar_imported, m2, m2_imported)
|
ofayans/freeipa | ipaplatform/setup.py | Python | gpl-3.0 | 1,334 | 0 | #!/usr/bin/python2
# Copyright (C) 2014 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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... | rver for iden | tity, policy, and audit.
"""
from os.path import abspath, dirname
import sys
if __name__ == '__main__':
# include ../ for ipasetup.py
sys.path.append(dirname(dirname(abspath(__file__))))
from ipasetup import ipasetup # noqa: E402
ipasetup(
name="ipaplatform",
doc=__doc__,
pack... |
undertherain/benchmarker | benchmarker/__profile__.py | Python | mpl-2.0 | 301 | 0 | """
This is helper module to profile th | e whole package
in Python 3.7 profiling modules from command line will be supported
and this module will no longer be needed
"""
import cProfile
from .__main__ import main
if __na | me__ == "__main__":
cProfile.run("main()", filename=".nemchmarker.cprofile")
|
wfn/stem | test/unit/version.py | Python | lgpl-3.0 | 9,206 | 0.002716 | """
Unit tests for the stem.version.Version parsing and class.
"""
import unittest
import stem.util.system
import stem.version
from stem.version import Version
from test import mocking
TOR_VERSION_OUTPUT = """Mar 22 23:09:37.088 [notice] Tor v0.2.2.35 \
(git-73ff13ab3cc9570d). This is experimental software. Do not ... | an(Version("0.2.2.36"), False)
self.assertFalse(Version("0.2.2.37") >= requirements)
self.assertFalse(Version("0.2.2.36") >= requirements)
self.assertTrue(Version("0.2.2.35") >= requirements)
def test_requirements_in_range(self):
"""
Checks a VersionRequirements with a singl | e in_range rule.
"""
requirements = stem.version._VersionRequirements()
requirements.in_range(Version("0.2.2.36"), Version("0.2.2.38"))
self.assertFalse(Version("0.2.2.35") >= requirements)
self.assertTrue(Version("0.2.2.36") >= requirements)
self.assertTrue(Version("0.2.2.37") >= requirements... |
andrewisakov/taximaster_x | snmp/settings.py | Python | unlicense | 379 | 0 | #!/usr/bin/python3
import os
# import logging
import logger as logger_
WS_SERVER = 'ws://127.0.0.1:4055/ws'
WS_TIMEOUT = 10
APP_DIR = os.path.dirname(__file__)
# SQ | L_DIR = os.path.join(APP_DIR, 'sql')
logger = logger_.rotating_log(os.path.join(
APP_DIR, 'kts_sn | mp.log'), 'kts_snmp_log')
SNMP_IP = '192.168.222.179'
SNMP_PORT = 11162
ROUTER_URL = 'http://127.0.0.1/snmp'
|
VA3SFA/rpi_hw_demo | pcd8544/IP.py | Python | gpl-2.0 | 2,974 | 0.003026 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2013-2015 Pervasive Displays, Inc.
# Copyright 2015, Syed Faisal Akber
#
# 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... | Mono.ttf', # R.Pi
'/usr/share/fonts/truetype/LiberationMono-Bold.ttf', # B.B
'/usr/share/fonts/truetype/DejaVuSansMono-Bold.ttf' # B.B
'/usr/share/fonts/TTF/FreeMonoBold.ttf', | # Arch
'/usr/share/fonts/TTF/DejaVuSans-Bold.ttf' # Arch
]
FONT_FILE = ''
for f in possible_fonts:
if os.path.exists(f):
FONT_FILE = f
break
if '' == FONT_FILE:
raise 'no font file found'
FONT_SIZE = 10
def main():
"""main program - dr... |
zyphrus/fetch-django | fetcher/views.py | Python | mit | 1,510 | 0.009272 | from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from fetcher import api
import requests
import json
def index(request):
return render(request, 'fetc... | = 'GET' and reques | t.META.get('CONTENT_TYPE') == 'application/json':
return HttpResponse(json.dumps(api.log()), content_type='application/json')
else:
return HttpResponseRedirect(reverse('fetcher:index'))
@csrf_exempt
def force_fetch(request):
if request.method == 'POST' and request.META.get('CONTENT_TYPE') == 'a... |
mupi/tecsaladeaula | core/templatetags/is_assistant_or_coordinator.py | Python | agpl-3.0 | 179 | 0 | from django import template
register = templ | ate.Library()
@register.filter()
def is_assistant_or_coordinator(user, course):
return course.is_assistant_ | or_coordinator(user)
|
IPyandy/pnil | eapi.py | Python | bsd-3-clause | 12,608 | 0.000635 | #!/usr/bin/env python
# Python Network Interface Library
#
# Author: Yandy Ramirez
# Twitter: @IPyandy (https://twitter.com/IPyandy)
# Site: http://ipyandy.net
# Code Verion: 0.0.1
#
# ----------------------------------------------------------------
'''
Library to make A... | ns:
for _ in enumerate(response):
for key in response[keys]:
print(response[keys][key])
return response
return response
def getInterfaces(self):
interfaces = self.getInterfacesStatus().keys()
... | faces', interfaces)
def getPlatform(self):
if not self._version_info:
self.getVersionInfo()
return self.createDataDict('platform', self._version_info['modelName'])
def getSerialNumber(self):
if not self._version_info:
self.getVersio... |
asherwunk/objconfig | tests/writer/test_json_writer.py | Python | mit | 1,712 | 0.014019 | """
Test objconfig.writer.Json
"""
from objconfig.writer import Json as JsonWriter
from objconfig.reader import Json as JsonReader
from objconfig.writer import AbstractWriter
from objconfig.writer import WriterInterface
import os
def test_emptyinstantiation_json():
writer = JsonWriter()
assert isinstance(wri... | in(os.path.dirname(os.path.realpath(__file__)), "test.json"), conf)
reader = JsonReader()
compconf = reader.fromFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "test.json"))
os.re | move(os.path.join(os.path.dirname(os.path.realpath(__file__)), "test.json"))
assert conf == compconf, "Json improperly rendered in file"
|
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/integrate/tests/test_quadpack.py | Python | mit | 13,179 | 0.000531 | from __future__ import division, print_function, absolute_import
import math
import sys
import numpy as np
from numpy import sqrt, cos, sin, arctan, exp, log, pi, Inf
from numpy.testing import (assert_, TestCase, run_module_suite, dec,
assert_allclose, assert_array_less, assert_almost_equal... | tan(2.0 ** ( | a + 2)) -
arctan(2.0 ** a)) /
(4.0 ** (-a) + 1))
assert_quad(quad(myfunc, 0, 5, args=0.4, weight='cauchy', wvar=2.0),
tabledValue, errTol=1.9e-8)
def test_double_integral(self):
# 8) Double Integral test
def simpfunc(y, x): ... |
tiborsimko/invenio-base | setup.py | Python | mit | 2,590 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Base package for building Invenio application factories."""
import os
from setup... | v>=1.8.0',
'pytest-pep8>=1.0.6',
'pytest>=2.8.0',
'invenio-config>=1.0.0',
]
extras_require = {
'docs': [
'Sphinx>=1.4.2',
],
'tests': tests_require,
}
extras_require['all'] = []
for reqs in extras_require.values():
extras_ | require['all'].extend(reqs)
setup_requires = [
'pytest-runner>=2.6.2',
]
install_requires = [
'blinker>=1.4',
'cookiecutter>=1.2.1',
'Flask>=0.11.1',
]
packages = find_packages()
setup(
name='invenio-base',
version=version,
description=__doc__,
long_description=readme + '\n\n' + hist... |
smmribeiro/intellij-community | python/testData/intentions/PyConvertTypeCommentToVariableAnnotationIntentionTest/simpleForLoop.py | Python | apache-2.0 | 50 | 0.02 | for x in undefined(): # ty<caret>pe: int
| pass | |
asweigart/moosegesture | tests/demoGestureApp.py | Python | bsd-3-clause | 3,638 | 0.004948 | """
MooseGesture Test application
Al Sweigart al@coffeeghost.net
http://coffeeghost.net/2011/05/09/moosegesture-python-mouse-gestures-module
Run the app and then draw by dragging the mouse. When you release the mouse
button, the gesture you drew will be identified.
This script requires the MooseGesture library, whic... | '
if event.type == MOUSEBUTTONUP:
# try to identify the gesture when the mouse dragging stops
mouseDown = False
strokes = moosegesture.getGesture(points)
segments = moosegesture.getSegments(points)
strokeText = ' '.jo | in(strokes)
textobj = font.render(strokeText, 1, (255,255,255))
textrect = textobj.get_rect()
textrect.topleft = (10, WINDOWHEIGHT - 30)
if event.type == MOUSEMOTION and mouseDown:
# draw the line if the mouse is dragging
points.append( (event.pos[0],... |
MungoRae/home-assistant | homeassistant/components/switch/neato.py | Python | apache-2.0 | 4,019 | 0 | """
Support for Neato Connected Vaccums switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.neato/
"""
import logging
import requests
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.entity import ToggleEntity
fr... | _state = self.robot.state
except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError) as ex | :
_LOGGER.warning("Neato connection error: %s", ex)
self._state = None
self._schedule_state = None
self._clean_state = None
def update(self):
"""Update the states of Neato switches."""
_LOGGER.debug("Running switch update")
self.neato.update_robots()
... |
gooddata/openstack-nova | api-guide/source/conf.py | Python | apache-2.0 | 9,312 | 0.000966 | # 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 the... | etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_... | to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to ... |
jlaunonen/kirppu | kirppu/migrations/0007_auto_misc_adjustments.py | Python | mit | 1,699 | 0.002354 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('kirppu', '0006_item_lost_property'), |
] |
operations = [
migrations.AlterField(
model_name='clerk',
name='access_key',
field=models.CharField(null=True, validators=[django.core.validators.RegexValidator(b'^[0-9a-fA-F]{14}$', message=b'Must be 14 hex chars.')], max_length=128, blank=True, help_text='Access code ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.