repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
google-research/google-research
amortized_bo/simple_ising_model.py
Python
apache-2.0
6,429
0.005755
# 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...
DCDCDC. This problem serves as a benchmark for solvers' ability to find all local optima. Attributes: length: Number of nodes. vocab_size: Numb
er of possible values for each position. Must be even. **kwargs: additional args passed to the BaseProblem constructor. """ def __init__(self, length=4, vocab_size=2, **kwargs): self._domain = domains.FixedLengthDiscreteDomain( vocab_size=vocab_size, length=length) super(AlternatingChainIsingMo...
44px/redash
redash/settings/helpers.py
Python
bsd-2-clause
471
0
import json import os def fix_assets_path(path): fullpath = os.path.join(os.path.dirname(__file__), "../", path) return
fullpath def array_from_string(s): array = s.split(',') if "" in array: array.remove("") return array def set_from_string(s): return set(array_from_string(s)) def parse_boolean(str): return json.loads(str.low
er()) def int_or_none(value): if value is None: return value return int(value)
mbuhot/mbuhot-euler-solutions
python/problem-017.py
Python
mit
1,881
0.02286
#! /usr/bin/env python3 description = """ Number letter counts Problem 17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters woul...
n % 100 if rest == 0: return '%s hundred' % say(hundreds) else: return '%s hundred and %s' % (say(hundreds), say(rest)) elif n < 1000000: thousands = (n // 1000) rest = n % 1000 if rest == 0: return '%s thousand' % say(thousands) else: return '%s thousand %s' % (say(tho...
t(say(95) == 'ninety five') assert(say(111) == 'one hundred and eleven') assert(say(592) == 'five hundred and ninety two') assert(say(111111) == 'one hundred and eleven thousand one hundred and eleven') print(sum(len(say(n).replace(' ', '')) for n in range(1, 1001)))
extremenetworks/xkit
EXOS/Python/watch/watch.py
Python
bsd-2-clause
5,605
0.004817
# watch.py # usage: watch.py [-h] [-c COUNT] [-i INTERVAL] [-d] command # # This script displays the output of a specified CLI command every n seconds # Example "run script watch.py "show port packet no-ref"" # # positional arguments: # command Command to iterate. Should be enclosed in quotes (i.e. # ...
ler) # Handle Auto-refreshing Commands if legacy_version: print 'WARNING: Switch is running pre 16.1 code. Please be sure to not use auto-refreshing commands\n' else: # Check to see if cli refresh is disabled cli_out = clicmd('show management | include "CLI refresh"', True) ...
i_refresh = False if cli_refresh: # Temporarily disable refreshing CLI commands to prevent script from hanging clicmd('disable cli refresh') if stat_diff: prev_output = try_cli(cmd) print prev_output count -=1 prev_output = prev_output.split('\n') ...
joushx/OAuth.py
github.py
Python
mit
388
0.018041
from
oauth import OAuth class Github(OAuth): def __init__(self, consumer_key, consumer_secret): self.r
equest_token_url = "https://github.com/login/oauth/request_token" self.authorize_url = "https://github.com/login/oauth/authorize" self.access_token_url = "https://github.com/login/oauth/access_token" self.consumer_key = consumer_key self.consumer_secret = consumer_secret
team-diana/generic_input_controller
scripts/commander.py
Python
mit
242
0.004132
from command
import Command class Commander(object): def __init__(self): pass def set_command(self, command): self.command = command def update_command(self, cmd_data): self.command.onc
allback(cmd_data)
pyta-uoft/pyta
examples/pylint/e1138_unsupported_delete_operation.py
Python
gpl-3.0
595
0.001681
from typing import List class NamedList: """A contaner class for storing a list of named integers.""" def __init__(self, names: List[str], values: List[int]) -> None: self._names = names self._values = values def __getitem__(self, name: str) -> int: idx = self._names
.index(name) return self._values[idx] def __contains__(self, name: str) -> bool: return name in self._names
named_list = NamedList(['a', 'b', 'c'], [1, 2, 3]) print('c' in named_list) # Prints True del named_list['c'] # Error on this line print('c' in named_list)
D3f0/coreemu
daemon/core/session.py
Python
bsd-2-clause
46,224
0.002228
# # CORE # Copyright (c)2010-2013 the Boeing Company. # See the LICENSE file included in this distribution. # # authors: Tom Goff <thomas.goff@boeing.com> # Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com> # ''' session.py: defines the Session class used by the core-daemon daemon program that manages a CORE ses...
def broadcast(self, src, msg): ''' Send Node and Link CORE API messages to all handlers connected to this session. ''' self._handlerslock.acquire() for handler in self._handlers: if handler == src: continue if isinstance(msg, coreapi.CoreNodeMe...
self.warn("sendall() error: %s" % e) self._handlerslock.release() def broadcastraw(self, src, data): ''' Broadcast raw data to all handlers except src. ''' self._handlerslock.acquire() for handler in self._handlers: if handler == src: co...
hkjallbring/pusher-http-python
pusher_tests/test_requests_adapter.py
Python
mit
702
0.01567
# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, division from pusher import Pusher import unittest import httpretty class TestRequestsBackend(unittest.TestCase): def setUp(self): self.pusher = Pusher.from_url(u'http://key:secret@api.pusherapp
.com/apps/4') @httpretty.activate def test_trigger_requests_success(self): httpretty.register_uri(httpretty.POST, "http://api.pusherapp.com/apps/4/events", body="{}", content_type="application/json") response = self.pusher.trigger(u'test_channel', u'test', {u'd...
__name__ == '__main__': unittest.main()
lasote/conan
conans/client/generators/visualstudio_multi.py
Python
mit
2,436
0.002874
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <P...
a bit complicated, so skipping for now condition =
" '$(Configuration)' == '%s' And '$(Platform)' == '%s' And '$(VisualStudioVersion)' == '%s' "\ % (configuration, platform, vsversion + '.0') name_multi = 'conanbuildinfo_multi.props' name_current = ('conanbuildinfo_%s_%s_%s.props' % (configuration, platform, vsversion)).lower() ...
treytabner/cloudprefs-old
simulate.py
Python
agpl-3.0
3,219
0.003728
"""Cloud Preferences simulation tool""" # Copyright 2013 Trey Tabner # # 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 a...
requests.post('%s/%s' % (ENDPOINT, url), data=data, headers=headers(user_id)) def delete(user_id, url): return requ
ests.delete('%s/%s' % (ENDPOINT, url), headers=headers(user_id)) def simulate(user_id): #response = delete(user_id, '') #assert response.status_code == 204 #response = post(user_id, # 'managed_cloud/build_config', # payload=['driveclient', ...
interactomix/iis
test_utils/base.py
Python
agpl-3.0
1,749
0
import tempfile from datetime import datetime import flask_testing from flask import url_for import iis from iis.models import User from iis.extensions import db class BaseTestCase(flask_testing.TestCase): DB_FILE = tempfile.mkstemp() SQLALCHEMY_DATABASE_URI = "sqlite:///" + DB_FILE[1] LOGGING = {"versi...
rl_for('user.login'), data=dict( username=username, password=password ), follow_redirects=False) return User.query.filter_by(username=username).one() def logout(self): self.client.get(url_for("user.logout")) def create_user(self, username, password): use...
self.user_manager.hash_password(password), email=username + "@localhost", confirmed_at=datetime.fromtimestamp(0.0), active=True) db.session.add(user) db.session.commit() return user def assertLoginRequired(self, url): self....
sebastian-software/jasy
jasy/test/style/strings.py
Python
mit
1,663
0.004811
#!/usr/bin/env python3 import sys import os import unittest import logging import inspect # Extend PYTHONPATH with local 'lib' folder if __name__ == "__main__": jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir)) sys.path.insert(0, jasyroot) ...
e(tree) return Engine.compressTree(tree) def test_basic(self): self.assertEqual(self.process(r''' .foo{ content: "Hello"; } '''), '.foo{content:"Hello";}') def test_quotes(self): self.assertEqual(self.process(r''' .foo{ ...
(self): self.assertEqual(self.process(r''' .foo{ content: 'Hello "Frank"'; } '''), '.foo{content:\'Hello "Frank"\';}') if __name__ == '__main__': logging.getLogger().setLevel(logging.ERROR) suite = unittest.TestLoader().loadTestsFromTestCase(Tests) ...
twitter/pants
tests/python/pants_test/backend/jvm/targets/test_jvm_app.py
Python
apache-2.0
14,693
0.006057
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from builtins import str from textwrap import dedent from pants.backend.jvm.ta...
edes/buoyancy', name='app', binary=':bin') app = self.create_app('src/java/org/archimedes/buoyancy', name='app2', binary=':app') with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmApp.*src/java/org/archimedes/buoyancy:app2\)
.*' r' Expected binary dependency'): app.binary class BundleTest(TestBase): def test_bundle_filemap_dest_bypath(self): spec_path = 'src/java/org/archimedes/buoyancy' densities = self.create_file(os.path.join(spec_path, 'config/densities.xml')) unused = self.make_t...
uw-it-aca/spotseeker_server
spotseeker_server/migrations/0003_auto_20181105_2251.py
Python
apache-2.0
648
0.001543
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db
import migrations, models class Migration(migrations.Migration
): dependencies = [ ('spotseeker_server', '0002_auto_20181029_2244'), ] operations = [ migrations.AlterField( model_name='spot', name='last_modified', field=models.DateTimeField(auto_now=True), ), migrations.AlterField( model_...
mgood7123/UPM
Tests/PACKAGES/CDE/tests/pwd_readfile_test/pwd_readfile_test.py
Python
gpl-3.0
124
0.016129
import
os # generate an ABSOLUTE PATH to my-file.txt f = os.getcwd() + '/my-file.txt' for line in open(f): print line,
TrueCar/sentry-notes
setup.py
Python
bsd-3-clause
863
0.001159
#!/usr/bin/env python """ Setup for Sentry Notes Plugin ============================== Adds the option to record simple plain-text notes to message groups in sentry's GUI """ # See ht
tp://packages.python.org/distribute/setuptools.html # for insight on how this works from setuptools import setup, find_packages setup( name="sentry-notes", version="0.1", license="3-clause BSD", description="Notation Tool for Sentry", long_description=__doc__, url="https://github.com/TrueCar/s...
", author="Truecar.com Development Team", author_email="dev@truecar.com", maintainer="Ted Schundler", maintainer_email="tschundler@truecar.com", packages=find_packages(), include_package_data=True, zip_safe=False, #package_data={'': ['*.txt', '*.html']}, install_requires=[ ...
tylertian/Openstack
openstack F/cinder/cinder/test.py
Python
apache-2.0
9,555
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
ething else # (like None) within_tolerance = False if hasattr(d1value, 'keys') and hasattr(d2value, 'keys'): self.assertDictMatch(d1value, d2value) elif 'DONTCARE' in (d1value, d2value): continue elif approx_equal and w...
n("d1['%(key)s']=%(d1value)s != " "d2['%(key)s']=%(d2value)s" % locals()) def assertDictListMatch(self, L1, L2, approx_equal=False, tolerance=0.001): """Assert a list of dicts are equivalent.""" def raise_assertion(msg): L1str = str(L1) L2str ...
kwilliams-mo/iris
lib/iris/tests/test_io_init.py
Python
gpl-3.0
5,347
0.00374
# (C) British Crown Copyright 2010 - 2013, Met Office # # This file is part of Iris. # # Iris is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any l...
at each filespec is identified as the expected format for (expected_format_name, file_spec) in test_specs: test_path = tests.get_data_path(file_spec) with open(test_path, 'r') as test_file: a = iff.FORMAT_AGENT.get_spec(test_path, test_file) self.assertEqu...
(a.name, expected_format_name) def test_format_picker_nodata(self): # The following is to replace the above at some point as no real files # are required. # (Used binascii.unhexlify() to convert from hex to binary) # Packaged grib, magic number offset by set length, this length is ...
pvagner/orca
test/keystrokes/gtk3-demo/role_label.py
Python
lgpl-2.1
6,801
0.001617
#!/usr/bin/python """Test of label presentation.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(KeyComboAction("<Control>f")) sequence.append(TypeAction("Dialog and Message Boxes")) sequence.append(KeyComboAction("Return")) sequence.append(PauseAction(3000)) sequence.app...
" VISIBLE: 'This message box has been popped', cursor=2", "SPEECH OUTPUT: 'h'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("<Shift><Control>Right")) sequence.append(utils.AssertPresentationAction( "6. This message box label caret select 'his' of 'This'", ["BR...
is message box has been popped', cursor=5", "SPEECH OUTPUT: 'his'", "SPEECH OUTPUT: 'selected' voice=system"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("KP_Enter")) sequence.append(utils.AssertPresentationAction( "7. This message box label caret selection Where Am I",...
SauloAislan/ironic
ironic/conf/oneview.py
Python
apache-2.0
2,255
0
# Copyright 2016 Intel Corporation # Copyright 2015 Hewlett Packard Development Company, LP # Copyright 2015 Universidade Federal de Campina Grande # # 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 t...
with OneView.')), cfg.StrOpt('tls_cacert_file
', help=_('Path to CA certificate.')), cfg.IntOpt('max_polling_attempts', default=12, help=_('Max connection retries to check changes on OneView.')), cfg.BoolOpt('enable_periodic_tasks', default=True, help=_('Whether to enable the peri...
seunghwanl/APMAE4990
scripts/regression.py
Python
apache-2.0
3,369
0.009498
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import r2_score, mean_squared_error from sklearn.grid_search import GridSearchCV from sklearn.e...
# if month == 'jul' and day == 'Sun': # plt.scatter(X, y, s = 1) # plt.legend(loc="lower right") # plt.title("RandomForest Regression " + m
onth + " " + day) # plt.xlabel("Hours") # plt.ylabel("Number of Pickups") # plt.show() y = np.asarray(y) X = np.asarray(X) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state = 42) # perform gridsea...
mikeengland/fireant
fireant/tests/queries/test_data_blending_integration.py
Python
apache-2.0
55,610
0.001259
from unittest import TestCase from pypika import Tables, functions as fn import fireant as f from fireant import DataSet, DataType, Database, Field, ReactTable from fireant.tests.database.mock_database import TestDatabase class DataSetBlenderIntegrationTests(TestCase): maxDiff = None def test_select_only_a...
self.assertEqual( 'SELECT "sq0"."$timestamp" "$timestamp","sq0"."$metric0" "$metric0" ' 'FROM (SELECT "timestamp" "$timestamp",SUM("metric") "$metric0" FROM "test0" GROUP BY "$timestamp") "sq0" ' 'ORDER BY "$timestamp" LIMIT 200000', str(query), ) def test_u...
t_when_alias_conflicts_with_metric_from_secondary( self, ): db = Database() t0, t1 = Tables("test0", "test1") primary_ds = DataSet( table=t0, database=db, fields=[ Field( "timestamp", label="T...
belese/luciphone
Luciphone/writeuid.py
Python
gpl-2.0
431
0.020882
from modules.py532lib.NFC import NFC as NFC print ('Write UID') #write .UID in current dir UID_FILE = ".UID" def write_uid(uid): f = open(UID_FILE,'w')
print("Write UID : %s"%str(uid)) uid = f.write(str(uid)) f.close NFC.stop() def stop(uid): NFC.stop() NFC.add_event_detect(NFC.NEWTAG,write_uid) NFC.add_event_detect(NFC.REMOVETAG,stop) pr
int('Put the disk on plate') NFC.start()
roadmapper/ansible
lib/ansible/module_utils/network/vyos/config/static_routes/static_routes.py
Python
gpl-3.0
20,425
0.001812
# # -*- coding: utf-8 -*- # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The vyos_static_routes class It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessar...
dden', 'rendered') and not want: self._module.fail_json(msg='value of config parameter must not be empty for state {0}'.format(self.state)) if self.state == 'overridden': commands.extend(self._state_overridden(want=want, have=have)) elif self.state == 'deleted': comma...
m = self.search_route_in_have(have, r['dest']) if self.state == 'merged' or self.state == 'rendered': commands.extend(self._state_merged(want=r, have=h_item)) elif self.state == 'replaced': commands.extend(self._state_replaced(want=r, have=h_item))...
HumanExposure/factotum
apps_api/core/authentication.py
Python
gpl-3.0
854
0
import datetime from rest_framework.authentication import TokenAuthentication from rest_framework import exceptions from factotum.environment import env class ExpiringTokenAuthentication(TokenAuthentication): keyword
= "Bearer" def authenticate_credentials(self, key): model = self.get_model() try: token = model.objects.get(key=key) except model.DoesNotExist: raise exceptions.AuthenticationFailed("Invalid token") if not token.user.is_active: raise exceptions...
milliseconds=env.FACTOTUM_WS_TOKEN_TTL ): raise exceptions.AuthenticationFailed("Token has expired") return token.user, token
ratschlab/ASP
examples/undocumented/python_modular/classifier_multiclasslinearmachine_modular.py
Python
gpl-2.0
1,156
0.036332
import classifier_multiclass_shared [traindat, label_traindat, testdat, label_testdat]
= classifier_multiclass_shar
ed.prepare_data(False) parameter_list = [[traindat,testdat,label_traindat,2.1,1,1e-5],[traindat,testdat,label_traindat,2.2,1,1e-5]] def classifier_multiclasslinearmachine_modular (fm_train_real=traindat,fm_test_real=testdat,label_train_multiclass=label_traindat,width=2.1,C=1,epsilon=1e-5): from shogun.Features impor...
bcorbet/SickRage
sickbeard/providers/iptorrents.py
Python
gpl-3.0
11,284
0.004342
# Author: seedboy # URL: https://github.com/seedboy # # This file is part of SickRage. # # SickRage 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 la...
ame_helpers import allPossibleShowNames class IPTorrentsProvider(generic.TorrentProvider):
def __init__(self): generic.TorrentProvider.__init__(self, "IPTorrents") self.supportsBacklog = True self.enabled = False self.username = None self.password = None self.ratio = None self.freeleech = False self.cache = IPTorrentsCache(self) s...
janutechnology/VirtShell
virtshell_server/virtshell_server/provisioning/images.py
Python
gpl-2.0
676
0.002959
from provisioning.images_repository import ImagesRepository import uuid class Im
ages(object): def __init__(self): self.images_repository = ImagesRepository() def get_all_images(self): return self.images_repository.get_all_images()
def get_image(self, name): return self.images_repository.get_image(name) def create_image(self, image): image['uuid'] = str(uuid.uuid4()) return self.images_repository.create_image(image) def delete_image(self, name): return self.images_repository.delete_image(name) d...
forj-oss/docs
conf.py
Python
apache-2.0
10,336
0.006772
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Forj documentation build configuration file, created by # sphinx-quickstart on Wed Feb 19 14:00:10 2014. # # 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 # autog...
{ # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tre
e into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Forj.tex', 'Forj Documentation', 'Forj community', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the...
fevangelista/pyWicked
external/pybind11/pybind11/_version.py
Python
mit
77
0
version_info = (1,
9, 'dev0') __version__ = '.'.join(map(str,
version_info))
pypa/virtualenv
src/virtualenv/activation/activator.py
Python
mit
1,411
0.003544
from __future__ import absolute_import, unicode_literals import os from abc import ABCMeta, abstractmethod from six import add_metaclass @add_metaclass(ABCMeta) class Activator(object): """Generates an activate script for the virtual environment""" def __init__(self, options): """Create a new activ...
:param options: the parsed options as defined within :meth:`add_parser_arguments` """ self.flag_prompt = os.path.basename(os.getcwd()) if options.prompt == "." else options.prompt @classmethod def supports(cls, interpreter): """Check if the activation script is supported in the given...
smethod def add_parser_arguments(cls, parser, interpreter): """ Add CLI arguments for this activation script. :param parser: the CLI parser :param interpreter: the interpreter this virtual environment is based of """ @abstractmethod def generate(self, creator): ...
coxmediagroup/googleads-python-lib
examples/dfp/v201505/network_service/make_test_network.py
Python
apache-2.0
1,901
0.006839
#!/usr/bin/python # # Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
se is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific languag
e governing permissions and # limitations under the License. """This example creates a test network. You do not need to have a DFP account to run this example, but you do need to have a Google account (created at http://www.google.com/accounts/newaccount if you currently don't have one) that is not associated with an...
lmazuel/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/deployment.py
Python
mit
3,290
0.000304
# 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 ...
'properties.deployer', 'type': 'str'}, 'author_email': {'key': 'properties.authorEmail', 'type': 'str'}, 'start_time': {'key': 'properties.startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'properties.endTime', 'type': 'iso-8601'}, 'active': {'key'
: 'properties.active', 'type': 'bool'}, 'details': {'key': 'properties.details', 'type': 'str'}, } def __init__(self, kind=None, deployment_id=None, status=None, message=None, author=None, deployer=None, author_email=None, start_time=None, end_time=None, active=None, details=None): super(Deploy...
psi4/psi4
psi4/driver/procrouting/sapt/__init__.py
Python
lgpl-3.0
973
0.001028
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2022 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
on 3. # # Psi4 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public Li...
with Psi4; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # from .sapt_proc import run_sapt_dft, sapt_dft, run_sf_sapt
cdelguercio/slothauth
slothauth/middleware.py
Python
apache-2.0
2,323
0.004735
from django.contrib.auth import authenticate, login from django.contrib.auth import get_user_model from . import settings Account = get_user_model() class PasswordlessUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): pas...
response = self.get_response(request) return response class ImpersonateMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if (hasattr(request.user, 'can_impersonate') and request.user.can_impersonate) or\ ...
request.user = Account.objects.get(id=request.session['impersonate_id']) elif "__impersonate" in request.GET: request.session['impersonate_id'] = int(request.GET["__impersonate"]) request.user = Account.objects.get(id=request.session['impersonate_id']) ...
kevinoconnor7/penelophant
penelophant/models/Bid.py
Python
apache-2.0
744
0.017473
""" Bid Model """ from penelophant
.database import db from .Model import Model from .User import User class Bid(Model): """ Bid data representation """ __mapper_args__ = { 'order_by': 'price DESC, bid_time ASC' } id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey(User.id, ondelete='RESTRI
CT', onupdate='CASCADE'), nullable=False ) auction_id = db.Column(db.Integer, db.ForeignKey('auction.id', ondelete='RESTRICT', onupdate='CASCADE'), nullable=False ) bid_time = db.Column(db.TIMESTAMP, default=db.func.now()) price = db.Column(db.Numeric('13,2'), default=0) user = db.relationship(...
ME-ICA/me-ica
meica.libs/mdp/hinet/__init__.py
Python
lgpl-2.1
2,949
0.000678
"""Hierarchical Networks Package. This package makes it possible to construct graph-like Node structures, especially hierarchical networks. The most important building block is the new Layer node, which works as an horizontal version of flow. It encapsulates a list of Nodes, which are trained and executed in parallel...
s, so one can derive subclasses for special routing situations. One such subclass for 2d image data is provided. It maps the data according to rectangular overlapping 2d input areas. One can then feed the output into a La
yer and each Node will get the correct input. """ from flownode import FlowNode from layer import Layer, SameInputLayer, CloneLayer from switchboard import ( Switchboard, SwitchboardException, MeanInverseSwitchboard, ChannelSwitchboard, Rectangular2dSwitchboard, Rectangular2dSwitchboardException, Doubl...
fkmclane/web.py
tests/test_header.py
Python
mit
5,961
0.000336
from fooster.web import web import pytest test_key = 'Magical' test_value = 'header' test_header = test_key + ': ' + test_value + '\r\n' poor_key = 'not' poor_value = 'good' poor_header = poor_key + ':' + poor_value + '\r\n' good_header = poor_key + ': ' + poor_value + '\r\n' case_key = 'wEIrd' case_key_title = c...
test_add_getitem(): headers = web.HTTPHeaders() headers.add(test_header) assert headers[test_key
] == test_value def test_getitem_empty(): headers = web.HTTPHeaders() with pytest.raises(KeyError): headers[test_key] def test_getlist_empty(): headers = web.HTTPHeaders() with pytest.raises(KeyError): headers.getlist(test_key) def test_getlist_default(): headers = web.HTTPHe...
mworks/mworks
examples/Tests/Stimulus/DriftingGrating/StartingPhase/get_current_phase.py
Python
mit
185
0
def get_current_phase(tag): sdu = getvar('#stimDisplayUpdate')
for item i
n sdu: if item['name'] == tag: return '%.2f' % -item['current_phase'] return ''
RFDesign/SiK
Firmware/tools/rssi.py
Python
bsd-2-clause
1,670
0.026347
#!/usr/bin/env python # RSSI production test import serial, sys, optparse, time, fdpexpect parser = optparse.OptionParser("update_mode") parser.add_op
tion("--baudrate", type='int', default=57600, help='baud rate') parser.add_option("--rtscts", action='store_true', default=False, help='enable rtscts') parser.add_option("--dsrdtr", action='store_tru
e', default=False, help='enable dsrdtr') parser.add_option("--xonxoff", action='store_true', default=False, help='enable xonxoff') opts, args = parser.parse_args() if len(args) == 0: print("usage: rssi.py <DEVICE...>") sys.exit(1) def rssi(device): port = serial.Serial(device, opts.baudrate, timeout=0, ...
hazelnusse/robot.bicycle
data/physicalparameters/RawData/PeriodMeasurements/RearWheel/populateTable.py
Python
bsd-2-clause
2,289
0.002621
import psycopg2 import scipy.io import os # Set to true if you want to query tables before adding data: queryConfigs = False queryTimeSeries = False # Create a connection to RoboticBicycle database conn = psycopg2.connect(database="robot_bicycle_parameters", user="hazelnusse") cur = conn.cursor() def insert_statemen...
ror, psy
copg2.InternalError) as inst: print("Exception in adding wheel compound pendulum data:") print(type(inst)) print(inst) conn.rollback() continue print(cur.statusmessage) cur.close() conn.close()
exiahuang/SalesforceXyTools
libs/cherrypy/wsgiserver/wsgiserver3.py
Python
apache-2.0
77,620
0.001391
"""A high-speed, production ready, thread pooled, generic HTTP server. Simplest example on how to use this module directly (without using CherryPy's application machinery):: from cherrypy import wsgiserver def my_crazy_app(environ, start_response): status = '200 OK' response_headers = [('Cont...
ef read(self, siz
e=None): data = self.rfile.read(size) self.bytes_read += len(data) self._check_length() return data def readline(self, size=None):
vjFaLk/frappe
frappe/automation/doctype/assignment_rule/test_assignment_rule.py
Python
mit
6,555
0.051869
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import random_string from frappe.test_runner import make_test_records class TestAutoAssign(unittest.TestCase): def setUp(self): ...
frappe.get_doc(dict( name = 'For Note 2', d
octype = 'Assignment Rule', priority = 1, document_type = 'Note', assign_condition = assign[1], unassign_condition = 'notify_on_login == 0', rule = 'Round Robin', assignment_days = days[1], users = [ dict(user = 'test3@example.com') ] )).insert() return assignment_rule def make_note(values=None)...
ceibal-tatu/pygobject
gi/pygtkcompat.py
Python
lgpl-2.1
14,279
0.001401
# -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab # # Copyright (C) 2011-2012 Johan Dahlin <johan@gnome.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Founda...
sys.modules['gtk'] = Gtk Gtk.gdk = Gdk Gtk.pygtk_version = (2, 99, 0) Gtk.gtk_version = (Gtk.MAJOR_VERSION, Gtk.MINOR_VERSION, Gtk.MICRO_VERSION) _install_enums(Gtk) # Action def set_tool_item_type(menuaction, gtype): warnings.warn('set_...
t supported', DeprecationWarning, stacklevel=2) Gtk.Action.set_tool_item_type = classmethod(set_tool_item_type) # Alignment orig_Alignment = Gtk.Alignment class Alignment(orig_Alignment): def __init__(self, xalign=0.0, yalign=0.0, xscale=0.0, yscale=0.0): orig_Alig...
keyz182/adamsays
says/models.py
Python
mit
350
0.005714
from django.db import models from dj
ango.contrib.auth.models import User # Create your models here. class Quote(models.Model): quote = models.CharField(max_length=2048) date = models.DateTimeField('date published') poster = models.ForeignKey(User) def __str__(self): # __unicode__ on Python 2
return self.quote
mjwtom/swift
test/unit/obj/test_diskfile.py
Python
apache-2.0
221,579
0.000005
# -*- coding:utf-8 -*- # Copyright (c) 2010-2012 OpenStack Foundation # # 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 ...
.0.0.1', 'port': 6000}, {'id': 2, 'device': 'sda1', 'zone': 2, 'ip': '127.0.0.2', 'port': 6000}, {'id'
: 3, 'device': 'sda1', 'zone': 4, 'ip': '127.0.0.3', 'port': 6000}, {'id': 4, 'device': 'sda1', 'zone': 5, 'ip': '127.0.0.4', 'port': 6000}, {'id': 5, 'device': 'sda1', 'zone': 6, 'ip': 'fe80::202:b3ff:fe1e:8329', 'port': 6000}, {'id': 6, 'device': 'sda1', 'zone': 7, ...
eesatfan/vuplus-enigma2
lib/python/Components/AVSwitch.py
Python
gpl-2.0
7,088
0.034142
from config import config, ConfigSlider, ConfigSelection, ConfigYesNo, \ ConfigEnableDisable, ConfigSubsection, ConfigBoolean, ConfigSelectionNumber, ConfigNothing, NoSave from enigma import eAVSwitch, getDesktop from SystemInfo import SystemInfo from os import path as os_path class AVSwitch: def setInput(self, inpu...
bufferScale(self): aspect = self.getOutputAspect() fb_size = getDesktop(0).size() return (aspect[0] * fb_size.height(), aspect[1] * fb_size.width()) def getAspectRatioSetting(self): valstr = config.av.aspectratio.value if valstr == "4_3_letterbox": val = 0 elif valstr == "4_3_panscan": val = 1 eli...
valstr == "16_9_always": val = 3 elif valstr == "16_10_letterbox": val = 4 elif valstr == "16_10_panscan": val = 5 elif valstr == "16_9_letterbox": val = 6 return val def setAspectWSS(self, aspect=None): if not config.av.wss.value: value = 2 # auto(4:3_off) else: value = 1 # auto eAVSw...
dirrelito/animated-invention
ThreadedTicTacToe/_old/ttt.py
Python
apache-2.0
5,563
0.039907
# old single process tictactoe game to be rewritten.... import numpy import os class TicTacToePlayer: def __init__(self, playerType, playerName, ttt_game_settings): if playerType not in ['AI', 'Terminal']: raise(ValueError()) self.type=playerType self.name=playerName self.board_size = ttt_game_settings['...
sition,direction): if direction == 'N': parsed_dir = (-1,0) elif direction =='S': parsed_dir = (1,0) elif direction == 'E': pars
ed_dir = (0,1) elif direction == 'W': parsed_dir = (0,-1) elif direction == 'NW': parsed_dir = (-1,-1) elif direction == 'SW': parsed_dir = (1,-1) elif direction == 'NE': parsed_dir = (-1,1) elif direction == 'SE': parsed_dir = (1,1) next_pos = numpy.asarray(position)+numpy.asarray(parsed_dir...
ngocson2vn/webapps
shortly/__init__.py
Python
gpl-2.0
18
0.055556
# T
his is a mo
dule
micjerry/groupservice
handlers/acceptinvite.py
Python
apache-2.0
951
0.003155
import tornado.web import tornado.gen import json import io import logging from mickey.basehandler import BaseHandler from mickey.groups import GroupMgrMgr, MickeyGroup class AcceptInviteHandler(BaseHandler): @tornado.web.asynchronous @tornado.gen.co
routine def post(self): data = json.loads(self.request.body.decode("utf-8")) groupid = data.get("groupid", "") logging.info("begin to add members to group %s" % groupid) if not groupid: logging.error("invalid request") self.set_status(403) self.f...
group = yield GroupMgrMgr.getgroup(groupid) if not group: logging.error("group %s does not exist" % groupid) self.set_status(404) self.finish() return rst_code = yield group.add_realmember(self.p_userid) self.set_status(rst_code) sel...
migcruz/dota2analytics
backend/apps/users/models.py
Python
mit
2,526
0
from __future__ import unicode_literals from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, BaseUserManager) from django.db import models from django.utils import timezone class EmailUserManager(BaseUserManager): def _create_user(self, email, passwo...
} ) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) last_updated = models.DateTimeField(auto_now=True) objects = EmailUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['f...
st_name', 'last_name'] class Meta: permissions = ( ('view_emailuser', 'Can view email users'), ) def __unicode__(self): return self.email def get_short_name(self): return '{first_name}'.format( first_name=self.first_name ) def get_full_...
jmakov/ggrc-core
src/ggrc_workflows/__init__.py
Python
apache-2.0
34,934
0.00853
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: miha@reciprocitylabs.com from datetime import datetime, date from flask import Blueprint from sqlalchemy i...
WorkflowBasicReader ) from ggrc_basic_permissions.models import Role, UserRole, ContextImplication from ggrc_basic_permissio
ns.contributed_roles import ( RoleContributions, RoleDeclarations, DeclarativeRoleImplications ) # Initialize Flask Blueprint for extension blueprint = Blueprint( 'ggrc_workflows', __name__, template_folder='templates', static_folder='static', static_url_path='/static/ggrc_workflows', ) for ...
cp16net/trove
trove/db/sqlalchemy/mappers.py
Python
apache-2.0
3,298
0
# Copyright 2011 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...
NDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import MetaData from sqlalchemy import orm from sqlalchemy.orm import exc as orm_e
xc from sqlalchemy import Table def map(engine, models): meta = MetaData() meta.bind = engine if mapping_exists(models['instance']): return orm.mapper(models['instance'], Table('instances', meta, autoload=True)) orm.mapper(models['root_enabled_history'], Table('root_enabled...
secnot/rectpack
setup.py
Python
apache-2.0
876
0.002283
from setuptools import setup long_description = """A collection of heuristic algorithms for solving the 2D knapsack problem, also known as the bin packing problem. In essence packing a set of rectangles into the smallest number of bins.""" setup( name="rectpack", version="0.2.2", description="2D Rectangle...
ription, url="https://github.com/secnot/rectpack/", author="SecNot"
, keywords=["knapsack", "rectangle", "packing 2D", "bin", "binpacking"], license="Apache-2.0", classifiers=[ "Development Status :: 3 - Alpha", "Programming Language :: Python", "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", ]...
innusource/siteg.py
_app/walker.py
Python
mit
303
0
from os import walk from defi
nitions import Config class Walker(object): def __init__(self, directory): super(Walker, self).__init__() cfg = Config() for (_path, _file, _archives) in walk(cfg.globals['root'] + directory): pass
self.archives = _archives
itsallvoodoo/csci-school
CSCI220/Week 15 - FINAL/Scrabble/StartScreen.py
Python
apache-2.0
2,963
0.015862
from graphics import * from Button import * from CreateNewUserScreen import * from ChangePasswordScreen import * import os class StartScreen: def is_game_in_progress(self,gid): for filename in os.listdir("games"): if str(gid) == filename: return True return Fa...
n = CreateNewUserScreen() screen.create_new_user(db) elif change_button.cli
cked(p): screen = ChangePasswordScreen() screen.change_password(db) elif quit_button.clicked(p): win.close() return "quit"
caravancoop/configstore
tests/test_awsssm.py
Python
mit
3,127
0.001279
import pretend import pytest from botocore.exceptions import ClientError from configstore.backends.awsssm import AwsSsmBackend def test_awsssm_init_bad_install(monkeypatch): monkeypatch.setattr('configstore.backends.awsssm.boto3', None) with pytest.raises(ImportError): AwsSsmBackend() def test_aw...
, ) fake_boto3 = pretend.stub( client=pretend.call_recorder(lambda service: fake_client), ) monkeypatch.setattr('configstore.backends.awsssm.boto3', fake_boto3) b = AwsSsmBackend('/myapp/staging/') value = b.get_setting('DEBUG') assert value == 'off' assert fake_boto3.client.ca...
l('ssm')] assert fake_client.get_parameter.calls == [ pretend.call(Name='/myapp/staging/DEBUG', WithDecryption=True), ] def test_awsssm_missing(monkeypatch): error = ClientError({'Error': {'Code': 'ParameterNotFound'}}, 'get_parameter') fake_client = pretend.stub( get_parameter=pretend...
kurkop/server-tools
__unported__/mass_editing/wizard/__init__.py
Python
agpl-3.0
1,106
0.001808
# -*- coding: utf-8 -*- ############################################################################## # # This module uses OpenERP, Open Source Management Solution Framework. # Copyright (C) 2012-Today Serpent Consulting Services (<http://www.serpentcs.com>) # # This program is free software: you can redistri...
NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have recei
ved a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import mass_editing_wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
one2pret/winsys
winsys/asyncio.py
Python
mit
2,311
0.019472
# -*- coding: iso-8859-1 -*- ur"""AsyncIO objects wrap the Win32 Overlapped API. They are instantiated by passing a handle which has been opened for Overlapped IO. They can be waited on by the functions in the :mod:`ipc` module and are True when complete, False otherwise. """ import pywintypes import winerror i...
nual_reset=True) self.overlapped = wrapped (win32file.OVERLAPPED) self.overlapped.hEvent = self.event.pyobject () def pyobject (self): ur"""Return the pyobject of the underlying event so that this object can be waited on by the :func:`ipc.all` or :func:`ipc.any` functions """ return s...
() def is_complete (self): ur":returns: `True` if the IO has completed" return self.event.isSet () __nonzero__ = is_complete def wait (self): ur"""Wait for the IO to complete in such a way that the wait can be interrupted by a KeyboardInterrupt. """ while not self.event.wait ...
un33k/django-contactware
contactware/signals.py
Python
bsd-3-clause
95
0
from django.dispatch import Signal contact_sent = Signal(providing_args=["request, contact"])
aznashwan/py-securestring
securestring.py
Python
gpl-2.0
3,385
0
# Copyright 2015, Nashwan Azhari. # Licensed under the GPLv2, see LICENSE file for details. """ A pure Python implementation of the functionality of the ConvertTo-SecureString and ConvertFrom-SecureString PoweShell commandlets. Usage example: from securestring import encrypt, decrypt if __name__ == "__main__": s...
yption of the above is: %s" % dec) except Exception as e: p
rint(e) # checking of operation symmetry: print("Encryption and decryption are symmetrical: %r", dec == str) # decrypting powershell input: psenc = "<your output of ConvertFrom-SecureString>" try: dec = decrypt(psenc) print("Decryption from ConvertFrom-SecureString's input: %s" % d...
dav-stott/phd-thesis
fw_gridding_idw.py
Python
mit
12,343
0.018067
# -*- coding: utf-8 -*- """ Created on Thu May 29 12:28:08 2014 @author: david """ import numpy as np import sys import os from osgeo import gdal from osgeo import ogr from osgeo import osr from osgeo import gdal_array from osgeo import gdalconst from scipy.ndimage import filters class Empty_Grid(): def __init...
z class WriteImage(): def __init__(self,
o
nchaparr/Geospatial-Analysis-with-Python
1138_08_03-flood-fill.py
Python
cc0-1.0
2,243
0.029871
""" Crawls a terrain raster from a starting point and "floods" everything at the same or lower elevation by producing a mask image of 1,0 values. """ import numpy as np from linecache import getline def floodFill(c,r,mask): """ Crawls a mask array containing only 1 and 0 values from the starting...
ows=6) print "Image opened" a = np.where(img<70, 1,0) print "Image masked" # Parse the headr using a loop and # the built-in linecache module hdr = [getline(source, i) for i in range(1,7)] values = [float(h.split(" ")[-1].strip()) for h in hdr] cols,rows,lx,ly,cell,nd = values xres = cell yres = cell * -1...
2582 sy = 2057 print "Beginning flood fill" fld = floodFill(sx,sy, a) print "Finished Flood fill" header="" for i in range(6): header += hdr[i] print "Saving grid" # Open the output file, add the hdr, save the array with open(target, "wb") as f: f.write(header) np.savetxt(f, fld, fmt="%1i"...
ric2b/Vivaldi-browser
chromium/chrome/test/enterprise/e2e/policy/allow_deleting_browser_history/allow_deleting_browser_history_webdriver_test.py
Python
bsd-3-clause
1,991
0.005023
# Copyright (c) 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from absl import app from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.suppo...
ot(driver, hi
stroy_list, 'history-item') checkbox = getElementFromShadowRoot(driver, histroy_item, '#main-container cr-checkbox') disabled = checkbox.get_attribute('disabled') if disabled == 'true': print('DISABLED') else: ...
acortelyou/drone-tools
dji2papywizard.py
Python
apache-2.0
5,866
0.003239
#!/usr/bin/env python """ Copyright 2016 Alex Cortelyou 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...
License. """ import os import argparse import xml.etree.ElementTree as ET from datetime import datetime from glob import glob import exifread # pylint: disable=C0103 #arguments parser = argparse.ArgumentParser(description='Extracts DJI image metadata into a Papywizard panohead data file for use with stitching softwa...
sean666888/The-Bomb
s.py
Python
mit
430
0.002326
#!/usr/bin/env python import socket TCP_IP = '127.0.0.1' TCP_PORT = 5005 BUFFER_SIZE = 20 # Normally 1024, but we want fast response s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr =
s.accept() print 'Connection
address:', addr while 1: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) # echo conn.close()
smallyear/linuxLearn
salt/salt/key.py
Python
apache-2.0
48,988
0.000367
# -*- coding: utf-8 -*- ''' The Salt Key backend API and interface used by the CLI. The Key class can be used to manage salt keys directly without interfacing with the CLI. ''' # Import python libs from __future__ import absolute_import, print_function import os import copy import json import stat import shutil import...
f.opts ) elif status.startswith('den'): if self.key.DEN: salt.output.display_output( {self.key.DEN: keys[self.key.DEN]}, 'key', self.opts ) elif status.startswith('all'): self....
salt.output.display_output( self.key.list_keys(), 'key', self.opts) def accept(self, match, include_rejected=False): ''' Accept the keys matched :param str match: A string to match against. i.e. 'web*' :param bool include_rejected:...
wcong/ants
ants/bootstrap/bootstrap.py
Python
bsd-3-clause
1,189
0.003364
#!/usr/bin/env python # encoding=utf8 __author__ = 'wcong' import sys from twisted.internet import reactor from ants.node import node from ants
import settings from conf import settings as project_settings import logging import argparse ''' what we do start the node let the node do what he need to do ''' parser = argparse.ArgumentParser(description='ants -- scale crawler') parser.add_argument('-tcp_port', help='transport port', type=int, dest='tcp_port') pa...
self.setting = settings.Settings() self.setting.setmodule(project_settings) if args: cmd_args = parser.parse_args(args) if cmd_args.tcp_port: self.setting.set('TRANSPORT_PORT', cmd_args.tcp_port) if cmd_args.http_port: self.settin...
yousoff92/data-collector
python/jobstreet/JobStreetExtractor.py
Python
mit
8,609
0.006621
""" Python source code to extract listing from mudah.my """ from functools import total_ordering from job
street.config import General, Authentication, Location import pandas as pd import requests i
mport webbrowser as web import urllib.parse as urlparse from urllib.parse import urlencode from bs4 import BeautifulSoup from datetime import datetime, timedelta import dateutil.relativedelta as rd import math import mechanicalsoup import logging as logger import os clear = lambda: os.system('cls') #on Windows System ...
legacysurvey/pipeline
py/legacyzpts/run-calib.py
Python
gpl-2.0
4,720
0.004237
#! /usr/bin/env python """This script runs calibration pre-processing steps including sky and PSF models. """ from __future__ import print_function from astrometry.util.fits import merge_tables from legacypipe.survey import run_calibs, LegacySurveyData def main(): """Main program. """ import argparse ...
--blob-mask-dir', type=str, default=None, help='The base directory to search for blob masks during sky model construction') parser.add_argument('-v', '--verbose', dest='verbose', action='count', default=0, help='Make more verbose') parser.add_argument('args',narg...
= parser.parse_args() import logging if opt.verbose: lvl = logging.DEBUG else: lvl = logging.INFO logging.basicConfig(level=lvl, format='%(message)s', stream=sys.stdout) # tractor logging is *soooo* chatty logging.getLogger('tractor.engine').setLevel(lvl + 10) survey = Leg...
saurabh6790/frappe
frappe/website/doctype/web_page/test_web_page.py
Python
mit
2,204
0.03902
from __future__ import unicode_literals import unittest import frappe from frappe.website.router import resolve_route import frappe.website.render from frappe.utils import set_request test_records = frappe.get_test_records('Web Page') def get_page_content(route): set_request(method='GET', path = route) response = f...
nicode(content)) def test_content_type(self): web_page = frappe.get_doc(dict( doctype = 'Web Page', title = 'Test Content Type', published = 1, content_type = 'Rich Text', main_section = 'rich text', main_section_md = '# h1\nm
arkdown content', main_section_html = '<div>html content</div>' )).insert() self.assertTrue('rich text' in get_page_content('/test-content-type')) web_page.content_type = 'Markdown' web_page.save() self.assertTrue('markdown content' in get_page_content('/test-content-type')) web_page.content_type = 'H...
AGarrow/larvae
larvae/tests/test_membership.py
Python
bsd-3-clause
694
0
from ..member
ship import Membership def test_basic_invalid_membership(): """ Make sure that we can create an invalid membership and break """ membership = Membership("person_id", "orga_id") membership.validate() membership.person_id = None try: assert "nonsens
e" == membership.validate() except ValueError: pass def test_basic_invalid_membership(): """ Ensure contact details work for memberships """ membership = Membership("person_id", "orga_id") membership.validate() membership.add_contact_detail(type='foo', va...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_11_01/models/_network_management_client_enums.py
Python
mit
27,671
0.007192
# 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 ...
APP_GW_SSL_POLICY20170401_S = "AppGwSslPolicy20170401S" class ApplicationGatewaySslPolicyType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Type of Ssl Policy """ PREDEFINED = "Predefined" CUSTOM = "Custom" class ApplicationGatewaySslProtocol(with_metaclass(_CaseInsensitiveEnumMeta, str,...
s. """ TL_SV1_0 = "TLSv1_0" TL_SV1_1 = "TLSv1_1" TL_SV1_2 = "TLSv1_2" class ApplicationGatewayTier(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Tier of an application gateway. """ STANDARD = "Standard" WAF = "WAF" STANDARD_V2 = "Standard_v2" WAF_V2 = "WAF_v2" clas...
noironetworks/heat
heat/tests/engine/tools.py
Python
apache-2.0
11,355
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
ronment({'KeyName': 'test'}) tmpl = templatem.Template(t, env=env) else: tmpl = templatem.Template(t) else: t = template_format.parse(template) tmpl = templatem.Template(t) stack = parser.Stack(ctx, stack_name, tmpl, convergence=convergence, ...
= fake_ks.FakeKeystoneClient() test_case.patchobject(keystone.KeystoneClientPlugin, '_create') keystone.KeystoneClientPlugin._create.return_value = fkc def setup_mock_for_image_constraint_with_mock(test_case, imageId_input, imageId_output=744): test_case.patc...
betatim/osf-cli
setup.py
Python
bsd-3-clause
2,524
0
# Always prefer setuptools over distutils import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'VERSION')) as f: __version__ = f.read().strip() with open(os.path.join(here, 'requirements.txt')) as f: required = f.read().spli...
pend(os.p
ath.join(here, 'VERSION')) setup( name='osfclient', # update `osfclient/__init__.py` as well version=__version__, description='An OSF command-line library', long_description=long_description, # The project's main homepage. url='https://github.com/dib-lab/osf-cli', # Author details ...
Ebag333/Pyfa
eos/effects/modulebonusafterburner.py
Python
gpl-3.0
479
0.002088
# moduleBonusAfterburner # # Used by: # Modules from group: Propulsion Module (62 of 127) type = "active" runTime = "late"
def handler(fit, module, context): fit.ship.increaseItemAttr("mass", module.getModifiedItemAttr("massAddition")) speedBoost = module.getModifiedItemAttr("speedFactor") mass = fit.ship.getModifiedItemAttr("mass") thrust = module.getModifiedItemAttr("speedBoostFactor") fit.ship
.boostItemAttr("maxVelocity", speedBoost * thrust / mass)
h2oai/h2o-dev
h2o-py/tests/testdir_jira/pyunit_hexdev_612.py
Python
apache-2.0
744
0.004032
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Test for HEXDEV-612.""" from tests import pyunit_utils import h2o import numpy as np def test_hd612(): """Test whether explicitly pr
oviding ``column_names`` to ``H2OFrame.from_python()`` produces an extra row.""" data = np.array([i for i in range(40)]).reshape(10, 4) df = h2o.H2OFrame.from_python(data) assert df.nrow == 10 assert df.ncol == 4 assert df.names == ["C1", "C2", "C3", "C4"] names = ["spam", "egg", "ham", "milk"...
ssert df.names == names if __name__ == "__main__": pyunit_utils.standalone_test(test_hd612) else: test_hd612()
Nvizible/shotgunEvents
src/examplePlugins/sharedStateB.py
Python
mit
2,306
0.000867
""" For detailed information please see http://shotgunsoftware.github.com/shotgunEvents/api.html Args based shared state ----------------------- This plugin demoes how three callbacks can share state through the args argument to registerCallback. The shared state stores two counters one (sequential) will be increm...
ack(scriptName, scriptKey, callbackB, args=_state) reg.registerCallback(scriptName, scriptKey, callbackC, args=_state) def callbackA(sg, logger, event, args): # We know callbackA will be called first because we registered it first. # As the first thing to run on each event, we can reinizialize the rotatin...
mple plugin, remember... Get the ids incremented and logged. printIds(*args) def callbackC(*args): # Just an example plugin, remember... Get the ids incremented and logged. printIds(*args) def printIds(sg, logger, event, args): # Here we can increment the two counters that are in shared state. Each ...
andymckay/zamboni
mkt/developers/management/commands/cleanup_addon_premium.py
Python
bsd-3-clause
364
0
from djang
o.core.management.base import BaseCommand import amo from mkt.webapps.models import AddonPremium class Command(BaseCommand): help = 'Clean up existing AddonPremium objects for free apps.' def handle(self, *args, **options): (AddonPremium.objects.filter(addon__premium_type__in=
amo.ADDON_FREES) .delete())
googleapis/python-datacatalog
samples/generated_samples/datacatalog_v1beta1_generated_data_catalog_get_iam_policy_async.py
Python
apache-2.0
1,506
0.000664
# -*- coding: utf-8 -*- # Copyright 2022 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...
strative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install
google-cloud-datacatalog # [START datacatalog_v1beta1_generated_DataCatalog_GetIamPolicy_async] from google.cloud import datacatalog_v1beta1 async def sample_get_iam_policy(): # Create a client client = datacatalog_v1beta1.DataCatalogAsyncClient() # Initialize request argument(s) request = datacat...
mauroalberti/gsf
pygsf/geometries/shapes/joins.py
Python
gpl-3.0
2,499
0.001601
from enum import Enum from typing import Union, List, Optional from .space2d import * from .space3d import * class JoinTypes(Enum): """ Enumeration for Line and Segment type. """ START_START = 1 # start point coincident with start point START_END = 2 # start point coincident with end point ...
f first.end_pt.is_coincident(second.start_pt): join_types.append(JoinTypes.END_START) if first.end_pt.is_coincident(second.end_pt): join_types.append(JoinTypes.END_END) re
turn join_types def analizeJoins3D( first: Union[Line3D, Segment3D], second: Union[Line3D, Segment3D] ) -> List[Optional[JoinTypes]]: """ Analyze join types between two lines/segments. :param first: a line or segment. :type first: Line or Segment. :param second: a line or segment....
taudor/pypuf_helper
test/test_transform_id.py
Python
gpl-3.0
677
0
import unittest from numpy import array, int8 from numpy.testing import assert_arr
ay_equal import pypuf_helper as ph class TestTransformID(unittest.TestCase): def test_01(self): k = 3 input_test = array([ [1, -1, 1, 1], [-1, -1, 1, 1] ], dtype=int8) result = array([
[[1, -1, 1, 1], [1, -1, 1, 1], [1, -1, 1, 1]], [[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]] ], dtype=int8) assert_array_equal( ph.transform_id(input_test, k), result, "transform_id fa...
ansible/ansible
lib/ansible/utils/display.py
Python
gpl-3.0
19,081
0.001992
# (c) 2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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 lat...
ing. We try first with ``wcswidth``, and fallback to iterating each character and using wcwidth individually, falling back to a value of 0 for non-printable wide characters On Py2, this depends on ``locale.setlocale(locale.LC_ALL, '')``, that in the case of Ansible is done in ``bin/ansible`` "...
: Display().warning( 'An error occurred while calling ansible.utils.display.initialize_locale ' '(%s). This may result in incorrectly calculated text widths that can ' 'cause Display to print incorrect line lengths' % _LOCALE_INITIALIZATION_ERR ) elif not _LOCALE_...
PetukhovVictor/compiler
src/Parser/AST/expressions/logical.py
Python
mit
1,676
0.002387
from Parser.AST.base import AST CLASS = "expressions.logical" class RelopBexp(AST): """ Relation operation boolean expression class for AST. interpret - runtime function for Evaluator (return result of applying the boolean operation to left and right values). Example: x > 56 """ def __init__(...
""" 'Or' operation boolean expression class for AST. interpret - runtime function for Evaluator (return result of applying the 'or' operation to left and right values). Example: x < 11 or x > 100 """ def __init__(self, left, right): super().__init__(CLASS, "or_bexp") self.left = le...
p(AST): """ 'Not' operation boolean expression class for AST. interpret - runtime function for Evaluator (return result of applying the 'not' operation to value). Example: x not 11 """ def __init__(self, exp): super().__init__(CLASS, "not_bexp") self.exp = exp self.child...
barriquello/iotstack
openwsn-fw-work/firmware/openos/bootloader/telosb/lib/nesdoc/components.py
Python
mit
3,812
0.018101
# Copyright (c) 2005 Intel Corporation # All rights reserved. # # This file is distributed under the terms in the attached INTEL-LICENSE # file. If you do not find these files, copies can be found by writing to # Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, # 94704. Attention: Intel ...
spec = xml_tag(comp, "specification") interfaces = spec.getElementsByTagName("interface") functions = spec.getElementsByTagName("function") spec = interfaces + functions provided = filter(lambda (x): x.getAttribute("provided") == "1", spec) used = filter(lambda (x): x.getAttribute("provided") == "0", spec)...
ace_compare) used.sort(interface_compare) generate_speclist(ht, "Provides", provided) generate_speclist(ht, "Uses", used) # wiring graph for configurations if xml_tag(comp, "configuration"): ht.tag("p") ht.heading("Wiring") ht.tag("p") ht.pushln("map", 'name="comp"') cmap = file("chtml/%...
Featuretools/featuretools
featuretools/utils/gen_utils.py
Python
bsd-3-clause
4,834
0.001241
import json import shutil import sys import warnings from itertools import zip_longest import s3fs from smart_open import open from tqdm import tqdm def session_type(): if 'IPython' not in sys.modules: # IPython hasn't been imported, definitely not return "python" from IPython import get_ipyt...
current = SCHEMA_VERSION.split('.') saved = version_string.split('.') warning_text_upgrade = ('The schema version of the saved %s'
'(%s) is greater than the latest supported (%s). ' 'You may need to upgrade featuretools. Attempting to load %s ...' % (cls_type, version_string, SCHEMA_VERSION, cls_type)) for c_num, s_num in zip_longest(current, saved, fillvalue=0): ...
cjaymes/pyscap
src/scap/model/oval_5/defs/independent/FileHash58TestElement.py
Python
gpl-3.0
902
0.001109
# Copyright 2016 Casey Jayme
s # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is distributed i
n the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http...
martflu/adaptive-audio
src/particle.py
Python
gpl-2.0
137
0.029197
imp
ort rectangle class particle: def __init__(self, x, y, w, h, c): self.rectangle = rectangle.rectangl
e(x, y, w, h, c)
fangohr/oommf-python
joommf/exceptions.py
Python
bsd-2-clause
39
0
class JoommfError(Ex
ception): pas
s
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/pldata/nltk_3.0a3/nltk/app/__init__.py
Python
mit
1,644
0.000608
# Natural Language Toolkit: Applications package # # Copyright (C) 2001-2013 NLTK Project # Author: Edward Loper <edloper@gmail.com> # Steven Bird <stevenbird1@gmail.com> # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Interactive NLTK Applications: chartparser: Chart Parser chunkpar...
rser_app import app as chartparser from .chunkparser_app import app as chunkparser from .collocations_app import app as collocations from .concordance_app import app as concordance from .nemo_app import app as nemo from .rdparser_app import app as rdparser from .srparser_app import app as srpars...
app as wordnet try: import pylab except ImportError: import warnings warnings.warn("nltk.app.wordfreq not loaded " "(requires the pylab library).") else: from .wordfreq_app import app as wordfreq # skip doctests from this package def setup_module(modu...
rwl/openpowersystem
ucte/operational_limits/voltage_limit.py
Python
agpl-3.0
1,642
0.004263
#------------------------------------------------------------------------------ # Copyright (C) 2009 Richard Lincoln # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation; version 2 dated June...
imitKind value = Voltage # >>> voltage_limit.attributes # <<< voltage_limit.refer
ences # @generated # >>> voltage_limit.references # <<< voltage_limit.operations # @generated # >>> voltage_limit.operations # EOF -------------------------------------------------------------------------
mbohlool/client-python
kubernetes/client/apis/custom_objects_api.py
Python
apache-2.0
69,951
0.003374
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os im...
ersion, plural, body, **kwargs): """ Creates a
cluster scoped Custom object This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_cluster_custom_object(group, version, plural, body, async=True) >>> result = thread.get() :param async bool ...
hornn/interviews
tools/bin/gppylib/system/osInterface.py
Python
apache-2.0
1,258
0.007154
#!/usr/bin/env python # # Copyright (c) Greenplum Inc 2009. All Rights Reserved. # """ This file defines the interface that can be used to fetch and update system configuration information, as well as the data object returned by the """ import os from gppylib.gplog import * from gppylib.utils import checkNotN...
ng python's sleep) # def sleep( self, sleepTime ) : raise Exception("not implemented") # # Management of registered configuration provider. Right now it # is a singleton, so initializeDatabase calls _could_ mess up # the singleton for other parts of code. Per
haps switch later # to a factory # gProvider = None def registerOsProvider(provider): global gProvider checkNotNone("New global osProvider", provider) if gProvider is not None: gProvider.destroy() gProvider = provider def getOsProvider(): global gProvider return checkNotNone("Globa...
cdondrup/pepper_planning
pepper_move_base/scripts/qualitative_move_base.py
Python
mit
3,768
0.004246
#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy from actionlib import SimpleActionClient from pnp_plugin_server.pnp_simple_plugin_server import PNPSimplePluginServer from pepper_move_base.msg import QualitativeMovePepperAction, QualitativeMovePepperResult from pnp_msgs.msg import ActionResult from nao_inte...
_pose.pose.position.x) target_pose = bl_pose target_p
ose.pose.position.x *= d target_pose.pose.position.y *= d target_pose.pose.orientation.x = 0. target_pose.pose.orientation.y = 0. target_pose.pose.orientation.z = math.sin(theta/2.) target_pose.pose.o...
magic0704/oslo.messaging
oslo_messaging/_drivers/zmq_driver/client/publishers/zmq_req_publisher.py
Python
apache-2.0
3,103
0
# Copyright 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 ...
ssaging._i18n import _LE, _LI LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class ReqPublisher(zmq_publisher_base.PublisherBase): def send_request(self, request): if request.msg_type != zmq_names.CALL_TYPE: raise zmq_publisher_base.UnsupportedSendPattern(request.msg_type) ...
elf._connect_to_host(request.target) self._send_request(socket, request) return self._receive_reply(socket, request) def _connect_to_host(self, target): try: self.zmq_context = zmq.Context() socket = self.zmq_context.socket(zmq.REQ) host = self.matchmak...
richardliaw/ray
rllib/utils/exploration/per_worker_gaussian_noise.py
Python
apache-2.0
1,807
0
from gym.spaces import Space from typing import Optional from ray.rllib.utils.exploration.gaussian_noise import GaussianNoise from ray.rllib.utils.schedules import ConstantSchedule class PerWorkerGaussianNoise(GaussianNoise): """A per-worker Gaussian noise class for distributed algorithms. Sets the `scale` ...
mework: Optional[str], num_worke
rs: Optional[int], worker_index: Optional[int], **kwargs): """ Args: action_space (Space): The gym action space used by the environment. num_workers (Optional[int]): The overall number of workers used. worker_index (Optional[int]): The index of the Wo...
CivicKnowledge/ambry
ambry/util/__init__.py
Python
bsd-2-clause
39,947
0.001252
"""Misc support code. Copyright (c) 2015 Civic Knowledge. This file is licensed under the terms of the Revised BSD License, included in this distribution as LICENSE.txt """ from collections import OrderedDict, defaultdict, Mapping, deque, MutableMapping, Callable from functools import partial, reduce, wraps import j...
e_algorithms#Least_Recently_Used ''' maxqueue = maxsize * 10 # @ReservedAssignment def decorating_function( user_function, len=len, iter=iter, tuple=tuple, sorted=sorted, KeyError=KeyError): cache = {} # mapping of args ...
round the queue kwd_mark = object() # separate positional and keyword args # lookup optimizations (ugly but fast) queue_append, queue_popleft = queue.append, queue.popleft queue_appendleft, queue_pop = queue.appendleft, queue.pop @wraps(user_function) def wrapper(*args...
noironetworks/neutron
neutron/agent/linux/dibbler.py
Python
apache-2.0
7,239
0
# Copyright 2015 Cisco Systems # 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...
'start', '-w', '%s' % dibbler_conf] return dibbler_cmd pm = external_process.ProcessManager( uuid=self.requestor_id, default_cmd_callback=callback, namespace=router_ns, service=PD_SERVICE_NAME, conf=cfg.C...
monitored_process=pm) def enable(self, pmon, router_ns, ex_gw_ifname, lla, prefix=None): LOG.debug("Enable IPv6 PD for router %s subnet %s ri_ifname %s", self.router_id, self.subnet_id, self.ri_ifname) if not self._is_dibbler_client_running(): dibbler_con...
del680202/MachineLearning-memo
src/tensorflow/cnn_deep_with_dropout.py
Python
apache-2.0
3,448
0.014211
from __future__ import print_function import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # number 1 to 10 data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) def compute_accuracy(v_xs, v_ys): global prediction y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep...
_2x2(h_conv3) #output size 4x4x128 ## func1 layer ## W_fc1 = weight_variable([4*4*128, 128])
b_fc1 = bias_variable([128]) h_pool2_flat = tf.reshape(h_pool3, [-1, 4*4*128]) #[n_samples, 4,4,128] => [n_samples, 4*4*128] h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) ### func2 layer ## W_fc2 = weight_variable([128, 128]) b_fc2 = bias_variable([128]) h_fc2 = tf.nn.relu(tf.matmul(h_fc1, W_fc2) + b_fc...