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 |
|---|---|---|---|---|---|---|---|---|
SasView/sasview | src/sas/qtgui/GUITests.py | Python | bsd-3-clause | 11,242 | 0.008806 | import os
import unittest
import sys
from PyQt5 import QtGui
from PyQt5 import QtWidgets
"""
Unit tests for the QT GUI
=========================
In order to run the tests, first install SasView and sasmodels to site-packages
by running ``python setup.py install`` in both repositories.
The tests can be run with ``pyt... | unittest.makeSuite(ScalePropertiesTest.ScalePropertiesTest, 'test'),
unittest.makeSuite(SetG | raphRangeTest.SetGraphRangeTest, 'test'),
unittest.makeSuite(LinearFitTest.LinearFitTest, 'test'),
unittest.makeSuite(PlotPropertiesTest.PlotPropertiesTest, 'test'),
unittest.makeSuite(PlotUtilitiesTest.PlotUtilitiesTest, 'test'),
unittest.makeSuite(ColorMap... |
angelapper/edx-platform | cms/djangoapps/contentstore/management/commands/delete_course.py | Python | agpl-3.0 | 2,796 | 0.005007 | """
Command for deleting courses
Arguments:
arg1 (str): Course key of the course to delete
Returns:
none
"""
from django.core.management.base import BaseCommand, CommandError
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from contentstore.utils import ... | rse
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from .prompt import query_yes_no
class Command(BaseCom | mand):
"""
Delete a MongoDB backed course
Example usage:
$ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --settings=devstack
$ ./manage.py cms delete_course 'course-v1:edX+DemoX+Demo_Course' --keep-instructors --settings=devstack
Note:
keep-instructors option i... |
AlienCowEatCake/ImageViewer | src/ThirdParty/Exiv2/exiv2-0.27.5-Source/tests/bugfixes/github/test_CVE_2017_17724.py | Python | gpl-3.0 | 654 | 0 | # -*- coding: utf-8 -*-
import system_tests
class TestFuzzedPoC(metaclass=system_tests.CaseMeta):
url = [
"https://github.com/Exiv2/exiv2/issues/210",
"https://github.com/Exiv2/exiv2/issues/209"
]
filename = system_test | s.path("$data_path/2018-01-09-exiv2-crash-002.tiff")
commands = [
"$e | xiv2 -pR $filename",
"$exiv2 -pS $filename",
"$exiv2 $filename"
]
retval = [1, 1, 0]
compare_stderr = system_tests.check_no_ASAN_UBSAN_errors
def compare_stdout(self, i, command, got_stdout, expected_stdout):
""" We don't care about the stdout, just don't crash """
pass... |
jedevc/EuPy | examples/hello.py | Python | mit | 736 | 0.005435 | import euphoria as eu
class HiBot(eu.ping_room.PingRoom, eu.standard_room.StandardRoo | m):
def __init__(self, roomname, password=None):
super().__init__(roomname, password, at | tempts=2)
self.nickname = "HiBot"
self.short_help_text = "Say hello to @HiBot!"
self.help_text = self.short_help_text + 2 * '\n' + "Just a quick demo bot."
def handle_chat(self, message):
if "hi" in message["content"].lower():
self.send_chat("Hi there!", message["id"])
... |
Xoristzatziki/Sample-App | _lib/forconfig.py | Python | lgpl-3.0 | 1,587 | 0.016383 | #!/usr/bin/python3
#Copyright Xoristzatziki
import configparser
import os,sys
class MyConfigs():
def __init__(self,filename):
self.myconfigfilename = filename
def readconfigvalue(self, wichsection, wichoption, default):
try:
cp = configparser.ConfigParser()
c... | with open(self.myconfigfilename, 'w') as f:
cp.write(f)
#print self.myconfigfilename
if __name__ == "__main__":
#print pygtk
# get the real location of this launcher file ( | not the link location)
#realfile = os.path.realpath(__file__)
inifile = os.path.join(os.path.expanduser('~'),'OCPany.conf')
test = MyConfigs(inifile)
test.writeconfigvalue('somesection',someparameter','avalue')
|
nibrahim/PlasTeX | unittests/FunctionalTests.py | Python | mit | 4,122 | 0.009461 | #!/usr/bin/env python
import unittest, re, os, tempfile, shutil, glob, difflib, subprocess
from unittest import TestCase
class Process(object):
""" Simple subprocess wrapper """
def __init__(self, *args, **kwargs):
if 'stdin' not in kwargs:
kwargs['stdin'] = subprocess.PIPE
if 'std... |
if 'stderr' not in kwargs:
kwargs['stderr'] = subprocess.STDOUT
self.process = subprocess.Popen(args, **kwargs)
self.log = self.process.stdout.read()
self.ret | urncode = self.process.returncode
self.process.stdout.close()
self.process.stdin.close()
class Benched(TestCase):
""" Compile LaTeX file and compare to benchmark file """
filename = None
def runTest(self):
if not self.filename:
return
src = self.fi... |
ioparaskev/cenotes | manage.py | Python | gpl-3.0 | 3,014 | 0.000995 | import json
from datetime import date
from urllib.parse import unquote
import functools
from flask_migrate import MigrateCommand
from flask_script import Manager
from cenotes_lib.crypto import get_supported_algorithm_options
from cenotes import create_app
from cenotes.api import craft_response, CENParams
from cenotes... | ", dkey="",
payload="ciphertext",
enote=Note(payload="ciphertext", expirat | ion_date=date.today())))
def list_url_endpoints():
output = []
for rule in manager.app.url_map.iter_rules():
if rule.endpoint == "static":
continue
options = {}
for arg in rule.arguments:
options[arg] = "[{0}]".format(arg)
methods = ','.join(rule.method... |
minghuascode/pyj | examples/funnysortedgridthing/SortedGridThing.py | Python | apache-2.0 | 2,659 | 0.00188 | import pyjd # this is dummy in pyjs.
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Button import Button
from pyjamas.ui.HTML import HTML
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.DockPanel import DockPanel
from pyjamas.ui.Scrol... | enumerate(row):
self.grid.setHTML(nrow, ncol, str(item))
cf.setWidth(nrow, ncol, "200px")
cf = self.header.getCellFormatter()
self.sortbuttons = []
for ncol in range(cols):
sb = Button("s | ort col %d" % ncol)
sb.addClickListener(self)
self.header.setWidget(0, ncol, sb)
cf.setWidth(0, ncol, "200px")
self.sortbuttons.append(sb)
def onClick(self, sender):
for (ncol, b) in enumerate(self.sortbuttons):
if sender == b:
sel... |
robmoggach/django-token-auth | src/token_auth/test_settings.py | Python | bsd-3-clause | 91 | 0.010989 | from settings im | port *
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '/tmp/token_a | uth.db'
|
facebookresearch/ParlAI | parlai/tasks/dbll_movie/build.py | Python | mit | 756 | 0 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
# Download and build the data if it does not exist.
from parlai.core.build_data import DownloadableFi | le
import parlai.tasks.dbll_babi.build as dbll_babi_build
import parlai.tasks.wikimovies.build as wikimovies_build
RESOURCES = [
DownloadableFile(
'http://parl.ai/downloads/dbll/dbll.tgz',
'dbll.tgz',
'd8c727dac498b652c7f5de6f72155dce711ff46c88401a303399d3fad4db1e68',
)
]
def build(op... | dbll_babi_build.build(opt)
|
dineshrajpurohit/ds_al | queue.py | Python | mit | 1,234 | 0.00081 | """Queue implementation using Linked list."""
from __future__ import print_function
from linked_list import Linked_List, Node
class Queue(Linked_List):
def __init__(self):
Linked_List.__init__(self)
def enqueue(self, item):
node = Node(item)
self.insert_front(node)
def dequeue(... | ("B")
queue.enqueue("C")
print("Queue Size:", queue.size())
print(queue)
print("DEQU | EUEING 1")
print(queue.dequeue())
print(queue)
print("Queue Size:", queue.size())
print("DEQUEUEING 2")
print(queue.dequeue())
print(queue)
print("Queue Size:", queue.size())
print("Queue Empty?", queue.is_empty())
print("DEQUEUEING 3")
print(queue.dequeue())
print(queue)
... |
google/loaner | loaner/web_app/backend/testing/loanertest_test.py | Python | apache-2.0 | 2,782 | 0.005392 | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nc': {'action_sample': self.fake_action}}
super(ActionTestCaseTest, self).setUp()
def test_success(self):
self.assertEqual(self.action, self.fake_action)
class ActionTestCaseTestNoTestingAction(loanertest.ActionTestCase):
"""Test what happens when you forget to specify self.testing_action."""
def setU... | nvironmentError, '.*Create a TestCase setUp .* variable named.*',
super(ActionTestCaseTestNoTestingAction, self).setUp)
class ActionTestCaseTestNoActions(loanertest.ActionTestCase):
"""Test what happens when there are no matching action modules available."""
def setUp(self):
pass
@mock.patch('__ma... |
walidsa3d/shaman | shaman/providers/api.py | Python | mit | 951 | 0 | from allocine import allocine
from constants import *
from elcinema imp | ort elcinema
from imdb import imdby as Imdb
from rotten import rot | ten
from tmdb import tmdb
def search(query, site):
if site == "imdb":
provider = Imdb()
elif site == "elcinema":
provider = elcinema()
elif site == "rottentomatoes":
provider = rotten(rotten_key)
elif site == "themoviedatabase":
provider = tmdb(tmdb_key)
elif site =... |
dsanders11/django-newsletter | test_project/test_project/settings.py | Python | agpl-3.0 | 2,081 | 0.000961 | import os
test_dir = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlit | e3',
'NAME': os.pat | h.join(test_dir, 'db.sqlite3'),
}
}
INSTALLED_APPS = [
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.auth',
'django.contrib.messages',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.staticfiles',
'imperavi',
'tinymce',
'newsletter... |
68foxboris/enigma2-openpli-vuplus | lib/python/Components/About.py | Python | gpl-2.0 | 4,073 | 0.035372 | # -*- coding: utf-8 -*-
import sys, os, time
from Tools.HardwareInfo import HardwareInfo
def getVersionString():
return getImageVersionString()
def getImageVersionString():
try:
if os.path.isfile('/var/lib/opkg/status'):
st = os.stat('/var/lib/opkg/status')
else:
st = os.stat('/usr/lib/ipkg/status')
tm ... | lob
driver = [x.split("-")[1][:8] for x in open(glob("/var/lib/opkg/info/vuplus-dvb-*.control")[0], "r") if x.startswith("Version:")][0]
return "%s-%s-%s" % (driver[:4], driver[4:6], driver[6:])
except:
return _("unknown")
def getPythonVersionString():
try:
import commands
status, output = comm | ands.getstatusoutput("python -V")
return output.split(' ')[1]
except:
return _("unknown")
def GetIPsFromNetworkInterfaces():
import socket, fcntl, struct, array, sys
is_64bits = sys.maxsize > 2**32
struct_size = 40 if is_64bits else 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
max_possible = 8 # i... |
danakj/chromium | chrome/browser/resources/chromeos/chromevox/tools/publish_webstore_extension.py | Python | bsd-3-clause | 4,983 | 0.009231 | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Publishes a set of extensions to the webstore.
Given an unpacked extension, compresses and sends to the Chrome webstore.
Relea... | , 'VERSION')
values = version.fetch_values([filename])
return version | .subst_template('@MAJOR@.@MINOR@.@BUILD@.@PATCH@', values)
def MakeChromeVoxManifest():
'''Create a manifest for the webstore.
Returns:
Temporary file with generated manifest.
'''
new_file = tempfile.NamedTemporaryFile(mode='w+a', bufsize=0)
in_file_name = os.path.join(_SCRIPT_DIR, os.path.pardir,
... |
dangillet/cocos | cocos/scenes/pause.py | Python | bsd-3-clause | 3,820 | 0.000524 | # ----------------------------------------------------------------------------
# cocos2d
# Copyright (c) 2008-2012 Daniel Moisset, Ricardo Quesada, Rayentray Tappa,
# Lucio Torre
# Copyright (c) 2009-2015 Richard Jones, Claudio Canepa
# All rights reserved.
#
# Redistribution and use in source and binary forms, with o... | r):
"""Layer that shows the text 'PAUSED'
"""
is_event_handler = True #: enable pyglet's events
def __init__(self):
super(PauseLayer, self).__init__()
x, y = director.get_window_size()
ft = pyglet.font.load('Arial', 36)
self.text = pyglet.font.Text(ft,
... |
def draw(self):
self.text.draw()
def on_key_press(self, k, m):
if k == pyglet.window.key.P and m & pyglet.window.key.MOD_ACCEL:
director.pop()
return True
|
kylehogan/haas | haas/migrations/versions/89630e3872ec_network_acl.py | Python | apache-2.0 | 2,070 | 0 | """network ACL
Revision ID: 89630e3872ec
Revises: 6a8c19565060
Create Date: 2016-05-06 09:24:26.911562
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '89630e3872ec'
down_revision = '6a8c19565060'
branch_labels = ('haas',)
def upgrade():
op.create_table(
... | op.bulk_insert(network_projects, networks)
op.alter_column(u'network', 'creator_id', new_column_name='owner_id')
op.drop_constraint(u'network_access_id_fkey',
| 'network',
type_='foreignkey')
op.drop_column(u'network', 'access_id')
def downgrade():
op.add_column(u'network',
sa.Column('access_id',
sa.INTEGER(),
autoincrement=False,
nullable=True... |
subhrm/google-code-jam-solutions | solutions/helpers/CodeJam-0.3.0/codejam/datastructures/summing_list.py | Python | mit | 1,482 | 0.002024 | cl | ass summing_list:
layers = [[0]]
size = 0
def __init__(self, iter=None):
if iter != None:
| for i in iter:
self.append(i)
def _sum(self, i):
t = 0
for r in self.layers:
if i % 2:
t += r[i - 1]
i >>= 1
return t
def sum_elements(self, i=None, j=None):
if j == None:
if i == None:
i = sel... |
Wopple/GJK | python/test.py | Python | bsd-3-clause | 2,305 | 0.009978 | #!/usr/bin/python
"""
Pygame script to test that the algorithm works.
"""
import sys
import pygame
from pygame.locals import *
import gjk
pygame.init()
SCREEN = pygame.display.set_mode((800, 600))
CLOCK = pygame.time.Clock()
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255... | = (255, 0, 0)
def run():
circle1 = ((400, 3 | 00), 100)
poly1 = (
( 00 + 400, 50 + 300),
(-50 + 400, 50 + 300),
(-50 + 400, 0 + 300)
)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.ke... |
kapilt/cloud-custodian | tools/c7n_azure/c7n_azure/query.py | Python | apache-2.0 | 13,063 | 0.001225 | # Copyright 2018 Capital One Services, 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... | ceQuery
def __init__(self, manager):
self.manager = manager
self.query = self.resource_quer | y_factory(self.manager.session_factory)
def validate(self):
pass
def get_resources(self, query):
return self.query.filter(self.manager)
def get_permissions(self):
return ()
def augment(self, resources):
return resources
@sources.register('resource-graph')
class Reso... |
0359xiaodong/viewfinder | backend/www/admin/metrics.py | Python | apache-2.0 | 4,540 | 0.012115 | # Copyright 2013 Viewfinder Inc. All Rights Reserved.
"""Handlers for database administration.
MetricsHandler: main handler for detailed metrics. We don't use ajax-y tables, so there is no data handler.
"""
from tornado.escape import url_escape
__author__ = '[email protected] (Marc Berhault)'
import base64
i... | kend.base.dotdict import DotDict
from viewfinder.backend.db import db_client, metric, schema, vf_schema
from viewfinder.backend.www.admin import admin, formatters, data_table
kDefaultMetricName = 'itunes.downloads'
class MetricsHandler(admin.AdminHandler):
"""Provides a list of all datastore tables and allows each ... | datastore=True)
@admin.require_permission(level='support')
@gen.engine
def get(self):
metric_name = self.get_argument('metric_name', kDefaultMetricName)
end_time = int(self.get_argument('end-secs', time.time()))
start_time = int(self.get_argument('start-secs', end_time - constants.SECONDS_PER_WEEK))
... |
JamesLinEngineer/RKMC | addons/plugin.video.salts/scrapers/rlseries_scraper.py | Python | gpl-2.0 | 4,255 | 0.004935 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | ong with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import re
import urlparse
import kodi
import log_utils # @UnusedImport
import dom_parser
from salts_lib import scraper_utils
from salts_lib.constants import FORCE_NO_MATCH
from salts_lib.constants i | mport QUALITIES
from salts_lib.constants import VIDEO_TYPES
import scraper
BASE_URL = 'http://rlseries.com'
class Scraper(scraper.Scraper):
base_url = BASE_URL
def __init__(self, timeout=scraper.DEFAULT_TIMEOUT):
self.timeout = timeout
self.base_url = kodi.get_setting('%s-base_url' % (self.ge... |
spaceone/httoop | tests/uri/test_uri.py | Python | mit | 930 | 0.021505 | from __future__ import unicode_literals
from httoop import URI
def test_simple_uri_comparision(uri):
u1 = URI(b'http://abc.com:80/~smith/home.html')
u2 = URI(b'http://ABC.com/%7Esmith/home.html')
u3 = URI(b'http://ABC.c | om:/%7esmith/home.html')
u4 = URI(b'http://ABC.com:/%7esmith/./home.html')
u5 = URI(b'http://ABC.com:/%7esmith/foo/../home.html')
assert u1 == u2
assert u2 == u3
assert u1 == u3 |
assert u1 == u4
assert u1 == u5
def test_request_uri_maxlength():
pass
def test_request_uri_is_star():
pass
def test_request_uri_containig_fragment():
pass
def test_invalid_uri_scheme():
pass
def test_invalid_port():
pass
def test_normalized_uri_redirects():
pass
def test_uri_composing_username_a... |
matematik7/CSSQC | tests/test_groupProperties.py | Python | mit | 1,126 | 0.006217 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------
# test_groupProperties.py
#
# test for groupProperties rule
# ----------------------------------------------------------------
# copyright (c) 2014 - Domen Ipavec
# Distri | buted under The MIT License, see LICENSE
# ----------------------------------------------------------------
import unittest
from cssqc.parser import CSSQC
from cssqc.qualityWarning import QualityWarning
class Test_groupProperties(unittest.TestCase):
def parse(self, data):
c = CSSQC({"groupProperties": "ga... | sample = '''div {
position: relative;
z-index: 6;
margin: 0;
padding: 0;
width: 100px;
height: 60px;
border: 0;
/* background & color */
background: #fff;
color: #333;
text-align: center
}
'''
c = self.parse(sample)
self.assertEqual(c.warnings, [
... |
google/jax | tests/nn_test.py | Python | apache-2.0 | 10,349 | 0.006184 | # 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, ... | else None)
@parameterized.parameters([int, float] + jtu.dtype | s.floating + jtu.dtypes.integer)
def testSoftplusZero(self, dtype):
self.assertEqual(jnp.log(dtype(2)), nn.softplus(dtype(0)))
def testReluGrad(self):
rtol = 1e-2 if jtu.device_under_test() == "tpu" else None
check_grads(nn.relu, (1.,), order=3, rtol=rtol)
check_grads(nn.relu, (-1.,), order=3, rtol... |
adebali/mistipy | tests/test_mistipy.py | Python | mit | 1,075 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_mistipy
----------------------------------
Tests for `mistipy` module.
"""
import pytest
# from contextlib import contextmanager
from click.testing import CliRunner
# from mistipy import mistipy
from mistipy import cli
@pytest.fixture
def response():
"""... | # from bs4 import BeautifulSoup
# assert 'GitHub' in BeautifulSoup(response.content).title.string
def test_command_line_interface():
runner = CliRunner()
result = runner.invoke(cli.main)
assert result.exit_code == 0
assert 'mistipy.cli.main' in result.output
help_result = runner.invoke(cli... | tput
|
siosio/intellij-community | python/testData/formatter/alightDictLiteralOnValueSubscriptionsAndSlices_after.py | Python | apache-2.0 | 326 | 0.003067 | my_dict = {
"one": | example_list[0],
"two": example_list[1],
"three": example_list[2:3],
"some really long element name that takes a lot of spa | ce": "four"
}
|
britcey/ansible | lib/ansible/modules/storage/netapp/netapp_e_lun_mapping.py | Python | gpl-3.0 | 12,380 | 0.003069 | #!/usr/bin/python
# (c) 2016, NetApp, Inc
#
# 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 in the hope that it will be useful,
# but WITHOU | T ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA ... |
karajrish/ChatterBot | chatterbot/adapters/logic/closest_match.py | Python | bsd-3-clause | 666 | 0 | from .logic import LogicAdapter
class ClosestMatchAdapter(LogicAdapter):
def get(self, text, list_of_statements):
"""
Takes a statement string and a list of statement strings.
Returns the closest matching statement from the list.
"""
from fuzzywuzzy import process
... | ext
# Check if an exact match exists
if text in list_of_statements:
return text
# Get t | he closest matching statement from the database
return process.extract(text, list_of_statements, limit=1)[0][0]
|
stencila/hub | manager/accounts/migrations/0004_auto_20200721_0252.py | Python | apache-2.0 | 663 | 0.003017 | # Generated by Django 3.0.8 on 2020-07-21 02:52
from django.db import migrations, models
class Migrati | on(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20200720_2208'),
]
operations = [
migrations.AddField(
model_name='accounttier',
name='active',
field=models.BooleanField(default=True, help_text='Is the tier active i.e. should be displa... | odels.CharField(help_text='The name of the tier.', max_length=64, unique=True),
),
]
|
kawamon/hue | apps/pig/src/pig/migrations/0001_initial.py | Python | apache-2.0 | 1,645 | 0.00304 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-06-06 18:55
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... | e_name='Is a user document, not a document submission.')),
],
),
migrations.CreateModel(
name='PigScript',
fields=[
| ('document_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='pig.Document')),
('data', models.TextField(default='{"name": "", "parameters": [], "script": "", "hadoopProperties": [], "properties":... |
ideanotion/infoneigeapi | infoneige/settings.py | Python | gpl-2.0 | 2,053 | 0.00341 | """
Django settings for infoneige project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... |
'django.middleware.common.Comm | onMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'infoneige.urls'
WSGI_APPLICATION = 'infoneige.wsgi.... |
Clinical-Genomics/scout | tests/load/test_load_case.py | Python | bsd-3-clause | 1,272 | 0.007862 | def test_load_case(case_obj, adapter):
## GIVEN a database with no cases
assert adapter.case_collection.find_one() is None
## WHEN loading a case
adapter._add_case(case_obj)
## THEN assert that the case have been loaded with correct info
assert adapter.case_collection.find_one()
def test_lo... | imsid(case_obj, adapter):
"""Test loading a case with lims_id"""
| ## GIVEN a database with no cases
assert adapter.case_collection.find_one() is None
## WHEN loading a case
adapter._add_case(case_obj)
## THEN assert that the case have been loaded with lims id
loaded_case = adapter.case_collection.find_one({"_id": case_obj["_id"]})
assert loaded_case["lims_i... |
EliotBryant/ShadDetector | shadDetector_testing/Colour Based Methods/ColorHistogram-master/color_histogram/core/color_pixels.py | Python | gpl-3.0 | 1,910 | 0.003665 | # -*- coding: utf-8 -*-
## @package color_histogram.core.color_pixels
#
# Simple color pixel class.
#
# @author tody
# @date 2015/08/28
import numpy as np
from color_histogram.cv.image import to32F, rgb2Lab, rgb2hsv, gray2rgb
## Implementation of color pixels.
#
# input image is automatically conver... | image.
# @param num_pixels target number of pixels from the image.
def __init__(self, image, num_pixels=1000):
self._image | = to32F(image)
self._num_pixels = num_pixels
self._rgb_pixels = None
self._Lab = None
self._hsv = None
## RGB pixels.
def rgb(self):
if self._rgb_pixels is None:
self._rgb_pixels = self.pixels("rgb")
return self._rgb_pixels
## Lab pixels.
def... |
GeoMop/GeoMop | testing/JobPanel/services/job_1.py | Python | gpl-3.0 | 103 | 0 | i | mport time
for i in range(30):
time.sleep(1)
print("running {} s".format(i+1))
pr | int("end")
|
Apreche/Project-DORF | game.py | Python | mit | 6,031 | 0.00315 | import sys
import pygame
import time
import cPickle
from view_port import ViewPort
from grid import Grid
from mover import RandomMover
from terrain import TerrainData
from terrain.generators import MeteorTerrainGenerator, Smoother
from terrain.generators import PlasmaFractalGenerator
class Game:
def __init__(sel... | K_x:
self.view.zoom_out()
if event.key == pygame.K_SPACE:
if not self.autoMovers:
self.mo | ve_movers()
if event.key == pygame.K_t:
self.autoMovers = not self.autoMovers
if event.key == pygame.K_s:
self.save_grid()
if event.key == pygame.K_l:
self.load_grid()
if self... |
dimagi/rapidsms | lib/rapidsms/contrib/stringcleaning/inputcleaner.py | Python | bsd-3-clause | 9,705 | 0.019784 | """
Provides utilities to cleanup text
"""
NUMBER_DICTIONARY = {
0:'Zero'
, 1: "One"
, 2: "Two"
, 3: "Three"
, 4: "Four"
, 5: "Five"
, 6: "Six"
, 7: "Seven"
, 8: "Eight"
, 9: "Nine"
, 10: "Ten"
, 11: "Eleven"
, 12: "Twelve"
, 13: "Thirteen"
, 14: "Fourteen"
, 15: "Fifteen"
, 16: "Sixteen"
, 17: "Seventeen"
, 18: "Eight... | found = True
break
if not found:
for key in PLACE_VALUE.keys():
if tokens[i] not in PLACE_VALUE.keys():
if self.soundex(tokens[i]) == self.soundex(key):
tokens[i] = key
... | t tokens:
return None
result = 0
expr = "result = "
for i, val in enumerate(tokens):
if str(val).isdigit():
expr = expr + "+" + str(val)
elif val in NUMBER_DICTIONARY.keys():
expr = expr + "+" + str(NUMBER_DICTIONARY[val])
... |
JioCloud/nova | nova/virt/libvirt/guest.py | Python | apache-2.0 | 6,242 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# Copyright (c) 2013 Hewlett-Pa... | ady to be launched
| """
try:
# TODO(sahid): Host.write_instance_config should return
# an instance of Guest
domain = host.write_instance_config(xml)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Error defining a domain with XML... |
soravux/scoop | scoop/broker/brokerzmq.py | Python | lgpl-3.0 | 13,389 | 0.000598 | #!/usr/bin/env python
#
# This file is part of Scalable COncurrent Operations in Python (SCOOP).
#
# SCOOP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the Licens... | FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with SCOOP. If not, see <http://www.gnu.org/licenses/>.
#
from collections import d | eque, defaultdict
import time
import zmq
import sys
import copy
import logging
try:
import cPickle as pickle
except ImportError:
import pickle
import scoop
from scoop import TIME_BETWEEN_PARTIALDEBUG
from .. import discovery, utils
from .structs import BrokerInfo
# Worker requests
INIT = b"I"
REQUEST = b"RQ"... |
YosaiProject/yosai_dpcache | yosai_dpcache/dogpile/core/util.py | Python | apache-2.0 | 133 | 0.007519 | import sys
py3k = sys.version_info >= (3, 0)
try:
import t | hreading
except ImportErro | r:
import dummy_threading as threading
|
rhoop/snmp2graphite | metricD.py | Python | apache-2.0 | 6,600 | 0.000152 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Richard Hoop - [email protected]
#
import sys
import argparse
import logging
import glob
import json
import netsnmp
import socket
import time
import signal
import threading
from raven import Client
# ====( headers )==== #
import pprint
pprint = pprint.pprint
from dae... | aphite['server'], graphite['port']))
| sock.sendall(message)
sock.close()
def load_config():
CHECKS = {}
for filename in glob.glob("checks/*.json"):
with open(filename, "rb") as fh:
logger.debug("Found file [%s]", filename)
CHECKS[filename.split("/")[1][:-5]] = json.loads(
" ".join(fh.readlines()... |
mganeva/mantid | Framework/PythonInterface/test/python/plugins/algorithms/FitGaussianTest.py | Python | gpl-3.0 | 2,677 | 0.014195 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
from __future__ import (absolute_import, divi... | ssible.
"""
self._linearWorkspace(0)
fitResult = FitGaussian(self.ws,0)
self.assertEqual(0.0, fitResult[0])
self.assertEqual(0.0, fitResult[1])
self._veryNarrowPeakWorkspace()
fitResult = FitGaussian(self.ws,0)
self.assertEqual(0.0, fitResult[0])
... |
def _guessPeak(self,peakCentre,height,sigma):
"""Test-fitting one generated Gaussian peak.
"""
self._gaussianWorkspace(peakCentre,height,sigma)
fitPeakCentre,fitSigma = FitGaussian(self.ws,0)
# require a close relative match between given and fitted values
diffPeak... |
thaim/ansible | lib/ansible/modules/network/fortios/fortios_firewall_schedule_onetime.py | Python | mit | 11,113 | 0.00171 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | https: "False"
state: "present"
firewall_schedule_onetime:
color: "3"
end: "<your_own_value>"
expiration_days: "5"
name: "default_name_6"
start: "<your_own_value>"
'''
RETURN = '''
build:
description | : Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by FortiGate on last operation applied
returned: alway... |
kain88-de/mdanalysis | package/MDAnalysis/core/topologyobjects.py | Python | gpl-2.0 | 33,789 | 0.000059 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- http://www.mdanalysis.org
# Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under th... | return self._bondtype
else:
return tuple(self.atoms.types)
@property
def is_guessed(self):
return bool(self._guessed)
def __hash__(self):
return hash((self._u, tuple(self.indices)))
def __repr__(self):
indices = sorted(self.indices)
return "... | rmat(i)
for i in indices]))
def __contains__(self, other):
"""Check whether an atom is in this :class:`TopologyObject`"""
return other in self.atoms
def __eq__(self, other):
"""Check whether two bonds have identical contents"""
if not self.universe == other.univ... |
cristianst85/binwalk | src/binwalk/plugins/compressd.py | Python | mit | 1,421 | 0.021816 | #import binwalk.core.C
import binwalk.core.plugin
#from binwalk.core.common import *
class CompressdPlugin(binwalk.core.plugin.Plugin):
# '''
# Searches for and validates compress'd data.
# '''
MODULES = ['Signature']
#READ_SIZE = 64
#COMPRESS42 = "compress42"
#COMPRESS42_FUNCTIONS = [
... | # compressed_data = fd.read(self.READ_SIZE)
# fd.close()
# if not self.comp.is_compresse | d(compressed_data, len(compressed_data)):
# result.valid = False
|
demisto/content | Packs/Unit42Intel/Integrations/FeedUnit42IntelObjects/FeedUnit42IntelObjects.py | Python | mit | 23,539 | 0.002549 | from typing import Dict, List, Optional
import urllib3
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
# disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 format with UTC, default in XSOAR
AF_TAGS_DATE_FO... | ed to be updated in demisto
list_of_all_updated_tags = argToList(integration_context.get('tags_need_to_be_fetched', ''))
time_from_last_update = integration_context.get('time_of_first_fetch')
index_to_delete = 0
for tag in list_of_all_updated_tags: # pragma: no cover
# if there are such tags, w... | ag_name', '')))
index_to_delete += 1
else:
context = get_integration_context()
context['time_of_first_fetch'] = date_to_timestamp(datetime.now(), DATE_FORMAT)
context['tags_need_to_be_fetched'] = list_of_all_updated_tags[index_to_delete:]
set_integrati... |
advisory/djangosaml2_tenant | djangosaml2/utils.py | Python | apache-2.0 | 1,490 | 0 | # Copyright (C) 2012 Yaco Sistemas (http://www.yaco.es)
#
# 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... | etadata_name, metadata in config.metadata.metadata.items():
result = metadata.any('idpsso_descriptor', 'single_sign_on_service')
if result:
idps = idps.union(set(result.keys()))
return dict([(idp, config.metadata.name(idp, langpref)) for idp in id | ps])
def get_location(http_info):
"""Extract the redirect URL from a pysaml2 http_info object"""
assert 'headers' in http_info
headers = http_info['headers']
assert len(headers) == 1
header_name, header_value = headers[0]
assert header_name == 'Location'
return header_value
|
RevansChen/online-judge | Codewars/8kyu/find-multiples-of-a-number/Python/test.py | Python | mit | 238 | 0.008403 | # Python - 3.6.0
Test.expect(find_multiples(5, 25) == [5, 10, 15, 20, 25], f'{str(find_multiples(5, 25))} should equal [5, 10, 15, 20, 25]')
Te | st.expect(find_multiples(1, 2) == [1, 2], f'{str(find_multipl | es(1, 2))} should equal [1, 2]')
|
larsks/cloud-init-patches | tests/unittests/test_handler/test_handler_apt_conf_v1.py | Python | gpl-3.0 | 4,917 | 0 | from cloudinit.config import cc_apt_configure
from cloudinit import util
from ..helpers import TestCase
import copy
import os
import re
import shutil
import tempfile
def load_tfile_or_url(*args, **kwargs):
return(util.decode_binary(util.read_file_or_url(*args, **kwargs).contents))
class TestAptProxyConfig(Tes... | alse(os.path.isfile(self.cfile))
contents = load_tfile_or_url(self.pfile)
self.assertTrue(self._search_apt_config(contents, "http", "myproxy"))
def test_apt_http_proxy_written(self):
cfg = {'http_proxy': 'myproxy'}
cc_apt_configure.apply_apt_config(cfg, self.pfile, self.cfile)
| self.assertTrue(os.path.isfile(self.pfile))
self.assertFalse(os.path.isfile(self.cfile))
contents = load_tfile_or_url(self.pfile)
self.assertTrue(self._search_apt_config(contents, "http", "myproxy"))
def test_apt_all_proxy_written(self):
cfg = {'http_proxy': 'myproxy_http_pr... |
protwis/protwis | common/migrations/0003_citation_page_name.py | Python | apache-2.0 | 413 | 0 | # Generated by D | jango 3.0.3 on 2020-08-20 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0002_citation'),
]
operations = [
migrations.AddField(
model_name='citation',
name='page_name',
field=models.T... | |
popazerty/beyonwiz-sh4 | lib/python/Components/About.py | Python | gpl-2.0 | 8,286 | 0.03705 | from Tools.Directories import resolveFilename, SCOPE_SYSETC
from Components.Console import Console
import sys
import time
import re
from boxbranding import getImageVersion, getMachineBrand
from sys import modules
import socket, fcntl, struct
def getVersionString():
return getImageVersion()
def getImageVersionString(... | x4000, # auto media select active
"dynamic": 0x8000, # dialup device with changing addresses
"lower_up": 0x10000, # driver signals L1 up
"dormant": 0x20000, # driver signals dormant
"echo": 0x40000, # echo sent packets
}
def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
... | = SIOCSIFHWADDR:
return ':'.join(['%02X' % ord(char) for char in info[18:24]])
elif addr == SIOCGIFFLAGS:
return socket.ntohl(struct.unpack("!L", info[16:20])[0])
else:
return socket.inet_ntoa(info[20:24])
def getIfConfig(ifname):
ifreq = {'ifname': ifname}
infos = {}
sock = socket.socket(socket.AF_INET, s... |
cpaton/dvblink-plex-client | plex/Contents/Code/localization.py | Python | mit | 4,066 | 0.000246 | IDS_PLUGIN_TITLE = L("IDS_PLUGIN_TITLE")
IDS_SETTINGS_MENU_ITEM = L("IDS_SETTINGS_MENU_ITEM")
IDS_RECORDED_TV_MENU_ITEM = L("IDS_RECORDED_TV_MENU_ITEM")
IDS_CHANNEL_MENU_ITEM = L("IDS_CHANNEL_MENU_ITEM")
IDS_GUIDE_MENU_ITEM = L("IDS_GUIDE_MENU_ITEM")
IDS_RADIO_MENU_ITEM = L("IDS_RADIO_MENU_ITEM")
IDS_SCHEDULED_RECORDIN... | IDS_GENRE_SERIAL = L("IDS_GENRE_SERIAL")
IDS_GENRE_SOAP = L("IDS_GENRE_SOAP")
IDS_GENRE_SPECIAL = L("IDS_GENRE_SPECIAL")
IDS_GENRE_THRILLER = L("IDS_GENRE_THRILLER")
IDS_GENRE_ADULT = L("IDS_GENRE_ADULT")
IDS_CONFLICT_RECORDING_LABEL = L("IDS_CONFLICT_RECORDI | NG_LABEL")
IDS_ENTER_KEYWORD_WARNING = L("IDS_ENTER_KEYWORD_WARNING") |
lukas-hetzenecker/home-assistant | homeassistant/components/philips_js/remote.py | Python | apache-2.0 | 3,097 | 0.000323 | """Remote control support for Apple TV."""
import asyncio
from haphilipsjs.typing import SystemType
from homeassistant.components.remote import (
ATTR_DELAY_SECS,
ATTR_NUM_REPEATS,
DEFAULT_DELAY_SECS,
RemoteEntity,
)
from . import LOGGER, PhilipsTVDataUpdateCoordinator
from .const import CONF_SYSTEM... | (self):
"""Return a device description for device registry."""
return {
"name": self._system["name"],
"identifiers": {
(DOMAIN, self._unique_id),
},
"model": self._system.get("model"),
"manufacturer": "Philips",
"sw_... | "),
}
async def async_turn_on(self, **kwargs):
"""Turn the device on."""
if self._tv.on and self._tv.powerstate:
await self._tv.setPowerState("On")
else:
await self._coordinator.turn_on.async_run(self.hass, self._context)
self.async_write_ha_state()
... |
beloglazov/openstack-neat | setup.py | Python | apache-2.0 | 4,540 | 0.001101 | # Copyright 2012 Anton Beloglazov
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | onstraints", IEEE Transactions on Parallel
and Distributed Systems (TPDS), IEEE CS Press, USA, 2012 (in press,
accepted on August 2, 2012). Download:
http://beloglazov.info/papers/2012-host-overload-detectio | n-tpds.pdf
"""
import distribute_setup
distribute_setup.use_setuptools()
from setuptools import setup, find_packages
setup(
name='openstack-neat',
version='0.1',
description='The OpenStack Neat Project',
long_description=__doc__,
author='Anton Beloglazov',
author_email='anton.beloglazov@gmai... |
fedspendingtransparency/data-act-broker-backend | dataactcore/migrations/versions/5de499ab5b62_cascade_useraffiliation_deletes.py | Python | cc0-1.0 | 1,559 | 0.010263 | """Cascade UserAffiliation deletes
Revision ID: 5de499ab5b62
Revises: 14f51f27a106
Create Date: 2016-12-13 00:21:39.842218
"""
# revision identifiers, used by Alembic.
revision = '5de499ab5b62'
down_revision = '14f51f27a106'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def... | reate_foreign_key('user_affiliation_cgac_fk', 'user_affiliation', 'cgac', ['cgac_id'], ['cgac_id'])
op.create_foreign_key('user_affiliation_user_fk', 'user_affiliation', 'users', ['user_id'], ['user_id'])
### end Alembi | c commands ###
|
buzzfeed/caliendo | test/test_replay.py | Python | mit | 2,701 | 0.007775 | import unittest
import time
import random
import os
os.environ['USE_CALIENDO'] = 'True'
from caliendo.db import flatfiles
from caliendo.facade import patch
from caliendo.patch import replay
from caliendo.util import recache
from caliendo import Ignore
import caliendo
from test.api import callback
from test.api.call... | ack')
def test(i):
cb_file = method_with_callback(callback_for_method, 0.5)
with open(cb_file, 'rb') as f:
contents = f.read()
assert contents == ('.' * (i+1)), "Got {0} was expecting {1}".format(contents, ('.' * (i+1)))
tes... | do_it(i)
with open(CACHED_METHOD_FILE, 'rb') as f:
assert f.read() == '.'
def test_replay_with_ignore(self):
def do_it(i):
@replay('test.api.callback.callback_for_method')
@patch('test.api.callback.method_with_callback', ignore=Ignore([1]))
def te... |
tensorflow/tensorflow | tensorflow/python/ops/ragged/row_partition.py | Python | apache-2.0 | 58,566 | 0.005703 | # Copyright 2020 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... | owPartition.with_precomputed_<encoding>`.
"""
#=============================================================================
# Constructor (private)
#=============================================================================
def __init__(self,
row_splits,
row_lengths=None,
... | nrows=None,
uniform_row_length=None,
nvals=None,
internal=False):
"""Creates a `RowPartition` from the specified encoding tensor(s).
This constructor is private -- please use one of the following ops to
build `RowPartition`s:
* `RowPartition.fr... |
grantula/fantasypremierleagueapi | fantasypremierleagueapi/tests/test_unit_tests.py | Python | mit | 763 | 0.001311 | # -*- coding: utf-8 -*-
"""
File: test_unit_tests.py
Path: fantasypremierleague/tests/
Author: Grant W
"""
import unittest
import fantasypremierleagueapi as fp
class TestEnsureOneItem(unittest.TestCase):
def setUp(self):
super().setUp()
@fp.ensure_one_item
def fake_func(self, list):
retu... | _works(self):
item = ['1']
assert self.fake_func(item) == item[0]
def test_ensure_one_item_raises_error_with_multiples(self):
item = ['1', '2']
with self.assertRaises(TypeError):
self.fake_func(item)
def test_ensure_one_item_raises_error_with_nothing(self):
... | (item)
|
bukun/maplet | extor/handlers/ext_tutorial_hander.py | Python | mit | 1,135 | 0.002643 | import json
from torcms.core.base_handler import BaseHandler
from torcms.model.category_model import MCategory
class TutorialIndexHandler(BaseHandler):
def initialize(self, **kwargs):
super(TutorialIndexHandler, self).initialize()
self.kind = kwargs.get('kind', 'k')
def get(self, *args, **kwa... | get('slug', '')
cat_rec = MCategory.get_by_slug(cat_slug)
if no | t cat_rec:
return False
kwd = {
'uid': '',
'cat_slug': cat_slug,
'cat_name' : cat_rec.name,
'page_slug':cat_slug + "_index"
}
self.render('post_{0}/post_list.html'.format(self.kind),
userinfo=self.userinfo,
... |
gotostack/swift | test/unit/common/test_swob.py | Python | apache-2.0 | 58,939 | 0 | # Copyright (c) 2012 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 ... | -Length' in headers)
del headers['Content-Length']
self.assert_('Content-Length' not in headers)
def test_update(self):
headers = swift.common.swob.HeaderKeyDict()
headers.update({'Content-L | ength': '0'})
headers.update([('Content-Type', 'text/plain')])
self.assertEquals(headers['Content-Length'], '0')
self.assertEquals(headers['Content-Type'], 'text/plain')
def test_get(self):
headers = swift.common.swob.HeaderKeyDict()
headers['content-length'] = 20
se... |
potatolondon/search | search/tests/base.py | Python | mit | 374 | 0 | import unittest
from google.appengine.ext import testbed
class AppengineTestCase(unittest.Tes | tCase):
def setUp(self):
super | (AppengineTestCase, self).setUp()
self.tb = testbed.Testbed()
self.tb.activate()
self.tb.init_search_stub()
def tearDown(self):
self.tb.deactivate()
super(AppengineTestCase, self).tearDown()
|
SalesforceFoundation/CumulusCI | cumulusci/tasks/salesforce/tests/test_custom_settings_wait.py | Python | bsd-3-clause | 6,537 | 0.000765 | import unittest
import responses
from cumulusci.core.config import (
UniversalConfig,
BaseProjectConfig,
TaskConfig,
)
from cumulusci.core.keychain import BaseProjectKeychain
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.tests.utils import MockLoggerMixin
from cumulusci.tasks.... | nses.activate
def test_run_custom_settings_wait_match_bool(self):
self.task_config.config["options"] = {
"object": "Customizable_Rollup_Setings__c",
"field": "Customizable_Rollups_Enabled__c",
| "value": True,
"poll_interval": 1,
}
# simulate finding no settings record and then finding one with the expected value
task, url = self._get_url_and_task()
responses.add(
responses.GET, url, json={"totalSize": 0, "done": True, "records": []}
)
... |
buaase/Phylab-Web | PythonExperimentDataHandle/test/P1011_test.py | Python | gpl-2.0 | 1,628 | 0.037469 | import P1011
import unittest
class test_phylab(unittest.TestCase):
def testSteelWire_1(self):
m = [10.000,12 | .000,14.000,16.000,18.0 | 00,20.000,22.000,24.000,26.00]
C_plus = [3.50, 3.81, 4.10, 4.40, 4.69, 4.98, 5.28, 5.59, 5.89]
C_sub = [3.52, 3.80, 4.08, 4.38, 4.70, 4.99, 5.30, 5.59, 5.89]
D = [0.789, 0.788, 0.788, 0.787, 0.788]
L = 38.9
H = 77.0
b = 8.50... |
spillz/minepy | util.py | Python | gpl-3.0 | 5,629 | 0.046189 | import numpy
import time
import pyglet
import pyglet.graphics as gl
import noise
from config import SECTOR_SIZE
cb_v = numpy.array([
[-1,+1,-1, -1,+1,+1, +1,+1,+1, +1,+1,-1], # top
[-1,-1,-1, +1,-1,-1, +1,-1,+1, -1,-1,+1], # bottom
[-1,-1,-1, -1,-1,+1, -1,+1,+1, -1,+1,-1], # left
[+... | c, +1,-1,+c, +1,+1,+c, -1,+1,+c], # front
[+1,-1,-c, -1,-1,-c, -1,+1,-c, +1,+1,-c], # back
],dtype = numpy.float32) |
c = 14.0/16
cb_v_cake = numpy.array([
[-1,+0,-1, -1,+0,+1, +1,+0,+1, +1,+0,-1], # top
[-1,-1,-1, +1,-1,-1, +1,-1,+1, -1,-1,+1], # bottom
[-c,-1,-1, -c,-1,+1, -c,+1,+1, -c,+1,-1], # left
[+c,-1,+1, +c,-1,-1, +c,+1,-1, +c,+1,+1], # right
[-1,-1,+c, +1,-1,+c, +1,+1,+c, -1,+1,+... |
spectralpython/spectral | spectral/database/aster.py | Python | gpl-2.0 | 15,620 | 0.001344 | '''
Code for reading and managing ASTER spectral library data.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
from spectral.utilities.python23 import IS_PYTHON3, tobytes, frombytes
from .spectral_database import SpectralDatabase
if IS_PYTHON3:
readline = lambda fin: fin.r... | tional database to manage ASTER spectral library data.'''
schemas = table_schemas
def _add_sample(self, name, sampleType, sampleClass, subClass,
particleSize, sampleNumber, owner, origin, phas | e,
description):
sql = '''INSERT INTO Samples (Name, Type, Class, SubClass, ParticleSize, SampleNum, Owner, Origin, Phase, Description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''
self.cursor.execute(sql, (name, sampleType, sampleClass, subClass,
... |
waseem18/oh-mainline | vendor/packages/python-dateutil/updatezinfo.py | Python | agpl-3.0 | 1,230 | 0.001626 | #!/usr/bin/python
from dateutil.zoneinfo import rebuild
import shutil
import sys
import os
import re
SERVER = "elsie.nci.nih.gov"
DIR = "/pub"
NAME = re.compile("tzdata(.*).tar.gz")
def main():
if len(sys.argv) == 2:
tzdata = sys.argv[1]
else:
from ftplib import FTP
print "Connecting t... | nt "Changing to %s..." % DIR
ftp.cwd(DIR)
print "Listing files..."
for name in ftp.nlst():
| if NAME.match(name):
break
else:
sys.exit("error: file matching %s not found" % NAME.pattern)
if os.path.isfile(name):
print "Found local %s..." % name
else:
print "Retrieving %s..." % name
file = open(name, "w")
ftp.r... |
jpardobl/django_sprinkler | django_sprinkler/cicles.py | Python | bsd-3-clause | 1,692 | 0.003546 | from django_sprinkler.models import Program, Context
from datetime import datetime
import pytz, logging
from django.conf import settings
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG if settings.DEBUG else logging.INFO)
logger_watering = logging.getLogger("watering")
logger_watering.setLevel(logg... | for pstep in | ctxt.active_program.steps.all():
if step == pstep:
#Arrancamos el aspersor que ha sido devuelto como activo
pstep.sprinkler.toggle(True)
continue
#apagamos el resto de aspersores
pstep.sprinkler.toggle(False)
def run():
ctxt = Context.objects.get_contex... |
lukas-ke/faint-graphics-editor | help/example_py/py_frame_example.py | Python | apache-2.0 | 148 | 0.027027 | from faint import *
#sta | rt
# Retrieving a frame from an image
image = get_active_image()
|
frame = image.get_frame(3)
frame.line(0,0,100,100)
|
gunan/tensorflow | tensorflow/python/ops/quantized_ops_test.py | Python | apache-2.0 | 4,127 | 0.007512 | # Copyright 2015 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... | permissions and
# limitations under the License.
# ===================================================== | =========================
"""Functional tests for quantized operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow... |
polyaxon/polyaxon | platform/polycommon/polycommon/settings/api.py | Python | apache-2.0 | 4,027 | 0.000745 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | if platform_host:
allowed_hosts.append(platform_host)
if ".polyaxon.com" not in allowed_hosts:
allowed_hosts.append(".polyaxon.com")
pod_ip = config.get_string("POLYAXON_POD_IP", is_optional=True)
if pod_ip:
allowed_hosts.append(pod_ip)
host_ip = conf... | ["{}.{}".format(host_cidr, i) for i in range(255)]
return allowed_hosts
context["ALLOWED_HOSTS"] = get_allowed_hosts()
processors = processors or []
processors = [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.c... |
engla/kupfer | contrib/evilplugin.py | Python | gpl-3.0 | 798 | 0.005013 | """
This is a plugin that should do everything wrong, for debugging Purposes
"""
__kupfer_name__ = u"Evil Plugin"
__kupfer_sources__ = (
"EvilSource",
"EvilInstantiationSource",
)
__description__ = u"Evil for debugging purposes (necessary evil)"
__version__ = ""
__author__ = "Ulrik Sverdrup <ulrik. | [email protected]>"
from kupfer.objects import Leaf, Action, Source
class EvilError (Exception):
pass
class EvilInstantiationSource (Source):
def __init__(self):
raise EvilError
class EvilSource (Source):
def __init__(self):
Source.__init__(self, u"Evil Source")
def initialize(sel... | rovides(self):
pass
|
dedayoa/django-country-dialcode | country_dialcode/forms.py | Python | mit | 54 | 0 | # -*- coding: ut | f-8 -*-
# place form | definition here
|
chrisz/pyhusmow | pyhusmow/status_logger.py | Python | gpl-3.0 | 4,539 | 0.002423 | import argparse
from datetime import datetime, timedelta
from sched import scheduler
from sys import stdout
from time import time
from .husmow import TokenConfig, API
def run_logger(tc, args, stop_time):
mow = API()
mow.set_token(tc.token, tc.provider)
mow.select_robot(args.mower)
sch = scheduler(ti... | amp'] else None
if status['status'] != mow_status['mowerStatus']:
if args.summary and status['status'] is not None:
# Write the summary. Skip the first iteration
write_log(
now().isoformat(),
status['status'],
... | status['status'] = mow_status['mowerStatus']
status['status_changed'] = now()
# The latest location has index 0
location = mow_status['lastLocations'][0]
currentTime = datetime.now()
write_log(currentTime.isoformat(), mow_status['mowerStatus'], mow_status['battery... |
kumar303/addons-server | src/olympia/api/permissions.py | Python | bsd-3-clause | 10,291 | 0 | from rest_framework.exceptions import MethodNotAllowed
from rest_framework.permissions import SAFE_METHODS, BasePermission
from olympia.amo import permissions
from olympia.access import acl
# Most of these classes come from zamboni, check out
# https://github.com/mozilla/zamboni/blob/master/mkt/api/permissions.py fo... | (self, request, view):
return acl.is_user_any_kind_of_reviewer(request.user)
def has_object_permission(self, request, view, obj):
return self.has_permission(request, view)
class AllowIfPublic(BasePermission):
"""
Allow access | when the object's is_public() method returns True.
"""
def has_permission(self, request, view):
return True
def has_object_permission(self, request, view, obj):
return (obj.is_public() and self.has_permission(request, view))
class AllowReadOnlyIfPublic(AllowIfPublic):
"""
Allow ac... |
felipevolpone/quokka | quokka/modules/comments/tasks.py | Python | mit | 195 | 0 | # coding: utf-8
from __future__ import print_function
from quokka import create_celery_app
celery = create_celery_app()
@celery.t | ask
def comment_task():
print("Doing something asy | nc...")
|
skapfer/rubber | src/latex_modules/xelatex.py | Python | gpl-2.0 | 273 | 0.010989 | import rubber.module_interface
class Module (rubber.module_interface.Module):
de | f __init__ (self, document, opt):
document.program = 'xelatex'
document.engine = 'XeLaTeX'
document.register_post_processor (old_suffix='.pdf | ', new_suffix='.pdf')
|
mattjmorrison/logilab-common-clone | test/unittest_testlib.py | Python | gpl-2.0 | 31,676 | 0.002494 | # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:[email protected]
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as publ... | AssertionError, self.tc.assertFileEqual, foo, spam)
self.tc.assertFileEqual(foo, foo)
def test_dir_equality(self):
ref = join(dirname(__file__), 'data', 'reference_dir')
same = join(dirname(__file__), ' | data', 'same_dir')
subdir_differ = join(dirname(__file__), 'data', 'subdir_differ_dir')
file_differ = join(dirname(__file__), 'data', 'file_differ_dir')
content_differ = join(dirname(__file__), 'data', 'content_differ_dir')
ed1 = join(dirname(__file__), 'data', 'empty_dir_1')
ed2... |
scheib/chromium | third_party/blink/web_tests/external/wpt/webdriver/tests/element_send_keys/conftest.py | Python | bsd-3-clause | 376 | 0 | import pytest
@pytest.fixture
def create_files(tmpdir_factory):
def inner(filenames):
filelist = []
tmpdir = tmpdir_factory.mktemp("tmp")
for filename in filenames:
fh = tmpdir.join(filename)
fh.write(filename)
filelist.append(fh)
return filelis... | ||
Comunitea/CMNT_00098_2017_JIM_addons | custom_sale_order_variant_mgmt/__init__.py | Python | agpl-3.0 | 150 | 0 | # -*- c | oding: utf-8 -*-
# © 2017 Comunitea
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import models
fr | om . import wizard
|
qPCR4vir/orange | Orange/testing/regression/tests_20/reference_linear-learner.py | Python | gpl-3.0 | 353 | 0.005666 | import orange
data = orange.ExampleTable("iris")
classifier = orange.LinearLearner(data)
for i, cls_name in enumerate(dat | a.domain.classVar.values):
print "Attrib | ute weights for %s vs. rest classification:\n\t" % cls_name,
for attr, w in zip(data.domain.attributes, classifier.weights[i]):
print "%s: %.3f " % (attr.name, w),
print |
charleshong/cs3240-labdemo | quack.py | Python | mit | 129 | 0.007752 | # Charles | Hong (csh6cw)
# 09/11/17
# quack.py
| __author__ = 'Charles Hong'
__emailID__ = 'csh6cw'
def quack(msg):
print(msg) |
alby128/syncplay | syncplay/__init__.py | Python | apache-2.0 | 123 | 0 | version = ' | 1.6.8'
re | vision = ' development'
milestone = 'Yoitsu'
release_number = '95'
projectURL = 'https://syncplay.pl/'
|
haihabi/simpy | simpy/core/result/base_function.py | Python | mit | 391 | 0 | import numpy as np
def data_concat(res | ult_a):
return np.concatenate(result_a, axis=0)
def data_mean(result_a):
return np.mean(result_a)
def data_identity(result_a):
return result_a
def data_stack(result_a):
return np.stack(result_a)
def data_single(result_a):
return result_a[0]
def data_stack_me | an(result_a):
return np.mean(data_stack(result_a), axis=0)
|
AfricaChess/lichesshub | tournament/migrations/0002_auto_20171202_0508.py | Python | mit | 550 | 0.001818 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-02 05:08
from __future__ import unicode_literals
from django.db import migrations, models
impor | t django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tournament', '0001_initial'),
]
operations = [
| migrations.AlterField(
model_name='game',
name='match',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='tournament.Match'),
),
]
|
uncled1023/pygments | Pygments/pygments-lib/pygments/lexers/make.py | Python | bsd-2-clause | 7,332 | 0.000546 | # -*- coding: utf-8 -*-
"""
pygments.lexers.make
~~~~~~~~~~~~~~~~~~~~
Lexers for Makefiles and similar.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import Lexer, RegexLexer, include, bygroups, \
... | ywords'),
include('ws')
],
'string': [
],
'keywords': [
(r'\b(WIN32|UNIX|APPLE|CYGWIN|BORLAND|MINGW|MSVC|MSVC_IDE|MSVC60|'
r'MSVC70|MSVC71|MSVC80|MSVC90)\b', Keyword),
],
'ws': [
(r'[ \t]+', Text),
(r'#.*\n', C... | xt):
exp = r'^ *CMAKE_MINIMUM_REQUIRED *\( *VERSION *\d(\.\d)* *( FATAL_ERROR)? *\) *$'
if re.search(exp, text, flags=re.MULTILINE | re.IGNORECASE):
return 0.8
return 0.0
|
charliequinn/python-litmos-api | src/litmos/api.py | Python | bsd-2-clause | 6,221 | 0.002572 | import html
import json
import time
import requests
class API(object):
ROOT_URL = 'https://api.litmos.com/v1.svc'
PAGINATION_OFFSET = 200
api_key = None
app_name = None
@classmethod
def _base_url(cls, resource, **kwargs):
return cls.ROOT_URL + "/" + \
resource + \
... | sponse):
return json.loads(html.unescape(response.text))
@classmethod
def find(cls, resource, resource_id):
response = cls._perform_request(
'GET',
cls._base_url(resource, resource_id=resource_id)
)
| return cls._parse_response(response)
@classmethod
def delete(cls, resource, resource_id):
cls._perform_request(
'DELETE',
cls._base_url(resource,
resource_id=resource_id
)
)
return True
@classmethod
de... |
Martin09/E-BeamPatterns | 100 Wafers - 1cm Squares/Multi-Use Pattern/v1.4/MembraneDesign_100Wafer_v1.4.py | Python | gpl-3.0 | 20,307 | 0.003102 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 14:11:31 2015
@author: Martin Friedl
"""
import itertools
from datetime import date
from random import choice as random_choice
import numpy as np
from Patterns.GrowthTheoryCell import make_theory_cell
from Patterns.GrowthTheoryCell_100_3BranchDevices import make_the... | h time:
mrkr_positions = [75 * n + (n - 1) * n // 2 for n in range(1, (mrkr_size - 1) // 2 + 1)]
for pos in mrkr_positions:
marker_arm.add(marker, origin=[pos, 0])
# Build the final PAMM Mark | er
pamm_cell = Cell('PAMM_Marker')
pamm_cell.add(marker) # Center marker
pamm_cell.add(marker_arm) # Right arm
pamm_cell.add(marker_arm, rotation=180) # Left arm
pamm_cell.add(marker_arm, rotation=90) # Top arm
pamm_cell.add(marker_arm, rotatio... |
gevaerts/bup | cmd/bloom-cmd.py | Python | lgpl-2.1 | 5,247 | 0.002287 | #!/bin/sh
"""": # -*-python-*-
bup_python="$(dirname "$0")/bup-python" || exit $?
exec "$bup_python" "$0" ${1+"$@"}
"""
# end of bup preamble
import glob, os, sys, tempfile
from bup import options, git, bloom
from bup.helpers import (add_error, debug1, handle_ctrl_c, log, progress, qprogress,
... | return
if base == idx:
idx = os.path.join(path, idx)
log("bloom: bloom file: %s\n" % rbloomfilename)
log("bloom: checking %s\n" % ridx)
for objsha in git.open_idx(idx):
if not b.exists(objsha):
add_error("bloom: ERROR: object %s missing"
% s | tr(objsha).encode('hex'))
_first = None
def do_bloom(path, outfilename):
global _first
b = None
if os.path.exists(outfilename) and not opt.force:
b = bloom.ShaBloom(outfilename)
if not b.valid():
debug1("bloom: Existing invalid bloom found, regenerating.\n")
b = Non... |
raidixlab/insane_striping | parse.py | Python | gpl-2.0 | 10,189 | 0.004762 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""This script automates testing of insane_striping algorithms.
You should fill configuration file with your own values,then start this script
as 'python parse.py <config>'. If you test LRC, make sure that stripe-searcher
is in './searcher' catalogue.
Results of tests will be c... | ons < disks'
exit()
if len(test1) > 2:
if test1[2][:6] == 'scheme':
get_scheme = test1[2][7:]
if test1[2][:6] == 'groups':
groups = int(test1[ | 2][7:])
length = int(test1[3][7:])
if len(test1) > 4:
global_s = int(test1[4][9:])
else:
global_s = 1
param = {'groups': groups, 'length': length, 'disks': disks_count, 'global_s': global_s}
if search_scheme(param) == 0:
... |
dbservice/dbservice | dbservice/apps/homes/admin.py | Python | mit | 1,248 | 0 | from django.contrib import admin
from dbservice.apps.utils import MEASUREMENT_UNIT_CHOICES
from . import models
admin.site.register(models.FixedValueMeterPort)
@admin.register(models.VirtualEnergyPo | rt)
class VirtualPortEnergyAdmin(admin.ModelAdmin):
fields = ('name', 'consumption', 'current', 'voltage', 'power | _factor')
view_on_site = True
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "consumption":
kwargs["queryset"] = models.MeterPort.objects.filter(
unit=MEASUREMENT_UNIT_CHOICES[0][0]
)
if db_field.name == "current"... |
sutartmelson/girder | girder/utility/webroot.py | Python | apache-2.0 | 3,397 | 0.000589 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... | pluginCss | '].append(plugin)
if os.path.exists(os.path.join(builtDir, plugin, 'plugin.min.js')):
self.vars['pluginJs'].append(plugin)
return super(Webroot, self)._renderHTML()
|
SymbiFlow/python-fpga-interchange | fpga_interchange/route_stitching.py | Python | isc | 16,298 | 0.00043 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
""" This file defines the RoutingTree class wh... | ch order, which makes comparing trees each,
just normalize both trees, and compare the result.
"""
branches.sort(key=lambda item: item.to_tuple())
def get_tuple_tree(root_branch):
""" Convert a rout branch in a two tuple. """
return root_branch.to_tuple(), tuple(
get_tuple_tree(branch) fo... | ing stitching of a routing tree. """
def __init__(self, device_resources, site_types, stubs, sources):
# Check that no duplicate routing resources are present.
tuple_to_id = {}
for stub in stubs:
for branch in yield_branches(stub):
tup = branch.to_tuple()
... |
googleapis/python-pubsublite | samples/generated_samples/pubsublite_v1_generated_topic_stats_service_compute_time_cursor_async.py | Python | apache-2.0 | 1,540 | 0.000649 | # -*- coding: utf-8 -*-
# Copyright 2022 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... | IONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT | EDIT!
#
# Snippet for ComputeTimeCursor
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-pubsublite
# ... |
thinkopensolutions/tko-addons | tko_br_delivery_sale_stock/models/sale.py | Python | agpl-3.0 | 1,287 | 0.004662 |
from odoo import models, api, _
from odoo.exceptions import UserError
class SaleOrder(models.Model):
_inherit ='sale.order'
@api.multi
def set_delivery_line(self):
# Remove delivery products from the sales order
self._remove_delivery_line()
for order in self:
if orde... | ess:
raise UserError(_('Please use "Check price" in order to compute a shipping price for this quotation.'))
else:
price_unit = order.carrier_id.rate_shipment(order)['price']
# TODO check whether it is safe to use d | elivery_price here
final_price = price_unit * (1.0 + (float(self.carrier_id.margin) / 100.0))
# order._create_delivery_line(carrier, final_price)
# set price in total_frete field and compute total again
order.total_frete = final_price
order... |
iEngage/python-sdk | iengage_client/models/user.py | Python | apache-2.0 | 9,891 | 0.000303 | # coding: utf-8
"""
Stakeholder engagement API
This API enables Intelligent Engagement for your Business. iEngage is a platform that combines process, augmented intelligence and rewards to help you intelligently engage customers.
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger... | he value is json key in definition.
"""
self.swagger_types = {
'user_id': 'int',
'first_name': 'str',
'last_name': 'str',
'email_id': 'str',
| 'profile_image': 'str',
'has_interest_updated': 'bool',
'birth_date': 'datetime',
'access_token': 'str',
'current_user_following': 'bool',
'current_user_friend': 'bool',
'equity_score': 'int',
'extra_data': 'str'
}
... |
imoan1983/medlist | src/downloadFiles.py | Python | apache-2.0 | 1,924 | 0.010915 | # -*- coding: utf-8 -*-
import datetime
import os
import urllib.request
import re
def getUrlList(url):
ret = []
baseUrl = re.findall('(http://.+?)/',url)[0]
httpRequest = urllib.request.Request(url)
httpResponse = urllib.request.urlopen(httpRequest)
html = httpResponse.read()... | f = open('win.ini','r')
s = f.read().split('\n')
urlList = s[0]
downloadDir = s[1]
f.close()
today = datetime.datetime.today().strftime('%Y%m%d')
#./dl/yyyyMMdd/
os.mkdir(os.path.join(downloadDir, today))
for line in open(urlList,'r'):... |
print(os.path.join(downloadDir, today))
return
if __name__ == "__main__":
import sys
#python3 donwloadFiles.py ../etc/urlList.tsv ../dl/
main(sys.argv)
|
twisted/mantissa | xmantissa/test/historic/stub_organizer2to3.py | Python | mit | 258 | 0.007752 | from axiom.test.historic.stubloader import saveStub
from | axiom.dependency import installOn
from xmantissa.people import Organizer
def createDatabase(s):
installOn(Organizer(store=s), s)
if __name__ == '__main__':
| saveStub(createDatabase, 13142)
|
london-escience/libhpc-cf | libhpc/component/bio.py | Python | bsd-3-clause | 13,873 | 0.008073 | # Copyright (c) 2015, Imperial College London
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of condi... | samtools_faidx_output_param', 'string', 'output', False)
samtools_faidx_result = Parameter('samtools_faidx_status', 'string', 'output', True)
samtools_mpileup_input = Parameter('samtools_mpileup_input_param', 'string', 'input', False)
samt | ools_mpileup_output = Parameter('samtools_mpileup_output_param', 'string', 'inout', False)
samtools_mpileup_result = Parameter('samtools_mpileup_status', 'string', 'output', True)
samtools_bcf2vcf_input = Parameter('samtools_bcf2vcf_input_param', 'string', 'input', False)
samtools_bcf2vcf_output = Parameter('samtools_... |
elainenaomi/sciwonc-dataflow-examples | sbbd2016/experiments/1-postgres/3_workflow_full_10files_primary_nosh_nors_annot_with_proj_3s/pegasus.bDkvI/pegasus-4.6.0/lib/python2.7/dist-packages/Pegasus/service/dashboard/dashboard.py | Python | gpl-3.0 | 20,107 | 0.005719 | # Copyright 2007-2012 University Of Southern California
#
# 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 ... | ashboard.close(all_workflows)
def workflow_stats(self):
try:
workflow = stampede_statistics.StampedeStatistics(self.__get_wf_db_url(), False)
workflow.initialize(root_wf_id = self._wf_id)
individual_stats = self._workflow_stat | s(workflow)
workflow2 = stampede_statistics.StampedeStatistics(self.__get_wf_db_url())
workflow2.initialize(self._root_wf_uuid)
all_stats = self._workflow_stats(workflow2)
return { 'individual' : individual_stats, 'all' : all_stats }
finally:
Dashb... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.