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
pythonfoo/pythonfooLite
Level_02/passwort.py
Python
gpl-3.0
222
0.009009
#!/usr/bin/env python3 from getp
ass import getpass PWD = "123456" # type: str eingabe = getpass() # type: str if eingabe == PWD: print("Richtig.") elif eingabe in PWD: print("Fast.") else: print("Falsc
h.")
arenadata/ambari
ambari-common/src/main/python/resource_management/libraries/functions/setup_ranger_plugin.py
Python
apache-2.0
4,473
0.014979
#!/usr/bin/env 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 "License");...
ITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ __all__ = ["setup_ranger_plugin"] import os from datetime import datetime from resource_management.libraries.functions.ranger_functions import Rangeradmin from resource...
t File, Execute from resource_management.libraries.functions.format import format from resource_management.libraries.functions.get_stack_version import get_stack_version from resource_management.core.logger import Logger from resource_management.core.source import DownloadSource from resource_management.libraries.resou...
dhruvaldarji/InternetProgramming
Assignment_6/Assignment_6/settings.py
Python
mit
3,248
0.001539
""" Django settings for Assignment_6 project. Generated by 'django-admin startproject' using Django 1.9.3. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import ...
ango.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Assignment_6.wsgi.app
lication' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password...
wengzhilai/family
iSoft/model/framework/PostBaseModel.py
Python
bsd-3-clause
130
0.055556
class PostBaseModel(o
bject): #主键 Key=None Token=None def __init__(self,jsonObj): self.__dict__=jsonO
bj
luotao1/Paddle
python/paddle/fluid/tests/unittests/test_space_to_depth_op.py
Python
apache-2.0
5,176
0
# Copyright (c) 2018 PaddlePaddle 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 appli...
eight * blocksize * (channel2 + channel_out * b)) if forward: out_[out_index] = in_[in_index] else: out_[in_index] = in_[out_index] def setUp(self): self.init_data() ...
f.x.shape[3], self.x.shape[2], self.x.shape[1], self.x.shape[0], self.blocksize, self.forward, self.out_1d) self.out = np.reshape(self.out_1d, self.infered_shape) self.attrs = {"blocksize": self.blocksize} self.outputs = {"Out": self.out} def init_dat...
craws/OpenAtlas-Python
openatlas/database/connect.py
Python
gpl-2.0
946
0
from typing import Any, Dict from flask import g from psycopg2 import connect, extras def open_connection(config: Dict[str, Any]) -> None: try: g.db = connect( database=config['DATABASE_NAME'], user=config['DATABASE_USER'], password=config['DATABASE_PASS'], ...
# pragma: no cover print("Database connection failed") raise Exception(e) g.cursor = g.db.cursor(cursor_factory=extras.DictCursor) def close_connection() -> None: if hasattr(g, 'db'): g.db.close() class Transaction: @staticmethod def begin() -> None: g.cursor.exe
cute('BEGIN') @staticmethod def commit() -> None: g.cursor.execute('COMMIT') @staticmethod def rollback() -> None: g.cursor.execute('ROLLBACK')
kerneltask/micropython
tests/basics/io_stringio1.py
Python
mit
894
0
try: import uio as io except ImportError: import io a = io.StringIO() print('io.StringIO' in repr(a)) print(a.getvalue()) print(a.read()) a = io.StringIO("foobar") print(a.getvalue()) print(a.read()) print(a.read()) a = io.StringIO() a.writ
e("foo") print(a.getvalue()) a = io.StringIO("foo") a.write("12") print(a.getvalue()) a = io.StringIO("foo") a.write("123") print(a.getvalue()) a = io.StringIO("foo") a.write("1234") print(a.getvalue()) a = io.StringIO() a.write("foo") print(a.read()) a = io.StringIO() print(a.tell()) a.write("foo") print(a.tell()...
ython throws for operations on closed I/O, MicroPython makes # the underlying string empty unless MICROPY_CPYTHON_COMPAT defined try: f() print("ValueError") except ValueError: print("ValueError")
tomviner/pytest
testing/test_tmpdir.py
Python
mit
12,284
0.00057
import os import stat import sys import attr import pytest from _pytest import pathlib from _pytest.pathlib import Path def test_tmpdir_fixture(testdir): p = testdir.copy_example("tmpdir/tmpdir_fixture.py") results = testdir.runpytest(p) results.stdout.fnmatch_lines(["*1 passed*"]) @attr.s class FakeC...
temp()).startswith("this") assert tmp2 != tmp def test_tmppath_relative_basetemp_absolute(self, tmp_path, monkeypatch): """#4425""" from _pytest.tmpdir import TempPathFactory monkeypatch.chdir(tmp_path) config = FakeConfig("hello") t = TempPathFactory.from_config(co...
def test_getbasetemp_custom_removes_old(self, testdir): mytemp = testdir.tmpdir.join("xyz") p = testdir.makepyfile( """ def test_1(tmpdir): pass """ ) testdir.runpytest(p, "--basetemp=%s" % mytemp) mytemp.check() mytemp...
BhallaLab/moose
moose-core/python/moose/neuroml/NetworkML.py
Python
gpl-3.0
25,761
0.010947
# -*- coding: utf-8 -*- ## Description: class NetworkML for loading NetworkML from file or xml element into MOOSE ## Version 1.0 by Aditya Gilra, NCBS, Bangalore, India, 2011 for serial MOOSE ## Version 1.5 by Niraj Dudani, NCBS, Bangalore, India, 2012, ported to parallel MOOSE ## Version 1.6 by Aditya Gilra, NCBS, Ban...
to create synapses at all potential locations/compartments specified in the MorphML cell file even before Projections tag is parsed. 'combineSegments' : True (False by default) to ask neuroml to combine segments belonging to a cable (Neuron generates multiple segmen...
er.info("Reading file %s " % filename) tree = ET.parse(filename) root_element = tree.getroot() _logger.info("Tweaking model ... ") tweak_model(root_element, params) _logger.info("Loading model into MOOSE ... ") return self.readNetworkML(root_element,cellSegmentDict,params...
deepmind/graph_nets
graph_nets/tests/blocks_test.py
Python
apache-2.0
43,860
0.003694
# Copyright 2018 The GraphNets 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 applicabl...
educer, expected_values): input_values_np = np.array([[0.1, -0.1], [0.2, -0.2], [0.3, -0.3], [0.4, -0.4], [0.5, -0.5],
[0.6, -0.6], [0.7, -0.7], [0.8, -0.8], [0.9, -0.9], [1., -1.]], dtype=np.float32) input_indices_np = np.array([1, 2, 2, 3, 3, 3, 4, 4, 5, 4], dtype=np.int32) n...
mozilla/verbatim
vendor/lib/python/translate/storage/test_dtd.py
Python
gpl-2.0
9,204
0.003151
#!/usr/bin/env python import warnings from py import test from py.test import mark from translate.misc import wStringIO from translate.storage import dtd from translate.storage import test_monolingual def test_roundtrip_quoting(): specials = ['Fish & chips', 'five < six', 'six > five', 'Use &nb...
#610 def test_entitityreference_order_in_source(self): """checks that an &entity; in the source is retained""" dtdsource = '<!ENTITY % realBrandDTD SYSTEM "chrome://brand
ing/locale/brand.dtd">\n%realBrandDTD;\n<!-- some comment -->\n' dtdregen = self.dtdregen(dtdsource) assert dtdsource == dtdregen # The following test is identical to the one above, except that the entity is split over two lines. # This is to ensure that a recent bug fixed in dtdunit.pa...
akretion/logistics-center
stef_logistics/__manifest__.py
Python
agpl-3.0
807
0
# © 2019 David BEAL @ Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Stef logistics center", "version": "12.0.1.0.0", "category": "Warehouse", "summary": "Stef logistics center", "author": "Akretion", "license": "AGPL-3", "website": "https://
www.akretion.com", "depends": ["stock", "logistics_center"], "external_dependencies": {"Python": []}, "data": [ "data/delivery_data.xml", "data/warehouse_data.xml", "data/logistics_flow_data.xml",
"views/partner_view.xml", # 'data/sale_data.xml', # 'data/repository_data.xml', # 'data/repository.task.csv', # 'data/backend_data.xml', # 'data/cron_data.xml', ], "demo": [], "installable": True, }
impallari/Impallari-Fontlab-Macros
IMP Kerning/20 ---.py
Python
apache-2.0
27
0.037037
#FL
M: --------- pa
ss
xiaozhu36/terraform-provider
examples/fc/hello.py
Python
apache-2.0
130
0.038462
import logging
def handler(event, context): lo
gger = logging.getLogger() logger.info('hello world') return 'hello world'
briancline/softlayer-python
SoftLayer/CLI/loadbal/service_delete.py
Python
mit
860
0
"""Deletes an existing load balancer service.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer
.CLI import environment from SoftLayer.CLI imp
ort exceptions from SoftLayer.CLI import formatting from SoftLayer.CLI import loadbal import click @click.command() @click.argument('identifier') @environment.pass_env def cli(env, identifier): """Deletes an existing load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, service_id...
Fabfm4/Sita-BackEnd
src/sita/authentication/serializers.py
Python
apache-2.0
6,676
0.003895
# -*- coding: utf-8 -*- import hashlib import random from rest_framework import serializers from sita.users.models import User from sita.subscriptions.models import Subscription from sita.utils.refresh_token
import create_token from hashlib import md5 from datetime import datetime, timedelta import pytz class LoginSerializer(serializers.Serializer): """ Serializer for user login """ email = serializers.EmailField( required=True ) password = serializers.CharField( required=True ...
=False, max_length=254 ) def validate(self, data): """ Validation email, password and active status """ try: user = User.objects.get(email__exact=data.get('email')) except User.DoesNotExist: raise serializers.ValidationError({"email":"inva...
geolovic/TProfiler
test/06_TProfiler_test.py
Python
gpl-3.0
12,892
0.000388
# -*- coding: utf-8 -*- """ José Vicente Pérez Granada University (Spain) March, 2017 Testing suite for profiler.py Last modified: 19 June 2017 """ import time import profiler as p import praster as pr import numpy as np import matplotlib.pyplot as plt print("Tests for TProfiler methods") def test01(): """...
) plt.show() fin = time.time() print("Test finalizado en " + str(fin - inicio) + " segundos") print("=" * 40) def test05(): """ Creates a TProfiler from an array with profile_data Test for calculate slopes """ inicio = time.time() print("=" * 40) print("Test 05 para TProfi...
ing functions calculate slopes") print("Test in progress...") # Test parameters pf_data = np.load("data/in/darro_pfdata.npy") dem = "data/in/darro25.tif" demraster = pr.open_raster(dem) srs = demraster.proj cellsize = demraster.cellsize # Creates the profile perfil = p.TProfile(pf_...
emoronayuso/beeton
asterisk-bee/asteriskbee/api_status/scripts_graficas/script_crontab.py
Python
gpl-3.0
1,417
0.016231
from crontab import CronTab from django.conf import settings ##################################################### ###Para mas info sobre el uso de python-crontab###### ### https://pypi.python.org/pypi/python-crontab ###### ##################################################### ##Directorio de la aplicaion ### STATIC_...
ntenido al archivo de cron tab.write() ##Mostramos la nueva linea que se incluira en el archivo de cron print tab.render() ############################################## ##PARA BORRAR UNA TAREA############# #cron_job = tab.find_command(cmd) #tab.remove_all(cmd) #Escribe el contenido al archivo de cron #tab.write()...
rint tab.render() ####################################
akx/shoop
shoop/core/pricing/default_pricing.py
Python
agpl-3.0
1,139
0
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.utils.translation import ugettext_lazy as _ from shoop.core.mod...
xt.shop shop_product = ShopProduct.objects.get(product=product, shop=shop) default_price = (shop_product.default_price_value or 0) return PriceInfo( price=shop.create_price(default_price * quantity), base_price
=shop.create_price(default_price * quantity), quantity=quantity, )
yausern/stlab
devices/Tektronics_Sequencer/element.py
Python
gpl-3.0
10,638
0.037413
# Implementation of sequence elements that are composed out of pulses # Author : W. Pfaff # modified by: Sarwan Peiter import numpy as np from copy import deepcopy import pprint import logging class Element: """ Implementation of a sequence element. Basic idea: add different pulses, and compose the actual numer...
('clock', 1e9) self.granularity = kw.pop('granularity', 4) self.min_samples = kw.pop('min_samples', 960) self.pulsar = kw.pop('pulsar', None) self.ignore_offset_correction = kw.pop('ignore_offset_correction',False) self.global_ti
me = kw.pop('global_time', True) self.time_offset = kw.pop('time_offset', 0) self.ignore_delays = kw.pop('ignore_delays',False) # Default fixed point, used for aligning RO elements. Aligns first RO self.readout_fixed_point = kw.pop('readout_fixed_point', 1e-6) # used to track if a correction has been applie...
ayouwei/minivpn
server/server.py
Python
apache-2.0
857
0.009335
#! /usr/bin/env python # -*- coding: utf-8 -*- import multiprocessing, Queue
import signal, time import setting from socketserver import SocketServer from tunserver import TunServer def sigHandler(signum, frame): print "signal %s received, client going to shutdown" % signum setting.running = False if __name__ == "__main__": signal.signal(signal.SIGINT, sigHandler) inqueue =...
e = multiprocessing.Queue(maxsize = 10) server_addr = "0.0.0.0" server_port = 8080 processes = [] processes.append(TunServer("tun Process", inqueue, outqueue)) processes.append(SocketServer("server Process", inqueue, outqueue, server_addr, server_port)) for t in processes: t.start() ...
pombredanne/bokeh
examples/plotting/file/markers.py
Python
bsd-3-clause
1,583
0.001895
from numpy.random import random from bokeh.plotting import figure, show, output_file def mscatter(p, x, y, marker): p.scatter(x, y, marker=marker, size=15, line_color="navy", fill_color="orange", alpha=0.5) def mtext(p, x, y, text): p.text(x, y, text=[text], text_color="firebrick", t...
"circle") mscatter(p, random(N)+4, random(N)+1, "square") mscatter(p, random(N)+6, random(N)+1, "triangle") msc
atter(p, random(N)+8, random(N)+1, "asterisk") mscatter(p, random(N)+2, random(N)+4, "circle_x") mscatter(p, random(N)+4, random(N)+4, "square_x") mscatter(p, random(N)+6, random(N)+4, "inverted_triangle") mscatter(p, random(N)+8, random(N)+4, "x") mscatter(p, random(N)+2, random(N)+7, "circle_cross") mscatter(p, ran...
huntcsg/slackly
src/slackly/oauth_utils.py
Python
mit
1,841
0.000543
#!/usr/bin/python3 from .compat import BaseHTTPRequestHandler, HTTPServer import urllib import json import sys import time import warnings from slackly import SlackClient warnings.warn("This part of slackly (oauth_utils) is highly experimental and will likely see api breaking changes") class CodeServer(BaseHTTPReq...
.path) query_values = urllib.parse.parse_qs(query) if 'code' in query_values: query_values['code'] = query_values['code'][0] if 'state' in query_values: query_values['state'] = query_values['state'][0] if query_values['state'] != self.state_validate: ...
print("Not a valid request") return print(json.dumps(query_values, indent=4)) client = SlackClient() response = client.api.oauth.access( client_id=client_id, client_secret=client_secret, code=query_values['code'], redirect_uri=red...
kfsone/tinker
python/packedstruct.py
Python
mit
9,560
0.001046
""" Tool for converting simple 'C' struct and #define lists into Python classes. The subset of C that is understand is limited to: #define <group>_<name> <value> struct X { <type> <name>; <type> <name>[dimension]; }; Blank lines and single-line comments are ignored. defines are expe...
self.logger.info("enum %s", typename) self.types.add(typename) text += "class %s:\n" % typename text += self.indent + "# Enums\n" self.logger.debug("enum %s.%s = %s", self._define_group, name, value) return text + self.indent + "%s = %s\...
ike #defines, structs and members from an iterable of lines of text, generating text to produce equivalent PackedStruct classes in Python. :param iterable: iterable of lines to parse :param prefix: [optional] prefix to require infront of structs/defines. :param net_endian: Set t...
probcomp/bdbcontrib
tests/test_draw_cc_state.py
Python
apache-2.0
2,579
0.005041
# -*- coding: utf-8 -*- # Copyright (c) 2010-2016, MIT Probabilistic Computing Project # # 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/LICENS...
. # See the License for the specific language governing permissions and # limitations under the License. import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import bayeslite import os import pandas as pd import random import cStringIO as StringIO from bayeslite.read_pandas import bayesdb...
m bdbcontrib.crosscat_utils import draw_state from crosscat.utils import data_utils as du def draw_a_cc_state(filename): rng_seed = random.randrange(10000) num_rows = 100 num_cols = 50 num_splits = 5 num_clusters = 5 nan_prop = .25 table_name = 'plottest' generator_name = 'plottest_cc...
kjchalup/dtit
setup.py
Python
mit
2,610
0.002682
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='fcit', # Versions...
e test', long_description=long_description, # The project's main homepage. url = 'https://github.com/kjchalup/fcit', # Author details author = 'Krzysztof Chalupka', author_email = 'janchatko@gmail.com', # Choose your license license='MIT', # See https://pypi.python.org/pypi?%3Aac...
mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Artificial ...
ZachGangwer/Exercism
python/pangram/pangram.py
Python
gpl-3.0
273
0.007326
def is_pangram(word): word = sorted(word) i = 1 count =
0 while i < len(word): if (word[i] != word[i-1]) & (word[i].isalpha()): count += 1 i += 1 if count == 26: return True else: return False
driesdesmet/django-cms
cms/plugin_rendering.py
Python
bsd-3-clause
6,339
0.005048
# -*- coding: utf-8 -*- from cms.models.placeholdermodel import Placeholder from cms.plugin_processors import (plugin_meta_context_processor, mark_safe_plugin_processor) from cms.utils import get_language_from_request from cms.utils.django_load import iterload_objects from cms.utils.placeholder import (get_page_fr...
t settings from django.template import Template, Context from django.template.defaultfilters import title from django.template.loader import render_to_string from django.utils.trans
lation import ugettext_lazy as _ # these are always called before all other plugin context processors DEFAULT_PLUGIN_CONTEXT_PROCESSORS = ( plugin_meta_context_processor, ) # these are always called after all other plugin processors DEFAULT_PLUGIN_PROCESSORS = ( mark_safe_plugin_processor, ) class PluginCon...
tinloaf/home-assistant
homeassistant/components/switch/aqualogic.py
Python
apache-2.0
3,306
0
""" Support for AquaLogic switches. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/switch.aqualogic/ """ import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.core import callback import homeass...
s', 'filter': 'Filter', '
filter_low_speed': 'Filter Low Speed', 'aux_1': 'Aux 1', 'aux_2': 'Aux 2', 'aux_3': 'Aux 3', 'aux_4': 'Aux 4', 'aux_5': 'Aux 5', 'aux_6': 'Aux 6', 'aux_7': 'Aux 7', } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SWITCH_TYPES)): ...
samvarankashyap/linch-pin
linchpin/provision/roles/azure/filter_plugins/map_results.py
Python
gpl-3.0
292
0
#!/usr/bin/env python from __future
__ import print_function import linchpin.FilterUtils.FilterUtils as filter_utils class FilterModule(object): ''' A filter to fix network format ''' def filters(self): return { 'map_results': filter_utils.map_results
}
AABoyles/Tabular.ui
Scripts/dumpStatesToDB.py
Python
gpl-2.0
1,190
0.004202
#!/usr/bin/python import time, s
qlite3, sys, urllib, csv begin = time.time() url = "http://www.correlatesofwar.org/COW2%20Data/SystemMembership/2011/states2011.csv" print "Downloading from", url response = urllib.urlretrieve(url, '../Data/states2011
.csv') print "Opening Database" con = sqlite3.connect('../Data/PyRBD.db') cur = con.cursor() rows = 0 with open(response[0], 'Ur') as csvFile: reader = csv.reader(csvFile) query = "INSERT INTO stateMembership(" for row in reader: if rows == 0: headers = ",".join(row) query...
j5shi/Thruster
pylibs/test/test_sys_settrace.py
Python
gpl-2.0
24,801
0.004798
# Testing the line trace facility. from test import test_support import unittest import sys import difflib import gc # A very basic example. If this fails, we're in deep trouble. def basic(): return 1 basic.events = [(0, 'call'), (1, 'line'), (1, 'return')] # Man...
(-4, 'return'), (-4, 'call'),
(-4, 'exception'), (-1, 'line'), (-1, 'return')] + [(5, 'line'), (6, 'line')] * 10 + [(5, 'line'), (5, 'return')]) class Tracer: def __init__(self): self.events = [] def trace(...
sony/nnabla
python/src/nnabla/backward_function/tanh_shrink.py
Python
apache-2.0
1,106
0.002712
# Copyright 2019,2020
,2021 Sony Corporation. # Copyright 2021 Sony Group Corpora
tion. # # 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 ...
splotz90/urh
src/urh/models/SimulatorMessageTableModel.py
Python
gpl-3.0
3,129
0.003196
from collections import defaultdict from PyQt5.QtCore import QModelIndex, Qt from urh.models.TableModel import TableModel from urh.signalprocessing.ProtocolAnalyzer import ProtocolAnalyzer class SimulatorMessa
geTabl
eModel(TableModel): def __init__(self, compare_frame_controller, generator_tab_controller, parent=None): super().__init__(None, parent) self.protocol = ProtocolAnalyzer(None) self.compare_frame_controller = compare_frame_controller self.generator_tab_controller = generator_tab_contr...
balajikris/autorest
src/generator/AutoRest.Python.Azure.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/__init__.py
Python
mit
658
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 may cause incorrect behavior and will be lost if the code is ...
ageAccountsOperations from .usage_operations import UsageOperations __all__ = [ 'StorageAccountsOperations', 'UsageOperations', ]
mkawalec/masters
contrib/plot_decay/plot2.py
Python
gpl-3.0
1,103
0.000907
#!/usr/bin/env python2 from glob import glob import re import matplotlib.py
plot as plt import numpy as np from sys import argv def get_a1(pattern): a1 = {} for fit_file in glob(pattern): with open(fit_file) as f: line = f.readline() coeffs = line.split(' ') fit_params = fit_file.split('-') if fit_params[0] not in a1: ...
in a1.keys(): a1[key] = sorted(a1[key], key=lambda x: x[0]) a1[key] = dict(y=map(lambda x: float(x[1]), a1[key]), x=map(lambda x: float(x[0]), a1[key])) return a1 def plot_a1(): a1 = get_a1(argv[1]) fig, ax = plt.subplots() for domain in sorted(a1.keys(), key=la...
DirectXMan12/nova-hacking
nova/tests/api/openstack/compute/contrib/test_flavor_swap.py
Python
apache-2.0
3,130
0.000639
# Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
self.assertFlavorSwap(flavors[0], '512') self.assertFlavorSwap(flavors[1], '') class FlavorSwapXmlTest(FlavorSwapTest): content_type
= 'application/xml' def _get_flavor(self, body): return etree.XML(body) def _get_flavors(self, body): return etree.XML(body).getchildren()
Kagee/youtube-dl
youtube_dl/extractor/teamcoco.py
Python
unlicense
3,246
0.001848
from __future__ import unicode_literals import base64 import re from .common import InfoExtractor from ..utils import qualities class TeamcocoIE(InfoExtractor): _VALID_URL = r'http://teamcoco\.com/video/(?P<video_id>[0-9]+)?/?(?P<display_id>.*)' _TESTS = [ { 'url': 'http://teamcoco.com/v...
.com/embed/v/%s' % video_id embed = self._download_webpage( embed_url, video_id, 'Downloading embed page') encoded_data = self._search_regex( r'"preload"\s*:\s*"([^"]+)"', embed, 'encoded data') data = self._parse_json( bas
e64.b64decode(encoded_data.encode('ascii')).decode('utf-8'), video_id) formats = [] get_quality = qualities(['500k', '480p', '1000k', '720p', '1080p']) for filed in data['files']: m_format = re.search(r'(\d+(k|p))\.mp4', filed['url']) if m_format is not None: ...
tensorflow/tensorflow
tensorflow/python/framework/c_api_util.py
Python
apache-2.0
7,542
0.009281
# Copyright 2017 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...
elf): return self._op_per_name.keys() @tf_contextlib.contextmanager def tf_buffer(data=None): """Context manager that creates and deletes TF_Buffer. Example usage: with tf_buffer() as buf: # get serialized graph def into buf ... proto_data = c_a
pi.TF_GetBuffer(buf) graph_def.ParseFromString(compat.as_bytes(proto_data)) # buf has been deleted with tf_buffer(some_string) as buf: c_api.TF_SomeFunction(buf) # buf has been deleted Args: data: An optional `bytes`, `str`, or `unicode` object. If not None, the yielded buffer will...
bestK1ngArthur/IU5
Term 5/Development of Internet applications/Lab6/Lab6/settings.py
Python
mit
3,298
0.001819
""" Django settings for Lab6 project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os # Buil...
ors AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth
.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = T...
zblz/naima
src/naima/models.py
Python
bsd-3-clause
15,997
0
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst import os import astropy.units as u import numpy as np from astropy.table import Table from astropy.utils.data import get_pkg_data_filename from .extern.validator import ( validate_array, validate_physical_type, valida...
n""" e = _validate_ene(e) return self._calc(e) class ExponentialCutoffBrokenPowerLaw: """ One dimensional power law model with a break
. Parameters ---------- amplitude : float Model amplitude at the break point e_0 : `~astropy.units.Quantity` float Reference point e_break : `~astropy.units.Quantity` float Break energy alpha_1 : float Power law index for x < x_break alpha_2 : float P...
Jet-Streaming/gyp
test/win/gyptest-link-nodefaultlib.py
Python
bsd-3-clause
596
0.010067
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source
code is governed by a BSD-style license that can be # found in the LICENSE file. """ Make sure nodefaultlib setting is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('nodefaultl...
il', chdir=CHDIR, status=1) test.pass_test()
fengjz1/eloipool-litecoin
eloipool.py
Python
agpl-3.0
26,968
0.034634
#!/usr/bin/python3 # Eloipool - Python Bitcoin pool server # Copyright (C) 2011-2013 Luke Dashjr <luke-jr+eloipool@utopios.org> # # 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 v...
ebug("%s to: %064x (pdiff %s)" % (pfx, tgt, target2pdiff(tgt))) userStatus[username] = [target, now, 0] return target getTarget.logger = logging.getLogger('getTarget') def TopTargets(n = 0x10): tmp = list(k for k, v in userStatus.items() if not v[0] is None) tmp.sort(key=lamb
da k: -userStatus[k][0]) tmp2 = {} def t2d(t): if t not in tmp2: tmp2[t] = target2pdiff(t) return tmp2[t] for k in tmp[-n:]: tgt = userS
affo/nova
nova/virt/vmwareapi/driver.py
Python
apache-2.0
27,905
0.000824
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # Copyright (c) 2012 VMware, Inc. # Copyright (c) 2011 Citrix Systems, Inc. # Copyright 2011 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. Yo...
help='The PBM status.'), cfg.StrOpt('pbm_wsdl_location', help='PBM service WSDL file location URL. ' 'e.g. file:///opt/SDK/spbm/wsdl/pbmService.wsdl ' 'Not setting this will disable storage policy based ' 'placement of instances.'), cfg....
'there is no defined storage policy for the specific ' 'request then this policy will be used.'), ] CONF = cfg.CONF CONF.register_opts(vmwareapi_opts, 'vmware') CONF.register_opts(spbm_opts, 'vmware') TIME_BETWEEN_API_CALL_RETRIES = 1.0 class VMwareVCDriver(driver.ComputeDriver): """The ...
Neuvoo/legacy-portage
pym/portage/package/ebuild/fetch.py
Python
gpl-2.0
36,523
0.032254
# Copyright 2010 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 from __future__ import print_function __all__ = ['fetch'] import codecs import errno import logging import random import re import shutil import stat import sys import tempfile import portage portage.proxy.lazyimp...
# 'nomirror' is bad/negative logic. You Restrict mirroring, not no-mirroring. if "mirror" in restrict or \ "nomirror" in restrict: if ("mirror" in features) and ("lmirror" not in features): # lmirror should allow you to bypass mirror restrictions. # XXX: This is not a good thing, and is temporary at bes...
\"mirror\" mode desired and \"mirror\" restriction found; skipping fetch.")) return 1 # Generally, downloading the same file repeatedly from # every single available mirror is a waste of bandwidth # and time, so there needs to be a cap. checksum_failure_max_tries = 5 v = checksum_failure_max_tries try: v = ...
square/pants
tests/python/pants_test/tasks/test_markdown_to_html.py
Python
apache-2.0
2,784
0.003951
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import unittest2 as ...
)) self.assertEqual
s( markdown_to_html.choose_include_text(ABC, 'start-at=bak', 'fake.md'), '\n'.join(['baker', 'charlie'])) self.assertEquals( markdown_to_html.choose_include_text(ABC, 'start-at=xxx', 'fake.md'), '') def test_include_start_after(self): self.assertEquals( markdown_to_html.cho...
platformio/platformio-core
platformio/util.py
Python
apache-2.0
9,050
0.000994
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
operties = { k.decode("utf8"): v.decode("utf8")
if isinstance(v, bytes) else v for k, v in service.properties.items() } json.dumps(properties) except UnicodeDecodeError: properties = None items.append( ...
nicproulx/mne-python
mne/commands/tests/test_commands.py
Python
bsd-3-clause
9,165
0
# -*- coding: utf-8 -*- import os from os import path as op import shutil import glob import warnings from nose.tools import assert_true, assert_raises from numpy.testing import assert_equal, assert_allclose from mne import concatenate_raws, read_bem_surfaces from mne.commands import (mne_browse_raw, mne_bti2fiff, mne...
bj_dir, 'sample-head-medium.fif') try: with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False): assert_raises(RuntimeError, mne_make_scalp_surfaces.run) os.environ['FREESURFER_HOME'] = tempdir # don't actually use it mne_make_scalp_surfaces.run() ass...
or, mne_make_scalp_surfaces.run) # no overwrite finally: if orig_fs is not None: os.environ['FREESURFER_HOME'] = orig_fs else: del os.environ['FREESURFER_HOME'] del os.environ['_MNE_TESTING_SCALP'] # actually check the outputs head_py = read_bem_surfaces(dens...
motherjones/mirrors
mirrors/migrations/0004_auto_20140609_1943.py
Python
mit
444
0
# -*- coding: utf-8 -*- from __future__ import unicode_liter
als from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('mirrors', '0003_componentrevision_version'), ] operations = [ migrations.AlterField( model_name='componentrevision', name='data', field=models.B
inaryField(null=True, editable=False, blank=True), ), ]
beiko-lab/gengis
bin/Lib/site-packages/numpy/polynomial/tests/test_hermite.py
Python
gpl-3.0
17,416
0.006833
"""Tests for hermite module. """ from __future__ import division import numpy as np import numpy.polynomial.hermite as herm from numpy.polynomial.polynomial import polyval from numpy.testing import ( TestCase, assert_almost_equal, assert_raises, assert_equal, assert_, run_module_suite) H0...
class TestIntegral(TestCase) : def test_hermint(self) : # check exceptions assert_raises(ValueError, herm.hermint, [0], .5) assert_raises(ValueError, herm.hermint, [0], -1) assert_raises(ValueError, herm.hermin
t, [0], 1, [0,0]) # test integration of zero polynomial for i in range(2, 5): k = [0]*(i - 2) + [1] res = herm.hermint([0], m=i, k=k) assert_almost_equal(res, [0, .5]) # check single integration with integration constant for i in range(5) : ...
sitture/trade-motors
src/vehicles/views.py
Python
mit
3,897
0.000257
from django.shortcuts import render, get_object_or_404 # import the custom context processor from vehicles.context_processor import global_context_processor from vehicles.models import Vehicle, VehicleMake, Category from settings.models import SliderImage from django.core.paginator import Paginator, InvalidPage, Empty...
category, make ).prefetch_related('images') else: vehicles_list = Vehicle.objects.get_ve
hicles_by_make( make ).prefetch_related('images') else: # if category is not found then get all of the vehicles if category: vehicles_list = Vehicle.objects.get_vehicles_by_category( category ).prefetch_related('images') els...
3dfxsoftware/cbss-addons
sale_multicompany_report/order.py
Python
gpl-2.0
1,880
0.005319
# -*- encoding: utf-8 -*- from openerp.osv import fields, osv from openerp.tools.translate import _ class sale_order_line(osv.Model): """ OpenERP Model : sale_order_line """ _inherit = 'sale.order.line' _columns = { 'att_bro': fields.boolean('Attach Brochure', required=False, help="""If y...
'There is no company configured for this user')) return user.company_id def _get_report_name(self, cr, uid, context): report = self.__get_company_object(cr, uid).sale_report_id if not report: rep_id = self.pool.get("ir.actions.report.xml").search( cr, uid,...
return report.report_name def print_quotation(self, cr, uid, ids, context=None): pq = super(sale_order, self).print_quotation(cr,uid,ids, context) return {'type': 'ir.actions.report.xml', 'report_name': self._get_report_name(cr, uid, context), 'datas': pq['datas'], 'nodestroy': Tru...
trivigy/aiologin
aiologin/__init__.py
Python
mit
7,901
0.000506
import asyncio from abc import ABCMeta from collections.abc import MutableMapping from aiohttp import web from aiohttp.web_request import Request from aiohttp_session import get_session from collections.abc import Sequence AIOLOGIN_KEY = '__aiologin__' ON_LOGIN = 1 ON_LOGOUT = 2 ON_AUTHENTICATED = 3 ON_FORBIDDEN = 4...
return self._unauthorized @property def forbidden(self): return self._forbidden @property def anonymo
us_user(self): return self._anonymous_user def setup(app, **kwargs): app.middlewares.append(middleware_factory(**kwargs)) def middleware_factory(**options): # noinspection PyUnusedLocal @asyncio.coroutine def aiologin_middleware(app, handler): @asyncio.coroutine def aiologin_...
TomMinor/MayaPerforce
Perforce/GUI.py
Python
mit
75,889
0.001146
import os import re import traceback import logging import platform from distutils.version import StrictVersion from PySide import QtCore from PySide import QtGui from P4 import P4, P4Exception, Progress, OutputHandler import Utils import AppUtils import GlobalVars import Callbacks reload(Utils) reload(AppUtils) re...
ialog): def __init__(self, totalFiles, parent=mainParent): super(SubmitProgressUI, self).__init__(parent) self.handler = None self.totalFiles = totalFiles self.currentFile = 0 def setHandler(self, handler): self.handler = handler def setMaximum(self, val): ...
elf, val): self.fileProgressBar.setValue(val) def incrementCurrent(self): self.currentFile += 1 self.overallProgressBar.setValue(self.currentFile) print self.totalFiles, self.currentFile if self.currentFile >= self.totalFiles: setComplete(True) def setComp...
TakesxiSximada/syaml
src/syaml/commands/__init__.py
Python
apache-2.0
53
0
import jumon def main(): jumon.entry(__name__)
IQSS/miniverse
dv_apps/metrics/stats_views_dataverses.py
Python
mit
6,085
0.004108
from .stats_view_base import StatsViewSwagger, StatsViewSwaggerKeyRequired from .stats_util_dataverses import StatsMakerDataverses class DataverseCountByMonthView(StatsViewSwaggerKeyRequired): """API View - Dataverse counts by Month.""" # Define the swagger attributes # Note: api_path must match the path...
else: exclude_uncategorized = True pub_state = se
lf.get_pub_state(request) if pub_state == self.PUB_STATE_ALL: stats_result = stats_datasets.get_dataverse_counts_by_type(exclude_uncategorized) elif pub_state == self.PUB_STATE_UNPUBLISHED: stats_result = stats_datasets.get_dataverse_counts_by_type_unpublished(exclude_uncategori...
rickypc/dotfiles
.rflint.d/order.py
Python
mit
3,013
0.000664
#!/usr/bin/env python # -*- coding: utf-8 -*- # Robot Lint Rules - Lint rules for Robot Framework data files. # Copyright (c) 2014, 2015, 2016
Richard Huang <rickypc@users.noreply.github.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lice
nse as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # 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 ...
kaedroho/wagtail
wagtail/core/signals.py
Python
bsd-3-clause
923
0.002167
from django.dispatch import Signal page_published = Signal(providing_args=['instance', 'revision']) page_unpublished = Signal(providing_args=['ins
tance']) pre_page_move = Signal(providing_args=['instance', 'parent_page_before', 'parent_page_after', 'url_path_before', 'url_path_after']) post_page_move = Signal(providing_args=['instance', 'parent_page_before', 'parent_page_after', 'url_path_before', 'url_path_after']) workflow_approved = Signal(providing_args=['i...
ser']) workflow_submitted = Signal(providing_args=['instance', 'user']) task_approved = Signal(providing_args=['instance', 'user']) task_rejected = Signal(providing_args=['instance', 'user']) task_submitted = Signal(providing_args=['instance', 'user']) task_cancelled = Signal(providing_args=['instance' 'user'])
readhub/readhub
config.py
Python
mit
665
0.001504
import os class Config(object): DEBUG = False # If using a DB do something like this: SQLALCHEMY_DATABASE_URI = os.environ.get('
DATABASE_URL', 'postgresql+pg8000://readhub_user@localhost:5432/readhub_db') # if using WTF forms you'll want some thing like this below # CSRF_SESSION_KEY = os.environ.get('SESSION_KEY') WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-never-guess' class Dev...
TESTING = True WTF_CSRF_ENABLED = False SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:test.db'
pdorrell/melody_scripter
setup.py
Python
mit
3,795
0.001845
# Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8')...
/v0.2.3.zip#egg=midi-0.2.3" ], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] extras_require={ 'dev': ['check-manifest'], 't
est': ['nose'], }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ }, # Although 'package_data' is the preferred approach, in some case ...
mycodeday/crm-platform
stock_account/wizard/stock_valuation_history.py
Python
gpl-3.0
8,050
0.00323
from openerp import tools from openerp.osv import fields, osv from openerp.tools.translate import _ class wizard_valuation_history(osv.osv_memory): _name = 'wizard.valuation.history' _description = 'Wizard that opens the stock valuation history table' _columns = { 'choose_date': fields.boolean('C...
((SELECT stock_move.id::text || '-' || quant.id::text AS id, quant.id AS quant_id, stock_move.id AS move_id, dest_location.id AS location_id, dest_location.company_id AS company_id, st...
product_template.categ_id AS product_categ_id, quant.qty AS quantity, stock_move.date AS date, quant.cost as price_unit_on_quant, stock_move.origin AS source FROM stock_quant as quant, stock_quant_mo...
arulalant/txt2ipa
kannada2ipa/kannada2ipaMap.py
Python
gpl-3.0
588,062
0.000005
#!/usr/bin/env python # -*- coding: utf-8 -*- # # # Author : Arulalan.T <arulalant@gmail.com> # Thanks to Mr. Govardhan Balaji <govigov03@gmail.com> # who contributed to create kannada2ipaMap # # from orddic import OrderedDict kan2ipa = OrderedDict([ ("ಳ್ಳಃ", "ɭɭəɦə"), ("ಳ್ಳಂ", "ɭɭəm"), ("ಳ್ಳೌ", "ɭɭəʋ")...
("ಳ್ಡಾ", "ɭɖa:"), ("ಳ್ಡ", "ɭɖʌ"), ("ಳ್ಠಃ", "ɭʈʰəɦə"),
("ಳ್ಠಂ", "ɭʈʰəm"), ("ಳ್ಠೌ", "ɭʈʰəʋ"), ("ಳ್ಠೋ", "ɭʈʰo:"), ("ಳ್ಠೊ", "ɭʈʰo"), ("ಳ್ಠೈ", "ɭʈʰaj"), ("ಳ್ಠೇ", "ɭʈʰe:"), ("ಳ್ಠೆ", "ɭʈʰe"), ("ಳ್ಠೃ", "ɭʈʰɻ̩"), ("ಳ್ಠೂ", "ɭʈʰu:"), ("ಳ್ಠು", "ɭʈʰʊ"), ("ಳ್ಠೀ", "ɭʈʰi:"), ("ಳ್ಠಿ", "ɭʈʰi"), ("ಳ್ಠಾ", "ɭʈʰa:"), ("ಳ್ಠ", "ɭʈʰʌ"), ("ಳ...
google/ashier
ashierlib/test/utils_test.py
Python
apache-2.0
2,733
0.006952
#!/usr/bin/python # # Copyright 2011 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...
that serves the same purpose as expect(1): it helps users script terminal interactions. However, unlike expect, Ashier is programming language agnostic and provides a readable template language for terminal output matching. These features make scripted terminal interactions simpler to create and easier to maintain. Th...
ttest.TestCase): """Unit tests for utils.SplitNone().""" def DoTest(self, arg, expected): self.assertEqual( utils.SplitNone(arg), expected) def testEmpty(self): self.DoTest([], []) def testOnlyNone(self): self.DoTest([None], []) def testOnlyNones(self): self.DoTest([None, None, Non...
whitehorse-io/encarnia
pyenv/lib/python2.7/site-packages/twisted/test/test_sob.py
Python
mit
5,632
0.003374
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import import os import sys from textwrap import dedent from twisted.trial import unittest from twisted.persisted import sob from twisted.python import components from twisted.persisted.styles import Ep...
tEverythingEphemeralGetattr(self): """ L{_EverythingEphermal.__getattr__} will proxy the __main__ module as an L{Ephemeral} object, and during load w
ill be transparent, but after load will return L{Ephemeral} objects from any accessed attributes. """ self.fakeMain.testMainModGetattr = 1 dirname = self.mktemp() os.mkdir(dirname) filename = os.path.join(dirname, 'persisttest.ee_getattr') global mainWhileLoadi...
jpajuelo/wirecloud
src/wirecloud/platform/core/models.py
Python
agpl-3.0
3,337
0.000899
# -*- coding: utf-8 -*- # Copyright (c) 2015 Conwet Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud 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 versio...
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 Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with Wirecloud. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from uuid import uuid4 from django.contrib.auth.models import User, Group...
WikiWatershed/model-my-watershed
src/mmw/apps/user/management/commands/drbusers.py
Python
apache-2.0
9,850
0
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from apps.user.models import UserProfile # Thanks to @ajrobbins for generating this DRB_ZIPS = ['07416', '07438', '07461', '07820', '07821', '07822', '07823', '07825', '07826', '07827', '07828', '07832', '07833', '07836', ...
', '08648', '08690', '08691', '08759', '088
02', '08804', '08808', '08822', '08825', '08826', '08827', '08848', '08865', '08867', '08886', '10940', '10963', '12093', '12167', '12406', '12410', '12421', '12430', '12434', '12438', '12441', '12455', '12459', '12464', '12465', '12468', '12474', '12492', '12701', '12719...
stack-of-tasks/sot-pattern-generator
src/dynamic_graph/sot/pattern_generator/__init__.py
Python
isc
136
0
fro
m . import meta_selector # noqa from .pg import PatternGenerator from .selector import Selector PatternGenerator('') Selector(''
)
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_ddos_protection_plans_operations.py
Python
mit
23,738
0.005055
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
otection_plan_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscripti
on_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # ...
dawran6/project-euler
14-longest-collatz-sequence.py
Python
mit
588
0.008503
from functools import lru_cache def
sequence(n): 'bad idea' while n is not 1: yield n n = 3*n+1 if n%2 else n/2 yield n def next_num(n): if n % 2: return 3
* n + 1 else: return n / 2 @lru_cache(None) def collatz_length(n): if n == 1: return 1 else: return 1 + collatz_length(next_num(n)) if __name__ == '__main__': i = 0 largest = 0 for n in range(1, 1_000_001): length = collatz_length(n) if length > largest...
openstack/neutron
tools/files_in_patch.py
Python
apache-2.0
2,508
0
#!/usr/bin/env python3 # Copyright 2020 Red Hat, 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 #...
IND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import re import sys file_names = set() def parse_input(input_file): global file_names while True: line_buffer
= input_file.readline() if not line_buffer: break line_match = re.search(r"^\s*---\s+([^\s@]+)[\s@]+", line_buffer) if not line_match: line_match = re.search(r"^\s*\+\+\+\s+([^\s@]+)[\s@]+", line_buffer) if line_match: ...
elpaxoudis/pattern-recognition
trainers.py
Python
gpl-2.0
1,725
0.031884
""" A class for training our perceptro
ns """ class Trainers: """ Constructor """ def __init__(self, data, r=1): self.data_vectors = data # training dataset self.r = r self.wrong_classified_vectors = ["dummy"] def gradientDes
cent(self, perceptron): print "Begin training..." last = len(self.data_vectors[0])-1 t = 0 # As long we have wrong classified vectors training is not complete while self.wrong_classified_vectors != []: self.wrong_classified_vectors = [] # For each vector in training dataset we check the classifier fo...
atantet/transferCZ
tau/get_tau_norm_red.py
Python
gpl-2.0
13,933
0.002799
import numpy as np from netCDF4 import Dataset import matplotlib.pyplot as plt from matplotlib import cm, colors from mpl_toolkits.basemap import Basemap, addcyclic from scipy.io import FortranFile # Amplification factor for the mean wind stress ampMean = 3.0 initDir = '../init/' nlat = 31 nlon = 30 year0 = 1961 year...
= sst.shape[0] dset.close() # Map definition llcrnrlon = lon.min() llcrnrlat = lat.min() urcrnrlon = lon.max() urcrnrlat = lat.max() nlev = 10 map = Basemap(projection='merc', llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat, urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat, resolution='c') (x, y) = map(LON, LAT) # Read zonal pseudo...
(nt, N) Wu = Wu.reshape(nt, N) mask = np.any(sst.mask, 0) | np.any(Wu.mask, 0) sstMasked = np.array(sst[:, ~mask]) WuMasked = np.array(Wu[:, ~mask]) lonlMasked = LON.flatten()[~mask] latlMasked = LAT.flatten()[~mask] nValid = N - mask.sum() # Remove radiative equilibrium temperature : Ta = T - T0 sstMasked -= T0 # Re...
ModernMT/MMT
src/textprocessing/script/pyflex.py
Python
apache-2.0
6,428
0.001557
import os import sys __author__ = 'Davide Caroselli' def escape(string): escaped = '' for c in string: if ('0' <= c <= '9') or ('A' <= c <= 'Z') or ('a' <= c <= 'z'): escaped += c else: escaped += '\\' + c return escaped def _abspath(root, path): if not os.pa...
n content.read() def _process_prefix(line, caseless, patterns): # Match any case only if caseless has been specified and line is not a single char match_anycase = False if caseless and len(line) > 1 and line[0].isalpha(): line = line.lower() match_anycase = True # No duplicates i...
erns: return None if match_anycase: string = '' for c in line: string += '(' + escape(c.upper()) + '|' + escape(c.lower()) + ')' line = string + '\\.' else: line = escape(line + '.') return '(' + line + ')' def _prefixes(path, caseless=None): if ca...
ak2703/edx-platform
common/djangoapps/student/views.py
Python
agpl-3.0
92,551
0.002636
""" Student Views """ import datetime import logging import uuid import json import warnings from collections import defaultdict from pytz import UTC from requests import HTTPError from ipware.ip import get_ip from django.conf import settings from django.contrib.auth import logout, authenticate, login from django.cont...
rt AuthException, AuthAlreadyAssociated from edxmako.shortcuts import render_to_response, render_to_string from course_modes.models im
port CourseMode from shoppingcart.api import order_history from student.models import ( Registration, UserProfile, PendingEmailChange, CourseEnrollment, CourseEnrollmentAttribute, unique_id_for_user, CourseEnrollmentAllowed, UserStanding, LoginFailures, create_comments_service_user, PasswordHistory, Use...
KunihikoKido/sublime-elasticsearch-client
commands/put_search_template.py
Python
mit
474
0
from .base import CreateBaseCommand class PutSearchTemplateCommand(CreateBaseCommand): command_name = "elasticsearch:put-search
-template" def run_request(self, template_id=None): if not template_id: self.show_input_panel( 'Search Template Id: ', '', self.run) return options = dict(
id=template_id, body=self.get_text() ) return self.client.put_template(**options)
cmouse/buildbot
worker/buildbot_worker/util/_hangcheck.py
Python
gpl-2.0
4,189
0.000239
""" Protocol wrapper that will detect hung connections. In particular, since PB expects the server to talk first and HTTP expects the client to talk first, when a PB client talks to an HTTP server, neither side will talk, leading to a hung connection. This wrapper will disconnect in that case, and inform the caller. "...
HangCheckProtocol, self).dataReceived(data) def connectionLost(self, reason): self._stopHungConnectionTimer() super(HangCheckProtocol, self).connectionLost(reason) def _startHungConnectionTimer(self): """ Start a timer to detect if the connection is hung. """ de...
ConnectionTimer = self._reactor.callLater( self._HUNG_CONNECTION_TIMEOUT, hungConnection) def _stopHungConnectionTimer(self): """ Cancel the hang check timer, since we have received data or been closed. """ if self._hungConnectionTimer: self._hungConn...
hdknr/paloma
src/paloma/models.py
Python
bsd-2-clause
33,915
0.000295
# -*- coding: utf-8 -*- from django.db.models import Q from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now from django.conf import settings from django import template # import Template,Context from djang...
= {} subclasses = cls.__subclasses__() for ref in obj._meta.get_all_related_objects(): if ref.model in subclasses: try: context.update( getattr(obj, ref.var_name ).target_context(*args, **kwargs) ...
abstract = True @deconstructible class Site(models.Model): ''' Site ''' name = models.CharField( _(u'Owner Site Name'), help_text=_(u'Owner Site Name'), max_length=100, db_index=True, unique=True) ''' Site Name ''' domain = models.CharField( _(u'@Domain'), help_text=_...
matthewoliver/swift
test/unit/test_locale/test_locale.py
Python
apache-2.0
2,743
0
#!/usr/bin/env python # coding: utf-8 # Copyright (c) 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
): if val is not None: os.environ[var] = val else: del os.environ[var] threading._DummyThread._Thread__stop = self.orig_stop def test_translations(self): path = ':'.join(sys.path) translated_message = check_output(['python', __file__, ...
a mesaĝo\n') if __name__ == "__main__": os.environ['LC_ALL'] = 'eo' os.environ['SWIFT_LOCALEDIR'] = os.path.dirname(__file__) sys.path = sys.argv[1].split(':') from swift import gettext_ as _ print(_('test message'))
monouno/site
judge/views/stats.py
Python
agpl-3.0
3,624
0.003311
from itertools import repeat, chain from operator import itemgetter from django.db.models import Count, Sum
, Case, When, IntegerField, Value, FloatField from django.db.models.expressions import CombinedExpression from django.http import JsonResponse from django.shortcuts import render from django.utils.translation import ugettext as _ from judge.models import Language, Submission chart_colors = [0x3366CC, 0xDC3912, 0xFF99...
, 0x22AA99, 0xAAAA11, 0x6633CC, 0xE67300, 0x8B0707, 0x329262, 0x5574A6, 0x3B3EAC] highlight_colors = [] def _highlight_colors(): for color in chart_colors: r, g, b = color >> 16, (color >> 8) & 0xFF, color & 0xFF highlight_colors.append('#%02X%02X%02X' % (min(int(r * 1.2), 255), ...
Gabriel-p/UBV_move
modules/zams_solutions.py
Python
gpl-3.0
4,495
0
from .ext_solutions import intrsc_values def main(id_star, x_star, y_star, extin_list, zams_indxs, zams_inter, M_abs, sp_type, m_obs, bv_obsrv, e_bv, ub_obsrv, e_ub): """ For each solution assigned to each observed star, find its absolute magnitude, intrinsic colors, spectral types, and distance...
m_uniq.append(m_obs[indx]) bv_obs_uniq[0].append(bv_obsrv[indx]
) bv_obs_uniq[1].append(e_bv[indx]) ub_obs_uniq[0].append(ub_obsrv[indx]) ub_obs_uniq[1].append(e_ub[indx]) # Distances. E_BV = extin_list[indx][0] A_v = 3.1 * E_BV dist_mod = m_obs[indx] - zams_inter[2][star_indxs[0]] d_kpc...
Alex-Chizhov/python_training
home_works/test/test_del_contact.py
Python
apache-2.0
595
0.005042
from model.info_contact import Infos import random def test_delete_some_contact(app, db, check_ui): if app.contact.count() == 0: app.contact.create(Infos(firstname="AAAAA")) old_contacts = db.get_contact_list() contact = ra
ndom.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) new_contacts = db.get_contact_list() old_contacts.remove(contact) assert old_contacts =
= new_contacts if check_ui: assert sorted(map(app.contact.clean, new_contacts), key=Infos.id_or_max) == sorted(app.contact.get_contact_list(), key=Infos.id_or_max)
germs-lab/RefSoil
script_to_clean_list/remove_comma.py
Python
gpl-2.0
134
0.014925
#!/user/bin/python import sys for line i
n open(sys.argv[1],'r'):
spl = line.strip().split(',') for x in spl: print x
mlvfx/vfxAssetBox
assetbox/plugins/nuke/host.py
Python
cc0-1.0
458
0
""" Host app for nu
ke, check if we are in nuke. """ from assetbox.base.plugins.host import BaseHost import sys class HostApp(BaseHost): """ The host application class, which is used to determine context. """ ID = 'Nuk
e' filetypes = ['abc', 'exr'] def get_host(self): """Return True if we are in Nuke.""" return 'Nuke' in sys.executable def start_QApp(self): """Create the QApplication.""" pass
AMorporkian/tagprostats
db.py
Python
mit
6,957
0.000862
from pony.orm import * from datetime import datetime db = Database('sqlite', 'players.sqlite', create_db=False) pony.options.MAX_FETCH_COUNT=50000 class Players
(db.Entity): _table_ = "profile_stats" id = PrimaryKey(int, auto=True) last_updated = Required(datetime) name = Required(unicode, 50) server = Optional(unicode, 25) profile_string = Required(unicode, 30) captures = Required(int) disconnects = Required(int) drops = Required(int) ...
(int) prevent = Required(int) returns = Required(int) support = Required(int) tags = Required(int) wins = Required(int) captures_per_hour = Optional(float) disconnects_per_hour = Optional(float) drops_per_hour = Optional(float) games_per_hour = Optional(float) grabs_per_hour = O...
larsks/python-ftn
fidonet/nodelist.py
Python
gpl-3.0
5,703
0.002806
import re import logging from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship, backref re_ip_in_phone = re.compile('000*-(\d+-\d+-\d+-\d+)') re_phone_all_zero = re.compile('000*-0+-0+-0+-0+') re_hostname = re.compile('[\w-]+\.[\w-]+') ...
d = Column(Integer, primary_key=True) kw = Column(String, index=True) name = Column(String) location = Column(String) sysop = Column(String) phone = Column(String) speed = Column(String) zone = Column(Integer, index=True) region = Column(Integer, index=True) net = Column(Integer, in...
e) node = Column(Integer) address = Column(String, index=True, unique=True) hub_id = Column(Integer, ForeignKey('nodes.id')) flags = relationship(Flag, backref='node') raw = relationship(Raw, backref='node') def __repr__ (self): return '<Node %s (%s)>' % (self.address, self.name) ...
tkaitchuck/nupic
build_system/autobuild/deploy.py
Python
gpl-3.0
7,654
0.013457
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditio...
buildSystemDi
r = os.path.abspath(os.path.normpath(os.path.join(mydir))) sys.path.append(buildSystemDir) import pybuild.utils as utils import pybuild.test_release as test testOnly = False # Initially grab the lock only for two minutes initialLockTime = 120 # If we decide to deploy, grab it for 6 hours to reduce frequency of copying...
SasView/sasview
src/sas/qtgui/Plotting/Slicers/Arc.py
Python
bsd-3-clause
4,351
0.002068
""" Arc slicer for 2D data """ import numpy as np from sas.qtgui.Plotting.Slicers.BaseInteractor import BaseInteractor class ArcInteractor(BaseInteractor): """ Select an annulus through a 2D plot """ def __init__(self, base, axes, color='black', zorder=5, r=1.0, theta1=np.pi / 8, ...
params = {} params["radius"] = self.radius params["theta1"] = self.theta1
params["theta2"] = self.theta2 return params def set_params(self, params): """ """ x = params["radius"] phi_max = self.theta2 nbins = self.npts self.set_cursor(x, self._mouse_y, phi_max, nbins)
kasemir/org.csstudio.display.builder
org.csstudio.display.builder.runtime/scripts/test-script.py
Python
epl-1.0
348
0.005747
import sys from connect2j import connectToJava if (len(sys.argv) > 1): gateway = None try: gateway = connectToJava(sys.argv[1]) map = g
ateway.getMap() map['1'] = 1 gateway.setMap(map) map["obj"].setValue("Hello") finally: if gateway != None:
gateway.shutdown()
pradyunsg/pip
src/pip/_vendor/rich/bar.py
Python
mit
3,264
0.001856
from typing import Optional, Union from .color import Color from .console import Console, ConsoleOptions, RenderResult from .jupyter import JupyterMixin from .measure import Measurement from .segment import Segment from .style import Style # There are left-aligned characters for 1/8 to 7/8, but # the right-aligned ch...
render # a symbol that's "center-aligned", but there is no good symbol in Unicode. # In this case, we fall back to right-aligned block symbol for simplicity. prefix = " " * prefix_bar_count if prefix_eights_count:
prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count] body = FULL_BLOCK * body_bar_count if body_eights_count: body += END_BLOCK_ELEMENTS[body_eights_count] suffix = " " * (width - len(body)) yield Segment(prefix + body[len(prefix) :] + suffix, self.style) yiel...
dedoogong/asrada
FaceLandmark_Detector_DAN/generate_hd5.py
Python
apache-2.0
1,140
0.005263
import numpy as np import cv2 import h5py min_img_size = 12 label_path = './label.txt' landmark_path = './landmark.txt' regression_
box_pat
h = './regression_box.txt' crop_image_path = './crop_image.txt' train_file_path = './train_12.hd5' label = np.loadtxt(label_path, int) landmark = np.loadtxt(landmark_path, float) regression_box = np.loadtxt(regression_box_path, float) label = np.transpose([label]) #landmark = np.transpose(landmark) labels = np.concat...
alexoneill/15-love
game/test.py
Python
mit
1,989
0.011061
#!/usr/bin/python2 # test.py # nroberts 04/10/2017 # Instead of lighting up a bridge, we light up the terminal from tennis_show import TennisShow import current_bridge from threading import Thread import Queue from colors import Colors thread_continuing = True class OutQueue: def put(self, event): print ...
print "Usage: Press 1 for player 1 swing, 2 for player 2 swing (followed by Enter)" print "To quit, press Ctrl+C and then Enter" inqueue = Queue.Queue() outqueue = OutQueue() show = TennisShow(bridge(), inqueue=inqueue, outqueue=outqueue) def cause_problems(): global thread_continuing ...
RossBrunton/BMAT
bmat/context_processors.py
Python
mit
786
0.007634
"""Context processors, these get called and add things to template contexts""" from django.conf import settings def analytics_and_ads(request): """ Adds the google analytics code to the context """ out = {} if request.user.is_authen
ticated() and request.user.settings.no_analytics: out["analytics_code"] = "" else: out["analytics_code"] = settings.ANALYTICS_CODE if request.user.is_authenticated() and request.user.settings.no_ads: out["ad_clie
nt"] = "" else: out["ad_client"] = settings.AD_CLIENT out["ad_slot_top"] = settings.AD_SLOT_TOP out["ad_slot_bottom"] = settings.AD_SLOT_BOTTOM return out def add_webstore_url(request): return {"webstore_url":settings.CHROME_EXTENSION_WEBSTORE}
Kickflip/python-kickflip
kickflip/kickflip.py
Python
apache-2.0
9,824
0
#! /usr/bin/env python import envoy import boto import requests import os import sys import time import random import string from oauthlib.oauth2 import MobileApplicationClient from requests_oauthlib import OAuth2Session from boto.s3.connection import Location from boto.s3.lifecycle import Lifecycle, Transition, Rule ...
upload_file(event.src_path) def on_modified(self, event): global playlist if '.m3u8' in event.src_path: playlist.add_from_file(event.src_path) playlist.dump_to_fil
e(event.src_path + '.complete.m3u8') upload_file(event.src_path + '.complete.m3u8') def on_created(self, event): self.process(event) def stream_video(video_path): global VIDEO_BITRATE g
laslabs/odoo-connector-carepoint
connector_carepoint/tests/test_related_action.py
Python
agpl-3.0
4,249
0
# -*- coding: utf-8 -*- # Copyright 2015-201
6 LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import mock from contextlib import contextmanager from odoo import _ from odoo.addons.connector_carepoint import related_action from .common import SetUpCarepointBase mk_file = 'odoo.addons.connector_carepoint.related_action' @c...
xception(Exception): pass class TestRelatedAction(SetUpCarepointBase): def setUp(self): super(TestRelatedAction, self).setUp() self.model = 'carepoint.carepoint.store' self.binding_id = self._new_record() self.job = mock.MagicMock() self.job.args = [self.model, self.bi...
komlenic/drubs
drubs/drubs.py
Python
gpl-2.0
9,647
0.014823
import yaml import tasks from os.path import isfile, isdir, dirname, abspath, join, basename, normpath, realpath from os import getcwd from fabric.state import env, output from fabric.tasks import execute from fabric.colors import red, yellow, green, cyan from fabric.contrib.console import confirm from fabric.api impor...
l' env.config_dir - the absolute path to the project config directory env.config - the actual contents of the config file Accepts one parameter 'config_file': the relative or absolute path to a drubs project config file. ''' if isfile(config_file): env.config_file = config_file env.config_dir = dir...
with open(config_file, 'r') as stream: env.config = yaml.load(stream) # If env.config evaluates to false, nothing parseable existed in the file. if not env.config: print(red("The project config file '%s' does not contain anything or is not valid. Exiting..." % (config_file))) exit(1) ...
layus/pylti
pylti/__init__.py
Python
bsd-2-clause
185
0
# -*- coding: utf-8 -
*- """ PyLTI is module that implements IMS LTI in python The API uses decorators to wrap function with LTI functionality. """ V
ERSION = "0.3.2" # pragma: no cover
logpai/logparser
benchmark/LogMine_benchmark.py
Python
mit
5,994
0.009343
#!/usr/bin/env python import sys sys
.path.append('../') from logparser import LogMine, evaluator import os import pandas as pd input_dir = '../logs/' # The input directory of log file output_dir = 'LogMine_result/' # The output directory of parsing results benchmark_settings = { 'HDFS': { 'log_file': 'HDFS/HDFS_2k.log', '...
2 }, 'Hadoop': { 'log_file': 'Hadoop/Hadoop_2k.log', 'log_format': '<Date> <Time> <Level> \[<Process>\] <Component>: <Content>', 'regex': [r'(\d+\.){3}\d+'], 'max_dist': 0.005, 'k': 1, 'levels': 2 }, 'Spark': { 'log_file': ...
groveco/django-sql-explorer
explorer/tests/test_csrf_cookie_name.py
Python
mit
1,142
0.003503
from django.test import TestCase, override_settings try: from django.urls import reverse except
ImportError: from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.conf import settings class TestCsrfCookieName(TestCase): def test_csrf_cookie_name_in_context(self): self.user = User.objects.create_superuser('admin', 'admin@admin-fake.com', 'pwd') ...
lf.client.get(reverse('explorer_index')) self.assertTrue('csrf_cookie_name' in resp.context) self.assertEqual(resp.context['csrf_cookie_name'], settings.CSRF_COOKIE_NAME) @override_settings(CSRF_COOKIE_NAME='TEST_CSRF_COOKIE_NAME') def test_custom_csrf_cookie_name(self): self.user = Use...
westernx/mayatools
mayatools/fluids/retime.py
Python
bsd-3-clause
6,890
0.003483
import math import os from optparse import OptionParser import qbfutures from .core import Cache, Frame, Shape, Channel def frange(a, b, step): v = float(a) b = float(b) step = float(step) while v <= b: yield v v += step def iter_ticks(src_start, src_end, dst_start, dst_end, sampl...
add_option('-s', '--start', type='float') option_parser.add_option('-e', '--end', type='float') option_parser.add_option('--src-start', '--os', type='float') option_parser.add_option('--src-end', '--oe', type='float') option_parser.add_option('-r', '--rate', type='float', default=1.0) option_parser....
, action='store_true') option_parser.add_option('-w', '--workers', type='int', default=20) option_parser.add_option('-a', '--advect', type='float', default=0.0) opts, args = option_parser.parse_args() if len(args) != 2: option_parser.print_usage() exit(1) res = schedule_retime(*ar...
zhaochl/python-utils
agrith_util/page_rank/page_rank_test.py
Python
apache-2.0
2,180
0.050781
#!/usr/bin/env python # coding=utf-8 #-*- coding:utf-8 -*- import random N = 8 #八个网页 d = 0.85 #阻尼因子为0.85 delt = 0.00001 #迭代控制变量 #两个矩阵相乘 def matrix_multi(A,B): result = [[0]*len(B[0]) for i in range(len(A))] for i in range(len(A)): for j in range(len(B[0])): for k in range(...
_multiN(d,matrix_multi(A,P))) #P=(1-d)*e/n+d*M'P PageRank算法的核心 norm = 0 #求解矩阵一阶范数 for i in range(N): norm += abs(New_P[i][0]-P[i][0]) print New_P #根据邻接矩阵求转移概率矩阵并转向 def tran_and_convert(A): result = [[0]*len(A[0]) for i in range(len(A))] result_convert = [[0]*len(A[0]) fo...
range(len(A)): for j in range(len(A[0])): result[i][j] = A[i][j]*1.0/sum(A[i]) for i in range(len(result)): for j in range(len(result[0])): result_convert[i][j]=result[j][i] return result_convert def main(): A = [[0,1,1,0,0,1,0,0],\ [0,0,0,1,1,0,0,0],\ [0,0,...