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
rackerlabs/horizon
openstack_dashboard/dashboards/project/networks/views.py
Python
apache-2.0
5,149
0.000971
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 NEC Corporation # # 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 #...
id=network.id) except: subnets = [] msg = _('Subnet list can not be retrieved.') exceptions.handle(self.request, msg) for s in subnets: s.set_id_as_name_if_empty() return subnets def get_ports_data(self): try: network_id = ...
msg = _('Port list can not be retrieved.') exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports def _get_data(self): if not hasattr(self, "_network"): try: network_id = self.kwargs['network_id'...
ekaputra07/wpcdesk
wpcdesk/comment_editor.py
Python
gpl-3.0
4,371
0.004576
# -*- coding: utf-8 -*- # wpcdesk - WordPress Comment Desktop # Copyright (C) 2012 Eka Putra - ekaputra@balitechy.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of ...
mment_date']) self.ui.edit_name.setText(data['comment_author']) self.ui.edit_email.setText(data['comment_email']) self.ui.edit_comment.setText(data['comment_content']) if data['comment_status'] == 'Approved': self.ui.cb_status.setChe
cked(True) else: self.ui.cb_status.setChecked(False) def saveComment(self): data = {} if self.ui.cb_status.isChecked(): data['status'] = 'approve' else: data['status'] = 'hold' data['content'] = str(self.ui.edit_comment.toPlainText()) ...
fukatani/CW_gui
examples/mnist/get_mnist_prediction.py
Python
bsd-3-clause
87
0
impo
rt chainer def main(): return chainer.datasets.
get_mnist(withlabel=False)[0]
coen-hyde/dotfiles
libs/eb/scli/constants.py
Python
mit
21,046
0.013779
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use # this file except in compliance with th...
ServiceRegion.UsWest2 : u'US West (Oregon)', } ServiceRegionId = { ServiceRegion
.ApNortheast1 : u'ap-northeast-1', ServiceRegion.ApSoutheast1 : u'ap-southeast-1', ServiceRegion.ApSoutheast2 : u'ap-southeast-2', ServiceRegion.EuWest1: u'eu-west-1', ServiceRegion.SaEast1: u'sa-east-1', ServiceRegion.UsEast1 : u'us-east-1', ServiceRegion.UsWest1 : u'us-west-1', Service...
helldorado/ansible
lib/ansible/modules/cloud/azure/azure_rm_servicebus.py
Python
gpl-3.0
6,397
0.003126
#!/usr/bin/python # # Copyright (c) 2018 Yuwei Zhou, <yuwzho@microsoft.com> # # 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 = {'metadata_version': '1.1', ...
ported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_servicebus version_added: "2.8" short_description: Manage Azure Service Bus. description: - Create, update or delete an Azure Service Bus namespaces. options: resource_group: description: - name of resource group. re...
- Assert the state of the route. Use 'present' to create or update and 'absent' to delete. default: present choices: - absent - present location: description: - Namespace location. sku: description: - Namespace s...
dsanders11/django-newsletter
docs/conf.py
Python
agpl-3.0
9,244
0.006274
# # django-newsletter documentation build configuration file, created by # sphinx-quickstart on Wed Nov 13 13:53:07 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration...
e=False) autodoc_default_flags = ['members', 'show-inheritance'] autodoc_member_order = 'bysource' # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it
here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates...
sudkannan/xen-hv
tools/python/xen/xend/XendBootloader.py
Python
gpl-2.0
7,323
0.004779
# # XendBootloader.py - Framework to run a boot loader for picking the kernel # # Copyright 2005-2006 Red Hat, Inc. # Jeremy Katz <katzj@redhat.com> # # This software may be freely redistributed under the terms of the GNU # general public license. # # You should have received a copy of the GNU General Public License # ...
otloader as %s." % str(args)) env = os.environ.copy() env['TERM'] = 'vt100' oshelp.close_fds() os.execvpe(args[0], args, env) except OSError, e: print e pass os._exit(1) # record that this domain i
s bootloading dom.bootloader_pid = child # On Solaris, the master pty side does not have terminal semantics, # so don't try to set any attributes, as it will fail. if os.uname()[0] != 'SunOS': tty.setraw(m2); fcntl.fcntl(m2, fcntl.F_SETFL, os.O_NDELAY); while True: try: ...
bwmichael/jccc-cis142-python
old/check-quadrant.py
Python
apache-2.0
3,124
0.003201
# Brandon Michael # cis142 # checkForQuadrant.py # Goal: This program will keep asking for input values to check for the quadrant postion, # origin, x-axis and y axis postions # Notes: I used a while loop to make testing values easier and I used the input x,y # Display program instructions print("####################...
e == 0: print("X - Axis") # Anything else and we need to check for quadr
ants else: # If x is a positive number and y is a negative positive its in Quadrant 1 if xValue > 0 and yValue > 0: print("Quadrant I") # If x is a negative number and y is a positive number then its in Quadrant 2 elif xValu...
sajuptpm/murano
contrib/plugins/murano_exampleplugin/murano_exampleplugin/cfg.py
Python
apache-2.0
822
0
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
cfg.StrOpt('endpoint_type', default='publicURL') ] conf.register_opts(opts, group="glance") return con
f.glance
duncan-r/SHIP
ship/utils/fileloaders/datloader.py
Python
mit
9,666
0.001552
""" Summary: Factory class for building the AUnits from an ISIS data file. This is used to read and build the parts of the ISIS dat file. Author: Duncan Runnacles Created: 01 Apr 2016 Copyright: Duncan Runnacles 2016 TODO: There are a few functions in here that should be made prote...
if first_word in unit_vars: # If building an UnknownUnit then create and reset if(in_unknown_section == True): self.createUnknownSection() self.updateSubContents() # Reset the reach for the UnknownUn
it unit_factory.same_reach = False '''Call the unit creator function and get back the unit and the updated contents list index. Most of these variables are self explanatory, but unit_vars[first_word] is the key for the unit type to mak...
sacharya/nova
nova/tests/conductor/test_conductor.py
Python
apache-2.0
83,151
0.000457
# Copyright 2012 IBM Corp. # Copyright 2013 Red Hat, 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 r...
(self): self.mox.StubOutWithMock(db, 'migration_get_in_progress_by_host_and_node') db.migration_get_in_progress_by_host_and_node(
self.context, 'fake-host', 'fake-node').AndReturn('fake-result') self.mox.ReplayAll() result = self.conductor.migration_get_in_progress_by_host_and_node( self.context, 'fake-host', 'fake-node') self.assertEqual(result, 'fake-result') def test_migration_update(self): ...
mathcamp/aws-formula
_states/elb.py
Python
mit
3,106
0.001288
""" This state is used to create and manage ELBs. Examples ======== .. code-block:: yaml .webserver-elb: elb.managed: - name: webserver-elb - region: us-west-1 - zones: - us-west-1a - us-west-1c - listeners:
- [80, 80, 'http', 'http'] - [443, 80, 'https', 'http', 'my_ssl_certificate'] - subnets: - subnet1 - subnet2 - security_groups: - my_elb_security_group - my_other_elb_security_group - scheme: internet-facing - health_check:...
80: type: app cookie_name: my_cookie 443: type: lb cookie_expire: 60 - instances: - i-deadbeef - i-01234abc .bad-elb: elb.absent: - name: bad-elb - region: us-west-1 .add-server:...
jameshy/libtree
tests/__init__.py
Python
mit
35
0
# C
opyright (c) 2015 Fabian Koch
em
lnls-fac/apsuite
apsuite/commisslib/measure_respmat_tbbo.py
Python
mit
8,002
0.000125
""".""" import numpy as np import pyaccel from siriuspy.namesys import SiriusPVName as _PVName from siriuspy.devices import SOFB from ..optimization import SimulAnneal from ..utils import ThreadedMeasBaseClass as _BaseClass, \ ParamsBaseClass as _ParamsBaseClass class Params(_ParamsBaseClass): """.""" ...
params.wait_time): break self.wait(self.params.timeout_orb) orb.append(np.hstack([self.trajx, self.trajy])) self._all_corrs[cor].strength = origkick if self._stopevt.is_set():
print('Stopped!') break else: self._matrix[cor] = np.array(orb).sum(axis=0)/(sig*delta) else: print('Finished!') def calc_model_respmatTBBO( tb_mod, model, corr_names, elems, meth='middle', ishor=True): """.""" bpms = np.arra...
uranusjr/django
django/test/client.py
Python
bsd-3-clause
26,876
0.000595
import json import mimetypes import os import re import sys from copy import copy from functools import partial from importlib import import_module from io import BytesIO from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit from django.conf import settings from django.core.handlers.base import BaseHa...
ontent = [] else: response.content = b'' return response class ClientHandler(BaseHandler): """ A HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to i...
s=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: ...
eri-trabiccolo/exaile
xlgui/devices.py
Python
gpl-2.0
4,732
0.000634
# Copyright (C) 2008-2010 Adam Olsen # # 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, or (at your option) # any later version. # # This program is distributed in the hope that...
olumn(col) self.populate_tree() event.add_callback(self.populate_tree, 'device_added') event.add_callback(self.populate_tree, 'device_removed') def populate_tree(self, *args): self.model.clear() for d in self.device_manager.list_devices():
self.model.append([d, None, d.get_name(), d.__class__.__name__]) def _get_selected_devices(self): sel = self.tree.get_selection() (model, paths) = sel.get_selected_rows() devices = [] for path in paths: iter = self.model.get_iter(path) device = self.mod...
markdrago/caboose
src/test/repo/date_iterator_tests.py
Python
mit
1,409
0.002839
import nose from nose.tools import * from unittest import TestCase from datetime import datetime, timedelta from repo.date_iterator import DateIterator class DateIteratorTests(TestCase): def test_date_iterator_returns_self_on_iter(self): d = DateIterator(datetime.now(), datetime.now()) eq_(d, d._...
next_date_7_days(self): start = datetime(2011, 3, 3) next = datetime(2011, 3, 10) end = datetime(2011, 3, 14) d = DateIterator(start, end, delta=time
delta(days=7)) first = d.next() second = d.next() eq_(next, second) @raises(StopIteration) def test_date_iterator_raises_stop_exception(self): start = datetime(2011, 3, 3) end = datetime(2011, 4, 1) d = DateIterator(start, end) first = d.next() ...
delattreb/TemperatureHumidityServer
src/dal/dal_dht22.py
Python
gpl-3.0
1,407
0.004975
""" dal_dht11 v1.0.0 Auteur: Bruno DELATTRE Date : 19/09/2016 """ from lib import com_logger class DAL_DHT22: def __init__(self, connection, cursor): self.connection = connection self.cursor = cursor self.logger = com_logger.Logger('DHT22 DAL') """ Select""" def get_dht2...
E date > "' + lastdate + '"') rows = self.cursor.fetchall() return rows except Exception as exp: self.logger.error(repr(exp)) self.connection.rollback() def get_lastdata(self): try: self.cursor.execute('SELECT MAX(date) FROM DHT22') ...
self.connection.rollback() """ Insert """ def set_dht22(self, name, temperature, humidity): try: self.cursor.execute( 'INSERT INTO DHT22 (date, name, temperature, humidity) VALUES (datetime("now","localtime"),"' + str(name) + '","' + str(temperature)[:4] + '","' ...
timj/scons
src/engine/SCons/Tool/sgicc.py
Python
mit
1,780
0.001685
"""SCons.Tool.sgicc Tool-specific initialization for MIPSPro cc on SGI. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtai...
THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" from . import cc def generate(env): """Add Builders and construction variables for gcc to an Environment.""" cc.generate(env) env['CXX'] = 'CC' env['SHOBJSUFFIX'] = '.o' env['STATIC...
h=4:
gerhc/django-encrypted-fields
encrypted_fields/fields.py
Python
mit
9,173
0.000654
import os import types import binascii from django.db import models from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import cached_property try: from django.utils.encoding import smart_text except ImportError: from django.utils.encoding impo...
# to be encrypted. self.decrypt_only = kwargs.pop('decrypt_only', False) self._crypter = self._crypter_klass(self.keydir) # Ensure the encrypted data does not exceed the max_l
ength # of the database. Data truncation is a possibility otherwise. self.enforce_max_length = getattr(settings, 'ENFORCE_MAX_LENGTH', False) if not self.enforce_max_length: self.enforce_max_length = kwargs.pop('enforce_max_length', False) super(EncryptedFieldMixin, self).__...
dsuch/ConcurrentLogHandler
src/portalocker.py
Python
apache-2.0
3,780
0.003704
# portalocker.py - Cross-platform (posix/nt) API for flock-style file locking. # Requires python 1.5.2 or better. """Cross-platform (posix/nt) API for flock-style file locking. Synopsis: import portalocker file = open("somefile", "r+") portalocker.lock(file, portalocker.LOCK_EX) file.seek...
another process has locked a portion of th
e file.') if exc_value[0] == 33: raise LockException(LockException.LOCK_FAILED, exc_value[2]) else: # Q: Are there exceptions/codes we should be dealing with here? raise def unlock(file): hfile = win32file._get_osfhandle(file.file...
hydroshare/hydroshare
hs_app_timeseries/receivers.py
Python
bsd-3-clause
16,631
0.002465
import os import shutil import logging import csv from dateutil import parser from django.dispatch import receiver from hs_core.signals import pre_create_resource, pre_add_files_to_resource, \ pre_delete_file_from_resource, post_add_files_to_resource, post_create_resource, \ pre_metadata_element_create, pre_m...
post_add_files_to_resource, sender=TimeSeriesResource) def post_add_files_to_resource_handler(sender, **kwargs): resource = kwargs['resource'] files = kwargs['files'] validate_files_dict = kwargs['validate_files']
user = kwargs['user'] source_names = kwargs['source_names'] if __debug__: assert(isinstance(source_names, list)) if files: file_name = files[0].name elif source_names: file_name = os.path.basename(source_names[0]) # extract metadata from the just uploaded file uplo...
rplevka/robottelo
tests/foreman/api/test_remoteexecution.py
Python
gpl-3.0
3,759
0.001862
"""Test for Remote Execution :Requirement: Remoteexecution :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: RemoteExecution :Assignee: pondrejk :TestType: Functional :CaseImportance: High :Upstream: No """ import pytest from nailgun import client from nailgun.entity_mixins import TaskFailedErro...
lt.stdout: assert 'FAIL' not in line result = default_sat.api.SmartProxy( id=default_sat.api.SmartProxy(name=default_sat.hostname).search()[0].id ).refresh() feature_list = [feat['name'] for feat in result['features']] assert {'Discovery', 'Dynflow', 'Ansible', 'SSH', 'Logs', 'Pulp'}.is...
e_run_capsule_upgrade_playbook_on_satellite(default_sat): """Run Capsule Upgrade playbook against the Satellite itself :id: 99462a11-5133-415d-ba64-4354da539a34 :steps: 1. Add REX key to the Satellite server. 2. Run the Capsule Upgrade Playbook. 3. Check the job output for proper f...
philipl/mplayer
TOOLS/mphelp_check.py
Python
gpl-2.0
2,073
0.002412
#!/usr/bin/python # Tool to compare MPlayer translation files against a base file. Reports # conflicting definitions, mismatching arguments, extra definitions # not present in the base file and (optionally) missing definitions. # Written by Uoti Urpala import sys import re def parse(filename): r = {} f = op...
print del other[key] if other: extra = other.keys() extra.sort() print 'Extra: ', '
'.join(extra) if show_missing and missing: missing.sort() print 'Missing: ', ' '.join(missing) if len(sys.argv) < 3: print 'Usage:\n'+sys.argv[0]+' [--missing] base_helpfile otherfile1 '\ '[otherfile2 ...]' sys.exit(1) i = 1 show_missing = False if sys.argv[i] in ( '--missing', '...
DedMemez/ODS-August-2017
contextlib.py
Python
apache-2.0
2,267
0.002647
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: contextlib import sys from functools import wraps from warnings import warn __all__ = ['contextmanager', 'nested', 'closing'] class GeneratorContextManager(object): def __init__(self, gen): self.gen = gen def __enter__(self): ...
self.gen.throw(type, value, traceback)
raise RuntimeError("generator didn't stop after throw()") except StopIteration as exc: return exc is not value except: if sys.exc_info()[1] is not value: raise return def contextmanager(func): @wraps(func...
Nickito12/stepmania-server
test/factories/user_factory.py
Python
mit
1,150
0.00087
""" User factory """ import factory from smserver import models from test.factories import base from test.factories.room_factory import RoomFactory class UserFactory(base.BaseFactory): """ Classic user name """ class Meta(base.BaseMeta): model = models.User name = factory.Sequence(lambda n: "Us...
mFactory) user = factory.SubFactory(UserFactory) class UserWithRoomFactory(UserFactory): """ User with a new room """ room = factory.SubFactory(RoomFacto
ry) def user_with_room_privilege(level=1, **kwargs): """ Return a User with privileges for a room """ user = UserWithRoomFactory(**kwargs) PrivilegeFactory(user=user, room=user.room, level=level) return user
austin987/bandit
docs/source/conf.py
Python
apache-2.0
2,480
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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing...
rwstauner/run_control
python/startup.py
Python
mit
665
0.010526
# pylint: disable=unused-import, unused-variable, missing-docstring def _readline(): try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") import os histfile = os.path.join(o
s.environ["HOME"], 'python', '.history') tr
y: readline.read_history_file(histfile) except IOError: pass import atexit atexit.register(readline.write_history_file, histfile) del os, histfile _readline() del _readline import sys sys.ps1 = "\001\033[01;33m\002>>>\001\033[00m\002 " sys.ps2 = "\001\033[01;33m\002...\001\033[00m\002 "
kinglyduck/hackerspace
src/hackerspace_online/settings/production.py
Python
gpl-2.0
1,941
0.003606
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os #root of project: ...../src BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deplo...
s07o7a(*durcp#sx!-8=cnq2-shiq61!7nznn=h$az7n' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # ALLOWED_HOSTS = [w
ww.hackerspace.sd72.bc.ca, hackerspace.sd72.bc.ca] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'timberline.hackerspace@gmail.com' EMAIL_HOST_PASSWORD ="" EMAIL_PORT = 587 EMAIL_USE_TLS = True # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENG...
iulian787/spack
var/spack/repos/builtin/packages/rocblas/package.py
Python
lgpl-2.1
4,299
0.002326
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Rocblas(CMakePackage): """Radeon Open Compute BLAS library""" homepage = "https://gi...
n_path(self.stage.s
ource_path, 'Tensile') args = [ '-Damd_comgr_DIR={0}'.format(self.spec['comgr'].prefix), '-DBUILD_CLIENTS_TESTS=OFF', '-DBUILD_CLIENTS_BENCHMARKS=OFF', '-DBUILD_CLIENTS_SAMPLES=OFF', '-DRUN_HEADER_TESTING=OFF', '-DBUILD_WITH_TENSILE=ON', ...
stormi/tsunami
src/primaires/objet/commandes/oedit/__init__.py
Python
bsd-3-clause
3,339
0.002402
# -*-coding:Utf-8 -* # Copyright (c) 2010 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 # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provid...
MaximeRaynal/SimpleNote
src/SimpleNote/wsgi.py
Python
mit
395
0.002532
""" WSGI config for SimpleNote project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault
("DJANGO_SETTINGS_MODULE", "SimpleNote.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
kirienko/gourmet
tests/test_importer.py
Python
gpl-2.0
1,162
0.018933
import unittest from gourmet.importers import importer class TestImporter (unittest.TestCase): def setUp (self): self.i = importer.Importer() def _get_last_rec_ (self): return self.i.added_recs[-1] def testRecImport (self): self.i.start_rec() attrs = [('title','Foo'),('...
lf.i.add_amt(2) self.i.add_unit('cups') self.i.add_ite
m('water') self.i.commit_ing() self.i.commit_rec() ings = self.i.rd.get_ings(self._get_last_rec_()) self.assertEqual(len(ings),1) ing = ings[0] self.assertEqual(ing.amount,2) self.assertEqual(ing.unit,'cups') self.assertEqual(ing.item,'water') if __name__...
Yelp/occam
occam/util.py
Python
mit
715
0.004196
import json from dateutil import parser as datetime_parser fro
m occam.app import get_redis from occam.runtime import OCCAM_SERVER_CONFIG_KEY def get_servers(): redis = get_redis() servers = json.loads(redis.get(OCCAM_SERVER_CONFIG_KEY)) return servers.items() def iterate_servers(): redis = get_redis() servers = json.loads(redis.get(OCC
AM_SERVER_CONFIG_KEY)) for server_name, server_location in servers.iteritems(): yield server_name, server_location def sorted_by_time_element(l, element_getter=None): if not element_getter: element_getter = lambda x: x key_getter = lambda x: datetime_parser.parse(element_getter(x)) re...
wright-group/PyCMDS
pycmds/hardware/opas/opas.py
Python
mit
19,921
0.001456
### import #################################################################### import os import time import pathlib import shutil import collections import appdirs import toml import numpy as np from PySide2 import QtWidgets import WrightTools as wt import attune import pycmds.project.project_globals as g import...
names = [i for i in self.motor_names if self.homeable.get(i)] if self.poynting_correction: self.poynting_correction.home() for n in self.poynting_correction.motor_names: names.pop(n, None) self._home_motors(names) def home_motor(self, inputs): # TO...
avior motor_name = inputs[0] if self.poynting_correction: if motor_name in self.poynting_correction.motor_names: self.poynting_correction.home(motor_name) return if self.homeable.get(motor_name): self._home_motors([motor_name]) def ini...
bbsan2k/nzbToMedia
libs/rebulk/test/test_match.py
Python
gpl-3.0
20,081
0.00239
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=no-self-use, pointless-statement, missing-docstring, unneeded-not import pytest import six from ..match import Match, Matches from ..pattern import StringPattern, RePattern from ..formatters import formatters class TestMatchClass(object): def test_...
.match2) matches.append(self.match3) matches.append(self.match4) del matches[1:3] assert len(matches) == 2 assert matches[0] == self.match1 assert matches[1] == self.match4 def test_set_slices(self): matches = Matches() matches.append(self.match1) ...
matches[1:3] = self.match1, self.match4 assert len(matches) == 4 assert matches[0] == self.match1 assert matches[1] == self.match1 assert matches[2] == self.match4 assert matches[3] == self.match4 def test_set_index(self): matches = Matches() matches.a...
plamut/superdesk-core
tests/io/iptc7901_tests.py
Python
agpl-3.0
2,239
0.000447
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import os f...
) def test_open_iptc7901_file(self): w
ith self.app.app_context(): item = self.open('IPTC7901.txt') self.assertEqual('preformatted', item['type']) self.assertEqual('062', item['ingest_provider_sequence']) self.assertEqual('i', item['anpa_category'][0]['qcode']) self.assertEqual(211, item['word_coun...
NOAA-ORR-ERD/hazpy.unit_conversion
hazpy/unit_conversion/lat_long.py
Python
unlicense
11,710
0.004953
#!/usr/bin/env python """ Assorted utilities for manipulating latitude and longitude values """ from __future__ import unicode_literals __version__ = "1.4" import math, struct def signbit(value): """ Test whether the sign bit of the given floating-point value is set. If it is set, this generally mean...
Deg(deg, min, sec, max=self.max) def direction(self): if self.value < 0.0: return self.negative_direction else: return self.positive_direction def degrees(self): deg = abs(self.value) return deg, self.direction() def degr
ees_minutes(self): deg, min = LatLongConverter.ToDegMin(abs(self.value)) return deg, min, self.direction() def degrees_minutes_seconds(self): deg, min, sec = LatLongConverter.ToDegMinSec(abs(self.value)) return deg, min, sec, self.direction() def __repr__(self): try: ...
genome/flow-core
flow/util/stats.py
Python
agpl-3.0
685
0.008759
import getpass import statsd import logging LOG = logging.getLogger(__name__) def increment_as_user(*label_components): try: statsd.increment(assemble_label(label_componen
ts, getpass.getuser())) statsd.increment(assemble_label(label_components, 'total')) except: LOG.exception('failed to increment as user %s', label_components) def increment(*args, **kwargs): try: statsd.increment(*args, **kwargs) except: LOG.exception('failed to increment arg...
= list(rest) + [tail] return '.'.join(lc)
gasman/wagtaildemo
wagtaildemo/settings/base.py
Python
bsd-3-clause
6,927
0.000866
# Django settings for wagtaildemo project. import os PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..', '..') BASE_DIR = PROJECT_ROOT DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) # Default to dummy email backend. Configure dev/production/local backend # ...
lse # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True DATE_FORMAT = 'j F Y' # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media') # URL that handles the...
ash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "...
yardencsGitHub/tf_syllable_segmentation_annotation
src/tweetynet/network.py
Python
bsd-3-clause
8,302
0.00277
"""TweetyNet model""" import torch from torch import nn from torch.nn import functional as F class Conv2dTF(nn.Conv2d): PADDING_METHODS = ('VALID', 'SAME') """Conv2d with padding behavior from Tensorflow adapted from https://github.com/mlperf/inference/blob/16a5661eea8f0545e04c86029362e22113c2ec09/...
nt tuple of ints Step size for sliding window of second max pooling layer. Default is (1, 8) hidden_size : int number of features in the hidden state ``h``. Default is None, in which case ``hidden_size`` is set to the dimensionality of the output of the convolutio...
layer on the outputs of each LSTM layer except the last layer, with dropout probability equal to dropout. Default: 0 num_layers : int Number of recurrent layers. Default is 1. bidirectional : bool If True, make LSTM bidirectional. Default is True. """ ...
giulioribe/car-pooling
testLock2.py
Python
gpl-3.0
303
0
"""import portalocke
r with portalocker.Lock('text.txt', timeout=5) as fh: fh.write("Sono in testLoxk2.py") """ from lockfile import LockFile lock = LockFile('text.txt') with lock: print lock.path,
'is locked.' with open('text.txt', "a") as file: file.write("Sono in testLock2.py")
leonth/private-configs
sublime-text-3/Packages/SublimePythonIDE/server/decorators.py
Python
mit
598
0.001672
# Copyright (c) 2013 Oscar Campos <oscar.campos@member.fs
f.org> # See LICENSE for more details """ .. module:: decorators :platform: Unix, Windows :synopsis: Decorators for SublimePython plugin .. moduleauthor:: Oscar Campos <oscar.campos@member.fsf.org> """ import os import functools def debug(f): @functools.wrap(f) def wrapped(*args, **kwargs): ...
nduser("~/trace"), "w") as fl: traceback.print_exc(file=fl) return wrapped
saukrIppl/seahub
tests/ui/driver.py
Python
apache-2.0
2,783
0.001078
import os import urlparse import requests import splinter from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from tests.common.utils import urljoin class Browser(object): '''Drives the browser in the...
first def element_text(self, selector): return self._el(selector).text def element_attr(self, selector, name): return self._el(selector)._element.get_attribute(name)
def click(self, selector): self._el(selector).click() def fill_form(self, form_kvs): self.b.fill_form(form_kvs) def find_by_name(self, name): return self.b.find_by_name(name) def submit(self, form_sel): self._el(form_sel)._element.submit() def submit_by_input_name(s...
nicolashainaux/mathmakerlib
tests/00_main/01_exceptions_test.py
Python
gpl-3.0
2,289
0
# -*- coding: utf-8 -*- # Mathmaker Lib offers lualatex-printable mathematical objects. # Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com> # This file is part of Mathmaker Lib. # Mathmaker Lib
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 # any later version. # Mathmaker Lib is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without...
details. # You should have received a copy of the GNU General Public License # along with Mathmaker Lib; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import pytest from mathmakerlib.calculus import Number from mathmakerlib.exceptions import Mathmaker...
cprakashagr/PythonClass
src/scraper/scraper/items.py
Python
mit
286
0
# -*- coding: utf-8 -*- # Define here the models
for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/to
pics/items.html import scrapy class ScraperItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass
SUSE/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/compute/v2015_06_15/models/virtual_machine_image.py
Python
mit
2,245
0.001782
# coding=u
tf-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 cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .virtual_machine_image_resource import VirtualMachineImag...
simonzhangsm/voltdb
tools/voter.d/voter.py
Python
agpl-3.0
2,792
0.013968
# This file is part of VoltDB. # Copyright (C) 2008-2018 VoltDB Inc. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, c...
itional', 'conditional', 'only build when the catalog file is missing')) def build(runner): if not runner.opts.conditional or not os.path.exists('voter.jar'): runner.java.compile('obj', 'src/voter/*.java', 'src/voter/procedures/*.java') runner.call('volt.compil...
def clean(runner): runner.shell('rm', '-rfv', 'obj', 'debugoutput', 'voter.jar', 'voltdbroot') @VOLT.Server('create', description = 'Start the Voter VoltDB server.', command_arguments = 'voter.jar', classpath = 'obj') def server(runner): runner.call('build', '-C') ru...
bsipocz/ginga
ginga/aggw/AggHelp.py
Python
bsd-3-clause
1,635
0.005505
# # AggHelp.py -- help classes for the Agg drawing # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD lic
ense. # Please see the file LICENSE.txt for details. import aggdraw as agg from ginga import colors class AggContext(object):
def __init__(self, canvas): self.canvas = canvas def set_canvas(self, canvas): self.canvas = canvas def get_color(self, color): if isinstance(color, str): r, g, b = colors.lookup_color(color) elif isinstance(color, tuple): # color is assumed to ...
eswartz/RenderPipeline
rpcore/pynative/shadow_atlas.py
Python
mit
3,799
0.001316
""" RenderPipeline Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use...
ion! """ def __init__(self, size, tile_size=32): self._size = size
self._tile_size = tile_size self._num_used_tiles = 0 self.init_tiles() def init_tiles(self): self._num_tiles = self._size // self._tile_size def row(): return [False for i in range(self._num_tiles)] # pylint: disable=unused-variable self._flags = [row() for j i...
mlperf/training_results_v0.6
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/onnx-tensorrt/third_party/onnx/onnx/bin/checker.py
Python
apache-2.0
749
0
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse from onnx import load, checker, NodeProto def chec
k_model(): # type: () -> None parser = argparse.ArgumentParser('check-model') parser.add_argument('model_pb', type=argparse.FileType('rb')) args = parser.parse_args() model = load(args.model_pb) checker.check_model(model) def check_node(): # type: () -> None parser = argparse.ArgumentParser...
parse_args() node = NodeProto() node.ParseFromString(args.node_pb.read()) checker.check_node(node)
CSC301H-Fall2013/ElectionSimulation
Code/ElectionSimulationInstaller/ElectionSimulation/manage.py
Python
mit
261
0.003831
#!/usr/bin/env python
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ElectionSimulation.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.
argv)
skosukhin/spack
var/spack/repos/builtin/packages/cppunit/package.py
Python
lgpl-2.1
1,545
0
############################################################################## # Copyright (c) 2013-2017, 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...
the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See...
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 Cppunit(AutotoolsPackage): ...
bitlinker/ArduWeather
Software/NarodmonDaemon/OregonSensor.py
Python
mit
2,140
0.001402
# Copyright (c) 2015 bitlinker@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish...
ype) self.__type = type self.__id = id self.__channel = channel self.__battery = batteryHigh def getType(self): return self.__type def getBatteryHigh(self): return self.__battery def getId(self): return self.__id def getChannel(self): r...
elf): return self.getName() + self.__id + str(self.__channel) def getValuesList(self): result = Sensor.getValuesList(self) if (self.__battery): result.append(SensorValue(self.getUUID(), self.VALUE_BATTERY, self.__battery)) return result
gdefias/StudyC
VS/test_CcallPY/Test_ccallpy/helloWorld.py
Python
gpl-2.0
153
0.045752
#codin
g=utf8 def hello(instr): bufstr = " helloWorld!" return (instr + bufstr), 123 if __name__ == "__main__": k = "yzh" pri
nt hello(k)
unnikrishnankgs/va
venv/lib/python3.5/site-packages/external/org_mozilla_bleach/bleach/version.py
Python
bsd-2-clause
136
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals VERSION =
(1, 5, 0) __version__ = '.'.join(
[str(n) for n in VERSION])
codepython/CollectorCity-Market-Place
stores/apps/sell/forms.py
Python
apache-2.0
1,696
0.014741
import re from django import forms from sell.models import ShippingData from django.contrib.localflavor.us.forms import USStateSelect, USZipCodeField class ShippingDataForm(forms.ModelForm): state = forms.CharField(widget=USStateSelect) save_shipping_info = forms.BooleanField(label="Save Shipping Infor
mation", widget=forms.CheckboxInput(), required=False) class Meta: model = ShippingData def clean_zip(self): zip = self.cleaned_data.get("zip", "") if zip.strip() == "": raise forms.ValidationError("Zip is a required field.") if not (re.match("[0-9]{5}(-[0-...
return zip def clean(self): first_name = self.cleaned_data.get("first_name", "") last_name = self.cleaned_data.get("last_name", "") country = self.cleaned_data.get("country", "") street = self.cleaned_data.get("street_address", "") city = self.cleaned_data.get(...
blesscat/flux_line_bot
fluxclient/scanner/scan_settings.py
Python
agpl-3.0
1,386
0
#!/usr/bin/env python3 from math import pi, atan class ScanSetting(object): """docstring for ScanSetting""" def __init__(self): super(ScanSetti
ng, self).__init
__() # for scan self.scan_step = 400 # steps self.theta_a = pi / 6 # radius between center and laser self.img_width = 640 self.img_height = 480 self.sensorWidth = 3.67 self.sensorHeight = 2.74 + 0.08 self.focalLength = 3.6 # ######### mockup 2...
leveille/blog.v1
wurdig/controllers/js.py
Python
mit
1,892
0.006342
import logging import hashlib from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to, etag_cache from pylons.decorators import jsonify from pylons.i18n.translation import _ from wurdig.lib.base import BaseController, render log = logging.getLogger(__nam...
'successfully been approved.'), 'Approve': _('Approve'), 'The item has successfully been disapproved.': _('The item has successfully ' 'been disapproved.'), 'Your+request+has+been+comp...
'completed+successfully'), 'An unexpected error has occurred.': _('An unexpected error has occurred.'), 'Enter key word(s)': _('Enter key word(s)') } return translations def translations(self): json_string = "if(!this.WURDIG) {var WURDIG = {...
smartczm/python-learn
Old-day01-10/s13-day12/pub-sub/publish02.py
Python
gpl-2.0
289
0.003745
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- # Author: ChenLiang import channel
02 obj = channel02.RedisHelper() while True: inp
= input('>> ') if inp == '': print("当前输入为空, 请重新输入...") continue else: obj.public(inp, 'fm103.7')
franklingu/leetcode-solutions
questions/1-bit-and-2-bit-characters/Solution.py
Python
mit
1,231
0.004874
""" We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. E...
2: Input: bits = [1, 1, 1, 0] Output: False Explanation: The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. Note: 1 <= len(bits) <= 1000. bits[i] is al
ways 0 or 1. """ class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ skip_next, curr = False, None for i in bits: if skip_next: skip_next = False curr = 2 con...
bullxpfs/lustre-shine
tests/Configuration/ConfigFileSystemTest.py
Python
gpl-2.0
21,146
0.003168
#!/usr/bin/env python # Shine.Configuration.FileSystem class # Copyright (C) 2009-2017 CEA """Unit test for Shine.Configuration.FileSystem""" import unittest import textwrap import time from Utils import makeTempFile, setup_tempdirs, clean_tempdirs from Shine.Configuration.FileSystem import FileSystem, ModelFileIOE...
scalable(self): """filesystem with nids with several ranges."""
before = time.time() self._fs = self.makeConfFileSystem(""" fs_name: nids nid_map: nodes=foo[1-9999] nids=bar[1-9999]@tcp """) elapsed = time.time() - before self.assertTrue(elapsed < 2, "%.2fs exceeds 2s threshold" % elapsed) self.assertEqual(len(self._fs.nid_map), 9999) d...
noironetworks/networking-cisco
networking_cisco/tests/unit/ml2_drivers/nexus/test_trunk.py
Python
apache-2.0
6,254
0.00016
# Copyright (c) 2017 Cisco Systems, 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 r...
_plugin_v2 PORT_ID = 'fake_port_id' TRUNK_ID = 'fake_trunk_id' DNS_NAME = 'test_dns_name' VM_NAME = 'test_vm_name' SEGMENTATION_VLAN = 'vl
an' SEGMENTATION_ID1 = 101 SEGMENTATION_ID2 = 102 SUBPORTS = [ {'segmentation_type': SEGMENTATION_VLAN, 'port_id': PORT_ID, 'segmentation_id': SEGMENTATION_ID1}, {'segmentation_type': SEGMENTATION_VLAN, 'port_id': PORT_ID, 'segmentation_id': SEGMENTATION_ID2}] TRUNK = { 'status': bc.constants.PO...
EnviroCentre/jython-upgrade
jython/lib/test/test_time.py
Python
mit
10,491
0.002288
from test import test_support import time import unittest class TimeTestCase(unittest.TestCase): def setUp(self): self.t = time.time() def test_missing_module_attribute(self): self.assertEqual(time.clock.__module__, 'time') self.assertEqual(time.time.__module__, 'time') def test...
ert # year > 9999, but Linux implementation does not. # self.assertRaises(ValueError, time.asctime, # (12345, 1, 0, 0, 0, 0, 0, 0, 0)) # XXX: For now, just make sure we don't have a crash: try: time.asctime((12345, 1, 1, 0, 0, 0, 0, 1, 0)) exc...
pIf(not hasattr(time, "tzset"), "time module has no attribute tzset") def test_tzset(self): from os import environ # Epoch time of midnight Dec 25th 2002. Never DST in northern # hemisphere. xmas2002 = 1040774400.0 # These formats are correct for 2002, and possibly...
fabiansinz/pipeline
python/pipeline/legacy/trk.py
Python
lgpl-3.0
20,366
0.00545
import warnings from pprint import pprint import datajoint as dj import pandas as pd from djaddon import hdf5 try: from pupil_tracking import PupilTracker except ImportError: warnings.warn("Failed to import pupil_tacking library. You won't be able to populate trk.EyeFrame") schema = dj.schema('pipeline_pupi...
n (ProtocolStep() & key).fetch.order_by('priority').as_dict(): # embed() print("....for protocol id:", key['filter_protocol_id'], "applying filter with filter_id = ", step['filter_id']) frames = FrameSelector().apply(frames, step, param=step['filter_param']) ...
a class FrameSelector(dj.Lookup): definition = """ # single filters to reject frames filter_id : tinyint # id of the filter --- filter_name : char(50) # descriptive name of the filter """ contents = [ {'filter_id': 0, 'filter_name': 'intensity_filter'}, ...
nxnfufunezn/qtile
libqtile/manager.py
Python
mit
59,901
0.00025
# vim: tabstop=4 shiftwidth=4 expandtab # Copyright (c) 2008, Aldo Cortesi. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limit...
proto.LeaveNotifyEvent, xcffib.xproto.FocusOutEvent, xcffib.xproto.FocusInEvent, xcffib.xproto.NoExposureEvent ]) self.conn.flush() self.conn.xsync() self._xpoll() # Map and Grab keys for
key in self.config.keys: self.mapKey(key) # It fixes problems with focus when clicking windows of some specific clients like xterm def noop(qtile): pass self.config.mouse += (Click([], "Button1", command.lazy.function(noop), focus="after"),) self.mouseMap = {} ...
apyrgio/snf-ganeti
test/py/ganeti.hypervisor.hv_kvm_unittest.py
Python
bsd-2-clause
16,077
0.003981
#!/usr/bin/python # # Copyright (C) 2010, 2011 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this l...
ILITY OF SUCH DAMAGE. """Script for testing the hypervisor.hv_kvm module""" import threading import tempfile import unittest import socket import os import struct import re from ganeti import serializ
er from ganeti import constants from ganeti import compat from ganeti import objects from ganeti import errors from ganeti import utils from ganeti import pathutils from ganeti.hypervisor import hv_kvm import ganeti.hypervisor.hv_kvm.netdev as netdev import ganeti.hypervisor.hv_kvm.monitor as monitor import testutils...
NileshPS/OS-and-Networking-programs
7_rpc/client.py
Python
gpl-3.0
331
0.006042
from xmlrpc.client import ServerProxy import sys def help(): print("Usage : r
emote_finger [-lmsp] user..") if __name__ == '
__main__': sys.argv = sys.argv[1:] if len(sys.argv) == 0: help() sys.exit(1) client = ServerProxy('http://localhost:8000') print(client.finger(sys.argv)) sys.exit(0)
giubil/trackit
api/files/api/app/views/aws/cost/stats.py
Python
apache-2.0
43,920
0.003575
from datetime import datetime from app import app from app.authentication import with_login from flask import Blueprint, jsonify, request, Response from app.generate_csv import generate_csv_clean from app.msol_util import get_next_update_estimation_message_aws from app.es.awsmetric import AWSMetric from app.es.awsstat ...
g): """---
get: tags: - aws produces: - application/json description: &desc Get total cost summary: *desc responses: 200: description: List of AWS accounts schema: properties: mon...
SEL-Columbia/commcare-hq
corehq/apps/receiverwrapper/tests/test_repeater.py
Python
bsd-3-clause
6,713
0.000447
from StringIO import StringIO from datetime import datetime, timedelta from casexml.apps.case.models import CommCareCase from casexml.apps.case.tests.util import check_xml_line_by_line from casexml.apps.case.xml import V1 from django.core.urlresolvers import reverse from django.test import TestCase from django.test.c...
s # gets loaded first. # This is deterministic but easily affected by minor code changes # check case stuff rec = records_by_repeater
_id[self.case_repeater.get_id] self.assertEqual(self.log[1][:2], (self.case_repeater.get_url(rec), 200)) self.assertIn('server-modified-on', self.log[1][3]) check_xml_line_by_line(self, self.log[1][2], case_block) # check form stuff rec = records_by_repeater_id[self.form_repeate...
priya-pp/Tacker
releasenotes/source/conf.py
Python
apache-2.0
8,504
0.000118
# 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...
'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [how...
image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, sh...
dper/pumptweet
setup.py
Python
mit
1,006
0.036779
#!/usr/bin/env python2 # setup.py from setuptools import setup, find_packages setup(name='pumptweet', version='2.1', description='Cross posts from Pump.io to Twitter.', setup_requires=['setuptools-markdown'], long_description_markdown_filename='README.md', classifiers=[ 'Development Status :: 3 - Alpha', 'In...
'Topic :: Communications', ], url='http://github.com/dper/pumptweet', author='Douglas Paul Perkins', author_email='contact@dperkins.org', license='MIT', packages=['pumptweet'], install_requires=[ 'pypump >= 0.7', 'python-twitter >= 3.1', ], include_package_data=True, scripts=[ 'pt.py', 'pt.sh', ],...
zip_safe=False)
bbondy/brianbondy.gae
libs/html5lib/serializer/__init__.py
Python
mit
585
0.005128
from html5lib import treewalkers from htmlserializer import HTMLSerializer from xhtmlserializer import XHTMLS
erializer def serialize(input, tree="simpletree", format="html", encoding=None, **serializer_opts): # XXX: Should we cache this? walker = treewalkers.getTreeWalker(tree) if format == "html": s = HTMLSerializer(**serializer_opts) elif format == "xhtml": s = XHTMLS...
se ValueError, "type must be either html or xhtml" return s.render(walker(input), encoding)
praveen-pal/edx-platform
lms/djangoapps/courseware/features/lti.py
Python
agpl-3.0
6,277
0.000956
#pylint: disable=C0111 from django.contrib.auth.models import User from lettuce import world, step from lettuce.django import django_url from common import course_id from student.models import CourseEnrollment @step('I view the LTI and it is not rendered$') def lti_is_not_rendered(_step): # lti div has no class...
_iframe('ltiLaunchFrame') as iframe: # iframe does not contain functions from terrain/ui_helpers.py assert iframe.is_element_not_present_by_css('.result', wait_time=5) @step('I view the LTI and it is rendered$') def lti_is_rendered(_step): # lti div has class rendered assert world.is_css_prese...
assert world.css_visible('iframe') #inside iframe test content is presented with world.browser.get_iframe('ltiLaunchFrame') as iframe: # iframe does not contain functions from terrain/ui_helpers.py assert iframe.is_element_present_by_css('.result', wait_time=5) assert ("This is LTI ...
adbar/url-tools
courlan/clean.py
Python
gpl-2.0
5,520
0.002899
""" Functions performing URL trimming and cleaning """ ## This file is available from https://github.com/adbar/courlan ## under GNU GPL v3 license import logging import re from collections import OrderedDict from urllib.parse import parse_qs, urlencode, urlparse, ParseResult from .filters import validate_url from ....
y newpath = PATH1.sub('/', parsed_url.path) # Leading /../'s in the path are removed newpath = PATH2.sub('', newpath) # fragment if strict is True: newfragment = '' else: newfragment = parsed_url.fragment #
lowercase + remove fragments parsed_url = parsed_url._replace( scheme=parsed_url.scheme.lower(), netloc=parsed_url.netloc.lower(), path=newpath, fragment=newfragment ) # strip unwanted query elements parsed_url = clean_quer...
ProkopHapala/SimpleSimulationEngine
python/pyRay/tests/testSceneList.py
Python
mit
624
0.110577
#!/usr/bin/python import sys sys.path.append("../../") #import pyRay as ra import pyRay.scene as scn # TODO : how to pass arguments from function header? object1 = ("obj1",(), [( "U","sdBox" ,"%s",((1.0,1.0,1.0),) ),( "S","sdSphere","%s",(1.2,) )]) object2 = ("obj1",("f","f3"),[( "U","sdBox" ,"%s",(...
0),) ),( "S","sdSphere","%s",("1",) )]) scene = [ ( "U","sdBox" ,"%s",((1.0,1.0,1.0),) ), ( "S","sdSphere","%s",(1.2,) ), ] scene_src = scn.parseSceneList(scene) pr
int scene_src
google/grr
grr/server/grr_response_server/flows/file.py
Python
apache-2.0
16,923
0.006736
#!/usr/bin/env python """Flows to collect file contents and metadata.""" from typing import Any, Mapping, Optional from grr_response_core import config from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs from grr_response_core.lib.rdfvalues import crypto as rdf_crypto from grr_response_core.lib.rdf...
ESS result = rdf_file_finder.CollectFilesByKnownPathResult( stat=stat_entry, hash=file_hash, status=status) self.SendReply(result) def ReceiveFetchedFile(self, stat_entry: rdf_client_fs.StatEntry, file_hash: rdf_crypto.Hash, ...
ully fetched. Args: stat_entry: rdf_client_fs.StatE
caktus/rapidsms-groups
groups/views.py
Python
bsd-3-clause
3,191
0
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from django.contrib im
port messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.db im
port transaction from django.db.models import Count from django.http import HttpResponseRedirect, HttpResponseForbidden from django.shortcuts import render, get_object_or_404 from rapidsms.models import Contact from groups.models import Group from groups.forms import GroupForm, ContactForm @login_required def list_...
Dawny33/Code
Code_Forces/A_string_task.py
Python
gpl-3.0
152
0.006579
T = raw_input().lower() vowels = "aeiouy" output = "" for
i in range(0,len(T)): if T[i] not in vowels: output += "." + T
[i] print output
wangming28/syzygy
syzygy/scripts/test_bot/PRESUBMIT.py
Python
apache-2.0
1,582
0.005689
#!python # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Vers
ion 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" BA...
r implied. # See the License for the specific language governing permissions and # limitations under the License. # # Additional presubmit script. This will be run for changes to files in this # subdirectory, as well as the root syzygy/PRESUBMIT.py. # # This script will be read as a string and intepreted, so __file__ i...
rmasters/inbox
migrations/versions/061_remove_easfoldersyncstatus_folder_rows_.py
Python
agpl-3.0
1,547
0.002586
"""Remove EASFolderSyncStatus + Folder rows f
or folders we never sync Revision ID: 2a748760ac63 Revises: 4af5952e8a5b Create Date: 2014-07-19 00:28:08.258857 """ # revision identifiers, used by Alembic. revision = 'bb4f204f192' down_revision = '2a748760ac63' from inbox.ignition import engine from inbox.models.session import session_scope from sqlalchemy.ext.d...
declarative_base from sqlalchemy.orm.exc import NoResultFound Base = declarative_base() Base.metadata.reflect(engine) def upgrade(): if 'easfoldersyncstatus' in Base.metadata.tables: from inbox.models.backends.eas import EASFolderSyncStatus from inbox.models import Folder from inbox.util...
kikokubo/Sick-Beard-TPB
lib/subliminal/services/usub.py
Python
gpl-3.0
4,305
0.00813
# -*- coding: utf-8 -*- # Copyright 2013 Julien Goret <jgoret@gmail.com> # # This file is part of subliminal. # # subliminal 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 Licen...
lf, filepath, languages, keywords=None, series=None, season=None, episode=None): ## Check if we really got informations about our episode if series and season and episode: re
quest_series = series.lower().replace(' ', '-') if isinstance(request_series, unicode): request_series = request_series.encode('utf-8') logger.debug(u'Getting subtitles for %s season %d episode %d with language %r' % (series, season, episode, languages)) r = self.sess...
ipa-led/airbus_coop
airbus_docgen/src/airbus_docgen/digraph/spline.py
Python
apache-2.0
717
0.001395
#!/usr/bin/env python # # Copyright 2015 Airbus # Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA) # # 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 # # ...
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" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitati...
ss SPLINE: Ortho = 'ortho'
unho/pootle
pootle/apps/accounts/apps.py
Python
gpl-3.0
566
0
# -*- coding: utf-8 -*- # # Copyright (C)
Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import importlib from django.apps import AppConfig class AccountsConfig(AppConfig):...
= "Accounts" version = "0.1.1" def ready(self): importlib.import_module("accounts.getters") importlib.import_module("accounts.receivers")
pevma/PtP
ProtoIPv4/IPv4_HTTP.py
Python
gpl-2.0
182,209
0.017381
#!/usr/bin/python # -*- coding: utf-8 -*- ## ## # Author: Peter Manev # # peter.manev@openinfosecfoundation.org # ## ## ## !!! IMPORTANT - LATEST DEV Scapy is needed !!! # REMOVE your current scapy installation !!! # th...
/IP(src=ipdst, dst=ipsrc)/TCP(flags="A", sport=portdst, dport=portsrc, \ seq=p.ack, ack=(p.seq + len(p[Raw]))) ##Now we build the Finshake finAck = Ether(src=packet[Ether].src, dst=packet[Ether].dst, type=0x800 ) \ /IP(src=ipsrc, dst=ipdst)/TCP(flags="FA",
sport=portsrc, dport=portdst, \ seq=returnAck.ack, ack=returnAck.seq) finalAck = Ether(src=packet[Ether].dst, dst=packet[Ether].src, type=0x800 ) \ /IP(src=ipdst, dst=ipsrc)/TCP(flags="A", sport=portdst, dport=portsrc, \ seq=finAck.ack, ack=finAck.seq+1) ## # Here we start orderin...
AutorestCI/azure-sdk-for-python
azure-batch/azure/batch/models/start_task.py
Python
mit
5,044
0.000595
# 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 ...
as a non-administrative user unique to the task. :type user_identity: ~azure.batch.models.UserIdentity :param max_task_retry_count: The maximum number of times the task may be retried. The Batch service retries a task if its exit code is nonzero. Note that this value specifically controls the number ...
ample, if the maximum retry count is 3, Batch tries the task up to 4 times (one initial try and 3 retries). If the maximum retry count is 0, the Batch service does not retry the task. If the maximum retry count is -1, the Batch service retries the task without limit. :type max_task_retry_count: int ...
vaygr/ansible
lib/ansible/modules/monitoring/uptimerobot.py
Python
gpl-3.0
3,698
0.001622
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
monitorid: 12345 apikey: 12345-1234512345 state: started ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.
module_utils.six.moves.urllib.parse import urlencode from ansible.module_utils.urls import fetch_url API_BASE = "http://api.uptimerobot.com/" API_ACTIONS = dict( status='getMonitors?', editMonitor='editMonitor?' ) API_FORMAT = 'json' API_NOJSONCALLBACK = 1 CHANGED_STATE = False SUPPORTS_CHECK_MODE = False ...
cdeil/ctools
scripts/obsutils.py
Python
gpl-3.0
9,202
0.040535
# ========================================================================== # This script provides a number of functions that are useful for handling # CTA observations. # # Copyright (C) 2011-2013 Juergen Knoedlseder # # This program is free software: you can redistribute it and/or modify # it under the terms of the ...
rence longitude value [deg] (default: 0.0) yval - Reference latitude value [deg] (default: 0.0) binsz - Pixel size [deg/pixel] (default: 0.05) nxpix - Number of pixels in X direction (default: 200) nypix - Number of pixels in Y di
rection (default: 200) outname - Counts map FITS filename (default: cntmap.fits) """ # Allocate counts map map = GSkymap(proj, coord, xval, yval, -binsz, binsz, nxpix, nypix, 1) # Fill all observations for run in obs: # Loop over all events for event in run.events(): # Determine sky pixel skyd...
tantSinnister/doto
doto/model/timerecord.py
Python
bsd-3-clause
2,998
0.000667
import doto.model import doto.model.task CREATE_CMD = """ CREATE TABLE IF NOT EXISTS timerecords ( id INTEGER NOT NULL, task_id INTEGER, start TIMESTAMP, end TIMESTAMP, PRIMARY KEY (id)...
end = :end WHERE id = :id; """ delete_query = 'DELETE FROM timerecords WHERE id = ?;' update = doto.model.crud.update(update_query, Timerecord) add_new = doto.model
.crud.insert(insert_query, Timerecord) delete = doto.model.crud.delete(delete_query) doto.model.setup_module(CREATE_CMD, ())
bazzile/imScrape
Scripts/v1/dev/auxiliary/move_imagery.py
Python
mit
1,527
0.001972
import os import shutil import re import zipfile import xml.etree.ElementTree as ET from tempfile import TemporaryDirectory import psycopg2 conn = psycopg2.connect( database='innoter', user='postgres', password='postgres', host='192.168.0.107', port='5432') cursor = conn.cursor() dst_dir = r"\\nas1\storage\DG_arc...
tch(r'.+ORDER_SHAPE.+', fnm, re.I) is None: # cursor.execute("""UPDATE geoarchive.dg_orders # SET aero = TRUE #
WHERE order_id = %s""", [order_id, ],) # conn.commit() # print(80*'=', order_id, 80*'=') # aero_list.append(order_id) # # print('\nDone:\n', len(aero_list)) # for i in aero_list: # print(i)
christopherjenness/ML-lib
ML/treemethods.py
Python
mit
31,697
0.000126
""" Tree based methods of learning (classification and regression) """ import abc import numpy as np import networkx as nx from scipy.stats import mode class BaseTree(object): """ Base Tree for classification/regression. Written for single variable/value binary split critereon. Many methods needs to be ...
predecessors.append(node_number) data_indices = np.array(range(len(self.y))) node_count = 0
while node_count < len(predecessors) - 1: current_node = predecessors[node_count] next_node = predecessors[node_count + 1] current_variable = self.graph.node[current_node]['variable'] current_cutoff = self.graph.node[current_node]['cutoff'] if current_...
jekhokie/scriptbox
python--advent-of-code/2020/5/solve.py
Python
mit
960
0.015625
#!/usr/bin/env python3 from math import floor, ceil lines = [] with open('input.txt', 'r') as f: lines = f.read().splitlines() def get_val(line, start_pos, end_pos, lhalf, uhalf, uhalf_char): for x in line[start_pos:end_pos:]: if x == uhalf_char: # take lower half uhalf -= ceil((uhalf - lhalf) / 2) ...
alf != uhalf: return Exception("Something went wrong: {} != {}".format(lhalf, uhalf)) return uhalf #--- challenge 1 seat_ids = [] for boarding_pass in lines: row = get_val(boarding_pass, 0, 7, 0, 127, 'F') column = get_val(boarding_pass, 7, 10, 0, 7, 'L') seat_ids.append(row * 8 + column) print("Solutio...
sing_seat = x print("Solution to challenge 2: {}".format(missing_seat))
dmccloskey/SBaaS_quantification
SBaaS_quantification/lims_quantitationMethod_io.py
Python
mit
26,562
0.03569
import json import re from SBaaS_LIMS.lims_calibratorsAndMixes_query import lims_calibratorsAndMixes_query from SBaaS_LIMS.lims_sample_query import lims_sample_query from .lims_quantitationMethod_query import lims_quantitationMethod_query from .stage01_quantification_MQResultsTable_query import stage01_quantification_...
x == min_ratio][0]; index_max = [cnt for cnt,x in enumerate(ratios) if x == max_ratio][0]; conc_min = min(concentrations); conc_max = max(concentrations);
sample_name_min = sample_names[index_min]; sample_name_max = sample_names[index_max]; data_1a.append({'concentration_ratio':row['lloq'], 'ratio':min_ratio, 'component_name':cn, 'sample_name':sample_name_mi...
chemelnucfin/tensorflow
tensorflow/contrib/distribute/python/keras_backward_compat_test.py
Python
apache-2.0
43,076
0.011213
# 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...
(use_numpy, use_validation_data, with_distribution, x_train, y_train, x_predict): """Generates the inputs for correctness check when enable Keras w
ith DS.""" training_epochs = 2 global_batch_size = 64 batch_size = global_batch_size # TODO(b/118776054): Use global batch size for Keras/DS support. use_per_core_batch_size = ( with_distribution and not distributed_training_utils.global_batch_size_supported( with_distribution)) if use...
ncliam/serverpos
openerp/addons/email_template/tests/test_mail.py
Python
agpl-3.0
14,322
0.004538
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of ...
ve as template # ---------------------------------------- # 1. Comment on pigs context = { 'default_composition_mode': 'comment', 'default_model': 'mail.group', 'default_res_id': self.group_pigs_id, 'default_use_template': False, 'defa...
} compose_id = mail_compose.create(cr, uid, {'subject': 'Forget me subject', 'body': 'Dummy body'}, context) compose = mail_compose.browse(cr, uid, compose_id, context) onchange_res = compose.onchange_template_id(email_template_id, 'comment', 'mail.group', self.group_pigs_id)['value'] ...
szecsi/Gears
GearsPy/Project/Components/Temporal/CellLti7.py
Python
gpl-2.0
1,209
0.033085
import Gears as gears from .. import * from .Filter import * class CellLti7(Filter) : def applyWithArgs( self, stimulus, ) : sequence = stimulus.getSequence().getPythonObject() stimulus.setLtiMatrix( [ 0, 0.47494, -0.0966925, 0.150786, -...
0.3339, 0.0221983 , 0.00646065 , 0.0351307, -0.0105551, -0.0244711, 0.0166167, -0.3339, 0.265154, -0.33863 , -0.0135562 , -0.00584964, 0.00101862, 0.00537899, -0.
00747239, 0.0221983, 0.33863, 0.186403 , -0.308048 , 0.000798099, -0.000257363, -0.000588159, 0.000383462, -0.00646065, -0.0135562, 0.308048 , 0.11294 , ] )
kirbyfan64/hytest
setup.py
Python
mit
1,421
0.004222
try: from setuptools import setup from setuptools.command.build_py import build_py setuptools = True except: from distutils.core import setup from distutils.command.build_py import build_py setuptools = False import os, re # XXX: This is a hack def patch(func): setattr(build_py, func.__na...
hy')] @patch def get_module_outfile(self, build_dir, *_): return os.path.join(build_dir, 'hytest.hy') this_dir = os.path.dirname(__file__) with open(os.path.join(this_dir, 'R
EADME.rst')) as f: readme = f.read() with open(os.path.join(this_dir, 'hytest.hy')) as f: version = re.search(r'\(def __version__ "([^"]+)"\)', f.read()).group(1) with open(os.path.join(this_dir, 'requirements.txt')) as f: hy_ver = f.read().strip() kw = {} if setuptools: kw['install_requires'] = hy_v...
ecolell/pfamserver
tests/api/v0/test_version.py
Python
agpl-3.0
394
0
from __future__ import unicode_literals import json def test_get_version(app, client, current_version): headers = [('Accept', 'application/
json'), ('Content-Type', 'application/json')] res = client.get('/api/v0/version', headers=headers) assert res.status_code == 200 data = json.loads(res.get_data(as_text=True)) assert data
['version'] == current_version
google-research/google-research
etcmodel/layers/embedding_test.py
Python
apache-2.0
9,033
0.001661
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ing_table.shape.as_list() input_ids = tf.constant([ [3, 2, 1], # [4, 0, 4], # ]) layer = etc_layers.EmbeddingLookup( vocab_size=vocab_size, embedding_size=embedding_size, projection_size=projection_size, use_one_hot_lookup=True) layer.build(None) # S...
ected = [ [ [1.3, -1.3, 0.3], # [1.2, -1.2, -0.2], # [1.1, -1.1, -0.5], # ], # [ [1.4, -1.4, 0.4], # [1.0, -1.0, 0.5], # [1.4, -1.4, 0.4], # ], # ] result = layer(input_ids) self.evaluate(tf.comp...
ericholscher/sublime-rst-completion
helpers.py
Python
bsd-3-clause
1,480
0.001351
import re from sublime import Region import sublime_plugin class BaseBlockCommand(sublime_plugin.TextCommand): def _get_row_text(self, row): if row < 0 or row > self.view.rowcol(self.view.size())[0]: raise RuntimeError('Cannot find table bounds.') point = self.view.text_point(row, ...
rip(): lower += 1 except Exception as e: print(e) pass else: lower -= 1
block_region = Region(self.view.text_point(upper - 1, 0), self.view.text_point(lower + 2, 0)) lines = [self.view.substr(region) for region in self.view.lines(block_region)] indent = re.match('^(\s*).*$', self._get_row_text(upper - 1)).group(1) return block_region, l...