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 |
|---|---|---|---|---|---|---|---|---|
django-rea/nrp | django_rea/board/views.py | Python | agpl-3.0 | 46,450 | 0.014855 | import datetime
from django.db.models import Q
from django.http import HttpResponse, HttpResponseServerError, Http404, HttpResponseNotFound, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
f... | me="Give")
commit.to_agent = context_agent
commit.context_agent = context_agent
commit.due_date = commit.start_date
commit.commitment_date = commit.start_date
commit.unit_of_quantity = com | mit.resource_type.unit
commit.exchange_stage = None
commit.created_by = request.user
commit.save()
return HttpResponseRedirect('/%s/%s/'
% ('board/dhen-board', context_agent_id))
@login_required
def receive_directly(request, context_agent_id):
if request.method == "P... |
hughperkins/kgsgo-dataset-preprocessor | thirdparty/future/src/future/backports/email/quoprimime.py | Python | mpl-2.0 | 10,923 | 0.000732 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Ben Gertzfield
# Contact: email-sig@python.org
"""Quoted-printable content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode US ASCII-like 8-bit data called `quoted-printable'. It... |
self.write_str(self.eol)
self.room = self.maxlinelen
def write_soft_break(self):
"""Write a soft break, then start a new line."""
self.write_str('=')
self.newline()
def write_wrapped(self, s, extra_room=0):
"""Add a soft line break if needed, then write s."""
... | e_char(self, c, is_last_char):
if not is_last_char:
# Another character follows on this line, so we must leave
# extra room, either for it or a soft break, and whitespace
# need not be quoted.
self.write_wrapped(c, extra_room=1)
elif c not in ' \t':
... |
Packetslave/strava | setup.py | Python | apache-2.0 | 1,182 | 0 | import os
from setuptools import find_packages
from setuptools import setup
version = '1.0'
install_requires = [
]
tests_require = install_requires + ['Sphinx', 'docutils',
'virtualenv', 'nose', 'coverage']
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open... | ges=find_packages(),
include_package_data=True,
zip_safe=True,
tests_require=tests_require,
test_suite='strava.tests',
url='https://github. | com/Packetslave/strava',
author='Brian Landers',
author_email='brian@610systems.com',
entry_points="""\
"""
)
setup(**kwargs)
|
CyberTaoFlow/scirius | rules/migrations/0030_auto_20150103_1136.py | Python | gpl-3.0 | 1,122 | 0.002674 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('rules', '0029_auto_20150102_1212'),
]
operations = [
migrations.AlterField(
model_name='category... | created'),
preserve_default=True,
),
migrations.AlterField(
model_name='sourceatversion',
name='updated_date',
field=models.DateTimeField(default=datetime.datetime(2015, 1, 3, 11, 36, 49, 970816), verbose_name=b'date updated', blank=True),
pre... | model_name='sourceupdate',
name='created_date',
field=models.DateTimeField(default=datetime.datetime(2015, 1, 3, 11, 36, 49, 971165), verbose_name=b'date of update', blank=True),
preserve_default=True,
),
]
|
matpalm/malmomo | stitch_imgs.py | Python | mit | 1,879 | 0.007983 | #!/usr/bin/env python
import argparse
import Image, ImageDraw, ImageChops
import os
import sys
import util
# stitches a bunch of images together into a grid
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--x', type=int, default=3, help="output columns")
p... | pixel_buffer)
| y_offset = (gy*H)+(gy*pixel_buffer)
background.paste(img, (x_offset, y_offset))
background.save("%s/stitched_%03d.png" % (opts.output_dir, i))
i += opts.nth
print "mencoder mf://%s/ -ovc lavc -mf fps=10 -o stitched.avi" % opts.output_dir
|
masterfish2015/my_project | python/demo1/jupyter_markdown-master/script.py | Python | mit | 1,530 | 0.014379 | import json
import nbformat
import nbconvert
from nbformat.v4 import new_code_cell, new_markdown_cell, new_notebook, new_output
from nbconvert.preprocessors import ExecutePreprocessor
kernel_name = 'python3' # set it programmatically so that you only need to change it in one place
display_name = 'Python 3'
outpu... | down_cell(data[i]['markdown'])]
cells | += [new_code_cell('%%html\n'+data[i]['html'])]
nb=new_notebook(cells=cells,metadata={'kernelspec': {
'name': kernel_name,
'display_name': display_name
}})
executor = ExecutePreprocessor(timeout=60, kernel_name=kernel_name)
executor.preprocess(nb, metadata)
nbfor... |
cylc/cylc | cylc/flow/task_state.py | Python | gpl-3.0 | 18,047 | 0 | # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licen... | as {trigger (str): satisfied (boolean), ...}.
._is_satisfied (boolean):
Are prerequisites satisfied?
._suic | ide_is_satisfied (boolean):
Are prerequisites to trigger suicide satisfied?
"""
# Memory optimization - constrain possible attributes to this list.
__slots__ = [
"external_triggers",
"is_held",
"is_queued",
"is_runahead",
"is_updated",
"kill_faile... |
enthought/etsproxy | enthought/mayavi/preferences/mayavi_preferences_page.py | Python | bsd-3-clause | 111 | 0 | # p | roxy module
from __future__ import absolute_import
from mayavi.preferences.mayavi_preferences_page | import *
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/setup.py | Python | bsd-3-clause | 4,087 | 0.010276 | from distutils.core import setup
from distutils.command.install_data import install_data
from distutils.command.install import INSTALL_SCHEMES
import os
import sys
class osx_install_data(install_data):
# On MacOS, the platform-specific lib dir is /System/Library/Framework/Python/.../
# which is wrong. Python 2... | n.replace(' ', '-'),
url = 'http://www.djangoproject.com/ | ',
author = 'Django Software Foundation',
author_email = 'foundation@djangoproject.com',
description = 'A high-level Python Web framework that encourages rapid development and clean, pragmatic design.',
download_url = 'http://media.djangoproject.com/releases/1.2/Django-1.2.5.tar.gz',
packages = pack... |
ppwwyyxx/tensorpack | examples/FasterRCNN/convert_d2/convert_d2.py | Python | apache-2.0 | 5,712 | 0.001751 | #!/usr/bin/env python
import argparse
import numpy as np
import pickle
from detectron2.config import get_cfg
def convert_config(cfg):
ret = []
ret.append(("MODE_MASK", cfg.MODEL.MASK_ON))
has_fpn = "fpn" in cfg.MODEL.BACKBONE.NAME
ret.append(("MODE_FPN", has_fpn))
if not has_fpn:
# we onl... | blkid}.conv2",
f"group{grpid}/block{blkid}/conv2")
_convert_conv(backbone_prefix + f"res{grpid + 2}.{blkid}.conv3",
f"group{grpid}/block{blkid}/conv3")
if blkid == 0:
_convert_conv(backbone_prefix + f"res{grpid + 2}.{blkid}.shor... | lvl in range(2, 6):
_convert_conv(f"backbone.fpn_lateral{lvl}", f"fpn/lateral_1x1_c{lvl}")
_convert_conv(f"backbone.fpn_output{lvl}", f"fpn/posthoc_3x3_p{lvl}")
# RPN:
_convert_conv("proposal_generator.rpn_head.conv", "rpn/conv0")
_convert_conv("proposal_generator.rpn_head.objectne... |
kejbaly2/devconfcz | bin/typeform.py | Python | gpl-3.0 | 31,579 | 0.001995 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Installation (Python 3)
-----------------------
virtualenv -p python3 ~/virtenvs/devconfcz/
source ~/virtenvs/devconfcz/bin/activate
pip install hyde requests click pandas df2gspread
Example Config
--------------
cat <<EOT >> ~/.config/typeform/confi... | al(datetime.date.today().toordinal() - 1))
epoch = time.mktime(time.strptime(dt, dt_format))
return int(epoch)
def _split_resources(proposals):
# split out proposals into speakers and sessions
sessions = proposals[SESSION_FIELDS]
speakers = proposals[SPEAKER_FIELDS]
return sessions, speakers... | from io import open as iopen
try:
i = requests.get(url)
if i.status_code == requests.codes.ok:
with iopen(path, 'wb') as file:
file.write(i.content)
cmd = "file {}".format(path)
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
outp... |
burke-software/django-content-edit | manage.py | Python | bsd-3-clause | 260 | 0.003846 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "content_edit_proj.settings")
from django.core.management im | port exe | cute_from_command_line
execute_from_command_line(sys.argv)
|
timabbott/zulip | zerver/lib/sqlalchemy_utils.py | Python | apache-2.0 | 1,660 | 0.001807 | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(... | if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
... | et_on_return=False)
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection
|
manojgudi/sandhi | modules/gr36/gnuradio-core/src/python/gnuradio/gr/qa_vector_map.py | Python | gpl-3.0 | 3,870 | 0.003359 | #!/usr/bin/env python
#
# Copyright 2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# ... | self.tb = None
def test_reversing(self):
# Chunk data in blocks of N and reverse the block contents.
N = 5
src_data = range(0, 20)
expected_result = []
for i in range(N-1, len(src_data), N):
| for j in range(0, N):
expected_result.append(1.0*(i-j))
mapping = [list(reversed([(0, i) for i in range(0, N)]))]
src = gr.vector_source_f(src_data, False, N)
vmap = gr.vector_map(gr.sizeof_float, (N, ), mapping)
dst = gr.vector_sink_f(N)
self.tb.conne... |
sridevikoushik31/nova | nova/tests/cells/test_cells_rpcapi.py | Python | apache-2.0 | 18,532 | 0.001619 | # Copyright (c) 2012 Rackspace Hosting
# 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 req... | l_info, method, args, version=None):
if version is None:
version = self.cells_rpcapi.BASE_RPC_API_VERSION
self.assertEqual(self.fake_context, call_info['context'])
self.assertEqual(self.fake_topic, call_info['topic'])
self.assertEq | ual(method, call_info['msg']['method'])
self.assertEqual(version, call_info['msg']['version'])
self.assertEqual(args, call_info['msg']['args'])
def test_cast_compute_api_method(self):
fake_cell_name = 'fake_cell_name'
fake_method = 'fake_method'
fake_method_args = (1, 2)
... |
jlecount-sungevity/holmium.core | tests/support/options/test_options.py | Python | mit | 483 | 0.006211 | import unittest
import holmium.core
class TestOptions(unittest.TestCase):
| def test_browser_set(self):
self.assertEqual(self.driver.name, "remote")
| def test_remote_set(self):
self.config["remote"] = "{{holmium.remote}}"
self.assertEqual(self.config["remote"], 'http://nowhere.org')
def test_useragent_set(self):
self.config["user_agent"] = "{{holmium.user_agent}}"
self.assertEqual(self.config["user_agent"], '"test useragent"')
|
TPopovich/mongo-connector | tests/test_util.py | Python | apache-2.0 | 1,776 | 0.001689 | # Copyright 2013-2014 MongoDB, 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 to in writin... | " Tests the utils
"""
def test_bson_ts_to_long(self):
"""Test bson_ts_to_long and long_to_bson_ts
"""
tstamp = timestamp.Timestamp(0x12345678, 0x90abcdef)
self.assertEqual(0x1234567890abcdef,
bson_ts_to_long(tstamp))
self.assertEqual(long_to_bs... | try_until_ok(self):
"""Test retry_until_ok
"""
self.assertTrue(retry_until_ok(err_func))
self.assertEqual(err_func.counter, 3)
if __name__ == '__main__':
unittest.main()
|
projectweekend/Pi-Pin-Manager | setup.py | Python | mit | 508 | 0.001969 | from distutils.core import setup
setup(
name='Pi-Pin-Manager',
version='3.1.0',
author='Brian Hines',
author_email='brian@projectweekend.net',
packages=['pi_pin_manager'],
url='http://projectweekend.github.io/Pi-Pin-Manager/',
license='LICENSE.tx | t',
description='Setup Raspberry Pi GPIO pins using a configuration file, not boilerplate.',
long_description=open('README.txt').read( | ),
install_requires=[
"PyYAML == 3.11",
"RPi.GPIO == 0.5.11",
],
)
|
LethusTI/supportcenter | vendor/django/tests/modeltests/save_delete_hooks/tests.py | Python | gpl-3.0 | 761 | 0 | from __future__ import absolute_import
from django.test import TestCase
from .models import Person
class SaveDeleteHookTests(TestCase):
def test_basic(self):
p = Person(first_name="John", last_name="Smith")
self.assertEqual(p.data, [])
p.save()
self.as | sertEqual(p.data, [
"Before save",
"After save",
])
self.a | ssertQuerysetEqual(
Person.objects.all(), [
"John Smith",
],
unicode
)
p.delete()
self.assertEqual(p.data, [
"Before save",
"After save",
"Before deletion",
"After deletion",
])
s... |
sghai/robottelo | tests/foreman/ui/test_hostunification.py | Python | gpl-3.0 | 22,724 | 0 | # -*- encoding: utf-8 -*-
"""Test class for Host/System Unification
:Requirement: Hostunification
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo.cli.... | 'organization-id': org.id,
'content-view-id': content_view.id,
'lifecycle-environment-id': env.id,
'activationkey-id': activation_key.id,
})
with VirtualMachine(distro=DISTRO_RHEL7) as vm:
vm.install_katello_ca()
vm.register_contenthost(org.l... | self.assertTrue(vm.subscribed)
with Session(self) as session:
session.nav.go_to_select_org(org.name)
self.assertIsNotNone(self.hosts.search(vm.hostname))
self.assertIsNotNone(self.contenthost.search(vm.hostname))
@run_only_on('sat')
@tier3
@upgrad... |
ScottWales/rose | lib/python/rose/upgrade.py | Python | gpl-3.0 | 26,666 | 0.0003 | # -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-5 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | args[0])
class MacroUpgrade(rose.macro.MacroBase):
"""Class derived from MacroBase to aid upgrade functionality."""
ERROR_RENAME_OPT_TO_SECT = "Error: cannot rename {0}={1} to {2}"
ERROR_RENAME_SECT_TO_OPT = "Error: cannot rename {0} to {1}={2}"
INFO_ADDED_SECT = "Added"
INFO_ADDED_VAR = "Added ... | _VAR = "Renamed {0}={1} -> {2}={3}"
UPGRADE_RESOURCE_DIR = MACRO_UPGRADE_RESOURCE_DIR
def act_from_files(self, config, downgrade=False):
"""Parse a change configuration into actions."""
res_map = self._get_config_resources()
add_config = res_map.get(MACRO_UPGRADE_RESOURCE_FILE_ADD)
... |
sparkslabs/kamaelia_ | Sketches/AB/backup/Bookmarks/DataCollector.py | Python | apache-2.0 | 13,360 | 0.010404 | #! /usr/bin/python
'''
Saves relevant data fed back from TwitterStream etc next to its PID and timestamp ready for analysis
Needs to do limited analysis to work out which keywords in the tweet stream correspond to which programme
'''
from datetime import datetime
import os
import string
import time as time2
from time... | filepath = "contentDebug.txt"
if os.path.exists(filepath):
file = open(filepath, 'r')
filecontents = file.read()
else:
filecontents = ""
... | open(filepath, 'w')
file.write(filecontents + "\n" + str(datetime.utcnow()) + " " + cjson.encode(newdata))
file.close()
else:
# This is a real tweet
tweetid = newdata['id']
... |
fmaguire/ete | ete3/tools/phylobuild_lib/utils.py | Python | gpl-3.0 | 21,864 | 0.009653 | from __future__ import absolute_import
from __future__ import print_function
# -*- coding: utf-8 -*-
# #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redi... | Nucleic Acids Res. 2004 Mar
19;32(5):1792-7."""
CLUSTALO_CITE | = u""" Sievers F, Wilm A, Dineen D, Gibson TJ, Karplus
K, Li W, Lopez R, McWilliam H, Remmert M, Söding J, Thompson JD,
Higgins DG. Fast, scalable generation of high-quality protein
multiple sequence alignments using Clustal Omega. Mol Syst Biol. 2011
Oct 11;7:539. doi: 10.1038/msb.2011.75."""
DIALIGN_CITE = u"""Subr... |
abalakh/robottelo | tests/foreman/cli/test_import.py | Python | gpl-3.0 | 64,380 | 0.000062 | # -*- encoding: utf-8 -*-
"""Test class for Host Collection CLI"""
import csv
import os
import re
import tempfile
from fauxfactory import gen_string
from itertools import product
from random import sample
from robottelo import ssh
from robottelo.cli.base import CLIReturnCodeError
from robottelo.cli.contenthost import ... | a "${HOME}"/puppet_work_dir')
def build_csv_file(rows=None, dirname=None): |
"""Generate a csv file, feed it by the provided data
(a list of dictionary objects) and return a path to it
"""
if rows is None:
rows = [{}]
file_name = tempfile.mkstemp()[1]
with open(file_name, 'wb') as csv_file:
csv_writer = csv.DictWriter(
csv_file, fieldnames=r... |
florensacc/snn4hrl | envs/point/multiMod2D_env.py | Python | mit | 2,207 | 0.00589 | from rllab.envs.base import Env
from rllab.envs.base import Step
from rllab.spaces import Box
import numpy as np
class MultiMod2DEnv(Env):
"""
This is a single time-step MDP where the action taken corresponds to the next state (in a 2D plane).
The reward has a multi-modal gaussian shape, with the mode mea... | def reset(self):
self._state = np.zeros(shape=(2,)) \
+ int(self.rand_init) * (
(np.random.rand(2, ) - 0.5) * 5 * np.linalg.norm(self.mu) ) ##mu is taken as largest
observation = np.copy(self._state)
return observation
def reward_state( | self, state):
x = state
mu = self.mu
A = np.array([[np.cos(2. * np.pi / self.n), -np.sin(2. * np.pi / self.n)],
[np.sin(2. * np.pi / self.n), np.cos(2. * np.pi / self.n)]]) ##rotation matrix
reward = -0.5 + 1. / (2 * np.sqrt(np.power(2. * np.pi, 2.) * self.sigma)) ... |
aipescience/django-daiquiri | daiquiri/files/migrations/0005_directory_layout.py | Python | apache-2.0 | 496 | 0.002016 | # Generated by Django 2.1.3 on 2018-1 | 1-20 08:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('daiquiri_files', '0004_django2'),
]
operations = [
migrations.AddField(
model_name='directory',
name='layout',
field=models.BooleanField(defa... | se,
),
]
|
frootloops/swift | utils/gyb_syntax_support/Token.py | Python | apache-2.0 | 5,109 | 0 | from kinds import lowercase_first_word
class Token(object):
"""
Represents the specification for a Token in the TokenSyntax file.
"""
def __init__(self, name, kind, text=None, is_keyword=False):
self.name = name
self.kind = kind
self.text = text or ""
self.is_keyword =... | 'Period', 'period', text='.'),
Token('Equal', 'equ | al', text='='),
Token('PrefixPeriod', 'period_prefix', text='.'),
Token('LeftParen', 'l_paren', text='('),
Token('RightParen', 'r_paren', text=')'),
Token('LeftBrace', 'l_brace', text='{'),
Token('RightBrace', 'r_brace', text='}'),
Token('LeftSquareBracket', 'l_square', text='['),
Token('Rig... |
jocelynj/weboob | weboob/backends/canalplus/backend.py | Python | gpl-3.0 | 2,271 | 0.002202 | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Nicolas Duhamel
#
# 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, version 3 of the License.
#
# This program is distributed in the hope that it will... | nalplusBackend(BaseBackend, ICapVideo):
NAME = 'canalplus'
MAINTAINER = 'Nicolas Duhamel'
EMAIL = 'nicolas@jombi.fr'
VERSION = '0.4'
DESCRIPTION = 'Canal plus french TV'
LICENSE = 'GPLv3'
CONFIG = ValuesDict(Value('quality', label='Quality of videos', choices=['hd', 'sd'], default='hd'))
... | iter_search_results(self, pattern=None, sortby=ICapVideo.SEARCH_RELEVANCE, nsfw=False, max_results=None):
with self.browser:
return self.browser.iter_search_results(pattern)
def get_video(self, _id):
with self.browser:
return self.browser.get_video(_id)
def fill_video(s... |
kingland/go-v8 | v8-3.28/tools/run-tests.py | Python | mit | 22,223 | 0.00927 | #!/usr/bin/env python
#
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# noti... | "nacl_ia32",
"nacl_x64",
"x64",
"x32",
"arm64"]
# Double the timeout for these:
SLOW_ARCHS = ["android_arm",
"android_arm64",
"android_ia32",
"arm",
"mips",
"mipsel",
... | ",
"nacl_ia32",
"nacl_x64",
"x87",
"arm64"]
def BuildOptions():
result = optparse.OptionParser()
result.add_option("--arch",
help=("The architecture to run tests for, "
"'auto' or 'native' for auto-detect"),
... |
GoogleCloudPlatform/covid-19-open-data | src/pipelines/epidemiology/us_nyt_covid.py | Python | apache-2.0 | 3,093 | 0.002586 | # Copyright 2020 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, ... | def parse_dataframes | (
self, dataframes: Dict[str, DataFrame], aux: Dict[str, DataFrame], **parse_opts
) -> DataFrame:
# Rename the appropriate columns
data = (
dataframes[0]
.rename(
columns={
"date": "date",
"state": "subregion1_n... |
JDSWalker/AdventOfCode | 2015/Day05/advent_of_code_2015_day_05.py | Python | mit | 6,750 | 0.001481 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Advent of Code 2015 from http://adventofcode.com/2015/day/5
Author: James Walker
Copyrighted 2017 under the MIT license:
http://www.opensource.org/licenses/mit-license.php
Execution:
python advent_of_code_2015_day_05.py
--- Day 5: Doesn't He Have Intern-Elves For ... | at(old_nice_count, new_nice_count)
def _run_test_case(self, test_case):
correct_output = self._solved_output.format(
test_case.expected1,
test_ca | se.expected2
)
test_output = self.get_puzzle_solution(test_case.input)
if correct_output == test_output:
print("Test passed for input '{0}'".format(test_case.input))
else:
print("Test failed for input '{0}'".format(test_case.input))
print(test_output)
... |
open-research/sumatra | sumatra/datastore/davfs.py | Python | bsd-2-clause | 3,593 | 0.003896 | '''
Datastore via remote webdav connection
'''
from __future__ import unicode_literals
from future import standard_library
standard_library.inst | all_aliases()
import os
import tarfile
import logging
from fs.contrib.davfs import DAVFS
from urllib.parse import urlparse
from contextlib import closing
from sumatra.core import component
from .archivingfs import ArchivingFileSystemDataStore, ArchivedDataFile, TIMESTAMP_FORMAT
class DavFsDataItem(ArchivedDataFile)... | first cause _get_info is called in Base __init__
self.store = store
super(DavFsDataItem, self).__init__(path, store)
def get_content(self, max_length=None):
obj = self.store.dav_fs.open(self.tarfile_path, 'rb')
with closing(tarfile.open(fileobj=obj)) as data_archive:
f ... |
gdos/parole | src/parole/map.py | Python | gpl-2.0 | 96,935 | 0.004931 | #Python Advanced Roguelike Engine (Parole)
#Copyright (C) 2006-2012 Max Bane
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later versio... | tribute of the L{MapObject} with the highest C{layer}, and possibly, if
the highest L{MapObject} does not have a C{bgShader} attribute, the
C{bgShader} attribute of the highest-layer object that does have one. User
code display L{Tile} contents in a different way by subclassing | L{Tile} and
overriding the L{resetPasses} method (the C{tileType} argument to
L{Map2D.__init__} allows you to create L{Map2D} instances with your custom
L{Tile} subclass).
A L{Tile} instance is fully picklable, assuming that all of its contents
are.
@ivar contents: Contains the L{MapObject}s ... |
FlaPer87/django-nonrel | tests/modeltests/user_commands/management/commands/dance.py | Python | bsd-3-clause | 398 | 0.005025 | from optparse import make_option
from django.core.management.base import BaseCommand
class Command(BaseCommand): |
help = "Dance around like a madman."
args = ''
requires_model_validation = True
option_list =[
make_option("-s", "--style", default="Rock'n'Roll")
]
def handle(self, *args, **options):
print "I don't feel like dancing | %s." % options["style"]
|
annarev/tensorflow | tensorflow/python/data/experimental/kernel_tests/directed_interleave_dataset_test.py | Python | apache-2.0 | 6,838 | 0.005411 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | or i in | range(num_datasets)
], weights)
dataset = dataset.take(num_samples)
next_element = self.getNext(dataset)
freqs = np.zeros([num_datasets])
for _ in range(num_samples):
freqs[self.evaluate(next_element())] += 1
with self.assertRaises(errors.OutOfRangeError):
self.evaluate(next_element... |
Ebag333/Pyfa | eos/effects/cloakingwarpsafe.py | Python | gpl-3.0 | 226 | 0 | # cloakingWarpSafe
#
# Used by:
# Modules named like: Covert Ops Cloaking Device | II (2 of 2)
type = " | active"
runTime = "early"
def handler(fit, ship, context):
fit.extraAttributes["cloaked"] = True
# TODO: Implement
|
klmitch/dtest | tests/test_inheritance.py | Python | apache-2.0 | 1,722 | 0 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | def tearDown(self):
assert_false(self.instance_setup)
# See if we inherited them
class TestInheritance(TestInheritanceBase):
@attr(must_skip=True)
def test_inheritance(self):
assert_true(self.class_setup)
assert_true(self.instance_setup)
TestInheritanceBase.class_setup = Fal... | nce(self):
# Make sure we can call our superclass method
super(TestInheritanceTwo, self).test_inheritance()
|
adaxi/couchpotato | couchpotato/core/plugins/dashboard.py | Python | gpl-3.0 | 3,841 | 0.008592 | from datetime import date
import random as rndm
import time
from couchpotato import get_db
from couchpotato.api import addApiView
from couchpotato.core.event import fireEvent
from couchpotato.core.helpers.variable import splitString, tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base i... | get('qualities', []):
contains['theater' if q_identifier in pre_releases else 'dvd'] = True
profile_pre[profile.get('_id')] = contai | ns
# Add limit
limit = 12
if limit_offset:
splt = splitString(limit_offset) if isinstance(limit_offset, (str, unicode)) else limit_offset
limit = tryInt(splt[0])
# Get all active medias
active_ids = [x['_id'] for x in fireEvent('media.with_status', 'acti... |
sunweaver/ganetimgr | context/pending_notifications.py | Python | gpl-3.0 | 1,458 | 0 | # -*- coding: utf-8 -*- vim:fileencoding=utf-8:
# Copyright (C) 2010-2014 GRNET S.A.
#
# 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 ... | ttp://www.gnu.org/licenses/>.
#
from apply.models import InstanceApplication, STATUS_PENDING
from django.core.cache import cache
def notify(request):
res = {}
if request.user:
if request.user.has_perm("apply.change_instanceapplication"):
res.update(can_handle_applications=True)
eli... | 'pendingapplications')
if cres is None:
pend = InstanceApplication.objects.filter(status=STATUS_PENDING)
res.update(pending_count=pend.count())
cache.set('pendingapplications', res, 45)
else:
res = cres
return res
|
generic-group-analyzer/gga | scripts/ggt_z3.py | Python | mit | 10,372 | 0.040012 | #!/bin/sh
''''exec python -- "$0" ${1+"$@"} # '''
from z3 import *
import json
import sys
import traceback
#################################################################################
# Complex numbers, see: http://leodemoura.github.io/blog/2013/01/26/complex.html
################################################... | o']
nzero = req['nzero']
s = Solver()
for f in zero:
s.add( translate_poly(Real,f) == 0 )
for disj in nzero:
s.add( Not(And([ (translate_poly(Real,f) == 0) for f in disj])) )
#debug(str(s.sexpr()))
res = s.check()
#d | ebug(str(res))
if res == sat:
m = s.model()
res = sorted(((k,str(m[k])) for k in m if str(m[k]) != "0"), lambda x,y: cmp(str(x[0]),str(y[0])))
res = "\n".join(map(lambda x: " %s = %s"%(x[0],x[1]),res))
#debug(str(list((k,m[k]) for k in m)))
return { "ok": True
, "res": "s... |
scivey/relevanced | clients/python/client/setup.py | Python | mit | 565 | 0.00354 | from setuptools import setup
version_path = 'relevanced_client/version.py'
exec(open(version_path). | read())
setup(
name="relevanced-client",
zip_safe=True,
version=VERSION,
description="Python client for relevanced-server.",
url="http://www.relevanced.org",
maintainer="Scott Ivey",
maintainer_email="scott.ivey@gmail.com",
packages=['relevanced_client', 'relevanced_client.gen_py', 'rel... | rift==0.9.2']
) |
gedare/gem5 | ext/pybind11/tests/test_alias_initialization.py | Python | bsd-3-clause | 1,879 | 0.002661 | import gc
def test_alias_delay_initialization1(capture):
"""A only initializes its trampoline class when we inherit from it; if we just
create and use an A instance directly, the trampoline initialization is bypassed
and we only initialize an A() instead (for performance reasons).
"""
from pybind1... | ()
"""
def test_alias_delay_initialization2(capture):
"""A2, unlike the above, is configured to always initialize the alias; while
the extra initialization and extra class layer has small virtual dispatch
performance penalty, it also allows us to do more things with the trampoline
class such as de... | f
class B2(A2):
def __init__(self):
super(B2, self).__init__()
def f(self):
print("In python B2.f()")
# No python subclass version
with capture:
a2 = A2()
call_f(a2)
del a2
gc.collect()
assert capture == """
PyA2.PyA2()
... |
MalkmusT/coala-quickstart | tests/generation/InfoCollectorTest.py | Python | agpl-3.0 | 2,740 | 0 | import os
import unittest
from coala_quickstart.generation.InfoCollector import (
collect_info)
from tests.TestUtilities import generate_files
package_json = """
{
"name": "awesome-packages",
"version": "0.8.0",
"license": "MIT",
"dependencies": {
"coffeelint": "~1",
"ramllint": "... | 2.2 <1.2.4"
},
"files": ["dist"],
"man" : ["./man/foo.1", "./man/bar.1"]
}
"""
editorconfig = """
root = true
[*]
end_of_line = lf
insert_final_newline = true
[*.{js,py}]
charset = utf-8
trim_trailing_whitespace = true
indent_size = tab
tab_width = 4
[*.py]
indent_style = space
indent_size = 4
[{packag... | }]
indent_style = space
indent_size = 2
"""
gemfile = """
source "https://rubygems.org"
gem "puppet-lint", "2.1.1"
gem "rubocop", "0.47.1"
gem "scss_lint", require: false
gem "RedCloth", :require => "redcloth"
gem "omniauth", ">= 0.2.6", :git => "git://github.com/intridea/omniauth.git"
group :assets do
gem 'some-g... |
mrf345/FQM | migrations/versions/8f8e67fcbd9c_.py | Python | mpl-2.0 | 772 | 0.001295 | """ Adding `on_hold` flag to tickets.
Revision ID: 8f8e67fcbd9c
Revises: 8aee5e17a98d
Create Date: 2020-02-1 | 0 20:07:59.376033
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '8f8e67fcbd9c'
down_revision = '8aee5e17a98d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
try:
op.add_colu... | Alembic - please adjust! ###
with op.batch_alter_table('serials') as batch:
batch.drop_column('on_hold')
# ### end Alembic commands ###
|
rajpushkar83/cloudmesh | todo/modules/workflow.py | Python | apache-2.0 | 5,445 | 0.001102 | from cloudmesh.shell.Shell import Shell
from flask import Blueprint
from flask import render_template, redirect, flash
from datetime import datetime
from flask.ext.wtf import Form
from wtforms import TextField, SelectField, TextAreaField
from cloudmesh.old_inventory.inventory import Inventory
from hostlist import expan... | orm.workflow
except:
print "file does not exists"
print "{0}.{1}".format(basename, diagram_format | )
print "OOOO", basename
Shell.blockdiag("--ignore-pil", "-Tsvg",
"-o", "{2}/{0}.{1}".format(basename, diagram_format, web_pwd),
"{2}/{0}.{1}".format(basename, "diag", web_pwd))
# Shell.blockdiag("-Tpng",
# "-o", "." + dir + filename + ".png",
# "." + d... |
red-hood/calendarserver | twistedcaldav/test/test_memcachepool.py | Python | apache-2.0 | 11,952 | 0.002343 | ##
# Copyright (c) 2008-2015 Apple 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 l... | stopConnecting} that doesn't do anything.
"""
class StubReactor(object):
"""
A stub L{IReactorTCP} that records the calls to connectTCP.
@ivar calls: A C{list} of tuples (args, kwargs) sent to connectTCP.
| """
implements(IReactorTCP)
def __init__(self):
self.calls = []
def connectTCP(self, *args, **kwargs):
self.calls.append((args, kwargs))
return StubConnector()
def addSystemEventTrigger(self, *args, **kwds):
pass
class PooledMemCacheProtocolTests(TestCase):
""... |
EmanueleCannizzaro/scons | test/TEX/TEXFLAGS.py | Python | mit | 3,365 | 0.004458 | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to us... | th('wrapper.out')))
test.fail_test(not os.path.exists(test | .workpath('bar.dvi')))
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
Sarthak30/Codeforces | suffix_structures.py | Python | gpl-2.0 | 289 | 0.024221 | s, t = raw_input(), raw_input()
u, v = sorted(s), sorted(t)
def subset(a, b):
i = 0
for c in a:
if i < len(b) and c == b[i]: i += 1
return | i == len(b)
if u == v: print "array"
elif subset(s, t): print "automaton"
elif subset(u, v): print "both"
el | se: print "need tree"
|
naivesound/glitch | vendor/github.com/thestk/rtaudio/contrib/python/pyrtaudio/PyRtAudioTest.py | Python | gpl-3.0 | 1,553 | 0.023181 |
import rtaudio as rt
from math import cos
import struct
class audio_generator:
def __init__(self):
self.idx = -1
self.freq = 440.
def __call__(self):
self.idx += 1
if self.idx%48000 == 0:
self.freq *= 2**(1/12.)
return 0.5*cos(2.*3.1416*self.freq*self.... | _into("f", playback, 4*o, self.gen()) for o in xrange(256)]
self.i = self.i + 256
if self.i > 48000*10:
print '.'
return 1
dac = rt.RtAudio()
n = dac.getDeviceCount()
print 'Number of devices available: ', n
for i in range(n):
try:
print dac.getDeviceInfo(i)
ex... | rror as e:
print e
print 'Default output device: ', dac.getDefaultOutputDevice()
print 'Default input device: ', dac.getDefaultInputDevice()
print 'is stream open: ', dac.isStreamOpen()
print 'is stream running: ', dac.isStreamRunning()
oParams = {'deviceId': 1, 'nChannels': 1, 'firstChannel': 0}
iParam... |
pengphei/cinemaman | ui/ExportToolView.py | Python | unlicense | 1,165 | 0.00983 | # -*- coding: utf-8 -*-
import Tkinte | r as tk
import tkFont
import ttk
from CMApp import *
class CMExportToolView(ttk.Frame):
"""
export excel table tool view
"""
def __init__(self, root, parent, width_):
ttk.Frame.__init__(self, parent, class_="CMExportToolView", width=width_)
self.root = root
self.parent = p... | self._setup_widgets()
return
def _setup_widgets(self):
self.ToolAdd = ttk.Button(self, text = '导出本天排表', command=self._export_this_day)
self.ToolAdd.pack(fill=tk.X, side=tk.TOP)
self.ToolDel = ttk.Button(self, text = '导出本天单影片排表', command=self._export_this_day_movie)
self.T... |
yamahata/tacker | tacker/tests/unit/test_agent_rpc.py | Python | apache-2.0 | 4,837 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 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.... |
fanout=True),
mock.call().create_consumer('foo-topic-op.node1', endpoints,
| fanout=False),
mock.call().consume_in_threads()
]
call_to_patch = 'tacker.common.rpc_compat.create_connection'
with mock.patch(call_to_patch) as create_connection:
rpc.create_consumers(endpoints, 'foo', [('topic', 'op', 'node1')])
... |
odoousers2014/LibrERP | material_asset/wizard/asset_assign_category.py | Python | agpl-3.0 | 2,528 | 0.003165 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012-2014 Didotech (<http://www.didotech.com>)
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Genera... | 'tz': context['tz'],
'uid': context['uid'],
'section_id': context['section_id'],
'project_id': context['project_id'],
'department_id': context['department_id'],
'asset_created': True
}
self.pool.get('stock.move').action_done(cr, uid, context['m... |
return {'type': 'ir.actions.act_window_close'}
|
abergmeier-dsfishlabs/bazel | tools/android/merge_manifests.py | Python | apache-2.0 | 15,264 | 0.006682 | # Copyright 2015 The Bazel 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 applicable la... | Args:
merger: First (merger) AndroidManifest.xml string.
mergees: mergee AndroidManifest.xml strings, a list.
exclude_permissions: Permissions to be excludeed from merging,
string list. "all" means don't include any permissions.
"""
self._merger = merger
self._mergees = mergees
... | .
Args:
dom: Document dom object from which to exclude permissions.
"""
if self._exclude_permissions:
exclude_all_permissions = EXCLUDE_ALL_ARG in self._exclude_permissions
for element in (dom.getElementsByTagName(self._USES_PERMISSION) +
dom.getElementsByTagName(self._USES_PERMISS... |
getyourguide/fbthrift | thrift/compiler/py/generate/t_output.py | Python | apache-2.0 | 5,552 | 0 | #!/usr/local/bin/python2.6 -tt
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (... | a
scope.'''
# TODO(dsanduleac): deprecate this and use a num_lines_printed
# abstraction instead. Then modify t_cpp_generator to always print
# newlines after statements. Should modify the behaviour of
# double_space as well.
self._flag = flag
@property
def on_f... | t):
def __init__(self, output, indent_char=' '):
Output.__init__(self, output)
self._indent = 0
# configurable values
self._indent_char = indent_char
def indent(self, amount):
assert self._indent + amount >= 0
self._indent += amount
def unindent(self, amoun... |
wschwa/Mr-Orange-Sick-Beard | tests/common_tests.py | Python | gpl-3.0 | 6,501 | 0.008153 | import unittest
import sys
import os.path
sys.path.append(os.path.abspath('..'))
from sickbeard import common
class QualityTests(unittest.TestCase):
# TODO: repack / proper ? air-by-date ? season rip? multi-ep?
def test_SDTV(self):
self.assertEqual(common.Quality.SDTV, common.Quality.nameQuality("... | UP"))
self.assertEqual(common.Quality.SDDVD, common.Quality.nameQuality("Test Show - S01E02 - SD DVD - GROUP"))
self.assertEqual(common.Quality.HDTV, common.Quality.nameQuality("Test Show - S01E02 - HD TV - GROUP"))
self.assertEqual(common.Quality.RAWHDTV, common.Quality.nameQuality("Test Show -... | TV - GROUP"))
self.assertEqual(common.Quality.FULLHDTV, common.Quality.nameQuality("Test Show - S01E02 - 1080p HD TV - GROUP"))
self.assertEqual(common.Quality.HDWEBDL, common.Quality.nameQuality("Test Show - S01E02 - 720p WEB-DL - GROUP"))
self.assertEqual(common.Quality.FULLHDWEBDL, common.Qua... |
bendalab/audioio | tests/test_playaudio.py | Python | gpl-3.0 | 3,956 | 0.000758 | from nose.tools import assert_equal, assert_greater, assert_greater_equal, assert_less, assert_raises
import time
import numpy as np
import audioio.playaudio as ap
import audioio.audiomodules as am
def test_beep():
am.enable_module()
print()
print('default module...')
ap.beep(blocking=True)
ap.bee... | ule...' % lib)
am.s | elect_module(lib)
ap.beep(blocking=True, verbose=2)
ap.beep(blocking=False, verbose=2)
time.sleep(2.0)
ap.handle.close()
am.enable_module()
def test_play():
am.enable_module()
print()
# sine wave:
rate = 44100.0
t = np.arange(0.0, 0.5, 1.0/rate)
mono_dat... |
ktok07b6/polyphony | tests/warning/pipeline_hazard01.py | Python | mit | 595 | 0.003361 | #The pipeline may not work correctly if there is both read and write access to the s | ame memory 'xs0'
from polyphony import testbench
from polyphony import pipelined
def pipeline_hazard01(xs0, xs1, xs2 | ):
for i in pipelined(range(len(xs0) - 1)):
xs1[i] = xs0[i]
xs0[i + 1] = xs2[i]
@testbench
def test():
data0 = [1, 2, 3]
data1 = [0, 0, 0]
data2 = [1, 2, 1]
pipeline_hazard01(data0, data1, data2)
assert 1 == data0[0]
assert 1 == data0[1]
assert 2 == data0[2]
assert ... |
Anderson0026/mapproxy | mapproxy/test/system/test_cache_source.py | Python | apache-2.0 | 5,009 | 0.005191 | # This file is part of the MapProxy project.
# Copyright (C) 2012 Omniscale <http://omniscale.de>
#
# 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... | et('/tms/1.0.0/tms_transf/EPSG25832/0/0/0.png')
eq_(resp.content_type, 'image/png')
self.created_tiles.append('tms_cache_out_EPSG25832/00/000/000/000/000/000/000.png')
def test_get_tile_fr | om_sub_grid(self):
# create tile in old cache
tile_filename = os.path.join(self.config['cache_dir'], 'old_cache_EPSG3857/01/000/000/001/000/000/000.png')
os.makedirs(os.path.dirname(tile_filename))
# use text to check that mapproxy does not access the tile as image
open(tile_file... |
YatharthROCK/agar | libraries/processing.py-0202-macosx/examples.py/Fisica/restitutions.py | Python | mit | 851 | 0.003525 | """
* Restitutions
*
* by Ricard Marxer
*
* This example shows how the restitution coefficients works.
"""
from fisica import Fisica, FWorld, FCircle
world = None
ballCount = 10
def setup():
global world
siz | e(400, 400)
smooth()
Fisica.init(this)
world = FWorld()
world.setEdges()
world.remove(world.left)
world.remove(world.right)
world.remove(world.top)
world.setEdgesRestitution(0.0)
for i in range(ballCount):
b = FCircle(25 | )
b.setPosition(map(i, 0, ballCount-1, 40, width-40), height/6)
b.setRestitution(map(i, 0, ballCount-1, 0.0, 1.0))
b.setNoStroke()
b.setFill(map(i, 0, ballCount-1, 60, 255), 80, 120)
world.add(b)
def draw():
background(255)
world.step()
world.draw()
def keyPressed()... |
rananda/cfme_tests | metaplugins/blockers.py | Python | gpl-2.0 | 4,897 | 0.003881 | # -*- coding: utf-8 -*-
"""A generalized framowork for handling test blockers.
Currently handling Bugzilla nad GitHub issues. For extensions, see this file and
:py:mod:`utils.blockers`.
If you want to mark test with blockers, use meta mark ``blockers`` and specify a list of the
blockers. The blockers can be directly ... | There is also a ``custom_action`` that
will get called if the blocker blocks. if the action does nothing, then it continues with next
actions etc., until it gets to the point that it skips the test because there are blockers.
"""
import pytest
from kwargify import kwargify as _kwargify
from fixtures.artifactor_plugi... | t version
from utils.blockers import Blocker
from utils.pytest_shortcuts import extract_fixtures_values
def kwargify(f):
"""Convert function having only positional args to a function taking dictionary.
If you pass False or None, a function which always returns False is returned.
If you pass True, a funct... |
wri/gfw-api | gfw/forestchange/glad.py | Python | gpl-2.0 | 7,407 | 0.003645 | # Global Forest Watch API
# Copyright (C) 2014 World Resource Institute
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version... | ram_key])
return datetime.datetime(year, 1, 1) + datetime.timedelta(day_number-1)
def getFullHistogram(args):
begin = datetime.datetime.strptime(str(START_YEAR), '%Y')
end = datetime.datetime.now()
rasters = rastersForPeriod(begin, end)
results = {}
for raster in rasters:
result = urlf... | ET,
deadline=60,
headers={'Content-Type': 'application/x-www-form-urlencoded'})
result = json.loads(result.content)
if 'error' not in result:
results[yearForRaster(raster)] = result['histograms'][0]['counts']
return 'respond', decorateWithArgs({
'min_dat... |
HPNetworking/HP-Intelligent-Management-Center | build/lib/pyhpeimc/plat/groups.py | Python | apache-2.0 | 9,544 | 0.006287 | #!/usr/bin/env python3
# author: @netmanchris
# This section imports required libraries
import requests
import json
from pyhpeimc.plat.device import *
HEADERS = {'Accept': 'application/json', 'Content-Type':
'application/json', 'Accept-encoding': 'application/json'}
"""
This section deals with HPE IMC Custom ... | m_view_url
r = requests.get(f_url, auth=auth, headers=headers)
try:
if r.status_code == 200:
custom_view_list = (json.loads(r.text))
if 'customView' in | custom_view_list:
custom_view_list = custom_view_list['customView']
if type(custom_view_list) == dict:
custom_view_list = [custom_view_list]
return custom_view_list
else:
return custom_view_list
except reques... |
gonzolino/heat | heat/tests/clients/test_designate_client.py | Python | apache-2.0 | 11,629 | 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
# ... | ate):
self._client.domains.update.return_value = None
mock_domain = self._get_mock_domain()
self._client.domains.get.return_value = mock_domain
client_designate.return_value = s | elf._client
domain = dict(
id='sample-id',
description='updated description',
ttl=4200,
email='xyz@test-domain.com'
)
self.client_plugin.domain_update(**domain)
self._client.domains.get.assert_called_once_with(
mock_domain.id... |
tadek-project/tadek-common | tests/engine/channels/helpers.py | Python | gpl-3.0 | 5,647 | 0.013813 | ################################################################################
## ##
## This file is a part of TADEK. ##
## ... | testres | ult.TestSuiteResult(id=name, path=_PATH,
parent=parent, attrs=attrs)
def structResult(nsuites=0, ncases=0, nsteps=0):
suites = [suiteResult("Suite%d" % (i + 1)) for i in xrange(nsuites)]
if nsuites:
cases = [caseResult("Case%d" % (i + 1), suite) for i in xrange(nca... |
lxml/lxml | src/lxml/_elementpath.py | Python | bsd-3-clause | 10,742 | 0.001769 | # cython: language_level=2
#
# ElementTree
# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
#
# limited xpath support for element trees
#
# history:
# 2003-05-23 fl created
# 2003-05-28 fl added support for // etc
# 2003-08-27 fl fixed parsing of periods in element names
# 2007-09-10 fl new selection ... | or signature == "-()-":
# [index] or [last()] or [last()-index]
if signature == "-":
# [index]
index = int(predicate[0]) - 1
if index < 0:
if index == -1:
| raise SyntaxError(
"indices in path predicates are 1-based, not 0-based")
else:
raise SyntaxError("path index >= 1 expected")
else:
if predicate[0] != "last":
raise SyntaxError("unsupported function")
... |
eSmelser/SnookR | SnookR/substitutes/migrations/0001_initial.py | Python | mit | 2,900 | 0.004483 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-31 23:57
from __future__ import unicode_literals
import autoslug.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migra | tion(migrations.Migration):
initial = True
dependencies = [
('teams', '0001_initial'),
('accounts', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Division',
fields=[
... | ue, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('slug', autoslug.fields.AutoSlugField(always_update=True, default='', editable=False, populate_from='name')),
('division_rep', models.ForeignKey(on_delete=django.db.mo... |
waheedahmed/edx-platform | lms/djangoapps/discussion_api/tests/test_views.py | Python | agpl-3.0 | 70,488 | 0.001873 | """
Tests for Discussion API views
"""
from datetime import datetime
import json
from urlparse import urlparse
import ddt
import httpretty
import mock
from nose.plugins.attrib import attr
from openedx.core.djangoapps.user_api.accounts.image_helpers import get_profile_image_storage
from pytz import UTC
from django.cor... | )
def test_404(self):
response = self.client.get(
| reverse("course_topics", kwargs={"course_id": "non/existent/course"})
)
self.assert_response_correct(
response,
404,
{"developer_message": "Course not found."}
)
def test_basic(self):
response = self.client.get(self.url)
self.asse... |
StefanoRaggi/Lean | Algorithm.Python/BrokerageModelAlgorithm.py | Python | apache-2.0 | 3,724 | 0.008861 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# 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 Licen... | (2013,10,11) # Set End Date
self.AddEq | uity("SPY", Resolution.Second)
# there's two ways to set your brokerage model. The easiest would be to call
# SetBrokerageModel( BrokerageName ); // BrokerageName is an enum
# SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage);
# SetBrokerageModel(BrokerageName.Default... |
kenorb-contrib/BitTorrent | python_bt_codebase_library/BTL/cpu_meter.py | Python | gpl-3.0 | 4,972 | 0.004023 | # 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.
#
# This program is distributed in the hope that it will be useful,
# bu... | ""
def __init__(self, update_interval = 2):
self.format = win32pdh.PDH_FMT_DOUBLE
self.hcs = []
self.hqs = []
self._setup_query("_Total")
num_cpus = win32api.GetSystemInfo()[4]
for x in xrange(num_cpus):
self._setup_query(x)
CPUMeterBase.__ini... | inum = -1
instance = None
machine = None
object = "Processor(%s)" % which
counter = "% Processor Time"
path = win32pdh.MakeCounterPath( (machine, object, instance,
None, inum, counter) )
hq = win32pdh.OpenQuery()
s... |
ParkJinSang/Logle | sample/mlp_learn.py | Python | mit | 498 | 0.002008 | __author__ = | 'USER'
from learning.mlp.neuralnetwork import NeuralNetwork
from learning.mlp import learning
number_of_layers = 3
size_array = [2, 2, 1]
learning_rate = 0.3
momentum = 0.1
bnn = NeuralNetwork(number_of_layers, size_array, learning_rate, momentum)
xor_in = [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
]
xor_out... | learning.predict(bnn, xor_in)
|
mmpagani/oq-hazardlib | openquake/hazardlib/gsim/fukushima_tanaka_1990.py | Python | agpl-3.0 | 6,500 | 0 | # The Hazard Library
# Copyright (C) 2014 GEM Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Th... | ubclass.
REQUIRES_SITES_PARAMETERS = set(())
#: Required rupture parameters are magnitude
REQUIRES_RUPTURE_PARAMETERS = set(('mag', ))
#: Required distance measure is rupture distance
REQUIRES_DISTANCES = set(('rrup',))
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
... | f input and result values.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
C = self.COEFFS[imt]
imean = (self._compute_magnitude_scaling(C, rup.mag) +
self._compute_distance_scaling(C, dists.rr... |
casnortheast/microbit_stub | bitcounter-range.py | Python | mit | 601 | 0 | from microbit_stub import *
while True:
if button_a.is_pressed():
for i in range(5):
if display.get_pixel(i, 0) | :
display.set_pixel(i, 0, 0)
sleep(10)
else:
display.set_pixel(i, 0, 9)
sleep(200)
break
elif button_b.is_pressed():
n = 0
for i in range(5):
if display.get | _pixel(i, 0):
n = n + 2 ** i
display.clear()
display.show(str(n))
sleep(1000)
display.clear()
break
else:
sleep(50)
|
watchdogpolska/poradnia.siecobywatelska.pl | poradnia/events/migrations/0012_auto_20180601_1104.py | Python | bsd-3-clause | 556 | 0.001799 | # Generated by Django 1.11.13 on 2018-06-01 09:04
from django.db import migrations, models
class Migration(migr | ations.Migration):
dependencies = [("events", "0011_auto_2 | 0180416_0138")]
operations = [
migrations.AlterField(
model_name="event",
name="deadline",
field=models.BooleanField(
default=False,
help_text="A significant event, especially highlighted, for example, in the list of cases.",
... |
sosey/ginga | ginga/gtkw/ImageViewGtk.py | Python | bsd-3-clause | 19,183 | 0.003388 | #
# ImageViewGtk.py -- classes for the display of FITS files in Gtk widgets
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
import sys, os
from ginga.gtkw import gtks... | return True
def size_request(self, widget, requisition):
"""Callback function to request our desired size.
"""
requisition.width, requisition.height = self.get_desired_size()
return True
def set_cursor(self, cur | sor):
win = self.imgwin.get_window()
if win is not None:
win.set_cursor(cursor)
def define_cursor(self, ctype, cursor):
self.cursor[ctype] = cursor
def get_cursor(self, ctype):
return self.cursor[ctype]
def switch_cursor(self, ctype):
... |
fbradyirl/home-assistant | homeassistant/components/volvooncall/device_tracker.py | Python | apache-2.0 | 1,079 | 0 | """Support for tracking a Volvo."""
import logging
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.util import slugify
from . import DATA_KEY, SIGNAL_STATE_UPDATED
_LOGGER = logging.getLogger(__name__)
asyn... | o is None:
retu | rn
vin, component, attr = discovery_info
data = hass.data[DATA_KEY]
instrument = data.instrument(vin, component, attr)
async def see_vehicle():
"""Handle the reporting of the vehicle position."""
host_name = instrument.vehicle_name
dev_id = "volvo_{}".format(slugify(host_name))... |
oomlout/oomlout-OOMP | old/OOMPpart_LEDS_05_I9_STAN_01.py | Python | cc0-1.0 | 242 | 0 | import OOMP
newPart = OOMP.oompItem(9118)
newPart.addTag("oompT | ype", "LEDS")
newPart.addTag("oompSize", "05")
newPart.addTag("oompColor", "I9")
newPart.addTag("oompDesc", "S | TAN")
newPart.addTag("oompIndex", "01")
OOMP.parts.append(newPart)
|
mooja/ssip3 | app/members/views.py | Python | mit | 4,530 | 0.002208 | from io import BytesIO
from django import forms
from django.http import HttpResponse
from django.template import Context, Template
from braces.views import LoginRequiredMixin
from django.views.generic import DetailView, ListView
from django.views.decorators.http import require_http_methods
from django.contrib import... | asswordForm(request.POST)
if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD:
request.session['password'] = pw_form.cleaned_data['password']
return redirect('members:member_list')
messages.error(request, "The password you entered was incorrect, pleas... | ord'] == MEMBERS_PASSWORD):
member_list = Member.objects.all()
return render(request, 'members/member_list.html', {
'member_list': member_list,
})
# password is wrong, render form
pw_form = PasswordForm()
return render(request, 'members/members_password_form.html', {
... |
harambe-dev/harambecoin | contrib/wallettools/walletunlock.py | Python | mit | 159 | 0 | from jsonrpc import ServiceProxy
access = ServiceProxy( | "http://127.0.0.1:52398")
pwd = raw_input("Enter wallet | passphrase: ")
access.walletpassphrase(pwd, 60)
|
aresnick/pynguin | doc/examples_src/threaded_pynd/00015.py | Python | gpl-3.0 | 83 | 0 | d | ef caught(pyn, fpyn):
fx, fy = fpyn.xy()
return pyn.dist | ance(fx, fy) <= 1
|
GutenkunstLab/SloppyCell | Example/Gutenkunst2007/Brown_2004_Rescaled/Nets.py | Python | bsd-3-clause | 1,573 | 0 | from SloppyCell.ReactionNetworks import *
import PC12Network
# Load the network from the XML file
net = PC12Network.baseNetwork
net.set_var_ic('EGF', 0)
net.set_var_ic('NGF', 0)
net.compile()
# Create our various conditions
# Growth factors are set to high saturation.
# EGF stimulation in the wild-type
egf_stim = n... |
ngf_ly = ngf_stim.copy('NGF_LY')
ngf_ly.set_var_ic('kPI3KRas', 0)
ngf_ly.set_var_optimizable('kPI3KRas', False) |
ngf_ly.set_var_ic('kPI3K', 0)
ngf_ly.set_var_optimizable('kPI3K', False)
# NGF stimulation with a dominant-negative Rap1
ngf_DN_Rap1 = ngf_stim.copy('NGF_DN_Rap1')
ngf_DN_Rap1.set_var_ic('kRap1ToBRaf', 0)
ngf_DN_Rap1.set_var_optimizable('kRap1ToBRaf', False)
# NGF stimulation with a dominant-negative Ras
ngf_DN_Ras ... |
elsantodel90/RAAGo | aago_ranking/events/admin.py | Python | gpl-3.0 | 889 | 0.001125 | from django.contrib import admin
from django.forms.widgets import Textarea, TextInput
from django.db.models import TextField, DecimalField
from aago_ranking.games.models import Game
from .models import Event, EventPlayer
# Register your models here.
class EventPlayerInline(admin.TabularInline):
model = EventPl... | ype': 'number'})},
} # yapf: disable
@admin.register(Event)
class EventAdmin(admin.ModelAdmin):
list_display = ('name', 'start_da | te', 'end_date')
inlines = (EventPlayerInline, EventGameInline)
formfield_overrides = {
TextField: {'widget': Textarea(attrs={'rows': 2})}
} # yapf: disable
|
SkierPGP/Skier | migrations/versions/skier_migrate_add_added_time_field.py | Python | agpl-3.0 | 1,319 | 0.013647 | """Add added_time field.
Revision ID: 376c313a482
Revises: 45fdf20fb2f
Create Date: 2015-08-19 16:00:42.264410
"""
# revision identifiers, used by Alembic.
revision = '376c313a482'
down_revision = '45fdf20fb2f'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():... | e', sa.VARCHAR(length=16), autoincrement=False, nullable=True),
sa.Column('key_id', sa.INTEGER(), autoincrement=False, nullable=True),
sa.ForeignKeyConstraint(['key_id'], ['key.id'], name='signature_key_id_fkey'),
| sa.PrimaryKeyConstraint('id', name='signature_pkey')
)
### end Alembic commands ###
|
jackkiej/SickRage | sickbeard/providers/torrent9.py | Python | gpl-3.0 | 4,474 | 0.003576 | # coding=utf-8
# Author: Ludovic Reenaers <ludovic.reenaers@gmail.com>
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage 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... | le, 'link': download_url, 'size': size, 'seeders': seeders, 'leechers': leechers, 'hash': ''}
if mode != 'RSS':
logger.log(u"Found result: {0} with {1} seeders and {2} leechers".format(title, seeders, leechers), logger.DEBUG)
items... | continue
# For each search mode sort all the items by seeders if available
items.sort(key=lambda d: try_int(d.get('seeders', 0)), reverse=True)
results += items
return results
provider = Torrent9Provider()
|
PythonCharmers/python-future | src/future/backports/email/base64mime.py | Python | mit | 3,761 | 0 | # Copyright (C) 2002-2007 Python Software Foundation
# Author: Ben Gertzfield
# Contact: email-sig@python.org
"""Base64 content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
ch... | bytes
from future.builtins import str
__all__ = [
'body_decode',
'body_encode',
'decode',
'decodestring',
'header_encode',
'header_length',
]
from base64 import b64encode
from binascii import b2a_base64, a2b_base64
CRLF = '\r\n'
NL = '\n'
EMPTYSTRING = ''
# See also Charset.py
MISC_LEN ... | rn the length of s when it is encoded with base64."""
groups_of_3, leftover = divmod(len(bytearray), 3)
# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
n = groups_of_3 * 4
if leftover:
n += 4
return n
def header_encode(header_bytes, charset='iso-8859-1'):
"""Encode a s... |
maciekcc/gemmlowp | meta/generators/cc_emitter.py | Python | apache-2.0 | 6,444 | 0.009156 | # Copyright 2016 The Gemmlowp 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 applicable... | '.join(['%s %s' % (t, n) for (t, n) in function_params])))
self.PushIndent()
def EmitFunctionBegin(self, function_name, params, return_type):
self.EmitIndented('%s %s(%s) {' %
(return_type | , function_name,
', '.join(['%s %s' % (t, n) for (t, n) in params])))
self.PushIndent()
def EmitFunctionEnd(self):
self.PopIndent()
self.EmitIndented('}')
self.EmitNewline()
def EmitClassBegin(self, class_name, template_params, specializations,
base_clas... |
brianwc/juriscraper | opinions/united_states/state/pasuperct.py | Python | bsd-2-clause | 590 | 0 | # Scraper for Pennsylvania Supreme Court
# C | ourtID: pasup
# Court Short Name: pasup
# Author: Andrei Chelaru
# Reviewer: mlr
# Date created: 21 July 2014
from juriscraper.opinions.united_states.state import pa
import re
class Site(pa.Site):
def __init__(self):
super(Site, self).__init__()
self.court_id = self.__module__
self.regex ... | es(self):
# Judges for this feed are provided as obscure numbers.
return None
|
pooyapooya/rizpardazande | rizpar/lib/python2.7/site-packages/nanpy/examples/i2c_scanner.py | Python | mit | 494 | 0.004049 | #!/usr/bin/e | nv python
# Description:
from nanpy.arduinotree import ArduinoTree
from nanpy.i2c import I2C_Master
from nanpy.serialmanager import SerialManager
import logging
log = logging.getLogger(__name__)
def main():
connection = SerialManager(sleep_after_connect=2)
connection.open()
print (connection.device)
... | aster = I2C_Master(a.wire)
print (['0x%02x' % x for x in master.scan()])
if __name__ == '__main__':
main()
|
shashanksingh28/code-similarity | userstudy/study/urls.py | Python | mit | 864 | 0 | """study URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas | ed views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
... | rom django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('codereco.urls')),
]
|
danielvdende/VizServe | server.py | Python | apache-2.0 | 3,799 | 0.003159 | import sys
sys.path.append("api")
sys.path.append("util")
from flask import Flask, make_response, request
from flask.ext.cors import CORS
import messages
import api
import json
app = Flask(__name__)
CORS(app)
# GENERAL
@app.errorhandler(404)
def not_found(error):
return make_response(json.dumps(messages.notFou... | 'PUT'])
def update_notebook(notebook_id):
r | eturn make_response(json.dumps(api.update_notebook(notebook_id, request.get_json())))
# Remove a given notebook. This will NOT remove the visualizations created
# within
@app.route("/api/v1.0/notebooks/<notebook_id>", methods=['DELETE'])
def remove_notebook(notebook_id):
return make_response(json.dumps(api.remove... |
marcy-terui/serverless-crypt | handler.py | Python | mit | 243 | 0.00823 | import json
im | port slscrypt
def hello(event, context):
| body = {
"message": slscrypt.get('test'),
"input": event
}
response = {
"statusCode": 200,
"body": json.dumps(body)
};
return response
|
ygol/odoo | addons/product_margin/models/product_product.py | Python | agpl-3.0 | 9,711 | 0.006796 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from odoo import api, fields, models
class ProductProduct(models.Model):
_inherit = "product.product"
date_from = fields.Date(compute='_compute_product_margin_fields_values', string='Margin Date F... | tot_products |= products
for prod in products:
prod_re[prod.id] = re_ind
re_ind += 1
res_val = tot_products._compute_product_margin_fields_values(fiel | d_names=[x for x in fields if fields in fields_list])
for key in res_val:
for l in res_val[key]:
re = res[prod_re[key]]
if re.get(l):
re[l] += res_val[key][l]
else:
re[l] = res_val[key... |
NixaSoftware/CVis | venv/bin/libs/python/pyste/dist/setup.py | Python | apache-2.0 | 331 | 0 | # Copyright Bruno d | a Silva de Oliveira 2006. Distributed under the Boost
# Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
from distutils.core impor | t setup
import py2exe
import sys
sys.path.append('../src')
setup(name='pyste', scripts=['../src/pyste.py'])
|
knowmetools/km-api | km_api/km_api/settings.py | Python | apache-2.0 | 10,854 | 0 | """
Django settings for km_api project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
h | ttps://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/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import logging
import os
import requests
# Ignored warnings:
SILENCED_SYSTEM_CH... | ut not all views
# are paginated.
"rest_framework.W001",
]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
AWS_DEFAULT_REGION = os.environ.get("DJANGO_AWS_REGION", "us-east-1")
# Configure logging to Sentry if a DSN is provided.
SENTRY_DSN = os.environ.get("DJANGO_SENTRY_DSN")
if SEN... |
ctaylo37/OTM2 | opentreemap/treemap/tests/test_images.py | Python | gpl-3.0 | 735 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from PIL import Image
from treemap.images import save_uploaded_image
from treemap.tests import LocalMediaTestCase, media_dir
class SaveImageTest(Loc | alMediaTestCase):
@media_dir
def test_rotates_image( | self):
sideways_file = self.load_resource('tree_sideways.jpg')
img_file, _ = save_uploaded_image(sideways_file, 'test')
expected_width, expected_height = Image.open(sideways_file).size
actual_width, actual_height = Image.open(img_file).size
self.assertEquals(expected_width, act... |
edigiacomo/asgi-mqtt | setup.py | Python | gpl-2.0 | 1,376 | 0.000727 | import os.path
import re
from setuptools import setup
def get_version(package):
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("^__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
setup(
name="asgimqtt",
version=get_version("asgimqtt"),
author="Emanuele Di Giacom... | 'Framework :: Django',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Progra... | :: Internet :: WWW/HTTP',
]
)
|
chetan51/nupic | examples/prediction/experiments/generated_data/description.py | Python | gpl-3.0 | 4,064 | 0.026329 | from nupic.encoders import (LogEncoder, DateEncoder, MultiEncoder, ScalarEncoder)
from nupic.data import FunctionSource
from nupic.frameworks.prediction.callbacks import displaySPCoincidences, printSPCoincidences
from nupic.data.dictutils import DictObj
nCoincidences = 30
iterationCount = 10000
nRandomFields = 1
ra... |
if 20 <= t.hour < 23:
p = 1.0 - p
if random.random() < p:
amount = random.randint(100, 1000)
else:
amount = random.randint(1, 10)
# Dictionary keys must match the names in the multiencoder
d["date"] = t
d["amount"] = amount
for i in xrange(info['nRandomFields']):
d["random%d" %i] = rando... | rn dict()
def getDatasets(baseDatasets, generate=False):
return baseDatasets
def getDescription(datasets):
encoder = MultiEncoder()
encoder.addEncoder("date", DateEncoder(timeOfDay=3))
encoder.addEncoder("amount", LogEncoder(name="amount", maxval=1000))
for i in xrange(0, nRandomFields):
s = ScalarEncod... |
warmsea/tc-srm | srm146/Yahtzee.py | Python | mit | 340 | 0 | """
http://community.topcoder.com/stat?c=proble | m_statement&pm=1692
Single Round Match 146 Round 1 - Division II, Level One
Single Round Match 212 Round 1 - Division II, Level One
"""
class Yahtzee:
def maxPoints(self, toss): |
sums = [0] * 7
for value in toss:
sums[value] += value
return max(sums)
|
mousepawgames/diamondquest | src/diamondquest/model/menu/menu.py | Python | gpl-3.0 | 8,321 | 0 | """
Menu Model [DiamondQuest]
Defines a menu.
Author(s): Wilfrantz Dede, Jason C. McDonald, Stanislav Schmidt
"""
# LICENSE (BSD-3-Clause)
# Copyright (c) 2020 MousePaw Media.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the... | stener to remove.
Returns
-------
status : bool
If the listener was found and removed th | en True is
returned, otherwise False.
"""
if listener in self.key_down_listeners[key]:
self.key_down_listeners[key].remove(listener)
return True
else:
return False
def handle_key_press(self, key):
"""Handle key presses when this item i... |
GETLIMS/LIMS-Backend | lims/workflows/migrations/0030_auto_20180306_1110.py | Python | mit | 1,035 | 0.001932 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-03-06 11:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('workflows', '0029_tasktemplate_product_input_not_required')... | terField(
model_name='tasktemplate',
name='product_input',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='product_input', to='inventory.ItemType'),
),
migrations.AlterField(
model_name='tasktemplate',
... | e',
name='product_input_measure',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='inventory.AmountMeasure'),
),
]
|
lyoung13/deep-learning-nanodegree | p4-language-translation/problem_unittests.py | Python | mit | 13,363 | 0.004269 | import numpy as np
import tensorflow as tf
import itertools
import collections
import helper
def _print_success_message():
print('Tests Passed')
def test_text_to_ids(text_to_ids):
test_source_text = 'new jersey is sometimes quiet during autumn , and it is snowy in april .\nthe united states is u... | st parfois calme pendant l\' automne , et il est neigeux en avril .\nles états-unis est généralement froid en juillet , et il gèle habituellement en novembre .\ncalifornia est généralement calme en mars , et il est généralement chaud en juin .\nles états-unis est parfois légère en juin , et il fait froid en septembre .... | test_target_text = test_target_text.lower()
source_vocab_to_int, source_int_to_vocab = helper.create_lookup_tables(test_source_text)
target_vocab_to_int, target_int_to_vocab = helper.create_lookup_tables(test_target_text)
test_source_id_seq, test_target_id_seq = text_to_ids(test_source_text, test_tar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.