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
natemara/aloft.py
setup.py
Python
mit
568
0.02993
from setuptools import setup with open('requir
ements.txt') as f: required = f.read().splitlines() setup( name="aloft.py", version="0.0.4", author="Nate Mara", author_email="[email protected]", description="A simple API for getting winds aloft data from NOAA", license="MIT", test_suite="tests", keywords="aviation weather winds aloft", url="https://githu...
Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], install_requires=required, )
luuvish/libvio
script/test/suite/vp9.py
Python
mit
2,045
0.004401
# -*- coding: utf-8 -*- ''' ================================================================================ This confidential and proprietary software may be used only as authorized by a licensing agreement from Thumb o'Cat Inc. In the event of publication, the following notice is applicable: Copyright (C...
out': 'vp9-libvpx.log', 'srcdir': join(rootpath, 'test/stream/vp9'), 'outdir': join(rootpath, 'test/digest/vp9'), 'includes': ('*.ivf', '*.webm'), 'excludes': ('vp91-2-04-yv444.webm', ) }, {
'suite' : 'compare-vp9-libvpx', 'model' : 'libvpx', 'codec' : 'vp9', 'action': 'compare', 'stdout': 'vp9-libvpx.log', 'srcdir': join(rootpath, 'test/stream/vp9'), 'outdir': join(rootpath, 'test/digest/vp9'), 'includes': ('*.ivf', '*.webm'), 'exclude...
shlomif/patool
patoolib/util.py
Python
gpl-3.0
15,258
0.002097
# -*- coding: utf-8 -*- # Copyright (C) 2010-2012 Bastian Kleineidam # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #...
if mime2 == 'application/x-empty': # The uncompressor program file(1) uses is not installed. # Try to get mime information from the file extension.
mime2, encoding2 = guess_mime_mimedb(filename) if mime2 in ArchiveMimetypes: mime = mime2 encoding = encoding2 elif mime2 in ArchiveMimetypes: mime = mime2 encoding = get_file_mime_encoding(outparts) if mime not in ArchiveMimetypes: ...
Senseg/robotframework
src/robot/libdocpkg/robotbuilder.py
Python
apache-2.0
4,395
0.000228
# Copyright 2008-2012 Nokia Siemens Networks Oyj # # 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...
oc) class KeywordDocBuilder(object): def build_keywords(self, lib): return [self.build_keyword(kw) for kw in lib.handlers.values()] def build_keyword(self, kw): return KeywordDoc(name=kw.name, args=self._get_args(kw), doc=kw.doc) def _get_args(self, kw): required, defaults = sel...
ormalize_arg(kw.arguments.varargs, kw.type) if varargs: args.append('*%s' % varargs) return args def _parse_args(self, kw): args = [self._normalize_arg(arg, kw.type) for arg in kw.arguments.names] default_count = len(kw.arguments.defaults) if not default_count: ...
OpenAgInitiative/gro-api
gro_api/actuators/tests.py
Python
gpl-2.0
7,616
0.000919
from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from ..gro_api.test import APITestCase, run_with_any_layout from ..resources.models import ResourceType, ResourceProperty, ResourceEffect from .models import ActuatorType, ControlProfile, Actuator from .serializers import Actuat...
'is_binary': True, } relay_air_heater_id = ActuatorType.objects.get_by_natural_key( 'Relay-Controlled Air Heater' ).pk res = self.client.put( self.url_for_object('actuat
orType', relay_air_heater_id), data=data ) self.assertEqual(res.status_code, 403) @run_with_any_layout def test_edit_custom_type(self): humidifier_id = ResourceEffect.objects.get_by_natural_key('A', 'HU').pk air_temp_id = ResourceProperty.objects.get_by_natural_key('A', 'TM').pk...
vmalloc/json_rest
json_rest/logging_utils.py
Python
bsd-3-clause
269
0.011152
from logging import Handler c
lass NullHandler(Handler): """ NullHandler from Python 2.7 - doesn't exist on Python 2.6 """ def handle(self, record): pass def emit(self, record): pass def createLock(self): self.lock = N
one
kr15h/digital-fabrication-studio
examples/anne-marie-projected-notebook/switch.py
Python
mit
1,658
0.00965
import RPi.GPIO as GPIO import time import os import psutil import subprocess # Get framebuffer resolution proc = subprocess.Popen(["fbset | grep 'mode '"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() i = out.index('"') + 1 out = out[i:] i = out.index('"') out = out[:i] i = out.index('x') xres ...
p GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) buttonPressed = False while True: input_state = GPIO.input(18) if input_state == False: if buttonPressed == False: print('Button Pressed') sysCmd = '/usr/bin/omxplayer --loop --no-osd ' + winArg + ' ...
os.system(sysCmd) buttonPressed = True else: for p in psutil.process_iter(): if p.name() == "omxplayer": print('killing process "omxplayer"') os.system('killall omxplayer') if p.name() == "omxplayer.bin": print('killing pro...
chukysoria/pyspotify-connect
spotifyconnect/metadata.py
Python
apache-2.0
1,798
0
from __future__ import unicode_literals import spotifyconnect from spotifyconnect import ffi, lib, serialized, utils __all__ = [ 'ImageSize', 'Metadata' ] class Metadata(object): """A Spotify track. """ def __init__(self, sp_metadata): self._sp_metadata = sp_metadata self.pla...
ack_name) self.track_uri = utils.to_unicode(sp_metada
ta.track_uri) self.artist_name = utils.to_unicode(sp_metadata.artist_name) self.artist_uri = utils.to_unicode(sp_metadata.artist_uri) self.album_name = utils.to_unicode(sp_metadata.album_name) self.album_uri = utils.to_unicode(sp_metadata.album_uri) self.cover_uri = utils.to_unic...
trailofbits/manticore
manticore/platforms/wasm.py
Python
agpl-3.0
17,265
0.002606
from .platform import Platform from ..wasm.structure import ( ModuleInstance, Store, FuncAddr, HostFunc, Stack, ProtoFuncInst, MemInst, MemAddr, GlobalInst, GlobalAddr, TableInst, TableAddr, ExternVal, Module, ) from ..wasm.types import Trap, TypeIdx, TableType, M...
me: The WASM module to execute :param kwargs: Accepts "constraints" to pass in an initial ConstraintSet """ super().__init__(filename, **kwargs) #: Initial set of constraints self.constraints = kwargs.get("constraints", Con
straintSet()) #: Prevents users from calling run without instantiating the module self.instantiated = [] #: Backing store for functions, memories, tables, and globals self.store = Store() self.modules = [] self.module_names = {} self.manual_exports = {} s...
ibuler/coco
coco/utils.py
Python
gpl-3.0
6,619
0.00047
#!coding: utf-8 import base64 import calendar import os import re import paramiko from io import StringIO import hashlib import threading import time import pyte def ssh_key_string_to_obj(text): key_f = StringIO(text) key = None try: key = paramiko.RSAKey.from_private_key(key_f) except para...
input command :param data: input data list, like [b'data', b'data'] :return: command unicode """ command = [] for d in data:
self.stream.feed(d) for line in self.screen.display: line = line.strip() if line: command.append(line) if command: command = command[-1] else: command = '' self.screen.reset() command = self.clean_ps1_etc(command...
djrscally/eve-wspace
evewspace/Teamspeak/models.py
Python
gpl-3.0
1,834
0.002726
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation,
either version 3 of the License, or # (at your option) any
later version. An additional term under section # 7 of the GPL is included in the LICENSE file. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU ...
dc3-plaso/plaso
plaso/cli/helpers/viper_analysis.py
Python
apache-2.0
3,976
0.003773
# -*- coding: utf-8 -*- """The Viper analysis plugin CLI arguments helper.""" from plaso.analysis import viper from plaso.cli.helpers import interface from plaso.cli.helpers import manager from plaso.lib import errors class ViperAnalysisArgumentsHelper(interface.ArgumentsHelper): """Viper analysis plugin CLI argum...
fault is: ' u'{0:s}'.format(cls._DEFAULT_HOST))) argument_group.add_argument( u'--viper-port', u'--viper_port', dest=u'viper_port', type=int, action='store', def
ault=cls._DEFAULT_PORT, metavar=u'PORT', help=( u'Port of the Viper server to query, the default is: {0:d}.'.format( cls._DEFAULT_PORT))) argument_group.add_argument( u'--viper-protocol', u'--viper_protocol', dest=u'viper_protocol', type=str, choices=viper.ViperAnalyzer....
gallifrey17/eden
modules/templates/Magnu/config.py
Python
mit
14,481
0.016618
# -*- coding: utf-8 -*- try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current from gluon.storage import Storage def config(settings): """ Template settings for a hosted environment...
inistration"), #description = "Site Administration", restricted = True, access = "|1|", # Only Administrators can see this module in the default menu & access the controller module_type = None # This item is ha
ndled separately for the menu )), ("appadmin", Storage( name_nice = T("Administration"), #description = "Site Administration", restricted = True, module_type = None # No Menu
okoala/sublime-bak
Backup/20150720091700/Babel/Babel.py
Python
mit
1,796
0.023942
import sublime import sublime_plugin import json from os.path import dirname, realpath, join from .node_bridge import node_bridge # monkeypatch `Region` to be iterable sublime.Region.totuple = lambda self: (self.a, self.b) sublime.Region.__iter__ = lambda self: self.totuple().__iter__() BIN_PATH = join(sublime.packa...
.view.size
()) return self.view.substr(region) selected_text = '' for region in self.view.sel(): selected_text = selected_text + self.view.substr(region) + '\n' return selected_text def has_selection(self): for sel in self.view.sel(): start, end = sel if start != end: return True return False def ge...
Drewsif/OpenVPN-Config-Generator
OpenVPNConfig.py
Python
mpl-2.0
14,441
0.002978
#!/usr/bin/env python # 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/ from __future__ import division, absolute_import, print_function, unicode_literals import OpenSSL im...
sicConstraints", False, b"CA:FALSE"), OpenSSL.crypto.X509Extension(b"keyUsage", False, b"digitalSignature,keyEncipherment"), OpenSSL.crypto.X509Extension(b"extendedKeyUsage", False, b"serverAuth"), OpenSSL.crypto.X509Extension(b"subjectKeyIdentifier", False, b"hash", subject=cert), ...
lse, b"server") ]) else: cert.add_extensions([ OpenSSL.crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"), OpenSSL.crypto.X509Extension(b"keyUsage", False, b"digitalSignature"), OpenSSL.crypto.X509Extension(b"extendedKeyUsage", False, b"clientAuth"), ...
plamut/ggrc-core
src/ggrc/models/option.py
Python
apache-2.0
765
0.013072
# Copyright (C) 2
017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc import db from ggrc.models.deferred import deferred from ggrc.models.mixins import Base, Described class Option(Described, Base, db.Model): __tablename__ = 'options' role = db.Column(db.String) # TODO: inh...
is nullable here) title = deferred(db.Column(db.String), 'Option') required = deferred(db.Column(db.Boolean), 'Option') def __str__(self): return self.title @staticmethod def _extra_table_args(cls): return ( db.Index('ix_options_role', 'role'), ) _publish_attrs = [ 'role', ...
vanant/googleads-dfa-reporting-samples
python/v2.0/get_user_role_permissions.py
Python
apache-2.0
2,441
0.004097
#!/usr/bin/python # # Copyright 2014 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...
e flags. argparser = argparse.ArgumentParser(add_help=False) argparser.add_argument( 'profile_id', type=int, help='The ID of the profile to list permissions for') argparser.add_argument( 'subaccount_id', type=int, help='The ID of the subaccount to list permissions for') def main(argv): # Authenticat...
oogleapis.com/auth/dfareporting', 'https://www.googleapis.com/auth/dfatrafficking']) profile_id = flags.profile_id subaccount_id = flags.subaccount_id try: # Construct and execute the subaccount request. request = service.subaccounts().get( profileId=profile_id, id=subaccount_id) ...
132nd-etcher/EMFT
emft/plugins/reorder/value/output_folder.py
Python
gpl-3.0
1,091
0
# coding=utf-8 import typing from collections import MutableMapping from emft.core.logging import make_logger from emft.core.path import Path from emft.core.singleton import Singleton LOGGER = make_logger(__name__) # noinspection PyAbstractClass class OutputFolder(Path): pass class OutputFolders(MutableMappin...
def __len_
_(self) -> int: return self._data.__len__() def __delitem__(self, key): return self._data.__delitem__(key) def __setitem__(self, key, value: OutputFolder): return self._data.__setitem__(key, value)
baverman/apns-client
apnsclient/transport.py
Python
apache-2.0
27,323
0.00377
# Copyright 2014 Sardar Yumatov # # 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,...
ache the connection. Use it to fetch feedback from APNs and then close when you are done. :Arguments: - address (str or tuple): target address. -
certificate (:class:`BaseCertificate`): provider's certificate instance. - cert_params (kwargs): :class:`BaseCertificate` arguments, used if ``certificate`` instance is not given. """ if certificate is not None: cert = certificate else: cert = self.pool.g...
hunter-cameron/Bioinformatics
python/checkm_select_bins.py
Python
mit
1,283
0.005456
import argparse import pandas parser = argparse.ArgumentParser(description="Subsets a checkm tab-separated outfile to include only entries that have the specified completeness/contamination level") parser.add_argument("-checkm", help="the checkm out file", required=True) parser.add_argument("-completeness", help="com...
p="\t", header=0, index_col=0) if args.completeness: df = df.query("Completeness {metric} {value}".format(metric=args.comp_metric, value=args.completeness)) if args.contamination: df = df.query("Contamination {metric} {value}".format(me
tric=args.cont_metric, value=args.contamination)) df = df.sort_index(0, 'Completeness', ascending=False) df.to_csv(args.out, sep="\t", index_label="Bin Id")
NaturalSolutions/NS.Bootstrap
Back/ecoreleve_server/Views/__init__.py
Python
mit
2,874
0.013918
### test if the match url is integer def integers(*segment_names): def predicate(info, request): match = info['match'] for segment_name in segment_names: try: print (segment_names) match[segment_name] = int(match[segment_name]) if int(ma...
oredSites/id', 'ecoReleve-Core/monitoredSites/{id}') ##### Stations #####
config.add_route('area', 'ecoReleve-Core/area') config.add_route('locality', 'ecoReleve-Core/locality') config.add_route('stations', 'ecoReleve-Core/stations/') config.add_route('stations/id', 'ecoReleve-Core/stations/{id}',custom_predicates = (integers('id'),)) config.add_route('stations/action',...
rento19962/cadquery
tests/TestImporters.py
Python
lgpl-3.0
1,871
0.006948
""" Tests file importers such as STEP """ #core modules import StringIO from cadquery import * from cadquery import exporters from cadquery import importers from tests import BaseTest #where unit test output will be saved import sys if sys.platform.startswith("win"): OUTDIR = "c:/temp" else: OUTDIR = "/tm...
hen imports it again :param importType: The type of file we're importing (STEP, STL, etc) :param fileName: The path and name of the file to write to """ #We're importing a STEP file if importType == importers.ImportTypes.STEP: #We first need to build a simple shape to...
Workplane("XY").box(1, 2, 3).val() #Export the shape to a temporary file shape.exportStep(fileName) # Reimport the shape from the new STEP file importedShape = importers.importShape(importType,fileName) #Check to make sure we got a solid back se...
hds-lab/textvisdrg
msgvis/apps/groups/models.py
Python
mit
2,224
0.004946
from django.db import models from msgvis.apps.corpus import utils from msgvis.apps.corpus import models as corpus_models from msgvis.apps.enhance import models as enhance_models from django.contrib.auth.models import User import operator from django.utils import timezone class Group(models.Model): """ A group ...
, self.include_types.all()) @property def message_count(self): return self.messages.count() def __repr__(self): return self.name def __unicode__(self): return self.__repr__() class
ActionHistory(models.Model): """ A model to record history """ owner = models.ForeignKey(User, default=None, null=True) created_at = models.DateTimeField(default=timezone.now, db_index=True) """Created time""" from_server = models.BooleanField(default=False) type = models.CharField(...
ateliedocodigo/py-healthcheck
healthcheck/__init__.py
Python
mit
310
0
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from functools import reduce # noqa except Excepti
on: pass try: from .tornado_handler import TornadoHandler # noqa except ImportError: pass from .environmentdump import Environment
Dump # noqa from .healthcheck import HealthCheck # noqa
gautes/TrollCoinCore
contrib/devtools/copyright_header.py
Python
mit
22,402
0.005089
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import re import fnmatch import sys import subprocess import datetime import os #############################...
_COPYRIGHT_COMPILED = re.compile(ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE) def compile_copyright_regex(copyright_style, year_style, name): return re.compile('%s %s %s' % (copyright_style, year_style, name)) EXPECTED_HOLDER_
NAMES = [ "Satoshi Nakamoto\n", "The Trollcoin Core developers\n", "The Trollcoin Core developers \n", "Trollcoin Core Developers\n", "the Trollcoin Core developers\n", "The Trollcoin developers\n", "The LevelDB Authors\. All rights reserved\.\n", "BitPay Inc\.\n", "BitPay, Inc\.\n",...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/mpls/signaling_protocols/rsvp_te/global_/graceful_restart/state/__init__.py
Python
apache-2.0
26,895
0.00119
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
294967295"]}, int_size=32, ), is_leaf=True, yang_name="recovery-time", parent=self, pa
th_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace="http://openconfig.net/yang/network-instance", defining_module="openconfig-network-instance", yang_type="uint32", is_config=False, ) load = kw...
EoRImaging/katalogss
katalogss/fhd_pype.py
Python
bsd-2-clause
7,360
0.016576
''' Read and manipulate FHD output in Python. ''' import os import numpy as np from scipy.io import readsav from astropy.io import fits global _fhd_base _fhd_base = '/nfs/eor-09/r1/djc/EoR2013/Aug23/' def fhd_base(): 'Return path to FHD output directory.' global _fhd_base return _fhd_base def set_fh...
at.flux).T['i'][0], cat.gain,cat.alpha, cat.freq, cat.flag] items
= [item.astype(np.float64) for item in items] cat = dict(zip(['id','x','y','ra','dec','flux','gain','alpha','freq', 'flag'],items)) return cat def gen_cal_cat(cat, freq=180., alpha=-0.8, file_path='catalog.sav'): ''' Generate IDL structure and save file from `katalogss` catalog di...
tonitran/dvc-embedded
runConfigs.py
Python
agpl-3.0
107
0.018692
#Constants PROD = 'prod' LOCAL = 'local' NOPI = '
nopi' #Set configs here ENV = PROD loggingEn
abled = True
legaultmarc/grstools
setup.py
Python
mit
2,558
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # How to build source distribution # python setup.py sdist --format bztar # python setup.py sdist --format gztar # python setup.py sdist --format zip import os from setuptools import setup, find_packages MAJOR = 0 MINOR = 4 MICRO = 0 VERSION = "{}.{}.{}".format(MAJOR, ...
>= 0.1.0", "matplotlib >= 2.0", "scipy >= 0.18"], classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research
", "Operating System :: Unix", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 3", "Topic :: Sc...
Edzvu/Edzvu.github.io
APNSWrapper-0.6.1/APNSWrapper/connection.py
Python
mit
7,014
0.013687
# Copyright 2009 Max Klymyshyn, Sonettic # 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 writ...
ntext = None def __init__(self, certificate = None, ssl_command = "openssl", force_ssl_command = False,
disable_executable_search = False, debug = False): self.connectionContext = None self.debug = debug if not os.path.exists(str(certificate)): raise APNSCertificateNotFoundError, "Apple Push Notification Service Certificate file %s not found."...
mcnowinski/various-and-sundry
lightcurve/super.calibrate.py
Python
mit
10,853
0.018336
# #calibrate.py # #calibrate fits images using darks, flats, and bias frames #corrected image = (image - bias - k(dark-bias))/flat #for k=1, i.e. image exp = dark exp, corrected image = (image - dark)/flat import os import glob import math import subprocess import re import sys import datetime import shutil from decim...
_bias_corrected = False dark_bias = None dark_master = 'mdark.' + date_suffix + '.fits' #master flat frame #folder with bias component frames *inc
luding* ending forward slash flat_path='./flat/' flat_is_bias_corrected = False flat_bias = None flat_is_dark_corrected = False flat_dark = None flat_ave_exptime = 0 flat_master = 'mflat.' + date_suffix + '.fits' #name of exposure variable in FITS header file exposure_label='EXPTIME' log=open(log_fname, 'a+') #trim...
h2oai/sparkling-water
py/tests/unit/with_runtime_sparkling/test_mojo_parameters.py
Python
apache-2.0
6,596
0.002729
# 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 ...
ols=features, bs=[1, 1], scale=[0.5, 0.5]) model = algorithm.fit(prostateDataset) compareParameterValues(algorithm, model, ["getFeaturesCols"]) def testDeepLearningParameters(prostateDataset): features = ['AGE', 'RACE', 'DPROS', 'DCAPS', 'PSA'] algorithm = H2ODeepLearning(seed=1, labelCol="CAPSULE", f...
res = ['AGE', 'RACE', 'DPROS', 'DCAPS', 'PSA'] algorithm = H2OKMeans(seed=1, featuresCols=features) model = algorithm.fit(prostateDataset) compareParameterValues(algorithm, model) def testIsolationForestParameters(prostateDataset): features = ['AGE', 'RACE', 'DPROS', 'DCAPS', 'PSA'] algorithm = H2...
grapesmoker/regulations-parser
regparser/history/annual.py
Python
cc0-1.0
3,599
0
import logging import re from lxml import etree import requests from regparser.federalregister import fetch_notice_json from regparser.history.delays import modify_effective_dates from regparser.notice.build import build_notice CFR_BULK_URL = ("http://www.gpo.gov/fdsys/bulkdata/CFR/{year}/title-{title}/" ...
ume that we care about""" vol_num = 1 volume = Volume(year, title, vol_num) while volume.exists: if volume.should_contain(part): return volume vol_num += 1 volume = Volume(year, title, vol_num) return
None def first_notice_and_xml(title, part): """Find the first annual xml and its associated notice""" notices = [build_notice(title, part, n, do_process_xml=False) for n in fetch_notice_json(title, part, only_final=True) if n['full_text_xml_url'] and n['effective_on']] modify...
jaeilepp/eggie
mne/tests/test_fixes.py
Python
bsd-2-clause
4,590
0.000218
# Authors: Emmanuelle Gouillart <[email protected]> # Gael Varoquaux <[email protected]> # Alex Gramfort <[email protected]> # License: BSD import numpy as np from nose.tools import assert_equal, assert_raises from numpy.testing import assert_array...
..fixes import _firwin2 as mne_firwin2 from ..fixes import _filtfilt as mne_filtfilt def test_counter(): """Test Counter replacement""" import collections try: Counter = collections.Counter except: pass else: a = Counter([1, 2, 1, 3]) b = _Counter([1, 2, 1, 3]) ...
: assert_equal(a[key], b[key]) def test_unique(): """Test unique() replacement """ # skip test for np version < 1.5 if LooseVersion(np.__version__) < LooseVersion('1.5'): return for arr in [np.array([]), np.random.rand(10), np.ones(10)]: # basic assert_array_equ...
troeger/opensubmit
executor/setup.py
Python
agpl-3.0
977
0.018443
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('requirements.txt') as f: required = f.read().splitlines() setup( name = 'opensubmit-exec', version = '0.7.32', url = 'https://github.com/troeger/opensubmit', license='AGPL', author = 'Peter T...
ail = '[email protected]', classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 3.6', 'Programming Lang
uage :: Python :: 3.5', 'Programming Language :: Python :: 3.4' ], install_requires=required, extras_require={'report-opencl': ["pyopencl"]}, packages = ['opensubmitexec'], package_data = {'opensubmitexec': ['VERSION']}, entry_points={ 'console_scripts': [ 'opensubmi...
keithio/django-mailify
mailify/signals.py
Python
mit
226
0.017699
from django.dispatch import Signal message = Signal(providing_args=['desc', 'from', 'recipients
', 'celery', 'when', 'keep', 'subject_context', 'me
ssage_context', 'subject_template', 'text_template', 'html_template'])
shlopack/cursovaya
template/f_h_21.py
Python
mit
25
0.08
t
emplate = '%.2f'%
(fh_21)
open-craft/xblock-mentoring
mentoring/title.py
Python
agpl-3.0
1,443
0
# -*- coding: utf-8 -*- # # Copyright (C) 2014 Harvard # # Authors: # Xavier Antoviaque <[email protected]> # # This software's license gives you freedom; you can copy, convey, # propagate, redistribute and/or modify this program under the terms of # the GNU Affero General Public License (AGPL) as publishe...
######## import logging from .light_children import LightChild, Scope, String # Globals ###################
######################################## log = logging.getLogger(__name__) # Classes ########################################################### class TitleBlock(LightChild): """ A simple html representation of a title, with the mentoring weight. """ content = String(help="Text to display", scope=Sc...
bjaraujo/ENigMA
trunk/wrappers/swig/python/setup.py
Python
gpl-2.0
831
0.001203
import sys import setuptools with open('README.md', 'r') as fh: long_description = fh.read() with open('version.h', 'r') as fh: version = fh.read().split('"')[1] setuptools.setup( name='ENigMApy', version=version,
author='bjaraujo', author_email='', description='ENigMA - Extended Numerical Multiphysics Analysis', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/bjaraujo/ENigMA', packages=['ENigMA'], include_package_data=True, classifiers...
'Operating System :: Microsoft :: Windows' if sys.platform == 'win32' else 'Operating System :: POSIX :: Linux' ], python_requires='>=3.5' )
lwahlmeier/python-threadly
threadly/Futures.py
Python
unlicense
4,445
0.000225
""" Futures tools for threadly """ import threading import time class ListenableFuture(object): """ This class i used to make a Future that can have listeners and callbacks added to it. Once setter(object) is called all listeners/callbacks are also called. Callbacks will be given the set object, an...
listener except the set object is passed as the first argument when the callable is called. Arguments for the listener can be given if needed. `cable` a callable that will be called when the future is completed, it must have at least 1 argument. `args` tuple arguments tha...
kwargs = kwargs or {} if self.settable is None: self.callables.append((cable, args, kwargs)) else: cable(self.settable, *args, **kwargs) def get(self, timeout=2 ** 32): """ This is a blocking call that will return the set object once it is set. `t...
jtmitchell/reeder-demo
reeder/rssfeeds/models.py
Python
gpl-2.0
1,244
0
# -*- coding: utf-8 -*- from django.db import models class RssFeed(models.Model): url = models.URLField(unique=True, db_index=True, default='') name = models.CharField(blank=True, default='', max_length=100) lastmodified = models.DateTimeField(editable=False, auto_now=True, ...
auto_now_add=True, db_in
dex=True) def __unicode__(self): if self.url: return "{} {} {}".format(self.feed, self.url, self.snippet[:10]) else: return "RssArticle {}".format(self.pk) class Meta: unique_together = ['feed', 'url']
fhoring/autorest
src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary_operations.py
Python
mit
110,391
0.000661
# 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 Ge
nerator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.pipeline import C
lientRawResponse from .. import models class DictionaryOperations(object): """DictionaryOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deseriali...
edwinsteele/sensorsproject
sensors/urls.py
Python
cc0-1.0
410
0.004878
from django.conf.urls import patterns, url import sensors.views urlpatterns = patterns('sensors.views', url(r'^$', sensors.views.HomeViewClass.as_view(), name='home'), url(r'^latest$', sensors.views.LatestViewClass.as_view(), name='latest'), url(r'^recent$', sensors.views.RecentViewClass.as_view(), name='r...
)
pjwerneck/device-mesh
mesh/views/api_errors.py
Python
apache-2.0
888
0
# -*- coding: utf-8 -*- from flask import request, Response from werkzeug.http import parse_accept_header import simplejson as json from uuid import uuid4 def generic_api_error(e): resp = json.dumps({"error": {"status": e.code, "title": e.name, "...
"message": e.description, "logref": uuid4().hex }}) return Response(resp, status=e.code, mimetype='application/json') def register_error_handlers(x): x.errorhandler(400)(generic_api_error) x.errorhandler(40...
rorhandler(403)(generic_api_error) x.errorhandler(404)(generic_api_error) x.errorhandler(405)(generic_api_error) x.errorhandler(406)(generic_api_error) x.errorhandler(409)(generic_api_error)
HXLStandard/libhxl-python
tests/test_model.py
Python
unlicense
18,634
0.001556
""" Unit tests for the hxl.model module David Megginson October 2014 License: Public Domain """ import io, unittest import hxl from hxl.datatypes import normalise_string from hxl.model import TagPattern, Dataset, Column, Row, RowQuery DATA = [ ['Organisation', 'Cluster', 'District', 'Affected'], ['#org', '#s...
f): self.column = Column(tag=TestColumn.HXL_TAG, attributes=TestColumn.ATTRIBUTES, header=TestColumn.HEADER_TEXT) def test_variables(self): self.assertEqual(TestColumn.HXL_TAG, self.column.tag) self.assertEqual(set(TestColumn.ATTRIBUTES), self.column.attributes) self.assertEqual(Tes...
_TEXT, self.column.header) def test_display_tag(self): self.assertEqual(TestColumn.HXL_TAG + '+' + "+".join(TestColumn.ATTRIBUTES), self.column.display_tag) def test_case_insensitive(self): column = Column(tag='Foo', attributes=['X', 'y']) self.assertEqual('foo', column.tag) se...
ivano666/tensorflow
tensorflow/contrib/learn/python/learn/estimators/tensor_signature.py
Python
apache-2.0
4,029
0.007198
# 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 by applicable law o...
"""Signature of the `Tensor` object. Useful to check compatibility of tensors. Attributes: dtype: `DType` object. shape: `TensorShape` object. """ def __new__(cls, tensor): if is
instance(tensor, ops.SparseTensor): return super(TensorSignature, cls).__new__( cls, dtype=tensor.values.dtype, shape=None, is_sparse=True) return super(TensorSignature, cls).__new__( cls, dtype=tensor.dtype, shape=tensor.get_shape(), is_sparse=False) def is_compatible_with(self, other): ...
bokeh/bokeh
sphinx/source/docs/user_guide/examples/graph_interaction_nodesadjacentnodes.py
Python
bsd-3-clause
1,359
0.006623
import networkx as nx from bokeh.io import output_file, show from bokeh.models import (BoxSelectTool, Circle, HoverTool, MultiLine, NodesAndAdjacentNodes, Plot, Range1d, TapTool) from bokeh.palettes import Spectral4 from bokeh.plotting import from_
networkx G=nx.karate_club_graph() plot = Plot(width=400, height=400, x_range=Range1d(-1.1,1.1), y_range=Range1d(-1.1,1.1)) plot.title.text = "Graph Interaction Demonstration" plot.add_tools(HoverTo
ol(tooltips=None), TapTool(), BoxSelectTool()) graph_renderer = from_networkx(G, nx.circular_layout, scale=1, center=(0,0)) graph_renderer.node_renderer.glyph = Circle(size=15, fill_color=Spectral4[0]) graph_renderer.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2]) graph_renderer.node_renderer...
calston/pitool
pitool/service.py
Python
mit
6,191
0.001454
import copy import exceptions import json import math import time try: import RPi.GPIO as gpio except: gpio = None from twisted.application import service from twisted.internet import task, reactor, defer from twisted.python import log from twisted.python.filepath import FilePath from twisted.web import serve...
flushBuffer() for g in self.inputs: g.listen() if trigger is None: reactor.c
allLater(self.window/1000000.0, self.sendOneshotBuffers) def cmd_stop_buffer_stream(self, args): if self.t: self.t.stop() log.msg("Stopping buffer send") self.t = None def cmd_start_buffer_stream(self, args): if not self.t: log.msg("Starting buf...
jdfekete/progressivis
progressivis/linalg/__init__.py
Python
bsd-2-clause
6,390
0
# flake8: noqa from .elementwise import ( Unary, Binary, ColsBinary, Reduce, func2class_name, unary_module, make_unary, binary_module, make_binary, reduce_module, make_reduce, binary_dict_int_tst, unary_dict_gen_tst, binary_dict_gen_tst, ) from .linear_map import ...
p", "Exp2", "Expm1", "Fabs", "Floor", "Frexp", "Invert", "Isfinite", "Isinf", "Isnan", "Isnat", "Log", "Log10", "Log1p", "Log2", "LogicalNot", "Modf", "Negative", "Positive", "Rad2deg", "Radians", "Reciprocal", "Rint", "Sign", ...
, "Sin", "Sinh", "Spacing", "Sqrt", "Square", "Tan", "Tanh", "Trunc", "Abs", "Add", "Arctan2", "BitwiseAnd", "BitwiseOr", "BitwiseXor", "Copysign", "Divide", "Divmod", "Equal", "FloorDivide", "FloatPower", "Fmax", "Fmin", "Fmod"...
cderici/question-analyzer
src/data/maltImporter.py
Python
gpl-2.0
1,766
0.023783
import codecs from question import Question class MaltImporter: questions = []; def getRawQuestionTexts(self, qFilePath): qFile = codecs.open(qFilePath, 'r', 'utf-8');##utf-8 file qTexts = qFile.readlines(); qTexts = [text.strip().split('|') for text in qTexts]; return q...
if(len(text) > 1): if(text[1] == "."): qParts.append(text); questions.append(qParts); qParts = []; else: qParts.append([t.replace('\ufeff', '') for t in text]); ...
def importMaltOutputs(self, qFilePath, qParsedFilePath): self.questions = []; qTexts = self.getRawQuestionTexts(qFilePath); qTextParts = self.getParsedQuestionTexts(qParsedFilePath); length = len(qTexts); for i in range(0, length): question = Question(qTexts[...
hagabbar/pycbc_copy
examples/noise/timeseries.py
Python
gpl-3.0
481
0
import pycbc.noise import pycbc.psd import pylab # The color of the noise matches a PSD which you provide flow = 30.0 delta_f = 1.0 / 16 flen = int(2048 / delta_f) + 1 psd = pycbc.psd.aLIGOZeroDetHighPower(flen, delta_f, flow) # Generate 32 seconds of noise at 4096 Hz delta_t = 1.0 / 4096 tsamples = int(32 / de
lta_t) ts = pycbc.noise.noise_from_psd(tsamples, delta_t, psd, seed=127) pylab.plot(ts.sample_times, ts) pylab.ylabel('Strain') py
lab.xlabel('Time (s)') pylab.show()
agry/NGECore2
scripts/mobiles/corellia/slice_hound.py
Python
lgpl-3.0
1,618
0.027194
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
nt(35) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setBoneAmount(30) mobileTemplate.setSocialGroup("slice hound") mobileTemplate.setAssistRange(2) mobileTemplate.setStalker(False) mobileTemplate.setOptionsBitmask(Options.ATTACKABLE) templates = Vector() templates.a
dd('object/mobile/shared_corellian_slice_hound.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTempl...
CybOXProject/python-cybox
examples/demo.py
Python
bsd-3-clause
1,287
0.001554
#!/usr/bin/env python # Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. ''' CybOX Common Indicator helper Demo Demonstrates the use of the Cybox Common Indicator helper. Creates a CybOX Observables document containing a ''' import sys from pprint import pprint ...
ables_doc = Observables([ domain, ipv4, url, email, file_,
]) print(observables_doc.to_xml(encoding=None)) pprint(observables_doc.to_dict()) if __name__ == "__main__": main() sys.exit()
theo-l/django
tests/managers_regress/tests.py
Python
bsd-3-clause
11,168
0.001074
from unittest import skipUnless from django.db import models from django.template import Context, Template from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_apps from django.utils.version import PY37 from .models import ( AbstractBase1, AbstractBase2, Abstra...
ract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase1.objects.all() @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') @isolate_apps('managers_regress') def test_swappable_manager(self): class SwappableModel(models.Model): class Meta...
sing the manager on a swappable model should # raise an attribute error with a helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, ms...
yangyingchao/TeleHealth
src/client/python/THSocket.py
Python
gpl-3.0
1,613
0.0031
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import THMessage import struct SERVER_PORT = 5678 SERVER_HOST = "localhost" TMP_FLAG = 1 HEADER_FMT = "BBBBL" HEADER_LENGTH = 16 # XXX: Update this. class ClientSocket: """ This class create a socket that connects to specified host server and ...
ORT): """ """ try: self.soc
k = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) self.isOK = True except: self.isOk = False finally: pass def Send(self, msg): """ Send msg with header. Procedure: 1. Send Header. 2...
saullocastro/pyNastran
pyNastran/bdf/cards/elements/beam.py
Python
lgpl-3.0
15,046
0.002858
# pylint: disable=R0904,R0902,E1101,E1103,C0111,C0302,C0103,W0101 from six import string_types import numpy as np from numpy.linalg import norm from pyNastran.utils import integer_types from pyNastran.bdf.cards.elements.bars import CBAR, LineElement from pyNastran.bdf.bdf_interface.assign_type import ( int...
elif n == 14: self.wb[0] = value elif n == 15: self.wb[1] = value elif n == 16: self.wb[2] = value else: if self.g0 is not None: if n == 5:
self.g0 = value else: # offt msg = 'Field %r=%r is an invalid %s entry or is unsupported.' % ( n, value, self.type) raise KeyError(msg) else: if n == 5: self.x[0] = value ...
willingc/vms
vms/job/models.py
Python
gpl-2.0
675
0.001481
from django.core.validators import RegexValidator from django.db import models from event.models import Event class Job(models.Model): id = models.AutoField(primary_key=True) event = models.ForeignKey(Event) name = models.CharField(
max_length=75, validators=[ RegexValidator( r'^[(A-Z)|(a-z)|(\s)|(\')]+$', ), ], ) start_date = models.DateField() end_date = models.DateField() description = models.TextField( blank=True, validators=[ RegexValid
ator( r'^[(A-Z)|(a-z)|(0-9)|(\s)|(\.)|(,)|(\-)|(!)|(\')]+$', ), ], )
adfinis-sygroup/pyapi-gitlab
gitlab_tests/pyapi-gitlab_test.py
Python
apache-2.0
20,830
0.004705
""" pyapi-gitlab tests """ import unittest2 as unittest import gitlab import os import time import random import string try: from Crypto.PublicKey import RSA ssh_test = True except ImportError: ssh_test = False user = os.environ.get('gitlab_user', 'root') password = os.environ.get('gitlab_password', '5ive...
andom.choice(string.ascii_uppercase + string.digits) for _ in range(8)) rsa_key = RSA.generate(1024) assert isinstance(self.git.adddeploykey(project_id=self.project_id, title=name,
key=str(rsa_key.publickey().exportKey(format="OpenSSH"))), dict) keys = self.git.getdeploykeys(self.project_id) self.assertGreater(len(keys), 0) key = keys[0] assert isinstance(self.git.getdeploykey(self.project_id, key["id"]), dict) self....
centricular/meson
mesonbuild/scripts/vcstagger.py
Python
apache-2.0
1,568
0.005102
#!/usr/bin/env python3 # Copyright 2015-2016 The Meson development team # 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...
__main__'
: sys.exit(run(sys.argv[1:]))
kohr-h/odl
odl/test/operator/pspace_ops_test.py
Python
mpl-2.0
6,845
0
# Copyright 2014-2017 The ODL contributors # # This file is part of ODL. # # 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 https://mozilla.org/MPL/2.0/. from __future__ import division import pytes...
y), true_adj(y))
op = odl.ProductSpaceOperator([[2 * A, -A]]) true_adj = odl.ProductSpaceOperator([[2 * A.adjoint], [-A.adjoint]]) adj = op.adjoint assert adj.domain == op.range assert adj.range == op.domain y = op.range.one() assert all_almost_equal(adj(y), true_adj(y...
ptroja/spark2014
docs/lrm/review/release 0_3/tn_local_check.py
Python
gpl-3.0
1,182
0.005922
#!/usr/bin/env python """ This does mostly the same as the review token commit hook, but is designed to run locally. It will echo to standard out a fixed up version of the review token given to it; this can be used to quickly apply any format changes to a token (such as new fields). It will then ...
tn_lib import parse_tn, write_tn # Deal with a bad command line if len(sys.argv) != 2: print >> sys.stderr, "You will need to specify a file to parse." sys.exit(1) # Parse TN tmp = parse_tn(os.path.basename(sys.argv[1]), open(sys.argv[1]).read()) # Print out corrected TN print write_tn(tmp).rstrip() # Report...
s.stderr, "-" * 80 print >> sys.stderr, "The review token %s contains "\ "the following errors:" % tmp["ticket"] for e in tmp["errors"]: print >> sys.stderr, " - %s" % e
IL2HorusTeam/il2fb-events-parser
docs/conf.py
Python
lgpl-3.0
8,504
0.00588
# coding: utf-8 # # IL-2 FB Events Parser documentation build configuration file, created by # sphinx-quickstart on Sat Nov 22 10:43:38 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 # autogenerated file....
static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] #
Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. ...
grandcat/chordentlich
code/helpers/test_iniParser.py
Python
apache-2.0
423
0.014184
#!/usr/bin/python3 # Note: Always use unittest.sh
to run the tests! import unittest import imp from helpers.iniParser import IniParser class TestIniParser(unit
test.TestCase): def test_property_get(self): inip = IniParser("configExample.ini") self.assertEqual(inip.get("PORT", "DHT"), '4424') self.assertEqual(inip.get("HOSTNAME", "DHT"), "127.0.0.1") if __name__ == '__main__': unittest.main()
grant-olson/pyasm
__init__.py
Python
bsd-3-clause
327
0.012232
from x86asm import codePackageFromFile from x86cpToMemory import CpToMemory
from pythonConstants import PythonConstants import cStringIO import excmem def pyasm(scope,s): cp = codePackageFromFile(cStringIO.StringIO(s),PythonConstants) mem = CpToMemory(cp) mem.Make
Memory() mem.BindPythonFunctions(scope)
google-research/google-research
gfsa/training/train_util.py
Python
apache-2.0
14,842
0.007681
# 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...
in jax.tree_leaves(agg_grads)])) # Apply updates. updated_optimizer = optimizer.apply_gradient(agg_grads,
**optimizer_hyper_params) return updated_optimizer, grads_ok, agg_metrics, agg_grads def _build_parallel_train_step(): """Builds an accelerated version of the train step function.""" # We need to wrap and unwrap so that the final function can be called with # keyword arguments, but we still maintain...
elkeschaper/tral
tral/conftest.py
Python
gpl-2.0
146
0
import pytest def py
test_runtest_setup(item): if 'notfixed' in item.keywords: pytest.skip("Skipping tests that are not fixed yet."
)
BlackPole/bp-enigma2
lib/python/Components/Converter/ServiceInfo.py
Python
gpl-2.0
6,815
0.028467
from Components.Converter.Converter import Converter from enigma import iServiceInformation, iPlayableService from Components.Element import cached from Tools.Transponder import ConvertToHumanReadable class ServiceInfo(Converter, object): HAS_TELETEXT = 0 IS_MULTICHANNEL = 1 IS_CRYPTED = 2 IS_WIDESCREEN = 3 SUBSE...
f.getServiceInfoString(info, iServiceInformation.sSID) elif self.type == self.FRAMERATE: return self.getServiceInfoString(info, iServiceInformation.sFrameRate, lambda x: "%d fps" % ((x+500)/1000)) elif self.type == self.TRANSFERBPS: return self.getServiceInfoString(info, iServiceInformation.sTransferBPS, lamb...
if feinfo is None: return "" feraw = feinfo.getAll(False) if feraw is None: return "" fedata = ConvertToHumanReadable(feraw) if fedata is None: return "" frequency = fedata.get("frequency") if frequency: frequency = str(frequency / 1000) sr_txt = "Sr:" polarization = fedata.get("...
datawire/mdk
functionaltests/source/continue_trace.py
Python
apache-2.0
330
0.00303
""
"Write some logs.""" from __future__ import print_function import sys import time from mdk import start mdk = start() def main(): context = sys.argv[1] session = mdk.join(context) session.info("process2", "world") time.sleep(5) # make sure it's written mdk.sto
p() if __name__ == '__main__': main()
simondlevy/m021v4l2
opencv/python/lic570_capture.py
Python
gpl-3.0
1,319
0.002274
#!/usr/bin/env python3 ''' lic570_capture.py : capture frames from Leopard Imaging LI-USB30-C570 camera and display them using OpenCV Copyright (C) 2017 Simon D. Levy This file is part of M021_V4L2. M021_V4L2 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Licens...
e the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with M021_V4L2. If not, see <http://www.gnu.org/licenses/>. ''' import cv2 from m021v4l2 import Capture1600x1200 from time import time cap = Capture1600x1200() start = time() while True: # Capture frame-by-frame ret, frame = cap.read(...
Naoto-Imamachi/MIRAGE
scripts/module/preparation/AA2_add_miRNA_infor_miR-155_rev_seed.py
Python
mit
1,046
0.011472
#!/usr/bin/env python import re from operator import itemgetter ref_file = open('../../../data/RNA-seq_miR-124_miR-155_transfected_HeLa/gene_exp_miR-155_overexpression_RefSeq_Rep_isoforms.diff','r') input_
file = open('../../../result/mirage_output_rev_seed_miR-155_vs_RefSeq_NM_2015-07-30.txt','r') output_file = open('../../../result/mirage_output_rev_seed_miR-155_vs_RefSe
q_NM_2015-07-30_miR-155_overexpression.result','w') ref_dict = {} header = '' for line in ref_file: line = line.rstrip() data = line.split("\t") if data[0] == 'gr_id': header = line continue refid = data[2] ref_dict[refid] = line for line in input_file: line = l...
gmathers/iii-addons
iii-repair/__init__.py
Python
agpl-3.0
21
0.047619
import
iii_mrp_r
epair
evernym/zeno
plenum/common/messages/message_base.py
Python
apache-2.0
5,968
0.000168
from collections import OrderedDict from operator import itemgetter from typing import Mapping, Dict from plenum.common.types import f from plenum.common.constants import OP_FIELD_NAME, SCHEMA_IS_STRICT from plenum.common.exceptions import MissingProtocolVersionError from plenum.common.messages.fields import FieldVal...
field, value)) def _raise_invalid_fields(self, field, value, reason): raise TypeError("{} {} " "({}={})".format(self.__error_msg_prefix, reason, field, value)) def _raise_invalid_message(self, reason): ...
x, reason)) @property def __error_msg_prefix(self): return 'validation error [{}]:'.format(self.__class__.__name__) class MessageBase(Mapping, MessageValidator): typename = None def __init__(self, *args, **kwargs): if args and kwargs: raise ValueError("*args, **kwargs can...
superfluidity/RDCL3D
code/lib/toscanfv/toscanfv_parser.py
Python
apache-2.0
2,078
0.006737
import json import pyaml import yaml from lib.util import Util from lib.parser import Parser import logging import traceback import glob import os logging.basicConfig(level=logging.DEBUG) log = logging.getLogger('ToscanfvParser') class ToscanfvParser(Parser): """Parser methods for toscanfv project type """ ...
super(ToscanfvParser, self).__init__() @classmethod def importprojectdir(cls,dir_project, file_type): """Imports all descriptor files under a given folder this method is specific for Toscanfv project type """ project = { 'toscayaml':{}, '...
: cur_type_path = os.path.join(dir_project, desc_type.upper()) log.debug(cur_type_path) if os.path.isdir(cur_type_path): for file in glob.glob(os.path.join(cur_type_path, '*.'+file_type)): if file_type == 'json': project[des...
idan/oauthlib
oauthlib/oauth2/rfc6749/endpoints/revocation.py
Python
bsd-3-clause
5,212
0.000767
""" oauthlib.oauth2.rfc6749.endpoint.revocation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An implementation of the OAuth 2 `Token Revocation`_ spec (draft 11). .. _`Token Revocation`: https://tools.ietf.org/html/draft-ietf-oauth-revocation-11 """ import logging from oauthlib.common import Request from ..errors im...
is unable to locate the token using the given hint, it MUST extend its search accross all of its supported token types. An authorization server MAY ignore this parameter, particularly if it is able to detect the token type automatically. This specification defines two such values: ...
defined in [RFC6749], `section 1.4`_ * refresh_token: A Refresh Token as defined in [RFC6749], `section 1.5`_ Specific implementations, profiles, and extensions of this specification MAY define other values for this parameter us...
haiyangd/cockpit_view
test/storagelib.py
Python
lgpl-2.1
6,735
0.001782
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Cockpit. # # Copyright (C) 2015 Red Hat, Inc. # # Cockpit is free software; you ca
n redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # Cockpit is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without eve...
# You should have received a copy of the GNU Lesser General Public License # along with Cockpit; If not, see <http://www.gnu.org/licenses/>. import os from testlib import * def content_action_btn(index): return "#content .list-group li:nth-child(%d) .btn-group" % index class StorageCase(MachineCase): def se...
MaestroGraph/sparse-hyper
sparse/tensors.py
Python
mit
10,861
0.003775
import torch from torch import FloatTensor, LongTensor from torch.autograd import Variable import torch.nn.functional as F from sparse.util import prod import util, sys from util import d """ Utility functions for manipulation tensors """ def flatten_indices_mat(indices, in_shape, out_shape): """ Turns a n ...
ix multiplication with gradients over the value-vector Does not work with batch dim. """ @staticmethod def forward(ctx, indices, values, size, xmatrix): # print(type(size), size, list(size), intlist(size)) matrix = torch.cuda.sparse.FloatTensor(indices, val
ues, torch.Size(intlist(size))) ctx.indices, ctx.matrix, ctx.xmatrix = indices, matrix, xmatrix return torch.mm(matrix, xmatrix) @staticmethod def backward(ctx, grad_output): grad_output = grad_output.data # -- this will break recursive autograd, but it's the only way to get ...
klebercode/esperancanordeste
esperancanordeste/catalog/views.py
Python
mit
2,030
0
# coding: utf-8 from django.db.models import Q from django.views import generic # from django.views.generic.dates import (YearArchiveView, MonthArchiveView, # DayArchiveView) from esperancanordeste.context_processors import EnterpriseExtraContext from esperancanordeste.catalog....
.request.GET.get('search', '') context['search'] = searc
h context['category_list'] = Category.objects.all() context['catalog_list'] = Catalog.objects.all() return context class ProductCategoryListView(ProductListView): """ Herda de EntryListView mudando o filtro para tag selecionada """ def get_queryset(self): """ In...
chrisortman/CIS-121
k0776243/exercises/ex18.py
Python
mit
526
0.015209
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok that *args is actually pointless, we can just do this def print_two_again(arg1, arg2): print "arg1: %r, arg2: %r" % (arg1,
arg2) # this just takes one argument def print_one(arg1): print "arg1: %r" % arg1
# this one takes no arguments def print_none(): print "I got nothin'." print_two("Zed", "Shaw") print_two_again("Zed","Shaw") print_one("First!") print_none()
wilima/herocomp
herocomp/asm/Asm.py
Python
mit
901
0
def filename_directive(filename): return "\t.file\t\"{0}\"\n".format(filename) def compiler_ident_directive(): return "\t.ident\t\"{0}\"\n".format("HEROCOMP - Tomas Mikula 201
7") def text_directive(): return "\t.text\n" def data_directive(): return "\t.data\n" def quad_directive(arg): return "\t.quad\t{}\n".format(arg) def global_array(identifier, size): return "\t.comm {0},{1},32\n".format(identifier, size * 8) def global_directive(arg): return "\t.global\t{0}...
def instruction(name, *args): code = "\t{0}\t".format(name) for i in range(len(args)): if i == len(args) - 1: code += "{0}".format(args[i]) else: code += "{0}, ".format(args[i]) code += "\n" return code def number_constant(number): return "${0}".format(nu...
acoecorelearning/Algebra1wRobots
4-RaceToTie2/raceToTie2.py
Python
gpl-3.0
884
0.020362
# This work is licensed by James Town and ACOE Core Learning under a # Creative Commons Attribution-NonCommercial-ShareAlike 4.0 # International License: http://creativecommons.org/licenses/by-nc-sa/4.0/ import linkbot # loads library for the Linkbots robot1 = linkbot.Linkbot('AB
CD') #assigns the name robot1 to the first robot robot2 = linkbot.Linkbot('1234') #assigns the name robot2 to the second robot robot1.setJointSpeeds(speed, 0, speed) #changes robot1's speed (degrees/second) robot1.moveNB(some number of degrees, 0, -so
me number of degrees) #moves the robot some number of degrees robot2.setJointSpeeds(speed, 0, speed) #changes robot2's speed (degrees/second) robot2.moveNB(some number of degrees, 0, -some number of degrees) #moves the robot some number of degrees robot1.moveWait() #waits for moveNB to finish robot2.moveWait() #waits...
updownlife/multipleK
dependencies/biopython-1.65/build/lib.linux-x86_64-2.7/Bio/Emboss/Applications.py
Python
gpl-2.0
53,929
0.003931
# Copyright 2001-2009 Brad Chapman. # Revisions copyright 2009-2010 by Peter Cock. # Revisions copyright 2009 by David Winter. # Revisions copyright 2009-2010 by Leighton Pritchard. # All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that ...
"Report warnings."), _Switch(["-error", "error"], "Report errors."), _Switch(["-die", "die"],
"Report dying program messages."), ] try: # Insert extra parameters - at the start just in case there # are any arguments which must come last: self.parameters = extra_parameters + self.parameters except AttributeError: # Should...
douglasstarnes/tcguestbook
main.py
Python
mit
1,494
0
from flask import Flask, request, render_template, redirect from flask import send_from_directory from mongoengine import Document, StringField, DateTimeField, connect import os import datetime app = Flask(__name__) app.debug = True class Entry(Document): author = StringField() message = StringField() ...
me ) entry.save() return redirect("/") # Redirect after POST is Good Behavor! @app.route("/styles/<path:filename>") def styles(filename): """Allow Flask to server our CSS files.""" return send_from_directory("styles", filename) if __name__ == "__main__": host = "localhost" p...
else: connect("tcguestbook") # A MongoDB connection app.run(port=port, host=host)
zerg000000/mario-ai
src/main/java/amico/python/agents/evaluationinfo.py
Python
bsd-3-clause
1,575
0.006349
__author__="Sergey Karakovskiy" __date__ ="$Mar 18, 2010 10:48:28 PM$" class Inspectable(object): """ All derived classes gains the ability to print the names and values of all their fields""" def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, dict([(x,y) for (x,y) in self.__...
print "flowersDevoured = ", evInfo[2] print "killsByFire = ", evInfo[3] print "killsByShell = ", evInfo[4] print "killsByStomp = ", evInfo[5] print "killsTotal = ", evInfo[6]
print "marioMode = ", evInfo[7] print "marioStatus = ", evInfo[8] print "mushroomsDevoured = ", evInfo[9] print "marioCoinsGained = ", evInfo[10] print "timeLeft = ", evInfo[11] print "timeSpent = ", evInfo[12] print "hiddenBlocksFound = ", evInfo[13] self.width...
kibitzr/kibitzr
kibitzr/cli.py
Python
mit
2,704
0
import sys import logging import click import entrypoints LOG_LEVEL_CODES = { "debug": logging.DEBUG, "info": logging.INFO, "warning": logging.WARNING, "error": logging.ERROR, } def merge_extensions(click_group): """ Each extension is called with click group for ultimate agility while p...
ontext def cli(ctx, log_level): """Run kibitzr COMMAND --help for detailed descriptions""" ctx.obj = {'log_level': LOG_LEVEL_CODES[log_level.lower()]} @cl
i.command() def version(): """Print version""" from kibitzr import __version__ as kibitzr_version print(kibitzr_version) @cli.command() def firefox(): """Launch Firefox with persistent profile""" from kibitzr.app import Application Application().run_firefox() @cli.command() @click.argument('...
vrbagalkote/avocado-misc-tests-1
generic/service_check.py
Python
gpl-2.0
3,084
0
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that i...
atadir + '/services.cfg' parser.read(config_file) services_list = parser.get(detec
ted_distro.name, 'services').split(',') if 'PowerNV' in open('/proc/cpuinfo', 'r').read(): services_list.extend(['opal_errd', 'opal-prd']) else: services_list.extend(['rtas_errd']) services_failed = [] runner = process.run for service in services_list: ...
vegphilly/vegphilly.com
vegancity/api.py
Python
gpl-3.0
4,516
0
from django.conf.urls import url from django.contrib.auth.models import User from tastypie import fields from tastypie.resources import ModelResource from tastypie.utils import trailing_slash from vegancity import models from .search import master_search from tastypie.api import Api def build_api(): v1_api = Api...
full=True) food_rating = fields.IntegerField(null=True, readonly=True) atmosphere_rating = fields.IntegerField(null=True, readonly=True) def prepend_urls(self): url_template = r'^(?P<reso
urce_name>%s)/search%s$' url_body = url_template % (self._meta.resource_name, trailing_slash()) response_url = url(url_body, self.wrap_view('get_search'), name='api_get_search') return [response_url] def get_search(self, request, **kwargs): raw_results ...
solvo/derb
report_builder/create_data.py
Python
gpl-3.0
9,928
0.003525
import random import datetime from async_notifications.models import EmailTemplate from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from report_builder import models PROJECT_NAMES = [ 'Project Manhattan', 'Sysadmin association project', 'Operation Know-...
work?', 'How consistently does your supervisor punish employees for bad work?', 'How reasonable are the decisions made by your supervisor?', 'Does your supervisor take too much time to make decisi
ons, too little time, or about the right amount of time?', 'How often does your supervisor listen to employees\' opinions when making decisions?', 'How easy is it for employees to disagree with the decisions made by your supervisor?', 'When you make a mistake, how often does your supervisor respond construc...
Eksmo/calibre
setup/upload.py
Python
gpl-3.0
10,267
0.009253
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <[email protected]>' __docformat__ = 'restructuredtext en' import os, subprocess, hashlib, shutil, glob, stat, sys, time from subprocess import check_call from tempfile import NamedT...
, '&&', 'python', 'hosting.py']+args) # }}} class UploadInstallers(Command): # {{{ def add_options(self, parser): parser.add_option('--replace', default=False, action='store_true', help= 'Replace existing installers, when uploading to google') def r
un(self, opts): all_possible = set(installers()) available = set(glob.glob('dist/*')) files = {x:installer_description(x) for x in all_possible.intersection(available)} tdir = mkdtemp() try: self.upload_to_staging(tdir, files) self.upload_t...
ncss-tech/geo-pit
updateAttTable/wholesale_change.py
Python
gpl-2.0
3,943
0.012934
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: charles.ferguson # # Created: 20/05/2015 # Copyright: (c) charles.ferguson 2015 # Licence: <your licence> #--------------------------------------------------------------...
' + upVal + ')') arcpy.SetProgressorPosition() elif upVal == 'None': arcpy.AddWarning('No update value specified for ' + key) arcpy.SetProgressorPosition() else: n=0 wc = '"AREASYMBOL" = ' "'" + areaParam + "' AND \"MUSYM\" = '" + key + ...
dit: ## with arcpy.da.UpdateCursor(spTblParam, "MUSYM", where_clause=wc)as rows: for row in rows: row[0] = str(upVal) rows.updateRow(row) n=n+1 if n > 0: ar...
dufresnedavid/canada
account_tax_expense_include/__openerp__.py
Python
agpl-3.0
1,843
0
# -*- encoding: utf-8 -*- ############################################################################## # # Odoo, Open Source Management Solution # Copyright (C) 2010 - 2014 Savoir-faire Linux # (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # ...
ncluded in expense ========================= This module adds a checkbox to tax to include tax in expense invoices. It is useful if your taxes are not included in the price, but you want to ease the life of your employees by allowing them to enter their expenses with the taxes included. Contributors ------------ * Jon...
pends": ["account"], "data": [ "account_tax_view.xml", ], "installable": True }
moneymaker365/plugin.video.ustvvod
resources/lib/main_aenetwork.py
Python
gpl-2.0
8,687
0.036491
#!/usr/bin/python # -*- coding: utf-8 -*- import common import connection import m3u8 import base64 import os import ustvpaths import re import simplejson import sys import time import urllib import xbmc import xbmcaddon import xbmcgui import xbmcplugin from bs4 import BeautifulSoup, SoupStrainer addon = xbmcaddon.Add...
l): episodes = [] episode_data = connection.getURL(episode_url) episode_tree = simplejson.loads(episode_data)['Items'] for episode_item in episode_tree: if episode_
item['isBehindWall'] == 'false': url = episode_item['playURL_HLS'] episode_duration = int(episode_item['totalVideoDuration']) / 1000 try: episode_airdate = common.format_date(episode_item['airDate'].split('T')[0],'%Y-%m-%d') except: episode_airdate = -1 episode_name = episode_item['title'] try...
PlayCircular/play_circular
apps/paginas/admin.py
Python
agpl-3.0
12,654
0.035731
#coding=utf-8 # Copyright (C) 2014 by Víctor Romero Blanco <info at playcircular dot com>. # http://playcircular.com/ # It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise. # You can get copies of the licenses here: http://www.affero.org/oagpl.html # AFFERO GENERAL PUBLIC LICENSE is also in...
return extra return extra verbose_name = _(u'idioma de categoria') verbose_name_plural = _(u'idiomas de categorias') ############################################################################################################################ class Idiomas_P
agina_Inline(admin.StackedInline): model = Idiomas_pagina formset = Idioma_requerido_formset prepopulated_fields = {"slug": ("titulo",)} extra = 1 max_num = 5 def get_extra(self, request, obj=None, **kwargs): extra = 1 if obj: extra = 0 return extra return extra verbose_name = _(u'idioma de la pagi...
nathanielbecker/business-contacter-django-app
myproject/cookie_app/migrations/0008_auto_20141120_0807.py
Python
apache-2.0
847
0.002361
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class
Migration(migrations.Migration): dependencies = [ ('cookie_app', '0007_auto_20141118_0707'), ] operations = [ migrations.CreateModel( name='DateTime', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_ke...
('datetime', models.DateTimeField(auto_now_add=True, null=True)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='barebones_crud', name='Created', field=models.ForeignKey(to='cookie_...
napalm-automation/napalm-logs
napalm_logs/transport/cli.py
Python
apache-2.0
559
0
# -*- coding: utf-8 -*- ''' CLI transport for napalm-logs. Useful for debug only, publi
shes (prints) on the CLI. ''' from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals # Import napalm-logs pkgs from napalm_logs.transport.base import TransportBase class CLITransport(TransportBase): ''' CLI transport class. ''' NO_ENCRYPT...
published over this channel. def publish(self, obj): print(obj)
stormi/tsunami
src/primaires/objet/types/pierre_feu.py
Python
bsd-3-clause
2,715
0.004071
# -*-coding:Utf-8 -* # Copyright (c) 2012 NOEL-BARON Léo # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # li...
"""Constructeur de l'objet""" BaseType.__init__(self, cle) self.efficacite = 30 # Editeur self.etendre_editeur("f", "efficacite", Entier, self, "efficacite", 1, 50) def travailler_enveloppes(self, enveloppes): """Travail sur les enveloppes""" ...
= "Entrez une efficacité : " efficacite.aide_courte = \ "Entrez l'|ent|efficacité|ff| initiale de la pierre, de " \ "|cmd|1|ff| (quasi nulle) à |cmd|50|ff| (maximale).\nCette " \ "efficacité conditionne la solidité de la pierre et se " \ "décrémente de 1\nà chaqu...
RyanDJLee/pyta
tests/test_type_inference/test_assign_tuple.py
Python
gpl-3.0
4,373
0.002058
import astroid from nose.tools import eq_ import tests.custom_hypothesis_support as cs from tests.custom_hypothesis_support import lookup_type from python_ta.transforms.type_inference_visitor import NoType from python_ta.typecheck.base import TypeInfo, TypeFail from typing import Tuple def generate_tuple(length: int,...
, 11 """ module, _ = cs._parse_text(program) for assign_node in module.nodes_of_class(astroid.Assign): assert not isinstance(assign_node.inf_type, TypeFail) def test_tuple_attribute_variable(): program = """ class A: def __init__(self): self.first_attr = 0 s...
st_attr, a.second_attr = some_list """ module, _ = cs._parse_text(program) for assign_node in module.nodes_of_class(astroid.Assign): assert not isinstance(assign_node.inf_type, TypeFail) def test_tuple_empty(): program = """ def f(x): a = () b = (x,) a = b """ ...
meihuanyu/rental
ipproxytool/spiders/proxy/hidemy.py
Python
mit
1,764
0.010204
#-*- coding: utf-8 -*- import utils from scrapy import Selector from .basespider import BaseSpider from proxy import Proxy class HidemySpider(BaseSpider): name = 'hidemy' def __init__(self, *a, **kw): super(HidemySpider, self).__init__(*a, **kw) self.urls = ['https://hidemy.name/en/proxy-l...
al.xpath('//td[2]/text()').extract_first() country = val.xpath('//td[3]/div/text()').extract_first() anonymity = val.xpath('//td[6]/text()').extract_first() proxy = Proxy() proxy.set_value( ip = ip, port = port, ...
self.add_proxy(proxy = proxy)
jonlabelle/SublimeJsPrettier
tests/validate_json_format.py
Python
mit
5,940
0
import codecs import json import re RE_LINE_PRESERVE = re.compile(r'\r?\n', re.MULTILINE) RE_COMMENT = re.compile( r'''(?x) (?P<comments> /\*[^*]*\*+(?:[^/*][^*]*\*+)*/ # multi-line comments | [ \t]*//(?:[^\r\n])* # single line comments ) | (?P<code> ...
lf.log_failure(W_NL_START, count) if not line.endswith('\n'): self.log_failure(W_NL_END, count) if RE_TRAILING_SPACES.match(line): self.log_failure(W_TRAILING_SPACE, count) if self.use_tabs and ( RE_L
INE_INDENT_TAB if self.use_tabs else RE_LINE_INDENT_SPACE).match(line) is None: self.log_failure(W_INDENT, count) count += 1 f.seek(0) text = f.read() self.index_lines(text) text = self.check_comments(text) self...
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/application_gateway_sku.py
Python
mit
1,526
0
# 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 ...
pacity: int """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, 'capacity': {'key': 'capacity', 'type': 'int'}, } def __init__(self, name=None, tier=None, capacity=None): super(ApplicationGatewaySku, self).__init__() ...
ier self.capacity = capacity
smontoya/authy-python3
authy/api/resources.py
Python
mit
6,164
0.002109
import requests import platform from authy import __version__, AuthyFormatException from urllib.parse import quote # import json try: import json except ImportError: try: import simplejson as json except ImportError: from django.utils import simplejson as json class Resource(object): ...
ils") return App(self, resp) class Stats(Instance): pass class StatsResource(Resource): def fetch(self): resp = self.get("/protected/json/app/stats") return Stats(self, resp) class Phone(Instance): pass class Phones(Resource): def verification_start(self, phone_number
, country_code, via = 'sms'): options = { 'phone_number': phone_number, 'country_code': country_code, 'via': via } resp = self.post("/protected/json/phones/verification/start", options) return Phone(self, resp) def verification_check(self, phone_n...