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
jhen0409/electron
script/upload.py
Python
mit
7,881
0.011166
#!/usr/bin/env python import argparse import errno import os import subprocess import sys import tempfile from lib.config import PLATFORM, get_target_arch, get_chromedriver_version, \ get_platform_key, get_env_var from lib.util import electron_gyp, execute, get_electron_version, \ ...
_chromedriver_version(), get_platform_key(), get_target_arch()) upload_electron(github, release, os.path.join(DIST_DIR, chromedriver)) mksnapshot = 'mksnapshot-{0}-{1}-{2}.zip'.format( ELECTRON_VERSION, get_platform_key
(), get_target_arch()) upload_electron(github, release, os.path.join(DIST_DIR, mksnapshot)) if PLATFORM == 'win32' and not tag_exists: # Upload PDBs to Windows symbol server. execute([sys.executable, os.path.join(SOURCE_ROOT, 'script', 'upload-windows-pdb.py')]) # Upload node headers. ...
rebost/django
django/contrib/gis/tests/layermap/tests.py
Python
bsd-3-clause
12,784
0.003598
from __future__ import absolute_import import os from copy import copy from decimal import Decimal from django.contrib.gis.gdal import DataSource from django.contrib.gis.tests.utils import mysql from django.contrib.gis.utils.layermapping import (LayerMapping, LayerMapError, InvalidDecimal, MissingForeignKey) from...
ayer w/the model. ds = DataSource(inter_shp) # Only the first two features of this shapefile are valid. valid_feats = ds[0][:2] for feat in valid_feats: istate = Interstate.objects.get(name=feat['Name'].value) if feat.fid == 0: self.assertEqual(D...
ed, # because the Interstate model's `length` field has decimal_places=2. self.assertAlmostEqual(feat.get('Length'), float(istate.length), 2) for p1, p2 in zip(feat.geom, istate.path): self.assertAlmostEqual(p1[0], p2[0], 6) self.assertAlmostE...
lbracken/news_data
pipeline/__init__.py
Python
mit
175
0.022857
# -*- codi
ng: utf-8 -*- """ news_data.pipeline ~~~~~~~~~~~~~~~~~~ news_data processing pipeline package :license: MIT, see LIC
ENSE for more details. """
cryos/tomviz
tomviz/python/deleteSlices.py
Python
bsd-3-clause
918
0.001089
def transform_scalars(dataset, firstSlice=None, lastSlice=None, axis=2): """Delete Slices in Dataset""" from tomviz import utils import numpy as np # Get the current dataset. array = utils.get_array(dataset) # Get indices of the slices to be deleted. indices = np.linspace(firstSlice, last...
ified slices. array = np.delete(array, indices, axis) # Set the result as the new scalars. utils.set_array(dataset, array) # Delete corresponding tilt anlges if dataset is a tilt series. if axis == 2: try: tilt_angles = utils.get_tilt_angles(dataset) tilt_angles = n...
lete(tilt_angles, indices) utils.set_tilt_angles(dataset, tilt_angles) except: # noqa # TODO what exception are we ignoring here? pass
deo1/deo1
NaiveNet/NaiveNet.py
Python
mit
5,324
0.019534
# with reference to: https://www.amazon.com/Make-Your-Own-Neural-Network-ebook/dp/B01EER4Z4G import numpy as np from numpy import random as rand import scipy.special from time import sleep def main(): print('\nTesting 3 bit binary encoding classification') # (out: [onehot], in: [binary]) binary_encodi...
learn_rate=0.3, initial_weights='gaussian', loss_function='squared'): self.inodes = input_nodes self.hnodes
= hidden_nodes self.onodes = output_nodes self.activation_function = lambda x: scipy.special.expit(x) # sigmoid / logistic self.lr = learn_rate self.__set_weights(initial_weights) self.__set_loss_function(loss_function) def __repr__(self): members = [(k, st...
hzlf/openbroadcast
website/apps/profiles/migrations/0002_auto__del_field_profile_mobile_provider__add_field_profile_description.py
Python
gpl-3.0
8,152
0.007851
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Profile.mobile_provider' db.delete_column('user_profiles', 'mobile_provider_id') ...
'django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'address2': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'birth_date': ('django.db
.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'description': ('lib.fields.extr...
kwminnick/rackspace-dns-cli
dnsclient/openstack/common/setup.py
Python
apache-2.0
12,670
0.000316
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # 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/...
if os.path.isdir('.git'): git_log_cmd = 'git log --stat' changelog = _run_shell_command(git_log_cmd) mailmap = parse_mailmap() with open("ChangeLog", "w") as changelog_file: changelog_file.write(canonicalize_emails(changelog, mailmap)) def genera
te_authors(): """Create AUTHORS file using git commits.""" jenkins_email = '[email protected]' old_authors = 'AUTHORS.in' new_authors = 'AUTHORS' if os.path.isdir('.git'): # don't include jenkins email address in AUTHORS file git_log_cmd = ("git log --format='%aN <%aE>' | ...
dtudares/hello-world
yardstick/yardstick/ssh.py
Python
apache-2.0
9,436
0
# Copyright 2013: Mirantis 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...
if session.recv_stderr_ready(): stderr_data = session.recv_stderr(4096) LOG.debug("stderr: %r" % stderr_data)
if stderr is not None: stderr.write(stderr_data) continue if session.send_ready(): if stdin is not None and not stdin.closed: if not data_to_send: data_to_send = stdin.read(4096) ...
botswana-harvard/edc-pharma
edc_pharmacy/old/dispense/labels/dispense_label_context.py
Python
gpl-2.0
1,755
0
from django.apps import apps as django_apps edc_pharma_app_config = django_apps.get_app_config('edc_pharma') edc_protocol_app_config = django_apps.get_app_config('edc_protocol') class DispenseLabelContext: """Format dispense record into printable ZPL label context.""" def __init__(self, prescriptions=None, ...
rescription.modified.str
ftime( '%Y-%m-%d'), 'subject_identifier': subject_identifier, 'prepared_by': prescription.user_modified, 'protocol': edc_protocol_app_config.protocol, 'initials': prescription.initials, } @property def context_list(self): context_l...
piotrgiedziun/university
secure_system_networks/lab2/scripts/scan_all.py
Python
mit
835
0
import nmap from prettytable import PrettyTable # scan network - dispaly all opened ports in given range nm = nmap.PortScanner() nm.scan('156.17.40.1-255', '22-443') tab = PrettyTable(["IP address", "Protocol", "Port", "Product name", "V
ersion", "Extra info"]) for host in nm.all_hosts(): for proto in nm[host].all_protocols(): lport = nm[host][proto].keys() lport.sort() for port in lport: # incompatible with installed nmap versi
on if not isinstance(port, int): continue item = nm[host][proto][port] # skip closed if not item['state'] == "open": continue tab.add_row([host, proto, port, item['product'], item['version'], item['extra...
int-0/aftris
beatbox.py
Python
gpl-3.0
1,953
0.00256
#!/usr/bin/env python import pygame from tools import singleton @singleton class Audio(object): def __init__(self, initial_musics={}, initial_sounds={}): if pygame.mixer.get_init() is None: pygame.mixer.init() self.__mute = False self.__sounds = initial_sounds ...
ted:
return True if sound_id not in self.sounds: return False self.__sounds[sound_id].play() return True # Create default instance AUDIO = Audio()
arvindn05/osc-core
osc-server-bom/root/opt/vmidc/bin/vmidcShell.py
Python
apache-2.0
21,993
0.014959
#!/usr/bin/python # Copyright (c) Intel Corporation # Copyright (c) 2017 # # 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 ...
emit(lines): """ Emit a series of lines to stdout """ for line in lines: sys.stdout.write(line) def collect(filename, regex = None, negregex = None, start = [],
end = []): """ Collect the lines from a file into an array, filtering the results filename - the filename to collect lines from regex - collect lines that only match the given expresssion negregex - exclude lines that match the given expression start - additional elements at ...
hpcloud-mon/python-monasca-events
monasca_events/v2_0/__init__.py
Python
apache-2.0
679
0
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #
Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # i
mplied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ['Client'] from monasca_events.v2_0.client import Client
ShassAro/ShassAro
Bl_project/blVirtualEnv/lib/python2.7/site-packages/django/contrib/formtools/tests/wizard/wizardtests/tests.py
Python
gpl-2.0
18,372
0.000544
from __future__ import unicode_literals import copy import os from django import forms from django.test import TestCase from django.test.client import RequestFactory from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tests.utils import skipIfCustomUser from django.co...
{'random_crap': 'blah blah'}]]) def test_cleaned_data(self): response = self.client.get(self.wizard_url) self.assertEqual(response.status_code, 200) response = self.client.post(self.wizard_url, self.wizard_step_data[0]) self.assertEqual(response.status_code, 200) ...
h open(THIS_FILE, 'rb') as post_file: post_data['form2-file1'] = post_file response = self.client.post(self.wizard_url, post_data) self.assertEqual(response.status_code, 200) self.assertTrue(temp_storage.exists(UPLOADED_FILE_NAME)) response = self.client.post(self.wizard...
ActiveState/code
recipes/Python/138889_extract_email_addresses/recipe-138889.py
Python
mit
743
0.012113
def grab_email(files = []): # if passed a list of text files, will return a list of # email addresses found in the files, matched according to #
basic address conventions. Note: supports most possible # names, but not all valid ones. found = [] if files != None: mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') for file in files: for line in open(file,'r'): ...
u = {} for item in found: u[item] = 1 # return list of unique email addresses return u.keys()
bram85/topydo
test/test_add_command.py
Python
gpl-3.0
16,738
0.000597
# Topydo - A todo.txt client written in Python. # Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]> # # 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,...
, self.out, self.error) command.execute() command = AddCommand.AddCommand(["Bar partof:1"], self.todolist) command.execute() self.assertEqual(self.todolist.todo(1).source(), self.today + " Foo id:1") self.assertEq...
e(), self.today + " Bar p:1") self.assertEqual(self.errors, "") def test_add_dep03(self): command = AddCommand.AddCommand(["Foo"], self.todolist) command.execute() command = AddCommand.AddCommand(["Bar after:1"], self.todolist, ...
Berulacks/ethosgame
ethos/levels/level0.py
Python
gpl-2.0
2,904
0.020317
import sys,os #sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) #from ethosgame.ethos.level import Level from ..level import Level #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObje
ct from ..drawnobject import DrawnObject import pygame from pygame.locals import * from pygame import Color, image, font, sprite class Level0(Level): def __init__(self):
super(Level0, self).__init__() self.activeSprites = sprite.RenderClear() self.drawnSprites = [] self.npc = GameObject(image.load('User.png'), 100,50) self.activeSprites.add(self.npc) self.block1 = GameObject(image.load('platform.png'), 100, 400) self.activeSpr...
RPGOne/Skynet
version_requirements.py
Python
bsd-3-clause
4,443
0.000225
from distutils.version import LooseVersion import functools import re import sys def _check_version(actver, version, cmp_op): """ Check version string of an active module against a required version. If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the depend...
__' or 'VERSION') Version may start with =, >=, > or < to specify the exact requirement Returns ------- func : function A decorator that raises an ImportError if a function is run in the absence of the input dependency. """ def decorator(obj): @functools.wraps(obj) ...
sion): return obj(*args, **kwargs) else: msg = '"%s" in "%s" requires "%s' msg = msg % (obj, obj.__module__, name) if not version is None: msg += " %s" % version raise ImportError(msg + '"') return fu...
CENDARI/dblookup
fabfile.py
Python
mit
2,134
0.00328
from fabric.api import env, local, lcd from fabric.colors import red, green from fabric.decorators import task, runs_once from fabric.operations import prompt from fabric.utils import abort from zipfile import ZipFile import datetime import fileinput import importlib i
mport os import random import re import subprocess import sys import time PROJ_ROOT = os.pa
th.dirname(env.real_fabfile) env.project_name = 'dblookup' env.python = 'python' if 'VIRTUAL_ENV' in os.environ else './bin/python' @task def setup(): """ Set up a local development environment This command must be run with Fabric installed globally (not inside a virtual environment) """ if os...
onfinternational/QGISProcessingScripts
Scripts/S1ProcessByRelativeOrbit.py
Python
mpl-2.0
5,838
0.007879
# -*- coding: utf-8 -*- """ Created on Tue Sep 26 18:14:51 2017 @author: cedric """ ''' This script apply calibration and orthorectification process of S1 GRD data ''' ''' IMPORT ''' import os from S1Lib.S1OwnLib import (ReturnRealCalibrationOTBValue, GetFileByExtensionFromDirect...
6) # 5 - Loop thru relative orbit given by the user and # 5a - Loop thru polygon for userPath in PathUserList: # Filter files that intersect the required path intersectRaster = getS1ByTile(Input_Polygon_FileEPSG4326, ManifestFiles, Relati...
0: PathDir = os.path.join(Output_Data_Folder, 'p' + str(userPath)) if not os.path.exists(PathDir): os.makedirs(PathDir) else: # if no data go to next path continue # Create Shape file of the current path PathShape = os.path.join(PathDir, 'p' + str(userPath) + '.shp'...
Razican/Exploding-Stars
web/spaceappsbilbao/NextGenThreat/views.py
Python
mit
2,281
0.017552
#-*-*- encoding: utf-8 -*-*- from django.shortcuts import render from django.template import RequestContext, loader, Context from django.http import JsonResponse from .models import Airburst def index(request): return render(request, 'NextGenThreat/index.html', {}) def radar(request): latest_airburst_list = Airbu...
ed_energy, 'impact_energy': airburst.impact_energy, 'latitude': airburst.latitude, 'longitude': airb
urst.longitude, 'date': airburst.date.isoformat(), 'altitude': airburst.altitude, } return JsonResponse(response)
google-research/google-research
demogen/model_config.py
Python
apache-2.0
9,065
0.003309
# 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...
the hyperparameter settings of the model. Args: root_dir: Optional root directory where experiment directory is located. Returns: A string
that contains the checkpoint containing weights and training/test accuracy of a model. Raises: ValueError: The model type is not in the dataset """ if not root_dir: assert self.root_dir root_dir = self.root_dir if self.model_type == 'nin': data_dir = 'NIN_' data_dir...
wmvanvliet/psychic
psychic/nodes/chain.py
Python
bsd-3-clause
3,338
0.003895
import nu
mpy as np from .basenode import BaseNode from ..dataset import DataSet from ..helpers import to_one_of_n def _apply_sklearn(n, d, last_node=False): if n.__module__.startswith('sklearn'): # Use the most suitable function if no
t last_node and hasattr(n, 'transform'): X = n.transform(d.X) elif hasattr(n, 'predict_proba'): X = n.predict_proba(d.X) elif hasattr(n, 'predict'): p = n.predict(d.X) if p.dtype == np.float: X = p else: X = to_o...
srcLurker/home-assistant
homeassistant/components/sensor/transmission.py
Python
mit
4,962
0
""" Support for monitoring the Transmission BitTorrent client API. For more details about this platform, please refer to the documentation a
t https://home-assistant.io/components/sensor.transmission/ """ import logging from datetime import timedelta import voluptuous as
vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_NAME, CONF_PORT, CONF_MONITORED_VARIABLES, STATE_UNKNOWN, STATE_IDLE) from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle import h...
Nebucatnetzer/tamagotchi
pygame/lib/python3.4/site-packages/faker/providers/job/uk_UA/__init__.py
Python
gpl-2.0
4,166
0.005346
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as BaseProvider # Ukrainian job names taken from # https://uk.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BF%D1%80%D0%BE%D1%84%D0%B5%D1%81%D1%96%D0%B9 # on 22th September 2014 class Provider(BaseProvider): jobs = [ ...
оцент', 'Драматург', 'Ді-джей', 'Дантист', # Е 'Економіст', 'Електрик', 'Електромонтер', 'Електромонтажник', 'Електрослюсар', 'Електротехнік', 'Епідеміолог', 'Етнограф', # Є 'Є
внух', 'Єгер', # Ж 'Журналіст', 'Живописець', # З 'Золотар', 'Зоолог', # І 'Інженер', 'Історик', # К 'Каскадер', 'Кінорежисер', 'Клавішник', 'Клоун', 'Композитор', 'Конструктор', 'Краєзнавець', 'Кушнір', 'Кіноактор', 'Кінокритик', 'Кінорежисер', 'К...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/internet/glib2reactor.py
Python
gpl-3.0
62
0.016129
../
../../../../share/pyshared/twisted
/internet/glib2reactor.py
codito/pomito
pomito/hooks/__init__.py
Python
mit
312
0
""" Hooks are notification only agents. They are notified of special events in a Pomodoro lifecycle. """ import abc class H
ook(metaclass=abc.ABCMeta): """Base class for all hooks""" @abc.abstractmethod def initialize(self): pass @a
bc.abstractmethod def close(self): pass
leppa/home-assistant
homeassistant/components/statsd/__init__.py
Python
apache-2.0
2,957
0.000676
"""Support for sending data to StatsD.""" import logging import statsd import voluptuous as vol from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PREFIX, EVENT_STATE_CHANGED from homeassistant.helpers import state as state_helper import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogg...
F_VALUE_MAP = "value_mapping" DEFAULT_HOST = "localhost" DEFAULT_PORT = 8125 DEFAULT_PREFIX = "hass" DEFAULT_RATE = 1 DOMAIN = "statsd" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CON...
vol.Optional(CONF_PREFIX, default=DEFAULT_PREFIX): cv.string, vol.Optional(CONF_RATE, default=DEFAULT_RATE): vol.All( vol.Coerce(int), vol.Range(min=1) ), vol.Optional(CONF_VALUE_MAP): dict, } ) }, extra=vol.ALLOW_...
stephanekirsch/e-colle
accueil/models/ramassage.py
Python
agpl-3.0
14,879
0.018956
from django.db import models, transaction, connection from django.http import Http404 from datetime import date, timedelta from django.db.models.functions import Lower from django.db.models import Count, Sum, Min, Max from .note import Note, array2tree from .classe import Classe from .semaine import Semaine from ecolle...
ment_id = et.id\ WHERE dec2.ramassage_id=%s AND dec2.temps - COALESCE(dec1.temps,0) != 0{}\ GROUP BY ma.nom, u.last_name, u.first_name, col.id, cl.id, et.nom, dec2.mois\ UNION ALL SELECT cl.id classe_id, cl.nom classe_nom, cl.annee, ma.nom matiere_nom, COALESCE(et.nom, 'Inconnu') etab, col.grade...
is mois, - SUM(dec1.temps) heures\ FROM accueil_decompte dec1\ LEFT OUTER JOIN accueil_decompte dec2\ ON dec1.colleur_id = dec2.colleur_id AND dec1.classe_id = dec2.classe_id AND dec1.matiere_id = dec2.matiere_id\ AND dec1.mois = dec2.mois AND dec2.ramassage_id=%s\ INNER JOIN acc...
mscuthbert/abjad
abjad/tools/pitchtools/test/test_pitchtools_PitchArrayCell_pitches.py
Python
gpl-3.0
756
0.001323
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_PitchArrayCell_pitches_01(): array = pitchtools.PitchArray([[1, 2, 1], [2, 1, 1]]) array[0
].cells[0].pitches.append(NamedPitch(0)) array[0].cells[1].pitches.append(NamedPitch(2)) ''' [c'] [d' ] [] [ ] [] [] ''' assert array[0].cells[0].pitches == [NamedPitch(0)] assert array[0].cells[1].pitches == [NamedPitch(2)] assert array[0].cells[2].pitches == [] asser...
: cell = pitchtools.PitchArrayCell([NamedPitch(0)]) assert cell.pitches == [NamedPitch(0)]
spiceqa/virt-test
qemu/tests/sr_iov_hotplug_negative.py
Python
gpl-2.0
4,079
0
import logging import os from autotest.client.shared import error from autotest.client import utils from virttest import utils_test, utils_misc, utils_net @error.context_aware def run_sr_iov_hotplug_negative(test, params, env): """ KVM sr-iov hotplug negatvie test: 1) Boot up VM. 2) Try to remove sr-i...
,addr=%s" % pci_addr if params.get("hotplug_params"): assign_param = params.get("hotplug_params").split() for param in assign_param: value = params.get(param) if value: pci_add_cmd += ",%s=%s" % (param, value) return pci_add_
cmd neg_msg = params.get("negative_msg") vm = env.get_vm(params["main_vm"]) vm.verify_alive() rp_times = int(params.get("repeat_times", 1)) pci_model = params.get("pci_model", "pci-assign") pci_addr = params.get("pci_addr") modprobe_cmd = params.get("modprobe_cmd") if modprobe_cmd: ...
medifle/python_6.00.1x
L3_P9_bisection_search.py
Python
mit
654
0.006116
# Lec 3, Problem 9 # bisection search print('Please think of a number between 0 and 100!') low = 0 high = 100 x = '0' while x != 'c': guess = (low + high) / 2 print('Is your secret number ' + str(guess) + '?') x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to ind
icate the guess is too low. Enter 'c' to indicate I guessed correctly. ") if x == 'c': print('Game over. Your secret number was: ' + str(guess)) break elif x == 'h': high = guess elif x == 'l': l
ow = guess else: print('Sorry, I did not understand your input.')
SoftwearDevelopment/spynl
spynl/main/utils.py
Python
mit
18,906
0.000529
"""Helper functions and view derivers for spynl.main.""" import json import logging import traceback import sys import os import contextlib from functools import wraps from inspect import isclass, getfullargspec import yaml from tld import get_tld from tld.exceptions import TldBadUrl, TldDomainNotFound from pyramid....
hitelist if not ur
l.endswith('://')] origin_allowed = origin in dev_list_urls dev_list_protocols = [url for url in dev_whitelist if url.endswith('://')] for protocol in dev_list_protocols: if origin.startswith(protocol): origin_allowed = True if not origin_allowed: try: tld = get_t...
a301-teaching/a301_code
a301lib/thermo.py
Python
mit
1,394
0.025108
import numpy as np g=9.8 #don't worry about g(z) for this exercise Rd=287. #kg/m^3 def calcScaleHeight(df): """ Calculate the pressure scale height H_p Parameters ---------- T: vector (float) temperature (K) p: vector (float) of len(T) pressure (pa) z: ...
------
Hbar: vector (float) of len(T) density scale height (m) """ z=df['z'].values Temp=df['temp'].values dz=np.diff(z) TLayer=(Temp[1:] + Temp[0:-1])/2. dTdz=np.diff(Temp)/np.diff(z) oneOverH=g/(Rd*TLayer) + (1/TLayer*dTdz) Zthick=z[-1] - z[0] oneOverHbar=np.sum(oneOverH*dz)/Zthic...
andresriancho/HTTPretty
setup.py
Python
mit
2,629
0.00038
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcao <[email protected]> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to ...
the following # con
ditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICUL...
ChristosChristofidis/h2o-3
h2o-py/tests/testdir_misc/pyunit_all_confusion_matrix_funcs.py
Python
apache-2.0
6,323
0.008857
import sys sys.path.insert(1, "../../") import h2o import random def all_confusion_matrix_funcs(ip,port): # Connect to h2o h2o.init(ip,port) metrics = ["min_per_class_accuracy", "absolute_MCC", "precision", "accuracy", "f0point5", "f2", "f1"] train = [True, False] valid = [True, False] print ...
y=air_train["fDayOfWeek"].asfactor(), validation_x=air_test[["Origin", "Dest", "Distance", "UniqueCarrier", "IsDepDelayed", "fDayofMonth", "fMonth"]], validation_y=air_test["fDayOfWeek"].asfactor(), distributi...
n="multinomial") def dim_check(cm, m, t, v): assert len(cm) == 2 and len(cm[0]) == 2 and len(cm[1]) == 2, "incorrect confusion matrix dimensions " \ "for metric/thresh: {0}, train: {1}, valid: " \ ...
airspeed-velocity/asv
asv/commands/rm.py
Python
bsd-3-clause
3,669
0
# Licensed under a 3-clause BSD style license - see LICENSE.rst import sys from fnmatch import fnmatchcase from . import Command, util from .. import console from ..console import log from ..results import iter_results class Rm(Command): @classmethod def setup_arguments(cls, subparsers): parser = sub...
ern in patterns: parts = pattern.s
plit('=', 1) if len(parts) != 2: raise util.UserError("Invalid pattern '{0}'".format(pattern)) if parts[0] == 'benchmark': if single_benchmark is not None: raise util.UserError("'benchmark' appears more than once") single_bench...
transientskp/tkp
tkp/accessors/dataaccessor.py
Python
bsd-2-clause
6,243
0.001121
import logging from tkp.quality.rms import rms_with_clipped_subregion from tkp.accessors.requiredatts import RequiredAttributesMetaclass from math import degrees, sqrt, sin, pi, cos logger = logging.getLogger(__name__) class DataAccessor(object): __metaclass__ = RequiredAttributesMetaclass _required_attribut...
econds. url(string): A (string) URL representing the location of the image at time of processing. wcs(:class:`tkp.utility.coordinates.WCS`): An instance of :py:class:`tkp.utility.coordinates.WCS`, describing the mapping from data pixels to sky-coor...
which provides key info in a simple dict format. """ def extract_metadata(self): """ Massage the class attributes into a flat dictionary with database-friendly values. While rather tedious, this is easy to serialize and store separately to the actual image data. ...
jessefeinman/FintechHackathon
python-getting-started/sample stuff/gettingstarted/urls.py
Python
bsd-2-clause
385
0.002597
from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() import hello.views # Examples: #
url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), urlpatterns = [ url(r'^$', hello.views.index, name='index'), url(r'^db', hello.views.db, name='db'), url(r'^admin/', in
clude(admin.site.urls)), ]
jdemel/gnuradio
gr-digital/examples/example_fll.py
Python
gpl-3.0
5,057
0.006723
#!/usr/bin/env python # # Copyright 2011-2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # SPDX-License-Identifier: GPL-3.0-or-later # # from __future__ import print_function from __future__ import division from __future__ import unicode_literals from gnuradio import gr, digital, filter from ...
poffset): gr.top_block.__init__(self) rrc_taps = filter.firdes.root_raised_cosine( sps, sps, 1.0, rolloff, ntaps) data = 2.0*numpy.random.randint(0, 2, N) - 1.0 data = numpy.exp(1j*poffset) * data self.src = blocks.vector_source_c(data.tolist(), False) sel...
ge_cc(sps, rolloff, ntaps, bw) self.vsnk_src = blocks.vector_sink_c() self.vsnk_fll = blocks.vector_sink_c() self.vsnk_frq = blocks.vector_sink_f() self.vsnk_phs = blocks.vector_sink_f() self.vsnk_err = blocks.vector_sink_f() self.connect(self.src, self.rrc, self.chn, s...
NTesla/wordpress-sploit-framework
web_server_builder.py
Python
gpl-3.0
2,235
0.026846
from BaseHTT
PServer i
mport HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler import sys import random global_url = global_parameters = global_method = global_payload = '' class HTTPHandler (SimpleHTTPRequestHandler): server_version = "LibHttpWSF/1.0" def do_GET(self): print "[+] New connection: %s:%d" % (self.client_a...
openstack/tosca-parser
toscaparser/__init__.py
Python
apache-2.0
643
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy o
f the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific l...
mport pbr.version __version__ = pbr.version.VersionInfo( 'tosca-parser').version_string()
HarrisonAlpine/google-classroom-tools
list_students.py
Python
mit
1,063
0.000941
#!/usr/bin/env python import googlehelper as gh import json import os # DEFAULT_COURSE_ID = '7155852796' # Computer Programming A1 # DEFAULT_COURSE_ID = '7621825175' # Robotics DEFAULT_COURSE_ID = '7557587733' # Computer Programming A4 if __name__ == '__main__': # course = gh.get_course(DEFAULT_COURSE_ID) ...
s f: print(json.dumps(students, indent=2), file=f) with open(txt_file) as f:
print(f.read())
crmccreary/openerp_server
openerp/addons/survey/wizard/__init__.py
Python
agpl-3.0
1,237
0.000808
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-TODAY OpenERP
S.A. <http://www.openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program i...
en the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############...
chrisxue815/leetcode_python
problems/test_0316_greedy.py
Python
unlicense
1,258
0
import unittest import utils def _find_max_possible_index(s, count, counts): counts = list(counts) for i in range(len(s) - 1, -1, -1): c = ord(s[i]) if counts[c]: counts[c] = 0 count -= 1 if count == 0: return i # O(n^2) time. O(1) space. ...
for _ in range(count): min_c = 256 min_i = 0 for i in range(lo, hi + 1): c = ord(s[i]) if counts[c] and c < min_c: min_c = c min_i = i result.append(chr(min_c)) counts[min_c] = 0 ...
_possible_index(s, count, counts) return ''.join(result) class Test(unittest.TestCase): def test(self): utils.test(self, __file__, Solution) if __name__ == '__main__': unittest.main()
0xa/pyopenvpn
ovpn_proxy.py
Python
mit
8,065
0.001984
#!/bin/python3 import random import logging import socket import io import ipaddress import threading import select import time import queue from argparse import ArgumentParser from datetime import datetime, timedelta from scapy.all import * from pyopenvpn import Client, Settings class SOCKS5Connection(threading.Thr...
break except (socket.timeout, BrokenPipeError): data = None if data: packet = TCP(sport=self.src_port, dport=self.dest_port, flags='A', seq=l_seq,
ack=r_seq) packet /= Raw(load=data) self.outgoing_packets.append(packet) l_seq += len(data) try: packet = self.tunnel_in_queue.get(block=False) self.sock.send(bytes(packet.payload)) assert packet.ack == l_seq ...
alexandriagroup/fnapy
tests/offline/test_manager.py
Python
mit
549
0.001825
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8
# # Copyright © 2016 <> # # Distributed under terms of the MIT license. # Third-party modules import pytest # Projects modules from fnapy.fnapy_manager import FnapyManager def test_manager_raises_TypeError_with_invalid_connection(): """FnapyManager should raise a TypeError when the connection is not a FnapyCon...
ner_id': 'XXX', 'shop_id': 'XXX', 'key': 'XXX'} manager = FnapyManager(connection)
aarontuor/antk
test/test_transforms.py
Python
mit
4,376
0.006627
import antk.core.loader as loader import numpy as np import scipy.sparse as sps """ :any:`center` :any:`l1normalize` :any:`l2normalize` :any:`pca_whiten` :any:`tfidf` :any:`unit_variance` """ x = np.array([[0.0,0.0,6.0], [2.0,4.0,2.0], [2.0,6.0,0.0]]) y = sps.csr_matrix(x) # numpy.testi...
normalize(x, axis=1), np.array([[0.0, 0.0, 1.0], [.25, .5, .25], [.25, .75, 0.0]])) def test_l1_sparse_test_axis1(): assert np.array_equal(loader.l1normalize(y, axis=1), np.array([[0.0, 0.0,...
ay_almost_equal(loader.l2normalize(x, axis=0), # np.array([[0.0, 0.0, 3.0 / np.sqrt(10.0)], # [1.0 / np.sqrt(2.0), 2.0 / np.sqrt(13.0), 1.0 / np.sqrt(10.0)], # [1.0 / np.sqrt(2.0), 3.0 / np.sqrt(13.0), 0.0]]), decimal=5) # # # def test_l2_s...
praxeo/outcumbent
Outcumbent/settings.py
Python
gpl-2.0
2,140
0.000467
""" Django settings for Outcumbent project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ('templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNI...
g turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ...
patrick91/pycon
backend/blog/migrations/0003_auto_20191130_0913.py
Python
mit
967
0.003102
# Generated by Django 2.2.7 on 2019-11-30 09:13 from django.db import migrations import i18n.fields class Migration(migrations.Migration): dependencies = [ ('blog', '0002_auto_20190809_2128'), ] operations = [ migrations.AlterField( model_name='post', name='conte...
igrations.AlterField( model_name='post', name='excerpt', field=i18n.fields.I18nTextField(verbose_name='excerpt'), ), migrations.AlterField( model_name='post', name='slug', field=i18n.fields.I18nCharField(blank=True, max_length=200, ...
migrations.AlterField( model_name='post', name='title', field=i18n.fields.I18nCharField(max_length=200, verbose_name='title'), ), ]
majerteam/sqla_inspect
sqla_inspect/py3o.py
Python
gpl-3.0
12,289
0.000489
# -*- coding: utf-8 -*- # * Authors: # * Arezki Feth <[email protected]>; # * Miotte Julien <[email protected]>; # * TJEBBES Gaston <[email protected]> """ Py3o exporters >>> model = Company.query().first() >>> template = Template.query().first() >>> odt_file_datas = compile_template(model, template.data_obj...
one: continue if column['__col__'].uselist: subres = column['__prop__'].make_doc() for subkey, value in subres.items():
new_key = u"%s.first.%s" % (key, subkey) res[new_key] = u"%s - %s (premier élément)" % ( label, value ) new_key = u"%s.last.%s" % (key, subkey) res[new_key] = u"%s - %s (dernie...
naught101/sobol_seq
sobol_seq/__init__.py
Python
mit
374
0.002674
""" Sobol sequence gener
ator. https://github.com/naught101/sobol_seq """ from .sobol_seq import i4_sobol_generate, i4_uniform, i4_sobol, i4_sobol_generate_std_normal from .sobol_seq import i4_bit_hi1, i4_bit_lo0, prime_ge __all__ = ["i4_sobol_generate", "i4_uniform", "i4_sobol", "i4_bit_hi1",
"i4_bit_lo0", "prime_ge", "i4_sobol_generate_std_normal"]
tcstewar/spinnbot
plot_lr_1.py
Python
gpl-2.0
3,783
0.011102
import pylab pylab.figure(figsize=(8,4)) pylab.axes((0.11, 0.13, 0.85, 0.8)) color=['k', 'b', 'g', 'r'] pylab.plot([0, 1, 2, 3, 4, 5, 6, 7],[0.45077721721559999, 0.40372168451659995, 0.38063819377489994, 0.36765218894180002, 0.36047701604800009, 0.34854098046839999, 0.33848337337579998, 0.32900642344309999], label='...
599998, 0.26403148906309992, 0.25519789108
169999, 0.24432621429909998],yerr=[[-0.027047134775899984, -0.017672144615600016, -0.003892905421899906, -0.0040572456741999607, -0.0032339877449999999, -0.0027035312431000769, -0.0065918208782000387, -0.0028030154090999682],[-0.015704226333299987, -0.011571601761000028, -0.0034103611732000938, -0.0039626564557000421, ...
dementrock/nbgrader
nbgrader/formgrader/formgrade.py
Python
bsd-3-clause
14,959
0.002206
import json import os from functools import wraps from flask import Flask, request, abort, redirect, url_for, render_template, \ send_from_directory, Blueprint, g, make_response from ..api import MissingEntry app = Flask(__name__, static_url_path='') blueprint = Blueprint('formgrade', __name__) def auth(f): ...
dex={}".format(url, request.args.get('index'))
else: return url @app.errorhandler(500) def internal_server_error(e): return render_template( 'gradebook_500.tpl', base_url=app.auth.base_url, error_code=500), 500 @app.errorhandler(502) def upstream_server_error(e): return render_template( 'gradebook_500.tpl', ...
nathanbjenx/cairis
cairis/bin/at2om.py
Python
apache-2.0
5,006
0.014183
#!/usr/bin/python # 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 # ...
cle_environment>\n </obstacle>\n' xmlBuf += '</goals>\n\n' fromAssocs = [] toAssocs
= {} assocs = [] for e in graph.get_edge_list(): fromName = e.get_source() toName = e.get_destination() if fromName in acs: if fromName not in toAssocs: toAssocs[fromName] = [toName] else: toAssocs[fromName].append(toName) elif toName in acs: fromAssocs.append((fr...
freeserver/readerss
grabber/engines/Sqlalchemy.py
Python
agpl-3.0
3,081
0.00779
from engines.base import BaseDB from models.model import Feed, Entry from sqlalchemy import create_engine, Column, String, Integer, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class SqlalchemyDB(BaseDB): """ The SQLAlchemy ...
return SQLAFeed elif table == SQLAEntry.TYPE: if data: return SQLAEntry(**data) else: return SQLAEntry else: raise Exception("Table type not found: {0}".format(table)) class SQLAFeed(Feed, Base): __tablename__ = Feed.TYPE id = Colum...
olumn(String) subtitle = Column(String) updated = Column(DateTime(timezone=True)) published = Column(DateTime(timezone=True)) link = Column(String) last_accessed = Column(DateTime(timezone=True)) minimum_wait = Column(Integer) errors = Column(Integer) class SQLAEntry(Entry, Base): ...
pythononwheels/pow_devel
pythononwheels/start/stubs/dash_handler_template.py
Python
mit
2,667
0.012748
from {{appname}}.handlers.powhandler import PowHandler from {{appname}}.conf.config impor
t myapp from {{appname}}.lib.application import app import simplejson as json import tornado.web from tornado import gen from {{appnam
e}}.pow_dash import dispatcher # Please import your model here. (from yourapp.models.dbtype) @app.add_route("/dash.*", dispatch={"get" :"dash"}) @app.add_route("/_dash.*", dispatch={"get" :"dash_ajax_json", "post": "dash_ajax_json"}) class Dash(PowHandler): # # Sample dash handler to embedd dash into PythonOnW...
NicoVarg99/daf-recipes
ckan/ckan/ckan/ckan/tests/legacy/functional/test_pagination.py
Python
gpl-3.0
6,052
0.004296
# encoding: utf-8 import re from nose.tools import assert_equal from ckan.lib.create_test_data import CreateTestData import ckan.model as model from ckan.tests.legacy import TestController, url_for, setup_test_search_index def scrape_search_results(response, object_type): assert object_type in ('dataset', 'grou...
tar/d41d8cd98f00b204e980
0998ecf8427e?s=16&amp;d=http://test.ckan.net/images/icons/user.png" /> <a href="/user/user_00">user_00</a> </li> ... <li class="username"> <img src="//gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e?s=16&amp;d=http://test.ckan.net/images/icons/user.png" /> <a href="/user/use...
siosio/intellij-community
python/helpers/pycharm/_jb_pytest_runner.py
Python
apache-2.0
1,933
0.005173
# coding=utf-8 # Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. import pytest from distutils import version import sys from _pytest.config import get_plugin_manager from pkg_resources import iter_entry_points...
if getattr(config.option, "numprocesses", None):
set_parallel_mode() start_protocol() sys.exit(pytest.main(args, plugins_to_load + [Plugin]))
brhoades/holdem-bot
poker/poker.py
Python
mit
2,684
0.003353
# Heads Up Texas Hold'em Challenge bot # Based on the Heads Up Omaha Challange - Starter Bot by Jackie <[email protected]> # Last update: 22 May, 2014 # @author Chris Parlette <[email protected]> # @version 1.0 # @license MIT License (http://opensource.org/licenses/MIT) class Pocket(object): ''' ...
# Get all kinds (e.g. four of a kind, three of a kind, pair) kinds = [value_count[0] for value_count in sorted_value_count] # Get values for kinds kind_values = [value_count[1] for value_count in sorted_value_count] # Royal flush if is_straight and is_flush and valu...
# Straight flush if is_straight and is_flush: return ['8'] + kind_values # Four of a kind if kinds[0] == 4: return ['7'] + kind_values # Full house if kinds[0] == 3 and kinds[1] == 2: return ['6'] + kind_values # F...
chrisenytc/coffy
coffees/urls.py
Python
mit
331
0.02719
from django.c
onf.urls import patterns, url from coffees import views urlpatterns = patterns('', # GET /api url(r'^$', views.index, name='coffees_index'), # POST /api/coffees url(r'^coffees/$', views.create, name='coffees_create'), # GET /api/<username> url(r'^(
?P<username>[\w-]+)/$', views.detail, name='coffees_detail'), )
hadim/profileextractor
tools/autocopyleft.py
Python
bsd-3-clause
1,265
0.012648
#-*- coding: utf-8 -*- import sys, fileinput, os # Configuration path_src = "../src/" fextension = [".py"] date_copyright = "2011" authors = "see AUTHORS" project_name = "ProfileExtractor" header_file = "license_header.txt" def pre_append(line, file_name): fobj = fileinput.FileInput(file_name, inplace=1) fir...
str_lhead = "" for l in licence_head: l = l.replace("DATE", date_copyright) l = l.replace("AUTHORS", authors) l = l.replace("
PROJECT_NAME", project_name) l = l.replace("FILENAME", name) str_lhead += l pre_append(str_lhead, f)
jaberg/nengo
nengo/templates/gate.py
Python
mit
3,030
0.020132
title='Gate' label='Gate' icon='gate.png' description="""<html>This template creates an ensemble that drives an inhibitory gate on an existing specified ensemble. </html>""" params=[ ('name','Name',str,'Name of the new gating ensemble'), ('gated','Name of gated ensemble',str,'Name of the existing ensemble to...
s) gate.put("pstc", pstc) gates.put(name, gate) if net.network.getMetaData("templates") == None: net.network.setMetaData("templates
", ArrayList()) templates = net.network.getMetaData("templates") templates.add(name) if net.network.getMetaData("templateProjections") == None: net.network.setMetaData("templateProjections", HashMap()) templateproj = net.network.getMetaData("templateProjections") templateproj.put(name, gate...
magenta/symbolic-music-diffusion
utils/train_utils.py
Python
apache-2.0
3,999
0.009002
# Copyright 2021 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
ence_count: int = 0 should_stop: bool = False def update(self, metric): """Update the state based on metric. Returns: Whether there was an improvement greater than min_delta from the previous best_metric and the updated EarlyStop object. """ if math.isinf( self.best_me...
should_stop = self.patience_count >= self.patience or self.should_stop return False, self.replace(patience_count=self.patience_count + 1, should_stop=should_stop) @struct.dataclass class EMAHelper: """Exponential moving average of model parameters. Attributes: mu: Mo...
Sbalbp/DIRAC
DataManagementSystem/scripts/dirac-dms-put-and-register-request.py
Python
gpl-3.0
2,952
0.034553
#!/bin/env python """ create and put 'PutAndRegister' request with a single local file warning: make sure the file you want to put is accessible from DIRAC production hosts, i.e. put file on network fs (AFS or NFS), otherwise operation will fail!!! """ __RCSID__ = "$Id: $" import os from DIRAC.Core.Base...
tSystem.Client.ReqClient import ReqClient from DIRAC.Core.Utilities.Adler import fileAdler if not os.path.exists( PFN ): gLogger.error( "%s does not exist" % PFN ) DIRAC.exit( -1 ) if not os.path.isfile( PFN ): gLogger.error(
"%s is not a file" % PFN ) DIRAC.exit( -1 ) PFN = os.path.abspath( PFN ) size = os.path.getsize( PFN ) adler32 = fileAdler( PFN ) request = Request() request.RequestName = requestName putAndRegister = Operation() putAndRegister.Type = "PutAndRegister" putAndRegister.TargetSE = targetSE opFile ...
scripnichenko/nova
nova/api/openstack/compute/quota_sets.py
Python
apache-2.0
8,030
0.000374
# 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...
m nova import quota ALIAS = "os-quota-sets" QUOTAS = quota.QUOTAS authorize = extensions.os_compute_authorizer(ALIAS) class QuotaSetsController(wsgi.Controller): def _format_quota_set(self, project_id, quota_set): """Convert the quota object to a result dict.""" if project_id:
result = dict(id=str(project_id)) else: result = {} for resource in QUOTAS.resources: if resource in quota_set: result[resource] = quota_set[resource] return dict(quota_set=result) def _validate_quota_limit(self, resource, limit, minimum, m...
yymao/slackbots
calc.py
Python
mit
1,617
0.004329
import re from urllib import quote_plus import math from common import escape _globals = {'__builtins__':{}} _locals = vars(math) try: import cosmo import smhm except ImportError: p
ass else: for k in cosmo.__all__: _locals[k] = cosmo.__dict__[k] for k in smhm.__all__: _locals[k] = smhm.__dict__[k] _help_msg = '''Supports most simple math functions and the following cosmology functions: - `cd`: comoving distance [Mpc] - `ld`: luminosity distance [Mpc] - `ad`: angular dista...
efault to 1. Also supports the mean stellar mass--halo mass relation from Behroozi+2013: - `smhm`: stellar mass [Msun] Call signature: `sm(hm, z)` ''' _escape_pattern = r'[^A-Za-z0-9\-+*/%&|~!=()<>.,#]|\.(?=[A-Za-z_])' _error_msg = '''Hmmm... something\'s wrong with the input expression. Type `/calc help` to see sup...
orbitfold/pyo
examples/tables/05_table_maker.py
Python
gpl-3.0
1,093
0.007319
#!/usr/bin/env python # encoding: utf-8 """ Creates a new sound table from random chunks of a soundfile. """ from pyo import * import random, os s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot() path = "../snds/baseballmajeur_m.aif" dur = sndinfo(path)[1] t = SndTable(path, start=0, stop=1) amp = Fade...
iform(0.05, t.getDur()-0.5) cross = random.uniform(0.04, duration/2) t.insert(path, pos=pos, crossfade=cross, start=start, stop=start+duration) def delayed_generation(): start = random.uniform(0, dur*0.7) duration = random.uniform(.1, .3) t.setSound(path, start=start, stop=start+duration) for i...
caller.play() gen() s.gui(locals())
davandev/davanserver
davan/config/no_private_config.py
Python
mit
1,198
0.010017
''' Created on 1 nov. 2016 @author: davandev Default configuration file used if not defined somewhere else ''' FIBARO_USER = "my_user" FIBARO_PASSWORD = "my_password" TELEGRAM_TOKEN = 'my_telegram_token' TELEGRAM_CHATID = {'chatid':'user3'} TELEGRAM_USER_DAVID = 'my_telegram_user1' TELEGRAM_U
SER_MIA = 'my_telegram_user2' CAMERA_USER = "my_cam_user" CAMERA_PASSWORD = "my_cam_password" VOICERSS_TOKEN = "my_voicerss_token" WEATHER_TOKEN = "my_weather_token" WEATHER_STATION_ID = "my_weather_station_token" USER_PIN = {'pin':'us
er'} TELLDUS_PUBLIC_KEY = "my_telldus_key" TELLDUS_PRIVATE_KEY = "my_telldus_key" ROUTER_USER = "my_router_user" ROUTER_PASSWORD = "my_router_password" RECEIVER_BOT_TOKEN = "my_token" GOOGLE_CALENDAR_TOKEN = "my_google_token" DEVICES_UNKNOWN={} DEVICES_FAMILY={} DEVICES_FRIEND={} DEVICES_HOUSE={} NOKIA...
VapourApps/va_master
va_master/consul_kv/initial_consul_data.py
Python
gpl-3.0
5,705
0.036284
initial_consul_data = { "update" : { "providers/va_standalone_servers" : {"username": "admin", "servers": [], "sec_groups": [], "images": [], "password": "admin", "ip_address": "127.0.0.1", "networks": [], "sizes": [], "driver_name": "generic_driver", "location": "", "defaults": {}, "provider_name": "va_sta...
nt'"}, "service_presets/ping_preset":{"name": "ping_preset", "script" : "ping -c1 {address} > /dev/null", "interval": "30s", "timeout": "10s"}, "service_presets/tcp_preset":{"name": "TCP", "tcp": "{address}", "interval": "30s", "timeout": "10s"}, "managed_actions/ssh/root" : { "actio...
'reboot', 'type' : 'confirm'}, # {'name' : 'delete', 'type' : 'confirm'}, {'name' : 'remove_server', 'type' : 'confirm', 'kwargs' : ['datastore_handler', 'server_name'], 'requires_ssh' : False}, {'name' : 'stop', 'type' : 'confirm'}, {'name' : 'show_proce...
jarussi/riotpy
riotpy/managers/team.py
Python
bsd-3-clause
1,661
0.002408
# coding: utf-8 from base import Manager from riotpy.resources.team import TeamResource class TeamManager(Manager): def get_team_list_by_summoner_ids(self, summoner_ids): """ Get a list of teams by summoner ids. :param ids: list of summoner_ids to look or all the ids separated by...
summoner_ids = ','.join(summoner_ids) content = self._get('/api/lol/{}/{}/team/by-summoner/{}'.format( self.api.reg
ion, self.version, summoner_ids) ) teams = [] for team_dict in content.values(): # assuming he can only be in one team. Easy to change if mistaken teams.append(self._dict_to_resource(team_dict[0], resource_class=TeamResource)) return teams ...
cinghiopinghio/dotinstall
dotinstall/__init__.py
Python
gpl-3.0
354
0
__productname__ = 'dotinstall' _
_version__ = '0.1' __copyright__ = "Copyright (C) 2014 Cinghio Pinghio" __author__ = "Cinghio Pinghio" __author_email__ = "[email protected]" __description__ = "Install dotfiles" __long_description__ = "Install dofile based on some rules" __url__ = "cinghiopinghio...." __license__ = "Licensed under the GNU GPL v
3+."
gvanrossum/asyncio
examples/hello_coroutine.py
Python
apache-2.0
380
0
"""Print 'Hello World' every two seconds, using
a coroutine.""" import asyncio @asyncio.coroutine def greet_every_two_seconds(): while True: print('Hello World') yield from asyncio.sleep(2) if __name__ == '__main__': loop = asyncio.get_event_loop() try: loop
.run_until_complete(greet_every_two_seconds()) finally: loop.close()
nzlosh/st2
st2actions/tests/unit/policies/test_concurrency_by_attr.py
Python
apache-2.0
17,676
0.004243
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
Runner, "run", mock.MagicMock(return_value=MOCK_RUN_RETURN_VALUE), ) @mock.patch.object( LiveActionPublisher, "publish_state", mock.MagicMock( side_effect=MockLiveActionPublisherSchedulingQueueOnly.publish_state ), ) def test_over_threshold_del...
ns(self): policy_db = Policy.get_by_ref("wolfpack.action-1.concurrency.attr") self.assertGreater(policy_db.parameters["threshold"], 0) self.assertIn("actionstr", policy_db.parameters["attributes"]) # Launch action executions until the expected threshold is reached. for i in rang...
mlperf/training_results_v0.7
Intel/benchmarks/minigo/8-nodes-32s-cpx-tensorflow/intel_quantization/quantize_graph/quantize_graph_pad.py
Python
apache-2.0
2,437
0.000821
# -*- coding: utf-8 -*- from tensorflow.core.framework import node_def_pb2 from tensorflow.python.framework import tensor_util from intel_quantization.quantize_graph.quantize_graph_base import QuantizeNodeBase from intel_quantization.quantize_graph.quantize_graph_common import QuantizeGraphHelper as helper class F...
new_node = node_def_pb2.NodeDef() new_node.CopyFrom(value.node) self.add_output_graph_node(new_node) def get_longest_fuse(self): return 2 # pad + conv def apply_the_transform(self): self._get_op_list() self._apply_pad_conv_fusion() ...
zation( self.output_graph) # self.remove_dead_nodes(self.output_node_names) return self.output_graph
jordanemedlock/psychtruths
temboo/core/Library/Zendesk/Views/GetViewCount.py
Python
apache-2.0
3,674
0.004899
# -*- coding: utf-8 -*- ############################################################################### # # GetViewCount # Returns the ticket count for a single view. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use ...
###################################################################### from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class GetViewCount(Choreography)...
ance of the GetViewCount Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(GetViewCount, self).__init__(temboo_session, '/Library/Zendesk/Views/GetViewCount') def new_input_set(self): return GetViewCountInputSet() def _ma...
xinghalo/DMInAction
src/mlearning/chap02-knn/dating/knn.py
Python
apache-2.0
2,943
0.043838
#-*- coding: UTF-8 -*- from numpy import * import operator def classifyPerson(): resultList = ['not at all','in small doses','in large doses'] percentTats = float(raw_input("percentage of time spent playing video games?")) ffMiles = float(raw_input("frequent filter miles earned per year?")) iceCream = float(raw_in...
} for i in range(k): voteIlable = labels[sortedDistIndices[i]] classCount[voteIlable] = classCount.get(voteIlable,0)+1 sortedClassCount = sorted(
classCount.iteritems(),key=operator.itemgetter(1),reverse=True) return sortedClassCount[0][0]
marcopompili/django-galleries
django_galleries/urls.py
Python
bsd-3-clause
571
0.005254
""" Created on 19/mag/2013 @author: Marco Pompili """ from django.conf.urls import patterns, url from django.views.generic import ListView from .models import Gallery urlpatterns = patterns('', url(r'^$', ListView.as_view(
queryset=Gallery.objects.all()[:], context_object_name='django_galleries', template_name='django_galleries/index.html' ), name='index'), url('^(?P<pk>\d+)/$', 'django_galleri
es.views.gallery'), )
eli261/jumpserver
apps/common/mixins/api.py
Python
gpl-2.0
2,727
0.000368
# -*- coding: utf-8 -*- # from django.http import JsonResponse from django.core.cache import cache from django.utils.translation import ugettext_lazy as _ from django.contrib import messages from ..const import KEY_CACHE_RESOURCES_ID __all__ = [ "JSONResponseMixin", "IDInCacheFilterMixin", "IDExportFilterMixin", ...
if isinstance(ids, list): queryset = queryset.filter(id__in=ids) return queryset class IDInCacheFilterMixin(object): def filter_queryset(self, queryset): queryset = super().filter_queryset(queryset) spm = self.request.query_params.get('spm') if not spm: ...
resources_id = cache.get(cache_key) if resources_id and isinstance(resources_id, list): queryset = queryset.filter(id__in=resources_id) return queryset class IDExportFilterMixin(object): def filter_queryset(self, queryset): # 下载导入模版 if self.request.query_params...
Dogcrafter/BotiBot
Utils.py
Python
gpl-2.0
3,000
0.035333
#!/usr/local/bin/python3.4 # coding=utf-8 ################################################################################################ # Name: Utils Klasse # # Beschreibung: Liest dyn. die Service Module ein, # welche in configuration.json eingetragen wurden. # # Version: 1.0.0 # Author: Dogcra...
[module]) i = 0 for func in functions_list: # handlers functionText = functions_list[i][0] if functionText == "getHelpTxt": self.setHelpTxt(getattr(self.__modules[module],functio
ns_list[i][0])()) else: function = getattr(self.__modules[module],functions_list[i][0]) dispatcher.addTelegramCommandHandler(functionText,function) i = i + 1
bospetersen/h2o-3
h2o-py/h2o/transforms/preprocessing.py
Python
apache-2.0
3,037
0.016464
from .transform_base import H2OTransformer class H2OScaler(H2OTransformer): """ Standardize an H2OFrame by demeaning and scaling each column. The default scaling will result in an H2OFrame with columns having zero mean and unit variance. Users may specify the centering and scaling values used in the standard...
m the respective column before scaling. :param scale: A boolean or list of numbers. If True, then columns will be scaled by the column's standard deviation. If False, then columns will not be scaled. If scales is an array, then len(scales) must match the num...
pective value in this array. :return: An instance of H2OScaler. """ self.parms = locals() self.parms = {k:v for k,v in self.parms.iteritems() if k!="self"} if center is None or scale is None: raise ValueError("centers and scales must not be None.") self._means=None self._stds=None @proper...
Logic-gate/shuffelz
shuffelz.py
Python
gpl-2.0
4,742
0.033741
#!/usr/bin/env python '''# shufflez.py ''' # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following ...
: li.write(i+'\n') li.close() def open_url(self, url, user_agent): try: header = { 'User-Agent' : str(user_agent) } req = urllib2.Request(url, headers=header) response = urllib2.urlo
pen(req) print 'STATUS', response.getcode() except: pass def google(self, term): links_from_google = [] words_from_google = [] try: gs = GoogleSearch(term) gs.results_per_page = 10 results = gs.get_results() for res in results: words_from_google.append(res.title.encode('utf8')) ...
karllessard/tensorflow
tensorflow/python/saved_model/nested_structure_coder.py
Python
apache-2.0
17,543
0.006156
# 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...
eded to restore a `Function` that was saved into a SavedModel. This may include concrete function inputs and outputs, signatures, function specs, etc. Example use: coder = nested_structure_coder.StructureCoder() # Encode into proto. signature
_proto = coder.encode_structure(function.input_signature) # Decode into a Python object. restored_signature = coder.decode_proto(signature_proto) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import six from tenso...
kylexiaox/WechatWebShareJs
apiAccess.py
Python
apache-2.0
1,927
0.003114
__author__ = 'kyle_xiao' import tornado.httpclient import urllib import json import hashlib class AccessTicket(object): def __init__(self, timestamp, appId
, key, nonceStr): """ :param timestamp: :param appId: :param key: :param nonceStr: """ self.appId = appId self.key = key self.ret = { 'nonceStr': nonceStr, 'jsapi_ticket': self.getTicket(), 'timesta...
def getAccessToken(self): """ get the wechat access_token :return: """ client = tornado.httpclient.HTTPClient() response = client.fetch("https://api.weixin.qq.com/cgi-bin/token?" + \ urllib.urlencode( ...
dchoruzy/python-stdnum
stdnum/iso7064/mod_11_10.py
Python
lgpl-2.1
2,129
0
# mod_11_10.py - functions for performing the ISO 7064 Mod 11, 10 algorithm # # Copyright (C) 2010, 2011, 2012, 2013 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; eithe...
t * def checksum(number): """Calculate the checksum. A valid number should have a checksum of 1.""" check = 5 for n in number: check = (((check or 10) * 2) % 11 + int(n)) % 10 return check def calc_
check_digit(number): """With the provided number, calculate the extra digit that should be appended to make it a valid number.""" return str((1 - ((checksum(number) or 10) * 2) % 11) % 10) def validate(number): """Checks whether the check digit is valid.""" try: valid = checksum(number) ==...
DIVERSIFY-project/SMART-GH
daemon-wservice/experiments/constants.py
Python
apache-2.0
2,244
0.028075
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 """ This module contains all the constants that our experiments need """ GPS_LOCATIONS = { 'Rathmines': (53.3265199,-6.2648571), 'Santry': (53.3944773,-6.2468027), 'Sandyford': (53.2698337,-6.2245713), 'IKEA': (53.40741905,-6.275007...
oad' : (53.3551831,-6.229539), 'Tallaght Village' : (53.2896093,-6.3595578), 'Clare Hall Estate' : (53.3990349,-6.1625034), 'Merrion Square' : (53.3396823,-6.24916614558252), 'Captain\'s Hill, Leixlip' : (53.3697544,-6.4869624), 'Baggot Street' : (53.3329104,-6
.2425717), 'Blanchardstown' : (53.3868998,-6.3775408), 'Donnybrook' : (53.3219341,-6.2361395), 'Castleknock' : (53.3729581,-6.3624744), 'Stillorgan' : (53.2888378,-6.198343), 'Heuston' : (53.34647135,-6.29405804549595) } def getLocation(constant): return GPS_LOCATION...
winkidney/cmdtree
src/cmdtree/tests/functional/test_command.py
Python
mit
1,660
0.000602
import pytest from cmdtree import INT, entry from cmdtree import command, argument, option @argument("host", help="server listen address") @option("reload", is_flag=True, help="if auto-reload on") @option("port", help="server port", type=INT, default=8888) @command(help="run a http server on given address") def run_s...
ine") @argument("script_path", help="file path of python _script") def run_test(script_path, kline): return script_path, kline assert entry( ["test_miss", "path", "--kline", "fake"] ) == ("path", "fake") d
ef test_should_double_option_order_do_not_cause_calling_error(): @command("test_order") @option("feed") @option("config", help="config file path for kline database") def hello(feed, config): return feed assert entry( ["test_order", "--feed", "fake"] ) == "fake"
PicOrb/docker-sensu-server
plugins/aux/check-boundary.py
Python
mit
2,430
0.004527
#!/usr/bin/python from sensu_plugin import SensuPluginMetricJSON import requests #import os import json from sh import curl from walrus import * #from redis import * import math #from requests.auth import HTTPBasicAuth import statsd import warnings from requests.packages.urllib3 import exceptions db = Database(host='l...
ST', '-H', 'Accept: application/json', '--user', '2A6B0U16535H6X0D5822:$2a$12$WB8KmRcUnGpf1M6oEdLBe.GrfBEaa94U4QMBTPMuVWktWZf91AJk') headers = {'X-Iam-Auth-Token': json.loads(str(token_curl))['authentication']['token'], 'X-Request-Id': 'DEADBEEF'} for endpoint in endpoints: a = db.ZSet('mea...
or int(current) > 99: current = 1 url = 'https://{0}/assets/v1/67000001/environments/814C2911-09BB-1005-9916-7831C1BAC182/{1}'.format(api, endpoint) with warnings.catch_warnings(): warnings.simplefilter("ignore", exceptions.InsecureRequestWarning) ...
xpharry/Udacity-DLFoudation
tutorials/reinforcement/gym/gym/scoreboard/client/__init__.py
Python
mit
86
0
import logging import os from gy
m import er
ror logger = logging.getLogger(__name__)
piantado/LOTlib
LOTlib/Legacy/Visualization/Stringification.py
Python
gpl-3.0
6,858
0.006707
""" Functions for mappings FunctionNodes to strings """ from LOTlib.FunctionNode import isFunctionNode, BVUseFunctionNode, BVAddFunctionNode import re percent_s_regex = re.compile(r"%s") def schemestring(x, d=0, bv_names=None): """Outputs a scheme string in (lambda (x) (+ x 3)) format. Arguments: ...
t None: bvn = x.added_rule.bv_prefix+str(d) bv_names[x.added_rule.name] = bvn assert len(x.args) == 1 ret = 'lambda<%s> %s: %s' % ( x.returntype, bvn, fullstring(x.args[0], d=d+1, bv_names=bv_names) ) if isinstance(x, BVAddFunctionNode) and x.added_r...
cept KeyError: x.fullprint() return ret else: name = x.name if isinstance(x, BVUseFunctionNode): name = bv_names.get(x.name, x.name) if x.args is None: return "%s<%s>"%(name, x.returntype) else: ...
sbesson/PyGithub
github/Topic.py
Python
lgpl-3.0
5,670
0.004938
############################ Copyrights and license ############################ # # # Copyright 2018 Steve Kowalik <[email protected]> # # ...
gAttribute(attributes["display_name"]) if "short_description" in attributes: # pragma no branch self._short_description = self._makeStringAttribute( attributes["shor
t_description"] ) if "description" in attributes: # pragma no branch self._description = self._makeStringAttribute(attributes["description"]) if "created_by" in attributes: # pragma no branch self._created_by = self._makeStringAttribute(attributes["created_by"]) ...
Senbjorn/mipt_lab_2016
contest_7/task_2.py
Python
gpl-3.0
71
0.028169
#task_2 a =
int(input()) print(sum(lis
t(map(int, list((bin(a))[2:])))))
Haunter17/MIR_SU17
exp3/exp3e/exp3e.py
Python
mit
24,990
0.023729
import numpy as np import tensorflow as tf import h5py import time import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import sys # Functions for initializing neural nets parameters def init_weight_variable(shape, nameIn): initial = tf.truncated_normal(shape, stddev=0.1, dtype=tf.float32) retu...
_weight_variable([self
.filter_row, self.filter_col, 1, self.k1], "W_conv1") self.b_conv1 = init_bias_variable([self.k1], "b_conv1") # tensor that computes the output of the first convolutional layer h_conv1 = tf.nn.relu(conv2d(x_image, self.W_conv1) + self.b_conv1) h_conv1 = tf.identity(h_conv1, name="h_conv_1") # flatten out ...
alvarovmz/PyLinkedIn
codegen/templates/LinkedInObject.IsInstance.list.complex.py
Python
gpl-3.0
148
0.074324
all( {% include "LinkedInObject.
IsInstance.py" with variable="element" type=type.name|add:"."|add:type.name only %} for element in {{
variable }} )
jorisvandenbossche/pandas
pandas/core/frame.py
Python
bsd-3-clause
376,408
0.00059
""" DataFrame --------- An efficient 2D container for potentially mixed-type time series or other labeled data series. Similar to its R counterpart, data.frame, except providing automatic data alignment and a host of useful data manipulation methods having to do with the labeling information """ from __future__ import...
types import ExtensionDtype from pandas.core.dtypes.missing import ( isna, notna, ) from pandas.core import ( algorithms, common as com, generic, nanops, ops, ) from pandas.core.accessor import CachedAccessor from pandas.core.apply import ( reconstruct_
func, relabel_result, ) from pandas.core.array_algos.take import take_2d_multi from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ( DatetimeArray, ExtensionArray, TimedeltaArray, ) from pandas.core.arrays.sparse import SparseFrameAccessor from pandas.core.construction import ( ...
Morgan-Stanley/treadmill
lib/python/treadmill/sproc/alert_monitor.py
Python
apache-2.0
4,428
0
"""Process alerts. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import errno import logging import os import os.path import click from treadmill import alert from treadmill import appenv from treadmill import...
gth', help='Keep at most that many files in alerts directory' ', default: {}'.format
(_DEF_MAX_QUEUE_LEN), type=int, default=_DEF_MAX_QUEUE_LEN ) @click.option( '--wait-interval', help='Time to wait between WT alerting retry attempts (sec)' ', default: {}'.format(_DEF_WAITING_PERIOD), type=int, default=_DEF_WAITING_PERIOD ) def ale...
jordanemedlock/psychtruths
temboo/core/Library/Amazon/S3/GetBucketLocation.py
Python
apache-2.0
4,330
0.005543
# -*- coding: utf-8 -*- ############################################################################### # # GetBucketLocation # Returns the Region where the bucket is stored. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may...
""" Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are "xml" (the default) and "json".) """
super(GetBucketLocationInputSet, self)._set_input('ResponseFormat', value) class GetBucketLocationResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the GetBucketLocation Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def...
IgnitionProject/ignition
demo/dsl/riemann/euler.py
Python
bsd-3-clause
356
0.002809
from ignit
ion.dsl.riemann import * q = Conserved('q') rho, rhou, E = q.fields(['rho', 'rhou', 'E']) u = rhou / rho gamma = Constant('gamma') P = gamma * (E - .5 * u * rhou) f = [rhou, P + u * rhou, u * (E + P)] #generate(f, q, "euler_kernel.
py") G = Generator() G.flux = f G.conserved = q G.eig_method = "numerical" G.write("euler_kernel.py")
cydenix/OpenGLCffi
OpenGLCffi/GL/EXT/SUN/mesh_array.py
Python
mit
153
0.019608
from OpenGLCffi.GL import params @params(api='gl', prms=['mode', 'first', 'count', 'width']) def glDrawMeshArra
ysSUN(mode, first, count, width): pass
kytos/python-openflow
tests/unit/v0x01/test_symmetric/test_hello.py
Python
mit
506
0
"""Hello message tests.""" from pyof.v0x01.symmetric.hello import Hello fro
m tests.unit.test_struct import TestStruct class TestHello(TestStruct): """Hello message tests (also those in :class:`.TestDump`).""" @classmethod def setUpClass(cls): """Configure raw file and its object in parent class (TestDump).""" super().setUpClass() super().set_raw_dump_fil...
super().set_raw_dump_object(Hello, xid=1) super().set_minimum_size(8)