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
huaiping/pandora
score/apps.py
Python
mit
85
0
from django.a
pps import AppConfig class Sc
oreConfig(AppConfig): name = 'score'
Apstra/aeon-venos
pylib/aeon/nxos/autoload/guestshell.py
Python
apache-2.0
7,748
0.000645
# Copyright 2014-present, Apstra, Inc. All rights reserved. # # This source code is licensed under End User License Agreement found in the # LICENSE file at http://www.apstra.com/community/eula from collections import namedtuple import time import logging from functools import partial from aeon.nxos.exceptions import ...
self.sz_has = None self._state = None self.exists = False # --------------------------------------------------------------- # ----- # ----- PROPERTIES # ----- # --------------------------------------------------------------- @property def state(...
except CommandError: # means there is no guestshell self.exists = False self._state = 'None' return self._state try: self._state = got['TABLE_detail']['ROW_detail']['state'] return self._state except TypeError: #...
mfcovington/djangocms-shiny-app
cms_shiny/migrations/0005_shinyapppluginmodel.py
Python
bsd-3-clause
775
0.002581
# -*- coding: utf-8 -*- from __future__ import unicode_l
iterals from django.db import models, migrations class Migr
ation(migrations.Migration): dependencies = [ ('cms', '0010_migrate_use_structure'), ('cms_shiny', '0004_auto_20150415_0111'), ] operations = [ migrations.CreateModel( name='ShinyAppPluginModel', fields=[ ('cmsplugin_ptr', models.OneToOneFiel...
cemc/cscircles-wp-content
lesson_files/lesson18/primality-big.py
Python
gpl-3.0
206
0.038835
def isItPrime(N): # same as befor
e for D in r
ange(2, N): if N % D == 0: print(N, "is not prime; divisible by", D) return print(N, "is prime") isItPrime(324635459)
NSLS-II-XPD/ipython_ophyd
profile_collection/startup/10-motors.py
Python
bsd-2-clause
2,079
0.000962
"Define all the motors on the beamline" from ophyd import EpicsMotor import ophyd from ophyd import EpicsSignal th_cal = EpicsMotor('XF:28IDC-ES:1{Dif:2-Ax:Th}Mtr', name='th_cal') tth_cal = EpicsMotor('XF:28IDC-ES:1{Dif:2-Ax:2Th}Mtr', name='tth_cal') ecal_x = EpicsMotor('XF:28IDC-ES:1{Dif:2-Ax:X}Mtr', name='ecal_x') ...
or('XF:28IDC-ES:1{Stg:Smpl2-Ax:X}Mtr', name='ss_stg2_x') # Sanjit Inlcuded this. Delete it if anything goes wrong ss_stg2_y = EpicsMotor('XF:28IDC-ES:1{Stg:Smpl2-Ax:Y}Mtr', name='ss_stg2_y') ss_stg2_z = Epics
Motor('XF:28IDC-ES:1{Stg:Smpl2-Ax:Z}Mtr', name='ss_stg2_z') # RPI DIFFRACTOMETER motors ### Change th only after changing in other plans th = EpicsMotor('XF:28IDC-ES:1{Dif:1-Ax:Th}Mtr', name='th') tth = EpicsMotor('XF:28IDC-ES:1{Dif:1-Ax:2ThI}Mtr', name='tth') diff_x = EpicsMotor('XF:28IDC-ES:1{Dif:1-Ax:X}Mtr', name='...
Code4SA/pmg-cms-2
app.py
Python
apache-2.0
533
0.001876
from pmg import app from pmg.tasks import StartSc
heduler from pmg.models.soundcloud_track import SoundcloudTrack from flask_script import Server, Manager from flask_migrate import MigrateCommand app.debug
= True manager = Manager(app) manager.add_command("runserver", Server(port=5000, threaded=True, host="0.0.0.0")) manager.add_command("db", MigrateCommand) manager.add_command("start_scheduler", StartScheduler) @manager.command def sync_soundcloud(): SoundcloudTrack.sync() if __name__ == "__main__": manager...
astrellon/cotsb
client/.ycm_extra_conf.py
Python
mit
5,739
0.019341
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either...
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # For more information, please refer to <http://unlicense.org/> import os import ycm_core from sys import platform as _platform # These are the compilation ...
HANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. flags = [ '-Wall', '-Wextra', '-Werror', '-Wno-long-long', '-Wno-variadic-macros', '-fexceptions', '-DNDEBUG', # THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which # language to use when compiling headers. So it will g...
54lihaoxin/leetcode_python
src/SearchInRotatedSortedArrayII/test_suite.py
Python
apache-2.0
1,694
0.020661
from CommonClasses import * from solution import Solution class TestSuite: def run(self): # self.test000() # self.test001() self.test002() # self.test003() # self.test004() def test000(self): print 'test 000\n' ...
n = 3 startTime = time.clock() r = Solution().search(l, n) timeUsed = time.clock() - startTime print ' input:\t{0}, {1}'.format(l, n) # print ' expect:\t{0}'.format(?) print ' output
:\t{0}'.format(r) print ' time used:\t{0:.6f}'.format(timeUsed) print def main(argv): TestSuite().run() if __name__ == '__main__': main(sys.argv)
singnet/singnet
agent/adapters/tensorflow/imagenet/__init__.py
Python
mit
19,222
0.006139
# # adapters/tensorflow/imagenet/__init__.py - a service adapter for the tensorflow ImageNet pre-trained graph # # Copyright (c) 2018 SingularityNET # # Distributed under the MIT software license, see LICENSE file. # import base64 import logging import os from pathlib import Path from typing import List import tensor...
Service from sn_agent.
service_adapter import ServiceManager, ServiceAdapterABC IMAGENET_CLASSIFIER_ID = 'deadbeef-aaaa-bbbb-cccc-111111111102' logger = logging.getLogger(__name__) FLAGS = None AGENT_DIRECTORY = Path(__file__).parent CHECK_ACCURACY = False MINIMUM_SCORE = 0.20 class TensorflowImageNet(ServiceAdapterABC): type_nam...
hyokun31/wisekb-management-platform
wisekb-uima-ducc/cassandra-server/pylib/cqlshlib/__init__.py
Python
apache-2.0
784
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this
file # to you under the Apache License, Version 2.0 (the # "License"); you may not 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...
THOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
tchellomello/home-assistant
tests/components/canary/__init__.py
Python
apache-2.0
1,712
0.000584
"""Tests for the canary component.""" from unittest.mock import MagicMock, PropertyMock from canary.api import SensorType def mock_device(device_id, name, is_online=True, device_type_name=None): """Mock Canary Device class.""" device = MagicMock() type(device).device_id = PropertyMock(return_value=device...
alue=name) type(device).is_online = PropertyMock(return_value=is_online) type(device).device_
type = PropertyMock( return_value={"id": 1, "name": device_type_name} ) return device def mock_location( location_id, name, is_celsius=True, devices=None, mode=None, is_private=False ): """Mock Canary Location class.""" location = MagicMock() type(location).location_id = PropertyMock(r...
noba3/KoTos
addons/plugin.video.mediathek/mediathek/ard.py
Python
gpl-2.0
8,249
0.041338
# -*- coding: utf-8 -*- #-------------LicenseHeader-------------- # plugin.video.Mediathek - Gives access to most video-platforms from German public service broadcasters # Copyright (C) 2010 Raptor 2101 [raptor2101@gmx.de] # # This program is free software: you can redistribute it and/or modify # it under the terms of...
list(self.regex_VideoPageLink.finditer(mainPage)); linkElements = list(self.regex_CategoryPageLink.finditer(mainPage)); counter = len(videoElements) + len(linkElements);
for element in linkElements: link = self.rootLink+element.group(1); title = element.group(2).decode('utf-8'); subTitle = element.group(3).decode('utf-8'); self.gui.buildVideoLink(DisplayObject(title,subTitle,"","",link,False),self,counter); for element in videoElements: videoId = elem...
lnielsen/invenio
invenio/modules/ranker/fixtures.py
Python
gpl-2.0
1,274
0.010989
# -*- coding: utf-8 -*- # ## This file is part of Invenio. ## Copyright (C) 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) an...
the GNU General Public License ## along with Invenio; if not, write to the Free Software Fou
ndation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from fixture import DataSet from invenio.modules.search.fixtures import CollectionData class RnkMETHODData(DataSet): class RnkMETHOD_1: last_updated = None id = 1 name = u'wrd' class CollectionRnkMETHODData(DataS...
afrolov1/nova
nova/api/openstack/compute/plugins/v3/server_diagnostics.py
Python
apache-2.0
2,189
0.000457
# 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...
ontext"] authorize(context) compute_api = compute.API() try: instance = compute_api.get(context, server_id, want_objects=True) except exception.InstanceNotFound as e: raise webob.exc.HTTPNotFound(expla
nation=e.format_message()) try: return compute_api.get_diagnostics(context, instance) except exception.InstanceInvalidState as state_error: common.raise_http_conflict_for_instance_invalid_state(state_error, 'get_diagnostics') class ServerDiagnostics(extensi...
OpenTreeOfLife/opentree
curator/languages/it.py
Python
bsd-2-clause
9,673
0.026605
# coding: utf8 { '!=': '!=', '!langcode!': 'it', '!langname!': 'Italiano', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOI...
gistrati', 'register': '
registrazione', 'Registration identifier': 'Registration identifier', 'Registration key': 'Chiave di Registazione', 'Registration successful': 'Registrazione avvenuta', 'reload': 'reload', 'Remember me (for 30 days)': 'Ricordami (per 30 giorni)', 'Request reset password': 'Richiedi il reset della password', 'Reset Pass...
maerteijn/python-postnl-locations
postnl/locations/client.py
Python
bsd-3-clause
3,143
0
from datetime import datetime, timedelta from suds import client, wsse import time from .utils import recursive_asdict, load_class class Locations(object): """Convenience class to communicate with the PostNL SOAP API""" def __init__(self, settings): self.settings = settings security = wsse.S...
cation.AllowSundaySorting = self.settings.get( 'allow_sunday_sorting', True) delivery_options = self.client.factory.create("ns3:ArrayOfstring") delivery_options.string = self.settings.get('delivery_options', ["PG
"]) location.DeliveryOptions = delivery_options options = self.client.factory.create("ns3:ArrayOfstring") options.string = self.settings.get('options', ["Daytime"]) location.Options = options return location def nearest_locations(self, postalcode, deliverydate=None): ...
kutenai/django
docs/conf.py
Python
bsd-3-clause
12,643
0.001503
# -*- coding: utf-8 -*- # # Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklabl...
fic and customize the look and feel of a theme # furt
her. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation...
reflectometry/direfl
setup_py2exe.py
Python
mit
12,830
0.0053
#!/usr/bin/env python # Copyright (C) 2006-2010, University of Maryland # # 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 us...
['libgdk_pixbuf-2.0-0.dll', 'libgobject-2.0-0.dll', 'libgdk-win32-2.0-0.dll', 'tcl84.dll', 'tk84.dll', 'QtGui4.dll', 'QtCore4.
dll', 'msvcr71
GoogleCloudPlatform/training-data-analyst
quests/data-science-on-gcp-edition1_tf2/04_streaming/simulate/df02.py
Python
apache-2.0
1,395
0.017204
#!/usr/bin/env python3 # Copyright 2016 Google 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 o...
implied. # See the License for the specific language governing permissions and # limitations under the License. import apache_beam as beam import csv def addtimezone(lat, lon): try: import timezonefinder tf = timezonefinder.TimezoneFinder() tz = tf.timezone_at(lng=float(lon), lat=float(lat)) ...
ine('DirectRunner') as pipeline: airports = (pipeline | beam.io.ReadFromText('airports.csv.gz') | beam.Map(lambda line: next(csv.reader([line]))) | beam.Map(lambda fields: (fields[0], addtimezone(fields[21], fields[26]))) ) airports | beam.Map(lambda f: '{},{}'.format(f[0]...
seece/cbpp
util.py
Python
mit
3,489
0.045285
import re class ArgumentList: #length = 0 # the length of the original argument list in characters #arr = [] # array of argument strings def __init__(self, length, arr): self.length = length self.arr = arr class StringPos: start = 0 end = 0 def __init__(self, pstart, pend): self.start = pstart self...
turn False return string[i] def stripComments(line): length = len(line) lastchar = "" instring = False # iterate line from right to left for i,
c in enumerate(reversed(line)): if instring and c!='"': continue if c=='"': instring = not instring # negation continue # if we hit a comment character outside a string if (lastchar == "/" and c == "/") or c == "'": return line[:(length-i-1)] + "\n" lastchar = c return line # the commen...
Bionetbook/bionetbook
bnbapp/bionetbook/_old/actions/models.py
Python
mit
3,335
0.002399
from django.core.urlresolvers import reverse from django.db import models from django.db.models import ObjectDoesNotExist from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ from django_extensions.db.models import TimeStampedModel from jsonfield import JSONField ...
ES class Action(TimeStampedModel): VERB_CHOICES = VERB_CHOICES step = models.ForeignKey(Step) name = models.CharField(_("Name"), max_length=255) slug = models.SlugField(_("Slug"), blank=True, null=True, max_length=255) duration_in_seconds = models.IntegerField(_("Dur
ation in seconds"), blank=True, null=True) verb = models.CharField(max_length=50, choices=VERB_CHOICES) verb_attributes = JSONField(blank=True, null=True) raw = models.TextField(blank=True, null=True) @property def protocol(self): return Protocol.objects.get(step__action=self) def __un...
AndreasMadsen/grace
Code/figures/ols_world_pca.py
Python
mit
2,246
0.020926
# -*- coding: utf-8 -*- from setup import * import grace import grace.ols import os.path as path import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.basemap as maps H = grace.ols.hat_matrix() days = grace.ols.time_vector() # # Compute the U tensor # # Get the ewh values for all positions as a ma...
0=0, resolution='c') m.drawcoastlines(linewidth=.5) m.drawparallels(np.arange(-90.,120.,30.), labels=[1,0,0,0]) m.drawmeridians(np.arange(0.,420.,60.), labels=[0,0,0,1]) im = m.imshow(U_grid[::-1,:,pc]) im.set_cmap('binary_r') m.colorbar() fig.savefig(figure_path('ols-pca-score-%d.pdf' %
(pc))) # # Plot Principal Compoent loadings # fig = plt.figure(figsize=(10, 4)) years_split = grace.times.date_to_days( np.unique( grace.times.days_to_date(days).astype('datetime64[Y]') ).astype('datetime64[D]')[1:] ) plt.plot(days, V[:, pc].A.ravel(), color="SteelBlue") plt.ylim(*plt.ylim()) plt.vli...
jmcnamara/XlsxWriter
xlsxwriter/test/comparison/test_textbox31.py
Python
bsd-2-clause
1,070
0
############################################################################### # # Tests for XlsxWriter. # # SP
DX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_compar
ison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename('textbox31.xlsx') self.ignore_elements = {'xl/drawings/...
DeflatedPickle/Colony
gametime.py
Python
mit
2,265
0.002208
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """""" import inspect import colony from colony.entities.attributes import Age __title__ = "GameTime" __author__ = "DeflatedPickle" __version__ = "1.1.1" class GameTime(object): def __init__(self, parent): self.parent = parent self._time = colony....
return "Morning" elif 12 <= self._time.get_hours().get() <= 18: return "Afternoon" elif 18 <= self._time.get_hours().get() <= 24: return "Evening" def update_time(self): self._time.increase_time(0, 0, 1) self._time.check_t
ime() self.parent.time_frame.time_formatted_variable.set(self._time.get_time_formatted()) self.parent.time_frame.time_world_variable.set(self.get_world_time_string()) if self._time.get_hours().get() == 0 and self._time.get_minutes().get() == 0 and self._time.get_seconds().get() == 0: ...
Yukarumya/Yukarum-Redfoxes
testing/mozbase/mozhttpd/tests/requestlog.py
Python
mpl-2.0
1,221
0.001638
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import mozhttpd import urllib2 import os import unittest import mozunit here = os.path.dirname(os.path.abspath(__file_...
request_log def test_logging_enabled(self): request_log = self.check_logging(log_requests=True) self.assertEqual(len(request_log), 1) log_entry = req
uest_log[0] self.assertEqual(log_entry['method'], 'GET') self.assertEqual(log_entry['path'], '/') self.assertEqual(type(log_entry['time']), float) def test_logging_disabled(self): request_log = self.check_logging(log_requests=False) self.assertEqual(len(request_log), 0) if...
Jumpscale/jumpscale_examples7
examples/serializers/blowfishtest.py
Python
apache-2.0
482
0.002075
import os import struct from JumpScale import j import JumpScale.baselib.serializers j.application.start("blowfishtest") from random import randrange msg = "" for i in range(1000): msg += chr(randrange(0, 256)) key = "" for i in range(56): key += chr(randrange(0, 256)) # b means blowfish s = j.db.serial...
b", key=key) nr =
100000 j.base.timer.start() for i in range(nr): data = s.dumps(msg) j.base.timer.stop(nr) j.application.stop()
praekelt/molo-ndoh-yep
ndohyep/settings/__init__.py
Python
bsd-2-clause
27
0
from b
ase import * #
noqa
js850/nested_sampling
nested_sampling/tests/_test_ns.py
Python
bsd-2-clause
2,120
0.008962
import unittest import numpy as np import socket import Pyro4 from nested_sampling import NestedSampling, MonteCarloWalker, Harmonic, Replica class TestNS(unittest.TestCase): """to test distributed computing must start a dispatcher with --server-name test and --port 9090 """ def setUp(self): self.s...
def setUp1(self, nproc=1, multiproc=True): self.ndim = 3 self.harmonic = Harmonic(self.ndim) self.nreplicas = 10 self.stepsize = 0.1 self.nproc = nproc self.mc_runner = MonteCarl
oWalker(self.harmonic, mciter=40) if multiproc == False: hostname=socket.gethostname() host = Pyro4.socketutil.getIpAddress(hostname, workaround127=True) self.dispatcher_URI = "PYRO:"+"test@"+host+":9090" else: self.dispatcher_URI = None ...
home-assistant/home-assistant
homeassistant/components/local_ip/sensor.py
Python
apache-2.0
1,075
0
"""Sensor platform for local_ip.""" from homeassistant.components.network import async_get_source_ip from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.he...
:ip" def __init__(self, name: str) -> None: """Initialize the sensor.""" self._attr_name = name async def async_update(self) -> None: """Fetch new state data for the sensor.""" self._attr_native_value = aw
ait async_get_source_ip(self.hass)
SINGROUP/pycp2k
pycp2k/classes/_thermostat_energy5.py
Python
lgpl-3.0
352
0.005682
from pycp2k.inputsection import InputSection class _thermostat_energy5(InputSection): def __init__(self): InputSection.__init__(self) self.Default_
keyword = [] self._name = "T
HERMOSTAT_ENERGY" self._repeated_default_keywords = {'Default_keyword': 'DEFAULT_KEYWORD'} self._attributes = ['Default_keyword']
RedHatInsights/insights-core
insights/parsers/tests/test_gluster_peer_status.py
Python
apache-2.0
1,655
0.002417
import doctest import pytest from insights.parsers import gluster_peer_status, SkipException from insights.tests import context_wrap OUTPUT = """ Number of Peers: 1 Hostname: versegluster1.verse.loc Uuid: 86c0266b-c78c-4d0c-afe7-953dec143530 State: Peer in Cluster (Connected) """.strip() OUTPUT_1 = """ Number of Pee...
b3'} ] def test_blank_output(): with pytest.raises(SkipException) as e: gluster_peer_status.GlusterPeerStatus(context_wrap("")) assert "No data." in str(e) def test_documentation(): failed_count, tests = doctest.te
stmod( gluster_peer_status, globs={'output': gluster_peer_status.GlusterPeerStatus(context_wrap(OUTPUT))} ) assert failed_count == 0
chrisbarber/dask
dask/dataframe/tests/test_hashing.py
Python
bsd-3-clause
899
0
import numpy as np import pandas as pd import pytest from dask.dataframe.
hashing import hash_pandas_object from dask.dataframe.utils import assert_eq @pytest.mark.parametrize('obj', [ pd.Series([1, 2, 3]), pd.Series([1.0, 1.5, 3.2]), pd.Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]), pd.Series(['a', 'b', 'c']), pd.Series([True, False, True]), pd.Index([1, 2, 3]), ...
), pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3]}), pd.util.testing.makeMissingDataframe(), pd.util.testing.makeMixedDataFrame(), pd.util.testing.makeTimeDataFrame(), pd.util.testing.makeTimeSeries(), pd.util.testing.makeTimedeltaIndex()]) def test_hash_pandas_object(obj): a = hash_pand...
jhajek/euca2ools
euca2ools/commands/iam/createsigningcertificate.py
Python
bsd-2-clause
2,698
0
# Copyright 2009-2015 Eucalyptus Systems, Inc. # # Redistribution and use of this software 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 ...
current user)'''), Arg('--out', metavar='FILE', rout
e_to=None, help='file to write the certificate to (default: stdout)'), Arg('--keyout', metavar='FILE', route_to=None, help='file to write the private key to (default: stdout)'), AS_ACCOUNT] def postprocess(self, result): if self.args['out']: ...
Fly33/telegram-ingress-bot
src/main.py
Python
bsd-2-clause
1,204
0.003322
# -*- coding: utf8 -*- import logging import logging.handlers import traceback from argparse import ArgumentParser from config import Config from telegram import Telegram TRACE = 5 def main(): parser = ArgumentParser() parser.add_argument("-c", "--config", help="yaml config file name", defau...
parser.parse_args() config = Config()
try: config.load(args.config) except: logging.error('Unable to open "{}" file.'.format(options.config)) return level = TRACE logging.addLevelName(TRACE, "TRACE") logger = logging.getLogger() logger.setLevel(level) formatter = logging.Formatter("%(asctime)s [%...
GoogleCloudPlatform/python-docs-samples
people-and-planet-ai/timeseries-classification/trainer.py
Python
apache-2.0
10,308
0.000873
# Copyright 2021 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 agreed to in writing, ...
artesian_coordinates class GeoPoint(keras.layers.Layer): def call(self: Any, latlon: Tuple[tf.Tensor, tf.Tensor]) -> tf.Tensor: lat, lon = latlon x = tf.cos(lon) * tf.sin(lat) y = tf.sin(lon) * tf.sin(lat) z = tf.cos(lat) ...
input_layers[lon_name]) return GeoPoint(name=f"{lat_name}_{lon_name}")(lat_lon_input_layers) def sequential_layers( first_layer: keras.layers.Layer, *layers: keras.layers.Layer ) -> keras.layers.Layer: return reduce(lambda layer, result: result(layer), layers, first_layer) preproc...
wodore/wodore-gae
main/control/tag.py
Python
mit
3,565
0.01655
# coding: utf-8 import copy from flask.ext import login from flask.ext import wtf from google.appengine.ext import ndb import flask import wtforms import auth import cache import config import model import task import util from main import app ######################################################################...
ol_id') tag = tag or util.param('tag') if col_id and col_id!=model.Collection.top_id(): col_key = model.Collection.id_to_key(col_id) col_db = col_key.get() else: col_ke
y = model.Collection.top_key() col_db = None if tag: tag_db = model.Tag.tag_to_key(tag,col_key).get() else: tag_db = None form = TagUpdateForm(obj=tag_db) if form.validate_on_submit(): if form.icon.data: fs = flask.request.files.getlist("icon") if fs: icon = data=fs[0].rea...
PeRDy/django-audit-tools
audit_tools/audit/cache.py
Python
gpl-2.0
2,088
0.001437
# -*- encoding: utf-8 -*- """ Module that defines an internal cache for managing processes and accesses through threads. """ from __future__ import unicode_literals import threading from mongoengine import DoesNotExist __all__ = ['cache'] THREAD_NAMESPACE = threading.local() class Cache(object): """ Cache...
ccess.
:rtype: :class:`audit_tools.audit.Access` """ a = getattr(self.namespace, "audit_current_access", None) return a def set_last_access(self, access): """ Set last access. :param access: Access object. :type access: :class:`audit_tools.audit.Access` "...
CharlesShang/FastMaskRCNN
libs/layers/roi.py
Python
apache-2.0
6,976
0.020642
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import libs.boxes.cython_bbox as cython_bbox import libs.configs.config_v1 as cfg from libs.boxes.bbox_transform import bbox_transform, bbox_transform_inv, clip_boxes from libs.logs.log impo...
verlaps.max(axis=1) # R max_overlaps = overl
aps[np.arange(rois.shape[0]), gt_assignment] # note: this will assign every rois with a positive label # labels = gt_boxes[gt_assignment, 4] labels = np.zeros([num_rois], dtype=np.float32) labels[:] = -1 # if _DEBUG: # print ('gt_assignment') # print (gt_assignment) ...
drabastomek/practicalDataAnalysisCookbook
Codes/Chapter08/graph_handling.py
Python
gpl-2.0
7,099
0.000704
import networkx as nx import networkx.algorithms as alg import numpy as np import matplotlib.pyplot as plt # create graph object twitter = nx.Graph() # add users twitter.add_node('Tom', {'age': 34}) twitter.add_node('Rachel', {'age': 33}) twitter.add_node('Skye', {'age': 29}) twitter.add_node('Bob', {'age': 45}) twit...
']['Skye']['relationship'] = 'friend' twitter['Greg']['Bob']['relationship'] = 'friend' twitter['Peter']['Greg']['relationship'] = 'friend' twitter['Lester']['Matt']['relationship'] = 'friend' twitter['Max']['Matt']['relationship'] = 'friend' twitter
['Rachel']['Linda']['relationship'] = 'friend' twitter['Tom']['Linda']['relationship'] = 'friend' twitter['Bart']['Greg']['relationship'] = 'sibling' twitter['Tom']['Greg']['relationship'] = 'sibling' twitter['Peter']['Lester']['relationship'] = 'generation' twitter['Tom']['Mike']['relationship'] = 'friend' twitter['Ra...
opencord/voltha
tests/atests/common/preprovisioning.py
Python
apache-2.0
8,118
0.005051
# # Copyright 2018 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
self.__onuCount = None self.__fields = [] self.__oltDeviceId = None def p_set_log_dirs(self, log_dir): testCaseUtils.config_dirs(self, log_dir) def p_configure(self, olt_ip_address, olt_port,
olt_type, onu_type, onu_count): self.__oltIpAddress = olt_ip_address self.__oltPort = olt_port self.__oltType = olt_type self.__onuType = onu_type self.__onuCount = onu_count def preprovision_olt(self): logging.info('Do PROVISIONING') testCaseUtils.send_comma...
andrewjss/uftrace
tests/t072_no_comment.py
Python
gpl-2.0
621
0.00161
#!/usr/bin/env python from runtest import TestBase class TestCase(TestBase): def __init__(self): TestBase.__init__(self, 'abc', """ # DURATION TID FUNCTION 0.508 us [ 772] | __monstartup(); 0.425 us [ 772] | __cxa_atexit(); [ 772] | main() { [ 772] | a() { ...
[ 772] | c(
) { 0.419 us [ 772] | getpid(); 0.844 us [ 772] | } 1.037 us [ 772] | } 1.188 us [ 772] | } 1.378 us [ 772] | } """) def runcmd(self): return '%s --no-comment %s' % (TestBase.ftrace, 't-abc')
SPIhub/hummingbird
src/utils/cmdline_args.py
Python
bsd-2-clause
2,729
0.005497
import sys import logging import argparse argparser = argparse.ArgumentParser(description='Hummingbird - ' 'Monitoring and Analysing FXI experiments.') _group = argparser.add_mutually_exclusive_group() _group.add_argument("-i", "--interface", help="start the con...
type=int, default=13131, help="overwrites the port, defaults to 13131") argparser.add_argument("-I", "--influxdb", const="influxdb://localhost/hummingbird", type=str, help="spool all scalar data to the specified InfluxDB instance", nargs = "?") argparser.add_argument("-v", ...
ment("-d", "--debug", help="output debug messages", action="store_true") argparser.add_argument("--profile", help="generate and output profiling information for the backend", action="store_true") argparser.add_argument("--no-restore", help="no restoring of Qsettings", ...
chuajiesheng/twitter-sentiment-analysis
apology/scripts/extraction.py
Python
apache-2.0
10,235
0.000782
import os from datetime import timezone, timedelta, datetime import json import csv def read_directory(directory_name): files = [] for (dirpath, dirnames, filenames) in os.walk(directory_name): files.extend(filenames) break return files def read_file(filename): is_tweet = lambda json...
674953612850798592', 'tag:search.twitter.com,2005:674953546610135041', 'tag:search.twitter.com,2005:675001
499311874048', 'tag:search.twitter.com,2005:675022070858784768', 'tag:search.twitter.com,2005:675126448173285377', 'tag:search.twitter.com,2005:676410019798228992', 'tag:search.twitter.com,2005:676449585385050112', 'tag:search.twitter.com,2005:676496351610462208', 'tag:search.twitter.com,2005:67...
josecostamartins/pythonreges
aula10/funcionario.py
Python
mit
1,679
0.010131
# -*- coding: utf-8 -*- # from __future__ import (unicode_literals, nested_scopes, generators, division, # absolute_import, with_statement, print_function) import datetime import math class Funcionario(object): def __init__(self, nome = "Albert", sobrenome = "Einstein", idade = 29, salari...
ncionario.sobrenome # print funcionario.cargo # print funcionario.salario # # # # marcos = Funcionario() # print marcos.sobrenome # print marcos.nome # # programador = Programador() # print pro
gramador.sobrenome # print programador.cargo # print programador.salario # print type([]) # print type((1,)) # print type(Usuario) # print type(usuario) # print Funcionario.__dict__ # print Funcionario.__bases__
yanchen036/tensorflow
tensorflow/contrib/data/python/ops/iterator_ops_test.py
Python
apache-2.0
4,700
0.004468
# Copyright 2018 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...
_add(1) latest_feature = variables.Variable( 0, name='latest_feature', dtype=dtypes.int64) store_latest_feature_op = latest_feature.assign(features) ops.add_to_collection('my_vars', global_step) ops.add_to_collection('my_vars',
latest_feature) return model_fn.EstimatorSpec( mode='train', train_op=control_flow_ops.group( [update_global_step_op, store_latest_feature_op]), loss=constant_op.constant(2.0)) def _read_vars(self, model_dir): """Returns (global_step, latest_feature).""" with ops.Grap...
BerenLuthien/HyperColumns_ImageColorization
TensorflowUtils.py
Python
bsd-3-clause
11,368
0.003343
__author__ = 'Charlie' # Utils used with tensorflow implemetation import tensorflow as tf import numpy as np import os, sys from six.moves import urllib import tarfile import zipfile from skimage import io, color import scipy.io def maybe_download_and_extract(dir_path, url_name, is_tarfile=False, is_zipfile=False): ...
(alpha * x, x, name) def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1
, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") def batch_norm(x, n_out, phase_train, scope='bn', decay=0.9, eps=1e-5, stddev=0.02): """ Code taken from http://stackoverflow.com/a/34634291/2267819 """ with tf.variable_scope(scope): beta = tf.get_variable(name='beta', shape=[n_out], initializ...
a10networks/a10sdk-python
a10sdk/common/A10BaseClass.py
Python
apache-2.0
37,904
0.005197
__author__ = 'mthompson' import copy import inspect import importlib import urllib import json from urlparse import urlparse import collections import re import os import keyword import sys reload(sys) sys.setdefaultencoding('utf-8') class A10BaseClass(object): is_POST = True def __init__(self): self...
r_name, sub_class)(DeviceProxy=DeviceProxy) except: try: sub_class = ''.join(x for x in k.replace("-", "_").replace("list", "").replace("list", ...
if not x.isspace()) obj_class = getattr(caller_name, sub_class)(DeviceProxy=DeviceProxy) except: #(RAUNAK):Added one more check for the VLAN tagged_ethernet_list like cases #Would check for the class with the na...
rjamorim/netsec-hw1
server.py
Python
unlicense
3,585
0.012831
# Network Security Spring 2015 Assignment 1 # Programming problem # Roberto Amorim - rja2139 import argparse import socket import os.path # Here I take care of the command line arguments parser = argparse.ArgumentParser(description='Server that holds encrypted data until client requests it.', add_help=True) parser.a...
sending = "serverdata" sock = socket.socket() try: sock.bind(("localhost", port2
)) except: print "Error binding to the requested port " + str(port2) + ". Do you have permission to bind to it?" os.remove("ServerTempFile") #cleanup exit(1) sock.listen(5) # First I send the signature client2sock, client2addr = sock.accept() print "Client 2 connected from " + client2addr[0] client2sock.se...
unnikrishnankgs/va
venv/lib/python3.5/site-packages/jupyter_console/ptshell.py
Python
bsd-2-clause
32,196
0.003386
"""IPython terminal interface using prompt_toolkit in place of readline""" from __future__ import print_function import base64 import errno from getpass import getpass from io import BytesIO import os import signal import subprocess import sys import time from warnings import warn try: from queue import Empty # ...
andler. This option is a list of string where the first element is the command itself and reminders are the options for the command. You can use {file} and {format} in the string to represent the location of the generated image file and image format. """ ) callable_ima...
hich is `msg["content"]["data"]` where `msg` is the message from iopub channel. For exmaple, you can find base64 encoded PNG data as `data['image/png']`. If your function can't handle the data supplied, it should return `False` to indicate this. """ ) mime_preference = ...
yeti/signals
signals/helpers.py
Python
mit
586
0
import os.path import glob def recursively_find_parent_containing_file(current_path, search_files): # Convert to absolute path, in case we received relative path current_path = os.path.abspath(current_path) while current_path
!= os.sep: for current_file in search_files: # Check if this path has any of the files we're looking for if len(glob.glob(current_path + os.sep + current_file)) > 0: return current_path, current_file current_path = os.path.normpath(os.path.join(current_
path, "..")) return None, None
MikeMatrix/ACE3
tools/stringtableduplicates.py
Python
gpl-2.0
1,652
0.001211
#!/usr/bin/env python3 import os import sys import xml.dom from xml.dom import minidom # STRINGTABLE DIAG TOOL # Author: KoffeinFlummi # --------------------- # Counts duplicates stringtable entries def check_module(projectpath, module): """ Checks the given module for all the different languages. """ loca...
##############") print("# Stringtable Duplicates Tool #") print("###############################\n") duplicates = 0 for module in os.listdir(proj
ectpath): d = check_module(projectpath, module) print("# {} {}".format(module.ljust(20), d)) duplicates += d print("\nTotal number of duplicates: {}".format(duplicates)) if __name__ == "__main__": main()
PetePriority/home-assistant
tests/components/sensor/test_rest.py
Python
apache-2.0
12,509
0
"""The tests for the REST sensor platform.""" import unittest from pytest import raises from unittest.mock import patch, Mock import requests from requests.exceptions import Timeout, MissingSchema, RequestException import requests_mock from homeassistant.exceptions import PlatformNotReady from homeassistant.setup imp...
onnectionError()) def test_setup_failed_connect(self, mock_req): """Test setup when connection error occurs.""" with raises(PlatformNotReady): rest.setup
_platform(self.hass, { 'platform': 'rest', 'resource': 'http://localhost', }, lambda devices, update=True: None) @patch('requests.Session.send', side_effect=Timeout()) def test_setup_timeout(self, mock_req): """Test setup when connection timeout occurs.""" ...
comsaint/ccbc-library
ccbc_library/wsgi.py
Python
mit
441
0.004535
""" WSGI config for ccbc_library 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_SETTING
S_MODULE", "ccbc_library.deploy_settings") from django.core.wsgi import get_wsgi_application from dj_static import Cling application = Cling(get_wsgi_application())
mchwalisz/thingspeak
examples/thingspeak_cpu_loop.py
Python
lgpl-3.0
778
0.001285
from time import localtime, strftime # download from http://code.google.com/p/psutil/ import psutil import time import thingspeak channel_id = 0 # PUT CHANNEL ID HERE write_key = 0 # PUT YOUR WRITE KEY HERE def doit(channel): cpu_pc =
psutil.cpu_percent() mem_avail_mb = psutil.virtual_memory().percent try: response = channel.update({1: cpu_pc, 2: mem_
avail}) print(cpu_pc) print(mem_avail_mb) print(strftime("%a, %d %b %Y %H:%M:%S", localtime())) print(response) except: print("connection failed") # sleep for 16 seconds (api limit of 15 secs) if __name__ == "__main__": channel = thingspeak.Channel(id=channel_id, write_...
bretlowery/snakr
lib/django/middleware/clickjacking.py
Python
bsd-3-clause
1,983
0
""" Clickjacking Protection Middleware. This module provides a middleware that implements protection against a malicious site loading resources from your site in a hidden frame. """ from django.conf import settings class XFrameOptionsMiddleware(object): """ Middleware that sets th
e X-Frame-Options HTTP header in HTTP responses. Does not set the header if it's already set or if the response contains a xframe_options_exempt value set to True. By default, sets the X-Frame-Options header to 'SAMEORIGIN', meaning the response can only b
e loaded on a frame within the same site. To prevent the response from being loaded in a frame in any site, set X_FRAME_OPTIONS in your project's Django secure to 'DENY'. Note: older browsers will quietly ignore this header, thus other clickjacking protection techniques should be used if protection in ...
Aurantia/AurantiaWebService
aurantia_webservice/core/utils.py
Python
gpl-3.0
973
0.018499
#!/usr/bin/env python # -*- encoding: utf-8 -*- from random import randrange from flask import jsonify from aurantia_webservice.models import Arduino def find_arduino(ip): ip_founded = Arduino.query.filter_by(ip_address=str(ip)).first() if ip_founded is not None: return True return False def ch...
e, message): resp_data = { 'code': str(code), 'message' : message
} resp = jsonify(resp_data) resp.status_code = int(code) return resp def generate_random_ip(): not_valid = [10,127,169,172,192] first = randrange(1,256) while first in not_valid: first = randrange(1,256) ip = ".".join([str(first),str(randrange(1,256)), str(randrange(1...
opencord/voltha
netconf/nc_rpc/base/delete_config.py
Python
apache-2.0
1,360
0
#!/usr/bin/env python # # Copyright 2017 the original author or 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 require...
Rpc)
: def __init__(self, request, request_xml, grpc_client, session, capabilities): super(DeleteConfig, self).__init__(request, request_xml, grpc_client, session, capabilities) self._validate_parameters() def execute(self): log.inf...
Normation/rudder-tools
contrib/inventory-hooks/aws.py
Python
gpl-3.0
2,553
0.007051
#!/bin/sh # vim: syntax=python ''':' # First try to run this script with python3, else run with python then python2 if command -v python3 >/dev/null 2>/dev/null; then exec python3 "$0" "$@" elif command -v python >/dev/null 2>/dev/null; then exec python "$0" "$@" else exec python2 "$0" "$@" fi ''' """ Rudder in...
if data.status_code == 404: return for key in data.text.split('\n'): if not key: continue if key in [ "rsa2048", "pkcs7", "signature", "security-credentials/", "user-data" ]: continue newurl = '{0}{1}'.format(url, key) if key.endswith('/'): ...
, k[newkey], ) else: data = requests.get(newurl) if data.status_code != 404: try: k[key] = json.loads(data.text) except ValueError: k[key] = data.text else: k[key] = None if __name__ == ...
anhstudios/swganh
data/scripts/templates/object/tangible/deed/event_perk/shared_fed_dub_2x10_honorguard_deed.py
Python
mit
491
0.044807
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/event_perk/shared_fed_dub_2x10_honorguard_deed.iff"
result.attribute_template_id = 2 result.stfName("event_perk","fed_dub_2x10_honorguard_deed_name") #### BEGIN MODIFICATIONS #### ####
END MODIFICATIONS #### return result
ska-sa/casperfpga
src/onegbe.py
Python
gpl-2.0
26,401
0.004167
import logging import struct from memory import Memory from network import Mac, IpAddress from gbe import Gbe LOGGER = logging.getLogger(__name__) # Offsets for fields in the memory map, in bytes OFFSET_CORE_TYPE = 0x0 OFFSET_BUFFER_SIZE = 0x4 OFFSET_WORD_LEN = 0x8 OFFSET_MAC_ADDR = 0xc OFFSET_IP_ADDR = ...
.name, )) if reply.arguments[0] != 'ok': raise RuntimeError('%s: failure starting DHCP client.' % self.name) reply, _ = self.parent.transport.katcprequest( name='tap-arp-config', request_timeout=1, require_ok=True, request_args=(self.name, 'mode', '-1')) ...
mand completed without error, so # update the basic core details self.get_gbe_core_details() def tap_start(self, restart=False): """ Program a 10GbE device and start the TAP driver. :param restart: stop before starting """ if len(self.name) > 8: ...
agoose77/hivesystem
manual/movingpanda/panda-12b.py
Python
bsd-2-clause
7,088
0.001552
import dragonfly import dragonfly.pandahive import bee from bee import connect import math, functools from panda3d.core import NodePath import dragonfly.scene.unbound, dragonfly.scene.bound import dragonfly.std import dragonfly.io import dragonfly.canvas import Spyder # ## random matrix generator from random impor...
n.inp1) connect(random_matrix, w_spawn.inp2) z_pandawalk = pandawalkbind().worker() t_bind = dragonfly.std.transistor("id")() connect(panda_id, t_bind) connect(t_bind, z
_pandawalk.bind) do_spawn = dragonfly.std.transistor(("id", ("object", "matrix")))() connect(w_spawn, do_spawn) connect(do_spawn, pandaspawn.spawn_matrix) trig_spawn = dragonfly.std.pushconnector("trigger")() connect(trig_spawn, t_panda_id_gen) connect(trig_spawn, do_spawn) connect(trig_spa...
our-city-app/oca-backend
src/rogerthat/bizz/job/save_service_identities.py
Python
apache-2.0
928
0.002155
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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/licen
ses/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 # limitations under the License. # # @@license_version:1.7@@ from google.appengine.ext import db from roge...
abhisheknaik96/differential-value-iteration
src/differential_value_iteration/import_test.py
Python
mit
834
0.003597
"""Tests for basic ability to import subpackages.""" from absl.test
ing import absltest from differential_value_iteration.algorithms import algorithms from differential_value_iteration.environments import micro class DifferentialValueIterationTest(absltest.TestCase): def test_algorithms_pac
kage_import(self): self.assertTrue(algorithms.RVI_Evaluation) self.assertTrue(algorithms.DVI_Evaluation) self.assertTrue(algorithms.MDVI_Evaluation) self.assertTrue(algorithms.RVI_Control) self.assertTrue(algorithms.DVI_Control) self.assertTrue(algorithms.MDVI_Control1) self.assertTrue(algor...
espressopp/espressopp
src/integrator/MDIntegrator.py
Python
gpl-3.0
3,045
0.005255
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the G...
egrator import sys class MDIntegratorLocal(object): def run(self, niter): if not isinstance(niter, int): raise ValueError('The provided number of steps have to be an integer not {} with value {}'.format(type(niter), niter))
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): return self.cxxclass.run(self, niter) def addExtension(self, extension): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): ...
MiracleWong/aming_python
deploy.py
Python
mit
3,534
0.007679
#!/usr/bin/python #-*- coding:utf-8 -*- import os import sys import urllib, urllib2 import tarfile from distutils.version import LooseVersion import shutil URL_LASTVER = "http://192.168.72.133:80/deploy/lastver" URL_LIVEVER = "http://192.168.72.136:8080/deploy/livever" URL_PKG= "http://192.168.72.136:80/deploy/package...
if os.path.exists(DOC_ROOT): target = os.readlink(DOC_ROOT) if target != pkg_path: os.unlink(DOC_R
OOT) os.symlink(pkg_path, DOC_ROOT) else: os.symlink(pkg_path, DOC_ROOT) def versionSort(l): from distutils.version import LooseVersion vs = [LooseVersion(i) for i in l] vs.sort() return [i.vstring for i in vs] def clean(): download_list = [i.split('-')[1][:-7] ...
DarthMaulware/EquationGroupLeaks
Leak #4 - Don't Forget Your Base/EQGRP-Auction-File/Linux/bin/pyside/OpRedrection.py
Python
unlicense
29,495
0.009493
#!/usr/bin/python import base import string import sys import os import crypto import struct import re import thread from socket import * from select import * def prints(myString): sys.stderr.write(myString) sys.stderr.write("\n") def doSysExit(num): print 0 sys.exit(num) #---------------------------...
>]") prints(" [-dontDone]") prints(" [-onlyDone]\n") #------------------------------------------------------------------------ # Name : GetTarget # Purpose:
Translate the user-supplied ip address into a target # Receive: ipAddress - The IP address of the SIDETRACK target # Return : The target corresponding to the ip address #------------------------------------------------------------------------ def GetTarget(ipAddress): for targ in base.targetDict.keys(): i...
mmccollow/TSV-Convert
lib/python2.6/distutils/__init__.py
Python
gpl-2.0
3,677
0.008975
import os import sys import warnings import opcode # opcode is not a virtualenv module, so we can use it to find the stdlib # Important! To work on pypy, this must be a module that resides in the # lib-python/modified-x.y.z directory dirname = os.path.dirname distutils_path = os.path.join...
ython_lib = sysconfig.get_python_lib def sysconfig_get_python_lib(plat_specific=0, standard_lib=0, prefix=None): if standard_lib and prefix is None: prefix = sys.real_prefix return old_get_python_lib(plat_specific, standard_lib, prefix) sysconfig_get_python_lib.__doc__ = old_get_pyt
hon_lib.__doc__ sysconfig.get_python_lib = sysconfig_get_python_lib old_get_config_vars = sysconfig.get_config_vars def sysconfig_get_config_vars(*args): real_vars = old_get_config_vars(*args) if sys.platform == 'win32': lib_dir = os.path.join(sys.real_prefix, "libs") if isinstance(real_vars, d...
Tastalian/avp-rrt-rss-2013
vippy/MintimeTrajectory.py
Python
apache-2.0
11,341
0.034565
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2012 Quang-Cuong Pham <cuong.pham@normalesup.org> # # 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/l...
in range(self.dim):
der=self.splines_list[i].derivatives(t) q_ve
skftn/findex-gui
findex_gui/controllers/session/api.py
Python
mit
969
0
from flask import session from flask_yoloapi import endpoint, parameter from findex_gui.web import app KEYS = [ "search_display_view" ] VALUES = [ "table", "fancy" ] @app.route("/api/v2/session/set", methods=["POST"]) @endpoint.api( parameter("key", type=str, required=True), parameter("val", type=s...
rameter("key", type=str, required=True), parameter("val", type=str, required=True) ) de
f api_session_get(key, val): if key not in KEYS: return Exception("key \"%s\" doesn't exist" % key) if key not in session: session[key] = "fancy" return session[key]
djaodjin/envconnect
envconnect/views/index.py
Python
gpl-2.0
1,189
0.000841
# Copyright (c) 2019, DjaoDjin inc. # see LICENSE. import logging from deployutils.helpers import update_context_urls from django.views.generic import TemplateView from ..compat import reverse from ..helpers import get_testing_accounts from ..mixins import AccountMixin, BreadcrumbMixin LOGGER = logging.getLogger(_...
data(**kwargs) context.update({ 'segments': self.get_segments(search_query='public') }) return context class A
ppView(AccountMixin, IndexView): """ Homepage for an organization. """ template_name = 'envconnect/app.html' def get_context_data(self, **kwargs): context = super(AppView, self).get_context_data(**kwargs) context.update({ 'FEATURES_DEBUG': self.account.pk in get_testing...
alexei-matveev/ccp1gui
interfaces/mndo.py
Python
gpl-2.0
43,261
0.016435
# # This file is part of the CCP1 Graphical User Interface (ccp1gui) # # (C) 2002-2007 CCLRC Daresbury Laboratory # # 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 ...
ecific calculation class""" def __init__(self,**kw): qm.QMCalc.__init__(self,**kw) self.set_name('unnamed') self.set_parameter("task",MENU_ENER) self.set_parameter("the
ory","AM1") self.set_parameter("symmetry",1) self.set_parameter("scf_method","rhf") self.set_parameter("hamiltonian","am1") self.set_parameter("basis","STO") self.set_parameter("scf_maxcyc","200") self.set_parameter("restart","0") self.set_parameter("accuracy","me...
Jumpscale/jumpscale_core8
lib/JumpScale/tools/expect/Expect.py
Python
apache-2.0
25,028
0.001678
import os import subprocess import errno from JumpScale import j PIPE = subprocess.PIPE if subprocess.mswindows: from win32file import ReadFile, WriteFile from win32pipe import PeekNamedPipe import msvcrt else: import select import fcntl if j.core.platformtype.myplatform.isLinu
x(): try: import pxssh except ImportError as e: # We want this to go to stderr, otherwise applications relying on stdout # output (build command generator scripts) are pretty busted. #print >> sys.stderr, "Module pxssh not found...Wont be able to ssh on linux!!!" print("c...
print("did not find pexpect") j.core.platformtype.myplatform.isLinux() try: j.sal.ubuntu.apt_install("python-pexpect") except: pass class Popen(subprocess.Popen): def recv(self, maxsize=None): return self._recv('stdout', maxsize) def recv_err(...
SandStormHoldings/ScratchDocs
couchdb_delviews.py
Python
mit
530
0.011321
from __future__ import print_function import datetime from couchdbkit import * from couchdbkit.designer import push from docs import initvars import config as cfg import sys import json # Wrap sys.stdout into a StreamWriter to allow writing unicode. import codecs import locale sys.stdout = codecs.getwriter(locale....
print('ai') if __name__=='__main__': s,d = init_conn() doc = Task
.get('_design/task') print(doc) #push_views(d)
schmidtj/PyGNA
PyGNA/Display.py
Python
bsd-3-clause
15,679
0.011098
""" Display class """ __author__ = """\n""".join(['Jeffrey Schmidt (jschmid1@binghamton.edu', 'Benjamin Bush (benjaminjamesbush@gmail.com)', 'Hiroki Sayama (sayama@binghamton.edu)']) __all__ = ['addInputValues','addExperimentalValues','addInputXValueList','addIn...
if __debug__: print set(self.yInputValues) inputProbDist = [float(x)/sum(self.histInputData) for x in self.histInputData] simulatedProbDist = [float(x)/sum(self.histSimulatedData) for x in self.histSimulatedData] self.BhattacharyyaDist = self.utility.Bha...
istance(self): if not self.BDGenerated: self.generateBhattacharyyaFromInputs() return self.BhattacharyyaDist def loglogPlot(self, title, xAxisName, yAxisName, zAxisName="None", legloc='best', multiLine=False): if self.compare: titleOne = title + ...
AlbertoPeon/invenio
modules/bibedit/lib/bibedit_templates.py
Python
gpl-2.0
16,853
0.00629
## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at...
g',
'bibEditImgCompressMenuSection', id='ImgViewMenu'), 'btnTagMARC': button('button', 'MARC', id='btnMARCTags', disabled='disabled'), 'btnTagNames': button('button', 'Human', id='btnHumanTags', disabled='disabled') ...
cedriclaunay/gaffer
python/GafferImageTest/OpenColorIOTest.py
Python
bsd-3-clause
4,580
0.036463
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # Copyright (c) 2012, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that ...
ce"].setValue(
"sRGB" ) self.assertNotEqual( n["out"].image(), o["out"].image() ) def testHashPassThrough( self ) : n = GafferImage.ImageReader() n["fileName"].setValue( self.fileName ) o = GafferImage.OpenColorIO() o["in"].setInput( n["out"] ) self.assertEqual( n["out"].image(), o["out"].image() ) o["inputSpace"...
connectIOT/iottoolkit
iottoolkit/interfaces/HttpObjectService.py
Python
apache-2.0
6,944
0.015409
''' Created on Oct 18, 2012 Create a RESTlite instance of a http server for SmartObjects. based on wsgi/restlite with the restObject extensions to match object path segments to resource names e.g. the URL path: /object1/barometricPressure/Description/Observers maps to the python API identifier: object1.barometricPress...
if prefType[0] == '*/*' : return providedTypes[0] # return our favorite type if we don't have a preferred type and */* is allowed else: raise restlite.Status('415 Unsupported Media Type') # no applicable type and client doesn't want whatever def _handleGET(self, currentResource): ...
invoke the serializer if hasattr(currentResource,'serialize') : # see if the resource has a serialize method responseType = self.contentTypeNegotiate(self.env['HTTP_ACCEPT'], currentResource.serializeContentTypes() ) self.start_response('200 OK', [('Content-Type', responseType)]) ...
wheeldog515/lightshowPi
py/hardware_controller.py
Python
bsd-2-clause
30,723
0.00166
#!/usr/bin/env python # # Licensed under the BSD license. See full license in LICENSE file. # http://www.lightshowpi.org/ # # Author: Ryan Jennings # Author: Chris Usey # Author: Todd Giles (todd@lightshowpi.org) # Author: Tom Enos (tomslick.ca@gmail.com) """Control the Raspberry pi hardware. The hardware controller...
EDManager(BaseManager): pass class Hardware(object): def __init__(self): self.cm = cm # list to store the Channels instances in self.channels = list() # network setup if used self.network = networking.Networking(cm) self.server = self.network.networking == "ser...
d = None if self.cm.configs.led: self.led = list() if self.cm.configs.led_multiprocess: LEDManager.register('LED', led_module.Led) for lc in self.cm.configs.led: self.cm.set_led(config_file=lc) self.ledmanager ...
Hope6537/hope-tactical-equipment
hope-note-module/hope-python-2.7-note/org/Userinfo.py
Python
apache-2.0
10,471
0.000133
# encoding:utf-8 __author__ = 'Hope6537' class Userinfo(object): def __init__(self, username, password): self._username = username self._password = password __slots__ = ('_username', '_password', "_score") # 用tuple定义允许绑定的属性名称 # 使用__slots__要注意,__slots__定义的属性仅对当前类起作用,对继承的子类是不起作用的 ...
默认的toString def __str__(self): return 'Userinfo object (username: %s)' % self._username # 有時候不可用 还需要覆盖一个repr _repr__ = __str__ def getUsername(self): if hasattr(self, '_username'): return self._username return None # 注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露...
法就是一个只读属性 class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must bet...
essepuntato/opencitations
script/tools/create_nq.py
Python
isc
4,821
0.003526
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright notice # and this permission notice appear in all copies. ...
"advance" % rdf_file_path) else: reperr.add_sentence("The file specified ('%s') doesn't exist." % rdf_file_path) return cur_graph def __load_graph(current_graph, file_path): errors = "" try: with open(file_path) as f: ...
on_ld_resource in json_ld_file: # Trick to force the use of a pre-loaded context if the format # specified is JSON-LD cur_context = json_ld_resource["@context"] json_ld_resource["@context"] = context_json current_graph.parse(data=json.dump...
jordan-developer/pyCMBS
pyocni/backends/dummy_backend.py
Python
apache-2.0
2,079
0.000962
# Copyright 2010-2012 Institut Mines-Telecom # # 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 agre...
e: Apache License, Version 2.0 """ #import pyocni.backend.backend as backend from pyocni.backends.backend import backend_interface import pyocni.pyocni_tools.config as config # getting the Logger logger = config.logger class backend(backend_interface): def create(self, entity): ''' Create an ent...
r Link) ''' logger.debug('The create operation of the dummy_backend') def read(self, entity): ''' Get the Entity's information ''' logger.debug('The read operation of the dummy_backend') def update(self, old_entity, new_entity): ''' Update a...
DistributedSystemsGroup/zoe-logger
web_logger/config.py
Python
apache-2.0
2,065
0.002906
# Copyright (c) 2015, Daniele Venzano # # 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 w...
auto_env_var_prefix="ZOE_WEB_", args_for_setting_config_path=["--config"], args_for_writing_out_config_file=["--write-confi
g"]) argparser.add_argument('--debug', action='store_true', help='Enable debug output') argparser.add_argument('--listen-address', type=str, help='Address to listen to for incoming connections', default="0.0.0.0") argparser.add_argument('--listen-port', type=int, help='Port to listen to for incoming connect...
mastizada/kuma
kuma/core/translations/search/filter/howto/name.py
Python
mpl-2.0
57
0
# -*
- coding: utf-8 -*-
gettext("""How-To & Tutorial""")
rjhunter8285/nsc-cloudproject-s22016
prototype/api/FlaskApp/FlaskApp/azure_components/static/app_json.py
Python
apache-2.0
1,143
0.007874
# json error messages for oauth, api parameters, getting, updating, uploading, and deleting images oauth_error_json = {'status': 'error', 'msg': "could not verify oauth credentials"} upload_image_blob_error_json = {'status': 'error', 'msg': "failure to upload image to azure storage"} upload_image_db_error_json = {'sta...
son = {'status': 'error', 'msg': "failure to update tags in documentdb"} api_parameters_error_json = {'status': 'error', 'msg': "api request missing header or body parameters"} # json success messages each api method upload_image_success_json = {'status': 'success', 'msg': "image uploaded"} delete_image_success_json =...
eleted"} update_tags_success_json = {'status': 'success', 'msg': "tags updated"}
crossgovernmentservices/csd-notes
lib/oidc.py
Python
mit
5,741
0
# -*- coding: utf-8 -*- """ OIDC client Flask extension """ from urllib.parse import urlencode from flask import url_for from jose import jwt import requests class KeyNotFound(Exception): pass def verify_id_token(token, config): header = jwt.get_unverified_header(token) keys = {key['kid']: key for key...
fig = self.refresh_keys(provider_name) claims = verify_id_token(token_response['id_token'], config) claims.update(self.userinfo(config, access_token)) return claims def token_request(self, config, auth_code): "
"" Exchange provider auth code for an ID Token and an Access Token """ request = TokenRequest( grant_type='authorization_code', code=auth_code, redirect_uri=config.get('redirect_uri') or self.callback_url, client_id=config['client_id'], ...
Agent007/deepchem
examples/low_data/tox_rf_one_fold.py
Python
mit
2,037
0.006382
""" Train low-data Tox21 models with random forests. Test last fold only. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import tempfile import num
py as np import deepchem as dc from datasets import load_tox21_ecfp from sklearn.ensemble import RandomForestClassifier # 4-fold splits K = 4 # num positive/negative ligands n
_pos = 10 n_neg = 10 # 10 trials on test-set n_trials = 20 tox21_tasks, dataset, transformers = load_tox21_ecfp() # Define metric metric = dc.metrics.Metric(dc.metrics.roc_auc_score, mode="classification") task_splitter = dc.splits.TaskSplitter() fold_datasets = task_splitter.k_fold_split(dataset, K) train_folds = ...
PainNarrativesLab/TwitterMining
tests/test_TwitterSearchTools.py
Python
mit
4,876
0.00082
from nose.tools import * from Loggers import SearchLogger from TwitterSearchTools import * from DaoMocks import * from TwitterMocks import * from ObserverMocks import * import unittest class SearchTest(unittest.TestCase): def setUp(self): self.object = Search() self.redis = RedisDaoMock() ...
.observer = '' def test_attach_observer(self): self.object.attach_observer(self.observer) self.assertTrue(len(self.object._observers), 1) def test_detach_observer(self): # TODO check with multiple observers that correct one removed self.object._observers.append(self.observer) ...
ject.detach_observer(self.observer) self.assertEquals(len(self.object._observers), 0) def test_detach_observer_exception(self): self.object._observers.append({'kind': 'housecat'}) with self.assertRaises(ObserverError): self.object.detach_observer(self.observer) def test_not...
lstorchi/teaching
xyzviewer/datastr/diz2.py
Python
gpl-3.0
194
0.020619
d = {"k1":1, "k2":"valore", 3:"val3", "quattro":4} f
or x in d.values(): print(x) print(" ") for x in d.keys(): print(x) print(" ") for x in d.items(): print(x) print(x[0], x[1
])
KeithCu/PyTorcs
sim/application/OpenRacingConfig.py
Python
gpl-2.0
4,130
0.026634
import elementtree.ElementTree as ET class GraphicRenderingQuality: High = 2 Medium = 1 Low = 0 #import clr #from System import * #from System.IO import * #from System.Xml import * #from System.Xml.Serialization import * #from OpenRacing.Core import * #from OpenRacing.Graphic import * #Put in a custom namespace t...
eManager node.</summary>""" # def __init__(self): # """ <summary>Represents a OpenRacing.RaceManager node.</summary>""" # # def get_RaceFile(self): # # <summary>String RaceFile element.</summary> # return self._element_racefile # # def set_RaceFile(self, value): # self._element_racefile = value # # RaceFile = prope...
node.</summary>""" # def __init__(self): # """ <summary>Represents a OpenRacing.Graphic node.</summary>""" # self._element_quality = "High" # # def get_Quality(self): # # <summary>String Quality element.</summary> # return self._element_quality # # def set_Quality(self, value): # self._element_quality = value # #...
endlessm/chromium-browser
third_party/catapult/third_party/gsutil/gslib/commands/perfdiag.py
Python
bsd-3-clause
94,422
0.006556
# -*- coding: utf-8 -*- # Copyright 2012 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 require...
be required for the operation. -d Sets the directory to store temporary local files in. If not specified, a default temporary directory will be used. -t Sets the list of diagnostic tests to perform. The default is to run the lat, rthru, and wthru diagno...
separated list containing one or more of the following: lat For N (set with -n) objects, write the object, retrieve its metadata, read the object, and finally delete the object. Record the latency of each operation. list W...
anhstudios/swganh
data/scripts/templates/object/mobile/shared_dressed_corellia_cec_officer.py
Python
mit
453
0.046358
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from sw
gpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_corellia_cec_officer.iff" result.attribute_template_id = 9 result.stfName("npc_name","human_base_male") #### BEGI
N MODIFICATIONS #### #### END MODIFICATIONS #### return result
albertocubeddu/serverUtility
amazon/awsLambdaFunction/startInstances.py
Python
mit
852
0.011737
i
mpo
rt boto3 region = 'ap-southeast-2' instancesContainer = [] ec2 = boto3.resource('ec2', region_name=region, api_version='2016-04-01') ec2Client = boto3.client('ec2', region_name=region, api_version='2016-04-01') #Retrieve all the instances instances = ec2.instances.filter(Filters = [{'Name':'tag:Name', 'Values':['t...
dcorbacho/libcloud
docs/examples/compute/openstack/custom_service_catalog_selection_args.py
Python
apache-2.0
768
0
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security # This assumes you don't have SSL set up. # Note: Code like this poses a security risk (MITM attack) and # that's the reason why you should never use it for anything else # besides testing. You have ...
'novaCompute', ex_forc
e_service_region='MyRegion')
pshen/ansible
lib/ansible/modules/network/net_vlan.py
Python
gpl-3.0
2,321
0
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # 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 Li...
Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = """ --- module: net_vlan version_added: "2.4" author: "Ricardo Carrillo Cruz (@rcar...
es. options: name: description: - Name of the VLAN. vlan_id: description: - ID of the VLAN. interfaces: description: - List of interfaces the VLAN should be configured on. collection: description: List of VLANs definitions. purge: description: - Purge VLANs not defi...
pytroll/python-geotiepoints
geotiepoints/tests/test_modisinterpolator.py
Python
gpl-3.0
4,321
0.000231
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2017-2021 Python-geotiepoints developers # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
self.assertEqual(lat250.shape, lats.shape) # self.assertTrue(np.allclose(lon250, lons, atol=1e-2)) # self.assertTrue(np.allclose(lat250, lats, atol=1e-2)) # Test level 2 lat5 = lat1[2::5, 2:-5:5] lon5 = lon1[2::5, 2:-5:5] satz5 = satz1[2::5, 2:-5:5] lons...
# Test nans issue (#19) satz1 = to_da(abs(np.linspace(-65.4, 65.4, 1354)).repeat(20).reshape(-1, 20).T) lons, lats = modis_1km_to_500m(lon1, lat1, satz1) self.assertFalse(np.any(np.isnan(lons.compute()))) self.assertFalse(np.any(np.isnan(lats.compute()))) def test_poles_dat...
hfp/tensorflow-xsmm
tensorflow/python/kernel_tests/cond_v2_test.py
Python
apache-2.0
37,016
0.009536
# Copyright 2018 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...
cond_op = output.op.inputs[0].op self.assertEqual(cond_op.type, "If") return output, cond_op def _createNestedCond(self, name): """Like _createCond but creates a neste
d cond_v2 call as well.""" pred = constant_op.constant(True, name="pred") x = constant_op.constant(1.0, name="x") def true_fn(): return cond_v2.cond_v2(pred, lambda: x, lambda: x + 1) def false_fn(): return x + 2 output = cond_v2.cond_v2(pred, true_fn, false_fn, name=name) cond_op...
t-wissmann/qutebrowser
tests/unit/misc/test_autoupdate.py
Python
gpl-3.0
2,969
0.000337
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2020 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # Copyright 2015-2018 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>: # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify #...
utoupdate, httpclient INVALID_JSON = ['{"invalid": { "json"}', '{"wrong": "keys"}'] class HTTPGetStub(httpclient.HTTPClient): """A stub class for HTTPClient. Attributes: url: the last url used by get() _success: Whether get() will emit a success signal. """ def __init__(self, succe...
() self.url = None self._success = success if json: self._json = json else: self._json = '{"info": {"version": "test"}}' def get(self, url): self.url = url if self._success: self.success.emit(self._json) else: s...
daniel-araujo/proctal
src/cli/tests/dump-range.py
Python
gpl-3.0
2,243
0.003121
#!/usr/bin/env python3 import sys from util import proctal_cli, sleeper class Error(Exception): pass class UnexpectedMatchValue(Error): def __init__(self, expected, found): self.expected = expected self.found = found message = "Expected to match {expected} but got {found}.".format( ...
guinea = sleeper.run() address = proctal_cli.allocate(guinea.pid(), self.offset + se
lf.length) address.add_address_offset(self.offset) proctal_cli.write(guinea.pid(), address, byte_type, value, array=self.length) start_address = address stop_address = start_address.clone() stop_address.add_address_offset(self.length) dumper = proctal_cli.dump( ...
zasdfgbnm/qutip
setup.py
Python
bsd-3-clause
4,890
0.00184
#!/usr/bin/env python """QuTiP: The Quantum Toolbox in Python QuTiP is open-source software for simulating the dynamics of closed and open quantum systems. The QuTiP library depends on the excellent Numpy, Scipy, and Cython numerical packages. In addition, graphical output is provided by Matplotlib. QuTiP aims to pro...
f2py_f2cmap'), 'w') as f: f.write("dict(real=dict(sp='float', dp='double', wp='double'), " + "complex=dict(sp
='complex_float', dp='complex_double', " + "wp='complex_double'))") def git_short_hash(): try: return "-" + os.popen('git log -1 --format="%h"').read().strip() except: return "" FULLVERSION = VERSION if not ISRELEASED: FULLVERSION += '.dev' + git_short_hash() def write_v...
roadmapper/ansible
lib/ansible/modules/network/fortios/fortios_user_local.py
Python
gpl-3.0
15,714
0.001527
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a ...
ool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true state: description: - Indicates whether to create or remove the object. type: str required: true ...