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 |
|---|---|---|---|---|---|---|---|---|
bmya/odoo-argentina | l10n_ar_account/models/__init__.py | Python | agpl-3.0 | 929 | 0 | ##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from . import account_journal
from . import account_tax
from . import acc... | account_invoice_line
from . import product_uom
from . import account_chart_template
from . import afip_vat_f2002_category
from . import product_template
from . import account_mov | e_line
from . import account_move
from . import afip_padron
from . import account_account
from . import account_account_tag
|
bearstech/ansible | lib/ansible/modules/network/netscaler/netscaler_cs_action.py | Python | gpl-3.0 | 9,091 | 0.00242 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Citrix Systems
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
... | tro_exception
PYTHON_SDK_IMPORTED = True
except ImportError as e:
PYTHON_SDK_IMPORTED = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.netscaler import (
ConfigProxy,
get_nitro_client,
netscaler_common_arguments,
log, logline | s,
ensure_feature_is_enabled,
get_immutables_intersection
)
def action_exists(client, module):
if csaction.count_filtered(client, 'name:%s' % module.params['name']) > 0:
return True
else:
return False
def action_identical(client, module, csaction_proxy):
if len(diff_list(client, ... |
drammock/expyfun | expyfun/_utils.py | Python | bsd-3-clause | 30,243 | 0 | """Some utility functions"""
# Authors: Eric Larson <larsoner@uw.edu>
#
# License: BSD (3-clause)
import warnings
import operator
from copy import deepcopy
import subprocess
import importlib
import os
import os.path as op
import inspect
import sys
import time
import tempfile
import traceback
import ssl
from shutil im... | rue else 'a'
lh = logging.FileHandler(fname, mode=mode)
else:
""" we should just be able to do:
lh = logging.StreamHandler(sys.stdout)
but because doctests uses some magic on stdout, | we have to do this:
"""
lh = logging.StreamHandler(WrapStdOut())
lh.setFormatter(logging.Formatter(output_format))
# actually add the stream handler
logger.addHandler(lh)
###############################################################################
# RANDOM UTILITIES
building_doc = any... |
conan-io/conan | conans/test/functional/util/tools_test.py | Python | mit | 5,578 | 0.002868 | # -*- coding: utf-8 -*-
import os
import platform
import subprocess
import unittest
import pytest
import six
from conans.client import tools
from conans.client.conf import get_default_settings_yml
from conans.client.tools.files import which
from conans.client.tools.win import vswhere
from conans.errors import ConanE... | .output)
settings.arch = "x86"
with six.assertRaisesRegex(self, ConanException, "Cannot build_sln_command"):
tools.msvc_build_command(settings, "project.sln", output=self.output)
# successful definition via settings
settings.build_type = "Debug"
cmd = tools.msvc_bui... | '/p:UseEnv=false /p:Platform="x86"', cmd)
self.assertIn('vcvarsall.bat', cmd)
def test_vswhere_path(self):
"""
Locate vswhere in PATH or in ProgramFiles
"""
# vswhere not found
with tools.environment_append({"ProgramFiles": None, "ProgramFiles(x86)": None, "PA... |
steveb/heat | heat/db/sqlalchemy/models.py | Python | apache-2.0 | 17,625 | 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
# ... | prev_raw_template_id = sqlalchemy.Column(
'prev_raw_template_id',
sqlalchemy.Integer,
sqlalchemy.ForeignKey('raw_template.id'))
prev_raw_template = relationship(RawTemplate,
foreign_keys=[prev_raw_template_id])
username = sqlalchemy.Column(sqlalche... | sqlalchemy.Column(
sqlalchemy.Integer,
sqlalchemy.ForeignKey('user_creds.id'))
owner_id = sqlalchemy.Column(sqlalchemy.String(36), index=True)
parent_resource_name = sqlalchemy.Column(sqlalchemy.String(255))
timeout = sqlalchemy.Column(sqlalchemy.Integer)
disable_rollback = sqlalchemy.Co... |
zamattiac/SHARE | providers/org/sldr/migrations/0001_initial.py | Python | apache-2.0 | 649 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-08 15:45
from __f | uture__ import unicode_literals
from django.db import migrations
import share.robot
class Migration(migrations.Migration):
dependencies = [
('share', '0001_initial'),
('djcelery', '0001_initial'),
]
operations = [
migrations.RunPython(
code=sh | are.robot.RobotUserMigration('org.sldr'),
),
migrations.RunPython(
code=share.robot.RobotOauthTokenMigration('org.sldr'),
),
migrations.RunPython(
code=share.robot.RobotScheduleMigration('org.sldr'),
),
]
|
raghakot/keras-vis | applications/self_driving/model.py | Python | mit | 845 | 0 | from keras.layers.core import Dropout, Flatten
from keras.layers.convolutional import MaxPooling2D, Conv2D
from keras.models import Model
from keras.layers import Input, Dense
FRAME_H = 7 | 0
FRAME_W = 180
def build_model():
inp = Input(shape=(FRAME_H, FRAME_W, 3))
x = Conv2D(filters=8, kernel_size=(5, 5), activation= | 'relu')(inp)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(filters=16, kernel_size=(5, 5), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(filters=32, kernel_size=(5, 5), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Flatten()(x)
x = Dropout(0.5)(x)
x = Dense(128, activa... |
hrashk/sympy | sympy/combinatorics/graycode.py | Python | bsd-3-clause | 11,202 | 0.000357 | from __future__ import print_function, division
from sympy.core import Basic
from sympy.core.compatibility import xrange
import random
class GrayCode(Basic):
"""
A Gray code is essentially a Hamiltonian walk on
a n-dimensional cube with edge length of one.
The vertices of the cube are represented by... | int(gray_to_bin(self.current), 2)
return self._rank
@property
def current(self):
| """
Returns the currently referenced Gray code as a bit string.
Examples
========
>>> from sympy.combinatorics.graycode import GrayCode
>>> GrayCode(3, start='100').current
'100'
"""
rv = self._current or '0'
if type(rv) is not str:
r... |
Tristramg/mumoro | server.py | Python | gpl-3.0 | 26,253 | 0.020876 | # -*- coding: utf-8 -*-
# This file is part of Mumoro.
#
# Mumoro 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.
#
# ... | data = MetaData(bind = engine)
res = layer.Layer(name, mode, data, metadata)
layer_array.append( {'layer':res,'name':name,'mode':mode,'origin':data,'color':color} )
return {'layer':res,'name':name,'mode':mode,'origin':data,'color':color}
def public_transport_layer(data, name, color):
engine = cre... | 'name':name,'mode':PublicTransport,'origin':data,'color':color} )
return {'layer':res,'name':name,'mode':PublicTransport,'origin':PublicTransport,'color':color}
def paths( starting_layer, destination_layer, objectives ):
if not starting_layer or not destination_layer:
raise NameError('Empty layer(s)')... |
cladmi/RIOT | tests/test_tools/tests/01-run.py | Python | lgpl-2.1 | 1,512 | 0 | #!/usr/bin/env python3
"""Test behaviour of the test running and the term program interaction."""
import sys
import p | expect
from testrunner import run
def _shellping(child, timeout=1):
"""Issue a 'shellping' command.
Raises a pexpect exception on failure.
:param timeout: timeout for the answer
"""
child.sendline('shellping')
child.expect_exact('shellpong\r\n', timeout=timeout)
def _ | wait_shell_ready(child, numtries=5):
"""Wait until the shell is ready by using 'shellping'."""
for _ in range(numtries - 1):
try:
_shellping(child)
except pexpect.TIMEOUT:
pass
else:
break
else:
# This one should fail
_shellping(chi... |
intel-analytics/analytics-zoo | pyzoo/zoo/examples/orca/learn/tf/image_segmentation/image_segmentation.py | Python | apache-2.0 | 9,188 | 0.001741 | #
# Copyright 2018 Analytics Zoo Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | in y_train_filenames])
val_images = np.stack([load_and_process_image(filepath) for filepath in x_val_filenames])
val_label_images = np.stack([load_and_process_image_label(filepath)
for fi | lepath in y_val_filenames])
train_shards = XShards.partition({"x": train_images, "y": train_label_images})
val_shards = XShards.partition({"x": val_images, "y": val_label_images})
# Build the U-Net model
def conv_block(input_tensor, num_filters):
encoder = layers.Conv2D(num_filters, (3, 3), pad... |
mkheirkhah/mptcp | src/dsdv/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 466,437 | 0.015177 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | ate_parameters=['3'])
## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration]
module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<4> [struct]
module.add_class('IntToType', import_f... | odule.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core')
## int-to-type.h (module 'core'): ns3::IntToType<5> [struct]
module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5'])
## int-to-type.h (module 'core'): ns3::IntToType<... |
lsst-sqre/s3s3 | s3s3/scripts/echo_s3s3_ini_template.py | Python | mit | 978 | 0 | #!/usr/bin/env python
"""
Echo the s3s3 configuration template.
"""
from pkg_resources import Requirement, resource_string
def try_resource(location):
"""
Try to get the resource in ``location``.
"""
try:
return resource_string(Requirement.parse('s3s3'), location)
except FileNotFoundError:... | The file is located in a different location depending on if it's
a sdist or bdist_wheel install.
"""
try:
conf = try_resource('extras/s3s3.ini.dist') # sdist
if not conf:
conf = try_resource('../../../extras/s3s3.ini.dist') # bdist
print(conf.decode('utf-8'))
re... | except Exception as e:
return False
def main():
if echo():
exit(0)
else:
exit(1)
if __name__ == "__main__":
main()
|
AlexStarov/Shop | applications/authModel/migrations/0008_email_hash.py | Python | apache-2.0 | 508 | 0.001969 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import applications.utils.captcha.utils
class Migration(migrations.Migration):
dependencies = [
('authModel', '0007_email_test'),
]
operations = [
migrations.AddField(
model... | ),
]
|
dc3-plaso/dfvfs | dfvfs/vfs/zip_file_system.py | Python | apache-2.0 | 4,907 | 0.006521 | # -*- coding: utf-8 -*-
"""The zip file system implementation."""
import zipfile
# This is necessary to prevent a circular import.
import dfvfs.vfs.zip_file_entry
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import zip_path_spec
from dfvfs.resolver import resolver
from dfvfs.vfs imp... | cessError: if the access to open the file was denied.
IOError: if the file system object could not be opened.
PathSpecError: if the path specification is incorrect.
ValueErro | r: if the path specification is invalid.
"""
if not path_spec.HasParent():
raise errors.PathSpecError(
u'Unsupported path specification without parent.')
file_object = resolver.Resolver.OpenFileObject(
path_spec.parent, resolver_context=self._resolver_context)
try:
zip_fi... |
django-bmf/django-bmf | djangobmf/migrations/0001_squashed_0_2_9.py | Python | bsd-3-clause | 12,381 | 0.005169 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
import djangobmf.storage
import djangobmf.fields.file
import django.utils.timezone
import djangobmf.utils.generate_filename
class Migration(migrat... | stract': False,
},
),
migrations.CreateModel(
name='Notification',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', | auto_created=True, primary_key=True)),
('watch_id', models.PositiveIntegerField(null=True, db_index=True)),
('triggered', models.BooleanField(verbose_name='Triggered', default=True, editable=False, db_index=True)),
('unread', models.BooleanField(verbose_name='Unread', def... |
aslab/rct | mrt/src/tum_simulator_ws/devel/lib/python2.7/dist-packages/ardrone_autonomy/msg/_navdata_time.py | Python | gpl-3.0 | 6,555 | 0.019222 | # This Python file uses the following encoding: utf-8
"""autogenerated by genpy from ardrone_autonomy/navdata_time.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class navdata_time(genpy.Message):
_md5sum = "8642a5656fdcc931093... | .seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
_x = self.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
if python3:
buff.write(struct.pack('<I%sB'%length, len | gth, *_x))
else:
buff.write(struct.pack('<I%ss'%length, length, _x))
_x = self
buff.write(_struct_d2HI.pack(_x.drone_time, _x.tag, _x.size, _x.time))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))... |
hsteinhaus/ardupilot | Tools/autotest/sim_vehicle.py | Python | gpl-3.0 | 31,053 | 0.00293 | #!/usr/bin/env python
"""
Framework to start a simulated vehicle and connect it to MAVProxy.
Peter Barker, April 2016
based on sim_vehicle.sh by Andrew Tridgell, October 2011
"""
import atexit
import getpass
import optparse
import os
import os.path
import signal
import subprocess
import sys
import tempfile
import ti... | straight to mavproxy"""
def __init__(self, *args, **kwargs):
optparse.OptionParser.__init__(self, *args, **kwargs)
def error(self, error):
"""Override default error handler called by optparse.OptionParser.parse_args when a parse error occurs; | raise a detailed exception which can be caught"""
if error.find("no such option") != -1:
raise CompatError(error, self.values, self.rargs)
optparse.OptionParser.error(self, error)
def parse_args(self, args=None, values=None):
"""Wrap parse_args so we can catch the exception rai... |
tohodson/modis-hdf5 | code/compile_hdf.py | Python | gpl-2.0 | 1,818 | 0.008801 | from pyIST import *
##############
terra_dir = '/Users/tohodson/Desktop/modis_download/MOST/MOD29E1D.005/'
aqua_dir = '/Users/tohodson/Desktop/modis_download/MOSA/MYD29E1D.005/'
hdf_file = '/Users/tohodson/Desktop/AQ_IST.hdf5'
DATAFIELD_NAME='Ice_Surface_Temperature_SP'
aqua_count = count_files(aqua_dir,'*.hdf')
te... | ), dtype=np.uint16, compression="lzf", shuffle=True)
aqua_set.attrs.create('dates',MODIS_dates(aqua_dir),dtype='S10' | )
counter = terra_count - aqua_count #align daily records with terra
for filename in find_files(aqua_dir, '*.hdf'):
hdf = SD(filename, SDC.READ)
# Read dataset.
data_raw = hdf.select(DATAFIELD_NAME)
aqua_set[counter] = data_raw[:,:]
counter = counter +1
print 'aqua ' + str(counter)
'''... |
jonwright/ImageD11 | scripts/huber2bruker.py | Python | gpl-2.0 | 20,959 | 0.015172 | #!/usr/bin/env python
from __future__ import print_function
## Automatically adapted for numpy.oldnumeric Sep 06, 2007 by alter_code1.py
# ImageD11_v0.4 Software for beamline ID11
# Copyright (C) 2005 Jon Wright
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GN... | if self.detrend is None:
return ar
# print "detrending",
s = ar.copy()
np = ar.shape[1]/2
s[:,:np].sort()
s[:,np:].sort()
n = self.detrend
nb = 5 # bad pixels (eg negative outliers)
o1 = | s[:,nb:(n+nb)].sum(axis=1)/n
o2 = s[:,(np+nb):(np+n+nb)].sum(axis=1)/n
s1 = ar.copy()
s1[:,:np] = (ar[:,:np].T - o1 + o1.mean() ).T
s1[:,np:] = (ar[:,np:].T - o2 + o2.mean() ).T
return s1
class edf2bruker:
def __init__(self,
dark,
flood,... |
Juanlu001/CBC.Solve | cbc/beat/heart.py | Python | gpl-3.0 | 897 | 0.001115 | from dolfin import error, info
class Heart:
def __init__(self, cell_model):
self._cell_model = cell_model
# Mandatory stuff
def mesh(self):
error("Need to prescribe domain") |
def conductivities(self):
error("Need to prescribe conducitivites")
# Optional stuff
def applied_current(self):
return None
def end_time(self):
info("Using default end time (T = 1.0)")
return 1.0
def essential_boundaries(self):
return None
def essen... |
def neumann_boundaries(self):
return None
def boundary_current(self):
return None
# Peculiar stuff (for now)
def is_dynamic(self):
return True
# Helper functions
def cell_model(self):
return self._cell_model
|
alexm92/sentry | src/sentry/api/serializers/models/user.py | Python | bsd-3-clause | 4,943 | 0.000809 | from __future__ import absolute_import
import six
from collections import defaultdict
from django.conf import settings
from sentry.app import env
from sentry.api.serializers import Serializer, register
from sentry.models import AuthIdentity, Authenticator, User, UserAvatar, UserOption
from sentry.utils.avatar import... | n item_list if x == user]
queryset = AuthIdentity.objects.filter(
user__in=item_list,
).select_related('auth_provider', 'auth_provider__organization')
results = {i.id: [] for i in item_list}
for item in queryset:
results[item.user_id].append(item)
return... | r a in UserAvatar.objects.filter(
user__in=item_list
)
}
identities = self._get_identities(item_list, user)
authenticators = Authenticator.objects.bulk_users_have_2fa([i.id for i in item_list])
data = {}
for item in item_list:
data[item] ... |
huntxu/neutron | neutron/agent/linux/interface.py | Python | apache-2.0 | 19,111 | 0 | # Copyright 2012 OpenStack Foundation
# 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 requ... | cation. This behaviour is selected by running
the DHCP agent with a configured interface driver whose
'use_gateway_ips' property is True.
When an operator deploys Neutron with an interface driver that
makes use_gateway_ips True, they should also ensure that a
gateway IP address... | DHCP-enabled subnet,
and that the gateway IP address doesn't change during the
subnet's lifetime.
"""
return False
def init_l3(self, device_name, ip_cidrs, namespace=None,
preserve_ips=None, clean_connections=False):
"""Set the L3 settings for the interface ... |
bentiss/hid-replay | tools/hid.py | Python | gpl-2.0 | 3,108 | 0.009653 | #! | /bin/env python3
# -*- coding: utf-8 -*-
#
# Hid replay / hid.py: table of hid usages and definitions
#
# Copyright (c) 2012-2017 Benjamin Tissoires <benjamin.tissoires@gmail.com>
# Copyrig | ht (c) 2012-2017 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ... |
pnavarro/neutron | neutron/tests/functional/agent/test_l3_agent.py | Python | apache-2.0 | 53,684 | 0.000112 | # Copyright (c) 2014 Red Hat, 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 require... | extra_routes=extra_routes,
dual_stack=dual_stack,
| v6_ext_gw_with_sub=(
v6_ext_gw_with_sub))
def manage_router(self, agent, router):
self.addCleanup(self._delete_router, agent, router['id'])
ri = self._create_router(agent, router)
return ri
def _create_router(self, agent, r... |
samedder/azure-cli | src/azure-cli-nspkg/setup.py | Python | mit | 1,582 | 0.000632 | #!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ------- | -------------------------------------------------------------------------------------
from codecs import open
from setuptools import setup
VERSION = "3 | .0.1+dev"
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :... |
bbaronSVK/plugin.video.stream-cinema | resources/lib/params.py | Python | gpl-3.0 | 420 | 0 | from __future__ import | print_function, unicode_literals
import sys
from resources.lib.kodiutils import params as decode
class Params:
handle = int(sys.argv[1]) if len(sys.argv) > 1 else -1
orig_args = sys.argv[2] if len(sys.argv) > 2 else ''
args = decode(sys.argv[2]) if len(sys.argv) > 2 else {}
resume = sys.argv[3][7:] ... | rams()
|
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.2/Lib/test/string_tests.py | Python | mit | 58,093 | 0.001635 | """
Common tests shared by test_str, test_unicode, test_userstring and test_string.
"""
import unittest, string, sys, struct
from test import support
from collections import UserList
class Sequence:
def __init__(self, seq='wxyz'): self.seq = seq
def __len__(self): return len(self.seq)
def __getitem__(self... | e(value))
for (key, value) in obj.items()
])
else:
r | eturn obj
# check that obj.method(*args) returns result
def checkequal(self, result, obj, methodname, *args):
result = self.fixtype(result)
obj = self.fixtype(obj)
args = self.fixtype(args)
realresult = getattr(obj, methodname)(*args)
self.assertEqual(
result... |
jim-pansn/graph-tool | doc/demos/animation_zombies.py | Python | gpl-3.0 | 5,436 | 0.001288 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# This simple example on how to do animations using graph-tool. Here we do a
# simple simulation of an S->I->R->S epidemic model, where each vertex can be in
# one of the following states: Susceptible (S), infected (I), recovered (R). A
# vertex in the S state becomes inf... | vertex_size=42,
vertex_anchor=0,
edge_color=[0.6, 0.6, 0. | 6, 1],
edge_sloppy=True,
vertex_surface=vertex_sfcs,
vertex_halo=newly_infected,
vertex_halo_size=1.2,
vertex_halo_color=[0.8, 0, 0, 0.6])
else:
count = 0
win = Gtk.OffscreenWindow()
win.set_default... |
ivansoban/ILEngine | thirdparty/assimp/port/PyAssimp/pyassimp/postprocess.py | Python | mit | 23,509 | 0.012676 | # <hr>Calculates the tangents and bitangents for the imported meshes.
#
# Does nothing if a mesh does not have normals. You might want this post
# processing step to be executed if you plan to use tangent space calculations
# such as normal mapping applied to the meshes. There's a config setting,
# <tt>#AI_CONFIG_P... | anded flag supersedes this
# setting and bundles all conversions typically required for D3D-based
# applications.
#
aiProcess_MakeLeftHanded = 0x4
## <hr>Triangulates all faces of all meshes.
#
# By default the imported mesh data might contain faces with more than 3
# indices. For rendering you'll usually want all fa... | ified! If you want
# 'triangles only' with no other kinds of primitives, try the following
# solution:
# <ul>
# <li>Specify both #aiProcess_Triangulate and #aiProcess_SortByPType <li>
# <li>Ignore all point and line meshes when you process assimp's output<li>
# <ul>
#
aiProcess_Triangulate = 0x8
## <hr>Removes some pa... |
0--key/lib | portfolio/Python/scrapy/inkshop/cartridgesavecouk.py | Python | apache-2.0 | 2,521 | 0.004363 | import re
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, FormRequest, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from scrapy.http import FormRequest
from productloader import load_product
im... | res['url'] = url
res['description'] = name
res['price'] = price
| res['sku'] = res['description']
yield load_product(res, response)
except IndexError:
return
def parse(self, response):
if not isinstance(response, HtmlResponse):
return
#categories
hxs = HtmlXPathSelector(response)
# printer brands
... |
Bolt64/my_code | twitter_bot/get_ip.py | Python | mit | 881 | 0.010216 | #!/usr/bin/p | ython3
"""
A script to get the public ip address from http://checkip.dyndns.org
"""
import urllib.error
import urllib.request
import re
import time
def contact_server():
"""
Try to get publ | ic ip address
"""
ipv4_address_pattern=re.compile(r'[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
ip_addresses=[]
try:
try:
with urllib.request.urlopen("http://checkip.dyndns.org") as urlobject:
ip_addresses=[addr for addr in ipv4_address_pattern.findall(str(urlobject.read()))]
... |
fifengine/fifengine | tests/swig_tests/action_tests.py | Python | lgpl-2.1 | 4,655 | 0.02986 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ####################################################################
# Copyright (C) 2005-2019 by the FIFE team
# http://www.fifengine.net
# This file is part of FIFE.
#
# FIFE is free software; you can redistribute it and/or
# modify it under the terms of the GNU L... | Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ####################################################################
from __future__ import absolute_import
from builtins import range
from .swig_test_utils import *
from fife.extensions.serializers.xmlanimation import ... | 's', 'se']
files = [template % dirname for dirname in dirnames]
self.engine = getEngine()
self.map = self.engine.getModel().createMap("map001")
self.grid = self.engine.getModel().getCellGrid("square")
self.layer = self.map.createLayer("Layer001", self.grid)
self.layer.setWalkable(True)
self.layer.... |
scotfu/uppir | test_simplexorrequestor.py | Python | mit | 2,272 | 0.011884 | # on success, nothing is printed
import simplexorrequestor
# I'm keeping some of these datastructures tiny in order to make the output
# more readable if an error is discovered
mirrorinfolist = [{'name':'mirror1'}, {'name':'mirror2'}, {'name':'mirror3'}, {'name':'mirror4'}, {'name':'mirror5'}]
blocklist = [12,34]
#... | rxgobj.get_next_xorrequest()
# success!
rxgobj.notify_success(request1,'a')
request3 = rxgobj.get_next_xorrequest()
# so request1 and request3 should be for the same mirror...
assert(request1[0] == request3[0])
# failure..
rxgobj.notify_failure( | request2)
request4 = rxgobj.get_next_xorrequest()
assert(request2[0] != request4[0])
# so request2 and request4 should be for different mirrors...
# success!
rxgobj.notify_success(request3,'b')
# we're out of blocks to request from the first mirror...
rxgobj.notify_success(request4,chr(2))
# we're out of blocks to ... |
lavish205/olympia | src/olympia/amo/tasks.py | Python | bsd-3-clause | 2,217 | 0 | import datetime
from django.apps import apps
from django.core.mail import EmailMessage, EmailMultiAlternatives
import olympia.core.logger
from olympia import amo
from olympia.activity.models import ActivityLog
from olympia.amo.celery import ta | sk
from olympia.amo.utils import get_email_backend
from olympia.bandwagon.models import Collection
log = olympia.core.logger.getLogger('z.task')
@task
def send_email(recipient, subject, message, from_email=None,
html_message=None, attachments=None, real_email=False,
cc=None, headers=No... | age
connection = get_email_backend(real_email)
result = backend(subject, message, from_email, to=recipient, cc=cc,
connection=connection, headers=headers,
attachments=attachments, reply_to=reply_to)
if html_message:
result.attach_alternative(html_message, ... |
peterwilletts24/MetCalcs | setup.py | Python | gpl-3.0 | 459 | 0.010893 | from distutils.core import setup
setup(
name='MetCalcs',
version= | '0.1.1',
author='Peter D. Willetts',
author_email='peterwilletts24@gmail.com',
packages=['metcalcs',],
#scripts=[],
license='LICENSE.txt',
description='Some functions for calculating met parameters from sounding variables, and from parcel ascents',
long_description=open('README.txt').rea... | ",
"scipy",]
)
|
joaduo/mepinta | core/python_core/mepinta/pipelineview/actiontree/tests/test_ActionTreeManager.py | Python | gpl-3.0 | 2,762 | 0.00181 | '''
Mepinta
Copyright (c) 2011-2012, Joaquin G. Duo, mepinta@joaquinduo.com.ar
This file is part of Mepinta under GPL 3
'''
import unittest
from mepinta.pipelineview.actiontree.data_model import ActionTree
from mepinta.pipelineview.actiontree.ActionTreeManager import ActionTreeManager
from pprint import pprint, pforma... | (answers, tree)
mngr.redoAction(tree)
self.print_verify(answers, tree)
mngr.addAction(tree, 'actiontree.UndoableGraph.generator.EmptyGraph')
self.print_verify(answers, tree)
mngr.addAction(tree, 'actiontre | e.UndoableGraph.generator.EmptyGraph')
self.print_verify(answers, tree)
mngr.addAction(tree, 'actiontree.UndoableGraph.generator.EmptyGraph')
act3 = tree.current_action
self.print_verify(answers, tree)
mngr.undoAction(tree)
self.print_verify(answers, tree)
mngr.re... |
mwest1066/PrairieLearn | elements/pl-integer-input/pl-integer-input.py | Python | agpl-3.0 | 8,803 | 0.001022 | import lxml.html
from html import escape
import chevron
import math
import prairielearn as pl
import numpy as np
import random
WEIGHT_DEFAULT = 1
CORRECT_ANSWER_DEFAULT = None
LABEL_DEFAULT = None
SUFFIX_DEFAULT = None
DISPLAY_DEFAULT = 'inline'
def prepare(element_html, data):
element = lxml.html.fragment_from... | >= 1:
html_params['correct'] = | True
elif score > 0:
html_params['partial'] = math.floor(score * 100)
else:
html_params['incorrect'] = True
except Exception:
raise ValueError('invalid score' + score)
if display == 'inline':
html_p... |
rmotr-group-projects/itp-w1-highest-number-cubed | tests/test_main.py | Python | mit | 443 | 0 | imp | ort unittest
from highest_number_cubed import highest_number_cubed
class TestHighestNumberCubed(unittest.TestCase):
def test_three(self):
self.assertEqual(highest_number_cubed(30), 3)
def test_two(self):
self.assertEqual(highest_number_cubed(12), 2)
| def test_one(self):
self.assertEqual(highest_number_cubed(3), 1)
def test_big(self):
self.assertEqual(highest_number_cubed(12000), 22)
|
tommy-u/chaco | chaco/scales_tick_generator.py | Python | bsd-3-clause | 1,682 | 0.004162 | """ Defines the ScalesTickGenerator class.
"""
from numpy import array
from traits.api import Any
from enable.font_metrics_provider import font_metrics_provider
from ticks import AbstractTickGenerator
# Use the new scales/ticks library
from scales.api import ScaleSystem
class ScalesTickGenerator(AbstractTickGenerat... | 123456789-+"
charsize = metrics.get_full_text_extent(test_str)[0] / len(test_str)
numchars = (bounds_high - bounds_low) / charsize
tmp = zip(*se | lf.scale.labels(data_low, data_high, numlabels=8, char_width=numchars))
# Check to make sure we actually have labels/ticks to show before
# unpacking the return tuple into (tick_array, labels).
if len(tmp) == 0:
return array([]), []
else:
return array(tmp[0]), tmp... |
vlegoff/tsunami | src/secondaires/navigation/editeurs/shedit/__init__.py | Python | bsd-3-clause | 10,053 | 0.001802 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | ((("Allure", ["vent debout", "au près", "bon plein",
"largue", "grand largue", "vent arrière"]),
("Facteur", "flottant"))))
facteurs.parent = self
facteurs.apercu = "{valeur}"
facteurs.aide_courte = dedent("""
Entrez |cmd|/|ff| pour revenir à la fenêtr... |
Entrez une allure, un signe |cmd|/|ff| et son facteur influençant
la vitesse. Si ce facteur est négatif, le navire va "culer".
Si ce facteur est positif, la vitesse (dépendant du vent)
sera multipliée par le facteur de l'allure précisé. Vent
debout est une a... |
pyhmsa/pyhmsa | pyhmsa/fileformat/xmlhandler/condition/calibration.py | Python | mit | 965 | 0.006218 | """
XML handler for calibrations
"""
# Standard library modules.
# Third party modules.
# Local modules.
from pyhmsa.spec.condition.calibration import \
(CalibrationConstant, CalibrationLinear,
CalibrationPolynomial, CalibrationExplicit)
from pyhmsa.fileformat.xmlhandler.condition.condition import _Conditio... | __init__(self, version):
super().__init__(CalibrationConstant, version)
class CalibrationLinearXMLHandler(_ConditionXMLHandler):
def __init__(self, version):
super().__init__(CalibrationLinear, version)
class CalibrationPolynomialXMLHandler(_ConditionXMLHandler):
def __init__(self, version)... | __(CalibrationExplicit, version)
|
yafeunteun/wikipedia-spam-classifier | revscoring/revscoring/languages/dutch.py | Python | mit | 3,534 | 0 | from .features import Dictionary, RegexMatches, Stemmed, Stopwords
name = "dutch"
try:
import enchant
dictionary = enchant.Dict("nl")
except enchant.errors.DictNotFoundError:
raise ImportError("No enchant-compatible dictionary found for 'nl'. " +
"Consider installing 'myspell-nl'.")... | via a list of
badword detecting regexes.
"""
informal_regexes = [
r"aap(jes)?",
r"banaan",
r"bent",
r"b | oe(it)?",
r"doei"
r"dombo",
r"domme",
r"eigelijk",
r"godverdomme",
r"groetjes",
r"gwn",
r"hoi",
r"hal+o+",
r"heb",
r"hee+[jyl]", r"heee+?l",
r"houd?",
r"(?:hoi+)+",
r"hoor",
r"izan",
r"jij",
r"jou",
r"jullie",
r"kaas",
r"klopt",
r"kots"... |
PragmaticMates/django-clever-selects | example/example/urls.py | Python | mit | 1,638 | 0.007326 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from views import HomeView, SimpleChainView, MultipleChainView, ModelChainView, EditCarView, DeleteCarView, \
AjaxChainedNames, AjaxChainedCountries, AjaxCh... | ew(), name='ajax_chained_countries'),
url(r'^ajax/chained-cities/$', AjaxChainedCities.as_view(), name='ajax_chained_cities'),
url(r'^ajax/chained-brand-models/$', AjaxChainedModels.as_view(), name='ajax_chained_models'),
url(r'^ajax/chained-colors/$', AjaxChainedColors.as_view(), name='ajax_chained_colors'... | del-chain/$', ModelChainView.as_view(), name='model_chain'),
url(r'^edit-car/(?P<pk>[-\d]+)/$', EditCarView.as_view(), name='edit_car'),
url(r'^delete-car/(?P<pk>[-\d]+)/$', DeleteCarView.as_view(), name='delete_car'),
url(r'^$', HomeView.as_view(), name='home'),
# url(r'^example/', include('example.f... |
wetneb/dissemin | deposit/migrations/0008_userpreferences.py | Python | agpl-3.0 | 1,117 | 0.003581 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-23 19:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | ed_by', to='deposit.Repository')),
('preferred_repository', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='preferrend_by', to='deposit.Repository')),
('user', models.OneToOneField(on_delete=django.db.models.dele | tion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
jeremy-bernon/Lilith | lilith/internal/effectivemu.py | Python | gpl-3.0 | 2,350 | 0.00383 | ##########################################################################
#
# This file is part of Lilith
# made by J. Bernon and B. Dumont
#
# Web page: http://lpsc.in2p3.fr/projects-th/lilith/
#
# In case of questions email bernon@lpsc.in2p3.fr dum33@ibs.re.kr
#
#
# Lilith is free software: you can redistribu... | prod,decay]
for template in mutemplate:
alpha_i = alpha[template["extra"]["syst"]]["val"]
alpha_0 = template["alpha0"]
mu_eff += template["phi"]*(alpha_i-alpha_0)
for pprime in prod_modes:
mu_eff += user_mu[ | pprime,decay]*template[prod,pprime]*(alpha_i-alpha_0)
effective_mu[prod,decay] = mu_eff
return effective_mu
|
tonybaloney/st2 | contrib/runners/mistral_v2/tests/unit/test_mistral_v2_policy.py | Python | apache-2.0 | 11,045 | 0.00335 | # Licensed to the StackStorm, Inc ('StackStorm') 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 use th... | Class(cls):
super(MistralRunnerPolicyTest, cls).setUpClass()
# Override the retry configuration here o | therwise st2tests.config.parse_args
# in DbTestCase.setUpClass will reset these overrides.
cfg.CONF.set_override('retry_exp_msec', 100, group='mistral')
cfg.CONF.set_override('retry_exp_max_msec', 200, group='mistral')
cfg.CONF.set_override('retry_stop_max_msec', 200, group='mistral')
... |
hellsgate1001/graphs | hack_plot/migrations/0010_auto_20150705_2020.py | Python | mit | 1,309 | 0.002292 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('hack_plot', '0009_auto_20150703_2236'),
]
operations = [
migrations.CreateModel(
name='SshHackLocation',
... | bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='sshhacklocation',
unique_together=set([('longitude', 'latitude')]),
),
migrations.RemoveField(
model_name='sshhackip',
name='latitude' | ,
),
migrations.RemoveField(
model_name='sshhackip',
name='longitude',
),
migrations.AddField(
model_name='sshhackip',
name='location',
field=models.ForeignKey(default=1, to='hack_plot.SshHackLocation'),
preserve_def... |
Zulan/PBStats | CvGameCoreDLL/update_interface_docstrings.py | Python | gpl-2.0 | 5,421 | 0.00535 | #!/usr/bin/env python
# The function declaration of Boost::Python objects are hardcoded
# as string. This Script should show changes/update this strings.
#
# (Example of such issue in Civ4:BTS is CyPlayer::initUnit.)
#
import os
import glob
import pdb
# pdb.set_trace()
REWRITE_FILES = True
VERBOSE = 1
DEBUG_WRITE =... | IOError:
if fname == "CvInfos": # Prevent rekursion
raise Exception("CvInfos.cpp missing")
info = get_cpp_file("CvInfos")
file_cache[fname] = info
return file_cache[fname]
def clean_args(sArgs):
""" Convert boost::python::list& into list, etc. """
sArgs = sArgs.replac... | = sArgs.find("::")
while colon_pos > -1:
b = max([
sArgs.rfind(" ", 0, colon_pos),
sArgs.rfind("(", 0, colon_pos)])
lArgs = [c for c in sArgs]
# print("Remove %i %i %s" % (b+1, colon_pos+2, lArgs[b+1:colon_pos+2]))
lArgs[b+1:colon_pos+2] = []
sArgs =... |
balloob/home-assistant | homeassistant/components/rainmachine/__init__.py | Python | apache-2.0 | 15,955 | 0.001818 | """Support for RainMachine devices."""
import asyncio
from datetime import timedelta
import logging
from regenmaschine import Client
from regenmaschine.errors import RainMachineError
import voluptuous as vol
from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_IP_ADDRESS,
CONF_PASSWORD,
CONF_PORT,... | raise ConfigEntryNotReady from err
else:
# regenmaschine can load multiple controllers at once, but we only grab the one
# we loaded above:
controller = next(iter(client.controllers.values()))
rainmachine = RainMachine(hass, config_entry, controller)
# Update the data object, wh... | :
await rainmachine.async_update()
hass.data[DOMAIN][DATA_CLIENT][config_entry.entry_id] = rainmachine
for component in ("binary_sensor", "sensor", "switch"):
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(config_entry, component)
)
@_verify_domain_co... |
cernops/cloudbase-init | cloudbaseinit/tests/metadata/services/test_ec2service.py | Python | apache-2.0 | 5,279 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2014 Cloudbase Solutions Srl
#
# 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/LICEN... | is_instance = isinstance(ret_value, error.HTTPError)
if is_instance and ret_value.code == 404:
self.assertRaises(base.NotExistingMetadataException,
self._service._get_ | response, req)
elif is_instance and ret_value.code != 404:
self.assertRaises(error.HTTPError,
self._service._get_response, req)
else:
response = self._service._get_response(req)
self.assertEqual(ret_value, response)
mock_urlopen.a... |
nylas/sync-engine | inbox/sendmail/base.py | Python | agpl-3.0 | 13,544 | 0.000074 | import pkg_resources
from datetime import datetime
import re
from inbox.api.validation import (
get_recipients, get_attachments, get_thread, get_message)
from inbox.api.err import InputError
from inbox.contacts.process_mail import update_contacts_from_message
from inbox.models import Message, Part
from inbox.model... | mespace=account.namespace,
| subjectdate=msg.received_date)
msg.is_created = True
msg.is_sent = True
msg.is_draft = False
msg.is_read = True
db_session.add(msg)
db_session.flush()
return msg
def block_to_part(block, message, namespace):
inline_image_uri = r'cid:{}'.format(block.public_id)
i... |
RAPD/RAPD | src/utils/lock.py | Python | agpl-3.0 | 1,987 | 0.002013 | """
Helper for keeping processes singletons
"""
__license__ = """
This file is part of RAPD
Copyright (C) 2016-2018 Cornell University
All rights reserved.
RAPD 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 Founda... | __created__ = "2016-03-02"
__maintainer__ = "Frank Murphy"
__email__ = "fmurphy@anl.gov"
__status__ = "Development"
# Standard imports
import fcntl
import os
def lock_file(file_path):
"""
Method to make sure only one instance is running on this machine.
If file_path is False, no locking will occur
If... | alse and can be locked, a False will be returned
Keyword arguments
file_path -- potential file for maintaining lock
"""
# If file_path is a path, try to lock
if file_path:
# Create the directory for file_path if it does not exist
if not os.path.exists(os.path.dirname(file_path)):
... |
jocave/snapcraft | snapcraft/tests/test_commands_prime.py | Python | gpl-3.0 | 5,460 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015, 2016 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... | self.verify_state('prime1', parts[1]['state_dir'], 'prime')
for i in [0, 2]:
self.assertFalse(os.path.exists(parts[i]['part_dir']),
'Pulled wrong part')
self.assertFalse(os.path.exists(parts[i]['state_dir']),
'Expected for o... | ile for build1')
def test_prime_ran_twice_is_a_noop(self):
fake_logger = fixtures.FakeLogger(level=logging.INFO)
self.useFixture(fake_logger)
parts = self.make_snapcraft_yaml()
main(['prime'])
self.assertEqual(
'Preparing to pull prime0 \n'
'Pulling... |
TheCheshireFox/foxy-player | foxy_player/foxy_player_api/migrations/0010_auto_20170416_1306.py | Python | apache-2.0 | 419 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-16 10:06
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
| ('foxy_player_api', '0009_auto_20170415_2318'),
]
operations = [
migrations.AlterUniqueTogether(
name='playlisttra | cks',
unique_together=set([]),
),
]
|
rocky/python-uncompyle6 | uncompyle6/semantics/customize26_27.py | Python | gpl-3.0 | 2,225 | 0.002247 | # Copyright (c) 2019 2021 by Rocky Bernstein
#
# 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... | ition> as <var>
# vs. older:
# except <condition> , <var>
#
# For 2.6 we use the older syntax which
# matches how we parse this in bytecode
########################################
if version > (2, 6):
TABLE_DIRECT.update({
'except_cond2': ( '%|except %c as %c:\n', 1, ... | e parameter of a function,
# it doesn't need the surrounding parenethesis.
'call_generator': ('%c%P', 0, (1, -1, ', ', 100)),
})
else:
TABLE_DIRECT.update({
'testtrue_then': ( 'not %p', (0, 22) ),
})
# FIXME: this should be a transformation
def n_... |
jlongever/redfish-client-python | on_http_redfish_1_0/models/computer_system_1_0_0_system_type.py | Python | apache-2.0 | 2,513 | 0.002388 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value | .to_dict()
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
... |
krafczyk/spack | var/spack/repos/builtin/packages/perl-font-ttf/package.py | Python | lgpl-2.1 | 1,568 | 0.001913 | ##############################################################################
# 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... |
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston | , MA 02111-1307 USA
##############################################################################
from spack import *
class PerlFontTtf(PerlPackage):
"""Perl module for TrueType Font hacking"""
homepage = "http://search.cpan.org/~bhallissy/Font-TTF-1.06/lib/Font/TTF.pm"
url = "http://search.cpan.or... |
kagel/foobnix | foobnix/helpers/dialog_entry.py | Python | gpl-3.0 | 12,111 | 0.004625 | #-*- coding: utf-8 -*-
'''
Created on 24 авг. 2010
@author: ivan
'''
from gi.repository import Gtk
import logging
from foobnix.fc.fc import FC
from foobnix.helpers.image import ImageBase
from foobnix.util.const import SITE_LOCALE, ICON_FOOBNIX
from foobnix.util.localization import foobnix_localization
from foobnix.gu... | ))
# link = Gtk.LinkButton("http://www.foobn | ix.com/support?lang=%s"%SITE_LOCALE, _("Download"))
frame = Gtk.Frame(label="Please donate and download")
vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
vbox.set_homogeneous(True)
vbox.pack_start(card, True, True)
#vbox.pack_start(terminal, True, True)
vbox.pack_start(l... |
logpai/logparser | logparser/LogSig/LogSig.py | Python | mit | 12,489 | 0.003043 | """
Description : This file implements the LogSig algorithm for log parsing
Author : LogPAI team
License : MIT
"""
from datetime import datetime
import random
import math
import time
import operator
import re
import os
import pandas as pd
import hashlib
class Para:
def __init__(self, p... | wordSeq = line.strip().split()
self.wordLL.append(tuple(wordSeq))
def termpairGene(self):
print('Generating term pairs...')
i = 0
for wordL in self.wordLL:
wordLT = []
for j in range(len(wordL)):
for k in range(j + 1, len(wordL),... | |
diogocs1/comps | web/addons/email_template/wizard/email_template_preview.py | Python | apache-2.0 | 3,851 | 0.002597 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2009 Sharoon Thomas
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it ... | efault_get(cr, uid, fields, context=context)
email_template = self.pool.get('email.template')
template_id = context.get('template_id')
if 'res_id' in fields and not result.get('res_id'):
records = self._get_records(cr, uid, context=context)
result['res_id'] = records and... | efault
if template_id and 'model_id' in fields and not result.get('model_id'):
result['model_id'] = email_template.read(cr, uid, int(template_id), ['model_id'], context).get('model_id', False)
return result
_columns = {
'res_id': fields.selection(_get_records, 'Sample Document')... |
crazcalm/PyTN_talk_proposal | recipies/recipe1/fib.py | Python | mit | 2,169 | 0.004149 | """
The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The next number is found by adding up the two numbers before it.
The 2 is found by adding the two numbers before it (1+1)
Similarly, the 3 is found by adding the two numbers before it (1+2),
And the 5 is (2+3),
... | > 0:
fib1, fib2 | = fib2, fib1 + fib2
current_fib = current_fib + 1
answer = fib2
return answer
"""
Solve with generators
"""
def fib3(nth_num=10):
"""
A generator that yields fib numbers
"""
# Base case
fib1 = 0
fib2 = 1
if nth_num <= 1:
yield fib1
elif nth_num == 2... |
chipaca/snapcraft | tests/unit/plugins/v1/python/test_sitecustomize.py | Python | gpl-3.0 | 5,261 | 0.00076 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017,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 ... | in the staging area
self._create_python_binary(stage_dir)
# Create a site.py, but only in install area (not staging area)
_create_site_py(install_dir)
# Create a user site dir in install area
_create_user_site_packages(install_dir)
raised = self.assertRaises(
... | stage_dir=stage_dir,
install_dir=install_dir,
)
self.assertThat(str(raised), Contains("Unable to find site.py"))
|
thaim/ansible | lib/ansible/plugins/callback/syslog_json.py | Python | mit | 3,681 | 0.004075 | # (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: syslog_json
callback_type: notification
... | le runs to a syslog server in json format
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'syslog_json'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
self.set_options()
syslog_host = self.get_option(... | e logger')
self.logger.setLevel(logging.DEBUG)
self.handler = logging.handlers.SysLogHandler(
address=(syslog_host, syslog_port),
facility=syslog_facility
)
self.logger.addHandler(self.handler)
self.hostname = socket.gethostname()
def runner_on_faile... |
myadventure/myadventure-api | app/models/__init__.py | Python | apache-2.0 | 27 | 0 | """
Initialize models
""" | ||
zmap/ztag | ztag/annotations/FtpCesarFtpd.py | Python | apache-2.0 | 1,652 | 0.003632 | import re
from ztag.annotation import Annotation
from ztag.annotation import OperatingSystem
from ztag import protocols
import ztag.test
class FtpCesarFtpd(Annotation):
protoc | ol = protocols.FTP
subprotocol = protocols.FTP.BANNER
port = None
impl_re = re.compile("^220[- ]CesarFTP 0\.\d+", re.IGNORECASE)
version_re = re.compile("CesarFTP (\d+\.\d+)([a-z])?", re.IGNORECASE)
tests = {
"FtpCesarFtpd_1": {
"glo | bal_metadata": {
"os": OperatingSystem.WINDOWS,
},
"local_metadata": {
"product": "Cesar FTP",
"version": "0.99",
"revision": "g"
}
}
}
def process(self, obj, meta):
banner = obj["banner"]
... |
kmaiti/AWSAutoScalingWithF5andCloudFormation | aws-autoscale-ec2-instance-modify.py | Python | gpl-3.0 | 6,954 | 0.012511 | #!/usr/bin/env python
"""
Purpose : Extract next sequence number of auto-scaled instance and set new tag to self instance. Script will be running from new instance.
will take input from command line instead of from json file
Future Plan :
will associate instance to a role based IAM profile
Usage :
python ec2-autoscale-... | _tag))
#will extract current instance ID using curl. ie curl http://169.254.169.254/latest/meta-data/instance-id
#
cmd = 'curl http://169.254.169.254/latest/meta-data/instance-id'
#shlex is simple lexical analyser for sp | litting a large string into tokens
args = shlex.split(cmd) #args will have value like : ['curl', 'http://169.254.169.254/latest/meta-data/instance-id']
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate() #out and err... |
cwyark/micropython | tests/cpydiff/types_bytes_subscrstep.py | Python | mit | 145 | 0 | """ |
categories: Types,bytes
description: Bytes subscr with st | ep != 1 not implemented
cause: Unknown
workaround: Unknown
"""
print(b'123'[0:3:2])
|
back-to/streamlink | tests/test_plugins.py | Python | bsd-2-clause | 1,609 | 0.000622 | import imp
import os.path
import pkgutil
import six
import unittest
import streamlink.plugins
from streamlink import Streamlink
class PluginTestMeta(type):
def __new__(mcs, name, bases, dict):
plugin_path = os.path.dirname(streamlink.plugins.__file__)
plugins = []
for loader, pname, ispk... | session = Streamlink()
def gentest(pname):
def load_plugin_test(self):
# Reset file variable to ensure it is still open when doing
# load_plugin else python might open the plugin source .py
# using ascii encoding instead of utf-8.
# S... | ata
file, pathname, desc = imp.find_module(pname, [plugin_path])
session.load_plugin(pname, file, pathname, desc)
# validate that can_handle_url does not fail
session.plugins[pname].can_handle_url("http://test.com")
return load_plugin_test
... |
iSTB/python-schemata | rst_cleaner.py | Python | mit | 1,813 | 0.006067 | #!/usr/bin/python3
"""
Cleans-up Sphinx-only constructs (ie from README.rst),
so that *PyPi* can format it properly.
To check for remaining errors, install ``sphinx`` and run::
python setup.py --long-description | sed -file 'this_file.sed' | rst2html.py --halt=warning
"""
impor | t re
import sys, io
def yield_sphinx_only_markup(lines):
"""
:param file_inp: a `filename` or ``sys.stdin``?
:param file_out: a `filename` or ``sys.stdout`?`
| """
substs = [
## Selected Sphinx-only Roles.
#
(r':abbr:`([^`]+)`', r'\1'),
(r':ref:`([^`]+)`', r'`\1`_'),
(r':term:`([^`]+)`', r'**\1**'),
(r':dfn:`([^`]+)`', r'**\1**'),
(r':(samp|guilabel|menuselection):`([^`]+)`', ... |
espressopp/espressopp | testsuite/AdResS/TDforce/test_TDforce.py | Python | gpl-3.0 | 16,457 | 0.010634 | #!/usr/bin/env python
#
# Copyright (C) 2013-2017(H)
# Max Planck Institute for Polymer Research
#
# This file is part of ESPResSo++.
#
# ESPResSo++ 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, ei... | ddTuples(tuples)
self.system.storage.setFixedTuplesAdress(ftpl)
self.system.storage.decompose()
# generate a verlet list
vl = espressopp.VerletListAdress(self.system, cutoff=1.5, adrcut=1.5,
dEx=1.0, dHy=1.0, adrCenter=[5.0, 5.0, 5.0], sphereAdr=False)
... | integrator = espressopp.integrator.VelocityVerlet(self.system)
integrator.dt = 0.01
adress = espressopp.integrator.Adress(self.system,vl,ftpl)
integrator.addExtension(adress)
espressopp.tools.AdressDecomp(self.system, integrator)
# set up TD force
thdforce = espresso... |
dimagi/commcare-hq | corehq/apps/receiverwrapper/tests/test_submit_errors.py | Python | bsd-3-clause | 14,436 | 0.00194 | import contextlib
import logging
import os
import tempfile
from django.db.utils import InternalError
from django.test import TestCase
from django.test.client import Client
from django.urls import reverse
from botocore.exceptions import ConnectionClosedError
from unittest.mock import patch
from casexml.apps.case.exce... | cls.client = Client()
cls.client.login(**{'username': 'test', 'password': 'foobar'})
cls.url = reverse("receiver_post", args=[cls.domain])
@classmethod
def tearDownClass(cls):
cls.couch_user.delete(cls.domain.name, deleted_by=None)
cls.domain.delete()
super(Submis... | l_xforms(self.domain.name)
def tearDown(self):
FormProcessorTestUtils.delete_all_cases_forms_ledgers(self.domain.name)
UnfinishedSubmissionStub.objects.all().delete()
def _submit(self, formname, open_rosa_header=None):
open_rosa_header = open_rosa_header or OPENROSA_VERSION_2
f... |
tinyogre/zklock | zklocktest.py | Python | lgpl-3.0 | 1,271 | 0.010228 | #
# To test this, first have a runnin | g l | ocal zookeeper installation
# (See http://zookeeper.apache.org/)
# Next, open a couple of shells
# Run this in the first one, watch the output. It will create a lock and hold it for 20 seconds.
# Run it again in the second one, watch that it doesn't acquire the lock until the fist instance exits,
# and then holds the... |
liosha2007/temporary-groupdocs-python3-sdk | groupdocs/ApiClient.py | Python | apache-2.0 | 11,500 | 0.004609 | #!/usr/bin/env python
"""Wordnik.com's Swagger generic API client. This client handles the client-
server communication, and is invariant across implementations. Specifics of
the methods and models for each application are generated from the Swagger
templates."""
import sys
import os
import re
import urllib.request, u... | ms, postData,
| headerParams=None, returnType=str):
if self.__debug and self.__logFilepath:
stdOut = sys.stdout
logFile = open(self.__logFilepath, 'a')
sys.stdout = logFile
url = apiServer + resourcePath
headers = {}
if self.headers:
... |
odoousers2014/LibrERP | task_time_control/project_task.py | Python | agpl-3.0 | 7,349 | 0.004084 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Pexego Sistemas Informáticos (http://www.pexego.es) All Rights Reserved
# $Jesús Ventosinos Mayor$
# $Javier Colmenero Fernández$
# Copyright (c) 2014 Dido... | function(_get_users_working, method=True, string='Working users', type='char', size=255, multi=True),
'user_is_working': fields.function(_get_users_working, method=True, string='I am working', | type='boolean', multi=True)
}
def stop_task(self, cr, uid, task_id, final, user_task, context=None):
if context is None:
context = {}
self.pool['time.control.user.task'].write(cr, uid, user_task.id, {'work_end': final})
context['user_id'] = uid
cont... |
vinni-au/vega-strike | data/bases/university_night.py | Python | gpl-2.0 | 169 | 0.035503 | import Base
import sys
import industrial_lib
time_of_ | day='_night'
(landing_platform,bar | ,weap) = industrial_lib.MakeCorisc (time_of_day,'bases/bartender_university.py')
|
rizar/attention-lvcsr | bin/check_all_fst_weights_are_zero.py | Python | mit | 633 | 0.004739 | #!/usr | /bin/env python
"""
Check if an FST has only zero weights.
"""
import argparse
import fst
import sys
def main(args):
L = fst.read(args.fst_file)
for state in L:
for arc in state:
if arc.weight != fst.TropicalWeight(0.0):
sys.stderr.write(
"Nonzero wei... | (1)
if __name__=='__main__':
parser = argparse.ArgumentParser(description="Zero the weight on all transitions in the FST")
parser.add_argument("fst_file", default='-', nargs='?')
args = parser.parse_args()
main(args)
|
lebinh/aq | tests/test_sqlite_util.py | Python | mit | 2,855 | 0.001051 | from unittest import TestCase
from aq.sqlite_util import connect, create_table, insert_all
| class TestSqliteUtil(TestCase):
def test_dict_adapter(self):
with connect(':memory:') as conn:
conn.execute('CREATE TABLE foo (foo)')
conn.execute('INSERT INTO foo (foo) VALUES (?)', ({'bar': 'blah'},))
values = conn.execute('SELECT * FROM foo').fetchone()
sel... | ual(len(values), 1)
self.assertEqual(values[0], '{"bar": "blah"}')
def test_create_table(self):
with connect(':memory:') as conn:
create_table(conn, None, 'foo', ('col1', 'col2'))
tables = conn.execute("PRAGMA table_info(\'foo\')").fetchall()
self.assertEqual... |
alexherns/biotite-scripts | build_connection_graph.py | Python | mit | 1,780 | 0.03427 | #!/usr/bin/env python2.7
import networkx as nx
import matplotlib.pyplot as plt
import sys, argparse, os, re
parser = argparse.ArgumentParser(description='''Visualizes connections in assembly
using networkx_viewer module.''',
formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False)
#Required argumen... | e[3]]:
attr= {'fill':'red'}
attr['direction']= " ".join(line[:4])
attr['count']= line[4]
if int(attr['count'])<args.m:
continue
edge.append(attr)
edges[lookup]= edge
G.add_nodes_from(nodes)
G.add_edges_from(edges.values())
#Draw the graph
| app= nv.Viewer(G)
app.mainloop()
|
stanford-futuredata/macrobase | tools/py_analysis/analyze_cluster.py | Python | apache-2.0 | 3,142 | 0.005729 | import pandas as pd
import numpy as np
from sklearn import linear_model, cluster
from collections import defaultdict, Iterable
from itertools import chain, combinations
import operator
import psycopg2
conn = psycopg2.connect("dbname='postgres' user='pbailis' host='localhost'")
cur = conn.cursor()
cols = "hardware_ma... | , .5)).fit(dummies)
for centerno in range(0, len(dbscan.components_)):
center = dbscan.components_[centerno]
nmatches = len([i for i in dbscan.labels_ if i == centerno])
t | arget_vals = [data.iloc[i, 0] for i in range(0, len(data)) if dbscan.labels_[i] == centerno]
if nmatches == 0:
continue
print "\n"
print "N: %d, Average: %f, Std.: %f" % (nmatches, float(sum(target_vals))/len(target_vals), np.std(target_vals))
for dim in range(0, len(center)):
... |
sradevski/homeAutomate | scripts/lights_controller.py | Python | mit | 665 | 0.040602 | #!/usr/bin/python
import sys
import remote_core as core
import radio_lights
def main(argv):
config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af"... | urn_off_single(config["lights"][lights_config_names[item[:1]]])
core.write_config(config)
if __name__ == "__main__":
main(sys.argv[1:]) | |
ChillarAnand/junction | junction/profiles/tests.py | Python | mit | 519 | 0 | from django.test import TestCase
from .models import Profile
from django.contrib.auth.models import User
# models test
class ProfileTest(TestCase):
def setUp(self):
self.user = User.objects.create(username='user1', password='123456')
Prof | ile.objects.create(city='noida', contact_no= | '1234567890')
def test_create_profile(self):
user = User.objects.get(username='user1')
profile_details = Profile.objects.get(user=user)
self.assertEqual(profile_details.city, 'noida')
|
sentriz/steely | steely/utils.py | Python | gpl-3.0 | 800 | 0 | import os
import imp
from tinydb import TinyDB
from paths import DB_DIR
def scan_plugins_dir(plugins_dir='plugins'):
"""Scan the given dir for files matching the spec for plugin files"""
for plugin_file in os.listdir(plugins_dir):
plugin_path = os.path.join(plugins_dir, plugin_file)
if (not pl... | ):
yield plugin_file, plugin_path
def load_plugin(filename, path):
return imp.load_source(file | name, path)
def list_plugins():
for plugin_file, plugin_path in scan_plugins_dir():
yield load_plugin(plugin_file, plugin_path)
def new_database(name):
full_path = os.path.join(DB_DIR, f'{name}.json')
return TinyDB(full_path)
|
Azure/azure-sdk-for-python | sdk/synapse/azure-synapse-artifacts/azure/synapse/artifacts/operations/_kql_script_operations.py | Python | mit | 24,579 | 0.005167 | # 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 ... | st:
api_version = kwargs.pop('api_version', "2021-11-01-preview") # type: str
accept = "application/json"
# Construct URL
url = kwargs.pop("template_url", '/kqlScripts/{kqlScriptName}')
path_format_arguments = {
"kqlScriptName": _SERIALIZER.url("kql_script_name", kql_script_name, 'str'),
... | # Construct parameters
query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any]
query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str')
# Construct headers
header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any]
header_parameters['Accept']... |
devurandom/portage | pym/portage/__init__.py | Python | gpl-2.0 | 21,844 | 0.031038 | # portage.py -- core Portage functionality
# Copyright 1998-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
VERSION="HEAD"
# ===========================================================================
# START OF IMPORTS -- START OF IMPORTS -- START OF IMPORTS -- START OF IMPO... | ease try a rescue portage located in the\n")
sys.stderr.write("!!! portage tree under '/usr/portage/sys-apps/portage/files/' (default).\n")
sys.stderr.write("!!! There is a README.RESCUE file that details the steps required to perform\n")
sys.stderr.write("!!! a recovery of portage.\n")
sys.stderr.write(" "+str(... | e 'merge' encoding, but that had
# various problems:
#
# 1) If the locale is ever changed then it can cause orphan files due
# to changed character set translation.
#
# 2) Ebuilds typically install files with utf_8 encoded file names,
# and then portage would be forced to rename those files to match
# ... |
Ryezhang/scrapy | scrapy/http/request/form.py | Python | bsd-3-clause | 7,658 | 0.001306 | """
This module implements the FormRequest class which is a more convenient class
(than Request) to generate Requests based on form data.
See documentation in docs/topics/request-response.rst
"""
import six
from six.moves.urllib.parse import urljoin, urlencode
import lxml.html
from parsel.selector import create_root... |
class FormRequest(Request):
def __init__(self, *args, **kwargs):
formdata = kwargs.pop('formdata', None)
if formdata and kwargs.get('method') is None:
kwargs['method'] = 'POST'
super(FormRequest, self).__init__(*args, **kwargs)
if formdata:
items = formdat... | ncoding)
if self.method == 'POST':
self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')
self._set_body(querystr)
else:
self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)
@classmethod
def from_r... |
andresfcardenas/marketing-platform | landing/migrations/0003_auto__add_formtext.py | Python | bsd-3-clause | 3,656 | 0.008206 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FormText'
db.create_table(u'landing_formtext', (
(u'id', self.gf('django.db.mode... | , [], {'max_length': '200'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}... | ': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'landing.testimonial': {
'Meta': {'object_name': 'Testimonial'},
'description': ('django.db.models.fields.TextField', [], {'max_length': '200'}),
u'id': ('django.db.models.fields.AutoField', [], {... |
googleads/google-ads-python | google/ads/googleads/v8/services/services/product_bidding_category_constant_service/client.py | Python | apache-2.0 | 18,954 | 0.001636 | # -*- coding: utf-8 -*-
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | pile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
... | return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "googleads.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs... |
DataONEorg/d1_python | gmn/src/d1_gmn/app/urls.py | Python | apache-2.0 | 8,003 | 0.00025 | # This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... | s.internal.error_500"
urlpatterns = [
# Django's URL dispatcher does not take HTTP method into account, so in the
# cases where the DataONE REST API specifies different methods as different
# methods against the same URL, the methods are dispatched to the same view
# function, which checks the method a... | dispatches to the appropriate handler.
# Tier 1: Core API (MNCore)
# MNCore.ping() - GET /monitor/ping
django.urls.re_path(
r"^v[12]/monitor/ping/?$",
d1_gmn.app.views.external.get_monitor_ping,
kwargs={"allowed_method_list": ["GET"]},
name="get_monitor_ping",
),
# MN... |
fbsder/zephyr | scripts/support/runner/jlink.py | Python | apache-2.0 | 3,770 | 0 | # Copyright (c) 2017 Linaro Limited.
#
# SPDX-License-Identifier: Apache-2.0
'''Runner for debugging with JLink.'''
from os import path
import os
from .core import ZephyrBinaryRunner, get_env_or_bail
DEFAULT_JLINK_GDB_PORT = 2331
class JLinkBinaryRunner(ZephyrBinaryRunner):
'''Runner front-end for the J-Link ... | link.sh')
def create_from_env(command, debug):
'''Create runner from environment.
Required:
- JLINK_DEVICE: device name
Required for 'debug':
| - GDB: gdb to use
- O: build output directory
- KERNEL_ELF_NAME: zephyr kernel binary in ELF format
Optional for 'debug':
- TUI: if present, passed to gdb server used to flash
Optional for 'debug', 'debugserver':
- JLINK_GDBSERVER: default is JLinkGDBServer
... |
Dingo5733/djangoblog19 | src/trydjango19/settings.py | Python | mit | 3,453 | 0.001448 | """
Django settings for blog project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Buil... | template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.applic | ation'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-v... |
chemelnucfin/tensorflow | tensorflow/python/data/experimental/ops/batching.py | Python | apache-2.0 | 13,674 | 0.003145 | # Copyright 2017 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... | s in parallel. If not
specified, `batch_size * num_paral | lel_batches` elements will be processed
in parallel. If the value `tf.data.experimental.AUTOTUNE` is used, then
the number of parallel calls is set dynamically based on available CPU.
Returns:
A `Dataset` transformation function, which can be passed to
`tf.data.Dataset.apply`.
Raises:
Valu... |
StackStorm/st2 | st2tests/integration/orquesta/test_wiring_functions_task.py | Python | apache-2.0 | 3,825 | 0.000523 | # 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 ... | _result = {"output": expec | ted_output}
self._execute_workflow(
wf_name, execute_async=False, expected_result=expected_result
)
def test_task_functions_in_jinja(self):
wf_name = "examples.orquesta-test-jinja-task-functions"
expected_output = {
"last_task4_result": "False",
... |
Alwnikrotikz/pmx | scripts/mdsetup_407.py | Python | lgpl-3.0 | 22,643 | 0.019035 | #!/usr/bin/env python
# pmx Copyright Notice
# ============================
#
# The pmx source code is copyrighted, but you can freely use and
# copy it as long as you don't change or remove any of the copyright
# notices.
#
# ----------------------------------------------------------------------
# pmx is Copyright (C... | e and
# this permission notice appear in supporting documentation, and that
# the name of Daniel Seeliger not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# DANIEL SEELIGER DISCLAIMS ALL WARRANTIES WITH REGARD | TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL DANIEL SEELIGER BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIO... |
data-henrik/watson-conversation-tool | wctool.py | Python | apache-2.0 | 13,189 | 0.012207 | # Copyright 2017-2018 IBM Corp. All Rights Reserved.
# See LICENSE for details.
#
# Author: Henrik Loeser
#
# Manage workspaces for IBM Watson Assistant service on IBM Cloud.
# See the README for documentation.
#
import json, argparse, importlib
from os.path import join, dirname
from ibm_watson import AssistantV1
from... | (json.dumps(assistant.get_workspace(workspace_id=workspaceID,export=exportWS).get_result(), indent=2))
# Get a specific workspace by ID and export to file
def getSaveWorkspace(workspaceID,outFile):
ws=assistant.get_workspace(workspace_id=workspaceID,export=True).get_result()
with open(outFile,'w') as jsonFile:... |
# The workspace parts to be updated were specified as command line options
def updateWorkspace(workspaceID,
intents,
entities,
dialog_nodes,
counterexamples,
metadata,
newName=None,
... |
slitvinov/lammps-sph-multiphase | python/examples/vizplotgui_gl.py | Python | gpl-2.0 | 4,373 | 0.02424 | #!/usr/bin/env python -i
# preceeding line should have path for Python on your machine
# vizplotgui_gl.py
# Purpose: viz running LAMMPS simulation via GL tool with plot and GUI
# Syntax: vizplotgui_gl.py in.lammps Nfreq compute-ID
# in.lammps = LAMMPS input script
# Nfreq = plot data point and viz s... | :
lmp.command("run %d pre no post no" % nfreq)
ntimestep += nfreq
if me == 0: update(ntimestep)
elif runflag and not running:
lmp.command("run %d pre yes post no" % nfreq)
ntimestep += nfreq
if me == 0: update(ntimestep)
elif not runflag an | d running:
lmp.command("run %d pre no post yes" % nfreq)
ntimestep += nfreq
if me == 0: update(ntimestep)
if breakflag: break
if runflag: running = 1
else: running = 0
time.sleep(0.01)
lmp.command("run 0 pre no post yes")
# uncomment if running in parallel via Pypar
#print "Proc %d out of %d procs... |
pombredanne/coloradoes.py | src/coloradoes/coloradoes.py | Python | bsd-2-clause | 3,539 | 0.001413 | import struct
import time
from .types import t_string, t_list, t_set, t_zset, t_hash
from .errors import *
class Coloradoes(object):
STRUCT_KEY = '!ic'
STRUCT_KEY_VALUE = '!icd'
STRUCT_ID = '!i'
def __init__(self, storage=None):
if storage is None:
rai | se ValueError('A storage is required')
super(Coloradoes, self).__init__()
self.storage = storage
self.database = 0
def set_database(self, database):
self.database = database
def rename(self, source, target):
value = self.storage.get(source)
if value:
... | rage.get(key) or 0) + increment
self.storage.set(key, str(id))
return id
def get(self, key):
return self.storage.get(key)
def set(self, key, value):
return self.storage.set(key, value)
def exists(self, key):
return self.storage.exists(key)
def delete(self, key... |
asteroidhouse/equibel | tests/completion_tests.py | Python | mit | 2,605 | 0.002303 | from sympy.logic.boolalg import *
import equibel as eb
def test_global_completion_cardinality():
G = eb.star_graph(3)
G.add_formula(1, 'p')
G.add_formula(2, 'p')
G.add_formula(3, '~p')
R_semantic = eb.global_completion(G, method=eb.SEMANTIC, | opt_type=eb.CARDINALITY, simplify=True)
assert(R_semantic.formula_conj(0) == eb.parse_formula('p'))
R_syntactic = eb.global_completion(G, method=eb.SYNTACTIC, opt_type=eb.CARDINALITY, simplify=True)
assert(R_syntactic == R_semantic)
def test_global_completion_two_nodes():
G = eb.path_graph(2)
... | ormula(0, 'p')
atoms = G.atoms()
R_semantic = eb.global_completion(G, method=eb.SEMANTIC, simplify=True)
print(R_semantic.formulas())
assert(R_semantic.formulas() == {0: atoms, 1: atoms})
R_syntactic = eb.global_completion(G, method=eb.SYNTACTIC, simplify=True)
assert(R_semantic == R_syntactic)... |
fieldOfView/OctoPrintPlugin | OctoPrintOutputController.py | Python | agpl-3.0 | 1,276 | 0.003135 | # Copyright (c) 2020 Aldo Hoeben / fieldOfView
# OctoPrintPlugin is released under the terms of the AGPLv3 or higher.
from cura.PrinterOutp | ut.GenericOutputController import GenericOutputController
try:
# Cura 4.1 and newer
| from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
except ImportError:
# Cura 3.5 - Cura 4.0
from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
from cura.PrinterOutput... |
toolhub/toolhub.co | accounts/urls.py | Python | bsd-3-clause | 1,267 | 0 | from django.conf.urls import url, patterns, include
from accounts import views
user_tool_patterns = patterns(
"",
url(r"^lending/$", views.LendingManager.as_view(), name="lending"),
url(r"^manager/$", views.ToolManager.as_view(), name="manager"),
)
# namespaced under account:
urlpatterns = patterns(
... | ws.ConfirmEmailView.as_view(),
name="confirm_email"),
url(r"^password/$", views.ChangePasswordView.as_view(),
name="password"),
url(r"^password/reset/$", views.PasswordResetView.as_view(),
name="password_reset"),
url(r"^password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$",
... | view(),
name="password_reset_token"),
url(r"^delete/$", views.DeleteView.as_view(), name="delete"),
url(r"^tool/", include(user_tool_patterns, namespace="tool")),
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.