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 |
|---|---|---|---|---|---|---|---|---|
mcgonagle/ansible_f5 | library/bigip_snmp_trap.py | Python | apache-2.0 | 13,740 | 0.000509 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | ate(self):
self._set_changed_options()
if self.client.check_mode:
return True
if all(getattr(self.want, v) is None for v in self.required_resources): |
raise F5ModuleError(
"You must specify at least one of "
', '.join(self.required_resources)
)
self.create_on_device()
return True
def should_update(self):
result = self._update_changed_options()
if result:
return T... |
aniruddhasanyal/idea_pot | manage.py | Python | mit | 805 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "anigma1.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
... | "forget to activate a virtual environment?"
)
raise
ex | ecute_from_command_line(sys.argv)
|
lituan/tools | pdb_download.py | Python | cc0-1.0 | 4,472 | 0.009615 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import urllib
import urllib2
import httplib
import lxml.etree as et
def check_pdb_status(pdbids):
"""Returns the status and up-to-date entry in the PDB for a given PDB ID"""
pdbids = [p.upper() for p in pdbids]
pdbids = ','.join(pdbids)
... | replace_pdbids = [r[2] for r in results if r[1] == 'OBSOLETE']
obsolete = [r for r in results if r[1] == 'OBSOLETE']
unknown = [r for r in results if r[1] == 'UNKNOWN']
if obsolete:
with open('obsolete.txt','w') as w_f:
for r in obsolete:
... | ,'status','replaceby')
print >> w_f,'{0:<10}{1:<10}{2:<10}'.format(r[0],r[1],r[2])
if unknown:
with open('unknown.txt','w') as w_f:
for r in unknown:
print >> w_f,'unknown pdb ids'
for p in unknown:
... |
hjhjw1991/monkeyJ | monkey_playback.py | Python | mit | 50,743 | 0.004809 |
<!DOCTYPE html>
<html lang="en" class="">
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object# article: http://ogp.me/ns/article# profile: http://ogp.me/ns/profile#">
<meta charset='utf-8'>
<link crossorigin="anonymous" href="https://assets-cdn.github.com/ass... | racle2k/a | ndroid-platform_sdk/commits/master.atom" rel="alternate" title="Recent Commits to android-platform_sdk:master" type="application/atom+xml">
<link rel="canonical" href="https://github.com/miracle2k/android-platform_sdk/blob/master/monkeyrunner/scripts/monkey_playback.py" data-pjax-transient>
</head>
<body ... |
eshijia/magnum | magnum/common/clients.py | Python | apache-2.0 | 8,321 | 0 | # Copyright 2014 - Rackspace Hosting.
#
# 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... | ion_name')
endpoint = self.url_for(service_type='compute',
| endpoint_type=endpoint_type,
region_name=region_name)
|
XXLRay/libreshot | libreshot/blender/scripts/lens_flare.py | Python | gpl-3.0 | 7,662 | 0.014357 | # OpenShot Video Editor is a program that creates, modifies, and edits video files.
# Copyright (C) 2009 Jonathan Thomas
#
# This file is part of OpenShot Video Editor (http://launchpad.net/openshot/).
#
# OpenShot Video Editor is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | cene.render.frame_map_old = 1
bpy.context.scene.render.frame_map_new = animation_speed
if params["start_frame"] == params["end_frame"]:
bpy.context.scene.frame_start = params["end_frame"]
bpy.context.scene.frame_end = params["end_frame"]
# Render the current animation to the params["output_path"] folder
bpy.ops.rend... | ion=params["animation"])
|
liosha2007/temporary-groupdocs-python3-sdk | groupdocs/models/GetJobDocumentsResponse.py | Python | apache-2.0 | 1,161 | 0.007752 | #!/usr/bin/env python
"""
Copyright 2012 GroupDocs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Yo | u may obtain a copy of the License at
http:/ | /www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permiss... |
syed/PerfKitBenchmarker | perfkitbenchmarker/disk.py | Python | apache-2.0 | 4,302 | 0.005114 | # Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | uper(BaseDisk, self).__init__()
self.disk_size = disk_spec.disk_size
| self.disk_type = disk_spec.disk_type
self.mount_point = disk_spec.mount_point
self.num_striped_disks = disk_spec.num_striped_disks
# Linux related attributes.
self.device_path = disk_spec.device_path
# Windows related attributes.
# The disk number corresponds to the order in which disks w... |
rbuffat/pyidf | tests/test_componentcostreference.py | Python | apache-2.0 | 3,417 | 0.004975 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.economics import ComponentCostReference
log = logging.getLogger(__name__)
class TestComponentCostReference(unittest.TestCase):
def setUp(self):
self.fd, self.path =... | e_building_permits_bonding_and_insurance
# real
var_reference_building_commissioning_fee = 7.7
obj.reference_building_commissioning_fee = var_reference_building_commissioning_fee
# real
var_reference_building_regional_adjustment_factor = 8.8
obj.reference_building_regiona... | ence_building_regional_adjustment_factor
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertAlmostEqual(idf2.componentcostref... |
iamkingmaker/cointrol | cointrol/trader/strategies.py | Python | mit | 2,030 | 0 | """
Implementation of various trading strategies.
"""
from cointrol.core.models import (
Order, TradingSession,
RelativeStrategyProfile, FixedStrategyProfile
)
class TradeAction:
BUY, SELL = Order.BUY, Order.SELL
def __init__(self, action, price):
self.action = action
self.price = p... | rn '{action} at ${price}'.format(
action=Order.TYPES[self.action],
price=self.price
)
class BaseTradingStrategy:
def __init__(self,
session: TradingSession,
last_order: Order):
self.session = sessi | on
self.profile = session.profile
self.last_order = last_order
def get_trade_action(self) -> TradeAction:
if self.last_order.type == Order.SELL:
return TradeAction(action=Order.BUY,
price=self.get_buy_price())
else:
return Trade... |
PuZZleDucK/pixelated-user-agent | service/pixelated/adapter/mailstore/leap_mailstore.py | Python | agpl-3.0 | 15,900 | 0.002138 | #
# Copyright (c) 2015 ThoughtWorks, Inc.
#
# Pixelated 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.
#
# Pixelated is distrib... | None, tags=set(), flags=set(), body=None, attachments=[]
return LeapMail(None, None, headers, tags, set(), body, attachments)
def _extract_filename(content_disposition):
match = re.compile('.*name=\"(.*)\".*').search(content_disposition)
filename = ''
if match:
filename = m | atch.group(1)
return filename
class LeapMailStore(MailStore):
__slots__ = ('soledad')
def __init__(self, soledad):
self.soledad = soledad
@defer.inlineCallbacks
def get_mail(self, mail_id, include_body=False):
message = yield self._fetch_msg_from_soledad(mail_id)
if not _... |
Garyuten/nasutoma_switch | examples/echo_client.py | Python | mit | 472 | 0.002119 | from __future__ import print_function
import websocket
if __name__ == "__main__":
w | ebsocket.enableTrace(True)
ws = websocket.create_connection("ws://nasutoma-here.cgfm.jp:8000/demo")
# ws = websocket.create_connection("ws://nasutoma-here.cgfm.jp:800 | 0", http_proxy_port=8000)
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
|
claudep/translate | translate/storage/test_txt.py | Python | gpl-2.0 | 1,434 | 0 | #!/usr/bin/env python
from translate.misc import wStringIO
from translate.storage import test_monolingual, txt
class TestTxtUnit(test_monolingual.TestMonolingualUnit):
UnitClass = txt.TxtUnit
class TestTxtFile(test_monolingual.TestMonolingualStore):
StoreClass = txt.TxtFile
def txtparse(self, txtsourc... | urce)
assert len(txtfile.units) == 3
print(txtsource)
print(txtfile.serialize())
| print("*%s*" % txtfile.units[0])
assert txtfile.serialize() == txtsource
assert self.txtregen(txtsource) == txtsource
|
cyberbikepunk/smurfs | geodjango_smurfs/wsgi.py | Python | gpl-2.0 | 409 | 0 | """
WSGI config for geodjango_smurfs project.
It e | xposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "geodjango_smurfs.settings") |
application = get_wsgi_application()
|
MarvinMenzerath/PiFace | hangman.py | Python | gpl-3.0 | 8,035 | 0.005352 | #!/usr/bin/python3
import sys
from time import sleep
from random import randint
import pifacecad
import pifacecad.tools
from pifacecad.lcd import LCD_WIDTH
WORDS = ["piface", "raspberrypi", "pferd", "eier", "schnitzel", "hund", "knopf", "vogelei"]
TOP_LEFT_INDEX, TOP_MIDDLE_INDEX, TOP_RIGHT_INDEX = range(3)
BOTTOM_L... | 0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]),
'bottom-left': pifacecad.LCDBitmap(
[0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x1f]),
'bottom-middle': pifacecad.LCDBitmap(
[0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1f]),
'bottom-right': pifacecad.LCDBitmap(
[0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x18]),
... | 0x4, 0xe, 0xa, 0xe]),
'top-right': pifacecad.LCDBitmap(
[0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0]),
'bottom-left': pifacecad.LCDBitmap(
[0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x1f]),
'bottom-middle': pifacecad.LCDBitmap(
[0x4, 0x4, 0x4, 0x0, 0x0, 0x0, 0x0, 0x1f]),
'bottom-right': pif... |
AsherYang/ThreeLine | server/ffstore/db/AdminDao.py | Python | apache-2.0 | 1,494 | 0.005124 | #! /usr/bin/python
# -*- coding:utf-8 -*-
"""
Author: AsherYang
Email: ouyangfan1991@gmail.com
Date: 2018/6/27
Desc: 后台管理数据库操作类
"""
import sys
sys.path.append('../')
from util import DbUtil
from util.DateUtil import DateUtil
class AdminDao:
def __init__(self):
pass
# 根据管理员电话号码查询管理员信息
def q... | _tel)
| return DbUtil.update(update)
|
akx/shoop | shoop/discount_pricing/admin_form_part.py | Python | agpl-3.0 | 2,820 | 0.000355 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
from djang... | d(self, shop):
name = self._get_field_name(shop)
return self[name]
class DiscountPricingFormPart(FormPart):
priority = 10
def get_form_defs(self):
yield TemplatedFormDef(
name="discount_pricing",
form_class=DiscountPricingForm,
template_name="shoop/... | form["discount_pricing"].save()
|
brainstorm/bcbio-nextgen-vm | bcbiovm/clusterk/clusterktasks.py | Python | mit | 3,627 | 0.004136 | """Run individual tasks within the Clusterk framework.
"""
import os
import shutil
im | port subprocess
import uuid
import yaml
from bcbio import utils
from bcbio.provenance import do
from bcbiovm.ship import pack, reconstitute
def runfn( | fn_name, queue, wrap_args, parallel, run_args):
"""Run external function submitting to existing queue.
"""
testing = True
run_id = uuid.uuid4()
work_dir = os.getcwd()
script_file = "bcbio-%s-%s-run.sh" % (fn_name, run_id)
arg_file = "bcbio-%s-%s-args.json" % (fn_name, run_id)
parallel_fi... |
virt-who/virt-who | tests/test_log.py | Python | gpl-2.0 | 6,445 | 0.000621 | from __future__ import print_function
"""
Test for the log module of virt-who.
Copyright (C) 2015 Christopher Snyder <csnyder@redhat.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either versi... | e_logger')
@patch('logging.FileHandler._open')
def test_get_logger_no_config(self, open, getQueueLogger, isdir):
open.return_value = None
isdir.return_value = True
queueLogger = log.QueueLogger('virtwho')
queueLogger.logger.handlers = []
mockQueueLogger = Mock(wraps=queue... | er
conf_values = {
'global': {
'debug': False,
'background': True,
'log_file': log.DEFAULT_LOG_FILE,
'log_dir': log.DEFAULT_LOG_DIR,
'log_per_config': False
}
}
config = StubEffectiveConfig(co... |
swcarpentry/amy | config/urls.py | Python | mit | 6,323 | 0.004112 | """amy URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vie... |
path('workshops/', RedirectView.as_view(pattern_name='dispatch')),
path('workshops/admin-dashboard/', RedirectView.as_view(pattern_name='admin-dashboard')),
path('workshops/trainee-dashboard/', RedirectView.as_v | iew(pattern_name='trainee-dashboard')),
path('workshops/trainee-dashboard/training_progress/', RedirectView.as_view(pattern_name='training-progress')),
path('workshops/autoupdate_profile/', RedirectView.as_view(pattern_name='autoupdate_profile')),
path('workshops/training_requests/', RedirectView.as_view(p... |
cauebs/cineminha-bot | fetch.py | Python | gpl-3.0 | 4,972 | 0.033011 | import requests
from requests.utils import quote
from bs4 import BeautifulSoup
from telegram import Emoji, InlineQueryResultArticle, InlineQueryResultPhoto, InputTextMessageContent
import os, strings
lang = os.environ.get('lang')
def serialize(near, date=0, time=0, sort=0, q='', id=''):
url = "http://google.com/mov... | ion")[1]
for i in div.children:
label = i.get_text().replace('›','').strip()
try:
for param in i.a['href'].split('&'):
if 'date' in param:
identifier = param.split('=')[1]
except:
identifier = "current"
days.append((label,identifier))
response.append(days)
if len(body) > | 0:
for div in body[0].children:
parent = {}
parent["type"] = div["class"][0]
parent["name"] = div.h2.get_text()
parent["id"] = div.a['href'].split('&')[-1]
if parent["type"] == "movie":
infos = div.find_all("div", class_="info")
if infos[0]["class"] == ["info"]:
parent["info"] = infos[0].... |
lowks/camlipy | camlipy/tests/test_camlipy.py | Python | mit | 3,051 | 0.002294 | # -*- encoding: utf-8 -*-
__author__ = 'Thomas Sileo (thomas@trucsdedev.com)'
import unittest
import os
import tempfile
from camlipy.tests import CamliPyTestCase
class TestCamliPy(CamliPyTestCase):
def testPutBlobStr(self):
test_blob_str = os.urandom(4096)
resp = self.server.put_blobs([test_bl... |
blob_size = int( | (max_upload_size / 1000) * 1.5 / nb_blobs)
test_blobs = [os.urandom(blob_size) * 1000 for i in xrange(blob_size)]
test_blobs_br = set([self.compute_hash(b) for b in test_blobs])
resp = self.server.put_blobs(test_blobs)
self.assertEqual(test_blobs_br, set([r['blobRef'] for r in resp['rece... |
marinamarina/sure-thing | migrations/versions/4ccfe9c1b8fa_.py | Python | gpl-3.0 | 1,149 | 0.013055 | """empty message
Revision ID: 4ccfe9c1b8fa
Revises: 1391ee426d4
Create Date: 2014-12-23 12:56:44.406087
"""
# revision identifiers, used by Alembic.
revision = '4ccfe9c1b8fa'
down_revision = '1391ee426d4'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - pl... | ges', 'author_id')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('mess | ages', sa.Column('author_id', sa.INTEGER(), nullable=True))
op.add_column('matches', sa.Column('played', sa.BOOLEAN(), nullable=True))
op.add_column('matches', sa.Column('match_ft_score', sa.VARCHAR(length=8), nullable=True))
op.add_column('matches', sa.Column('actual_winner', sa.INTEGER(), nullable=True))
... |
pbanaszkiewicz/amy | amy/workshops/migrations/0216_workshoprequest_instructor_availability.py | Python | mit | 625 | 0.0016 | # Genera | ted b | y Django 2.2.13 on 2020-08-09 14:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0215_auto_20200808_1356'),
]
operations = [
migrations.AddField(
model_name='workshoprequest',
name='instructor_ava... |
rafalo1333/kivy | kivy/cache.py | Python | mit | 7,962 | 0 | '''
Cache manager
=============
The cache manager can be used to store python objects attached to a unique
key. The cache can be controlled in two ways: with a object limit or a
timeout.
For example, we can create a new cache with a limit of 10 objects and a
timeout of 5 seconds::
# register a new Cache
Cach... | ']:
continue
heapq.heappush(heap_list, (obj['lastaccess'], key))
print('<<<', obj['lastaccess'])
n = 0
while n < maxpurge:
try:
lastaccess, key = heapq.heapp | op(heap_list)
print('=>', key, lastaccess, Clock.get_time())
except Exception:
return
del Cache._objects[category][key]
@staticmethod
def _purge_by_timeout(dt):
curtime = Clock.get_time()
for category in Cache._objects:
if cat... |
nicorikken/freedomvote | app/core/migrations/0004_politician_user.py | Python | gpl-3.0 | 582 | 0.001718 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0003_auto_20150521_0856' | ),
]
operations = [
migrations.AddField(
model_name='politician',
name='user',
field=models.ForeignKey(default=1, verbose_name='user', to=settings. | AUTH_USER_MODEL),
preserve_default=False,
),
]
|
JohnVinyard/zounds | zounds/ui/featureparser.py | Python | mit | 1,790 | 0 | import ast
class ExpressionVisitor(ast.NodeVisitor):
def __init__(self, document, locals):
super(ExpressionVisitor, self).__init__()
self.locals = locals
self.document = document
self.feature_name = None
self.doc = None
@p | roperty
def result(self):
if self.feature_name:
feature = self.document.features[self.feature_name]
else:
feature = None
return self.doc, feature
def visit_Expr(self, node):
| if self.document is None:
raise ValueError()
children = list(ast.iter_child_nodes(node))
if len(children) != 1:
raise ValueError()
feature_name = None
child = children[0]
if isinstance(child, ast.Attribute) \
and child.attr in self.d... |
minfun/leetcode | notes/data_structure_linked_list.py | Python | mit | 2,160 | 0.000463 | class LinkedList():
def __init__(sel | f, value=None):
self.value = value
self.before = None
self.behind = None
def __str__(self):
if self.value is not None:
return str(self.value)
else:
return 'None'
def init():
return LinkedList('HEAD')
def delete(linked_list):
if isinstance(... | st, LinkedList):
if linked_list.behind is not None:
delete(linked_list.behind)
linked_list.behind = None
linked_list.before = None
linked_list.value = None
def insert(linked_list, index, node):
node = LinkedList(node)
if isinstance(linked_list, LinkedList):
... |
livef1/Livef1-web | src/item.py | Python | gpl-2.0 | 2,348 | 0.024276 | #
| # livef1
#
# f1item.py | - Storage class for the drivers information
#
# Copyright (c) 2014 Marc Bertens <marc.bertens@pe2mbs.nl>
#
# 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 Licen... |
aliakseis/LIII | src/3rdparty/torrent-rasterbar/examples/run_benchmarks.py | Python | mit | 14,944 | 0.027637 | #!/usr/bin/env python
import sys
import os
import resource
import shutil
import shlex
import time
import subprocess
import random
import signal
import hashlib
# this is a disk I/O benchmark script. It runs menchmarks
# over different filesystems, different cache sizes and
# different number of peers (can be used to f... | mountpoint = c[2]
prefix = prefix_len( | path, mountpoint)
if prefix > max_match_len:
max_match_len = prefix
match_device = device
device = match_device
device = device.split('/')[-1][0:3]
print 'device for path: %s -> %s' % (path, device)
return device
def build_target_folder(config):
test = 'seed'
if config['test'] == 'upload': test = 'downl... |
kustodian/ansible | lib/ansible/modules/storage/netapp/na_ontap_cluster_peer.py | Python | gpl-3.0 | 12,647 | 0.003242 | #!/usr/bin/python
# (c) 2018-2019, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | s:
state:
choices: ['present', 'absent']
description:
- Whether the specified cluster peer should exist or not.
default: present
source_intercluster_lifs:
description:
- List of intercluster addresses of the source cluster.
- Used as peer-addresses in destination cluster.
- A... | hese intercluster lifs should belong to the source cluster.
version_added: "2.8"
aliases:
- source_intercluster_lif
dest_intercluster_lifs:
description:
- List of intercluster addresses of the destination cluster.
- Used as peer-addresses in source cluster.
- All these intercluster l... |
sanjaymandadi/mozu-python-sdk | test/functional_test/security_test/appauthenticator_test.py | Python | apache-2.0 | 619 | 0.016155 | import unittest
import logging
from mozurestsdk.security.appauthenticator import AppAuthenticator;
from mozurestsdk.config impo | rt __baseUrl__
class AppAuthenticator_Test(unittest.TestCase):
def test_authenticate(self):
logging.basicConfig(level=logging.INFO)
authenticator = AppAuthenticator("mzint.sdk.1.0.0.release","32223d1c8c694c9196e95a032bb100b5",__baseUrl__, False);
auth = authenticator.authenticate();
... | Token"]);
self.assertIsNotNone(authenticator.auth["refreshToken"]);
if __name__ == '__main__':
unittest.main()
|
kimvais/nimismies | nimismies/__init__.py | Python | mit | 1,159 | 0 | #
# -*- coding: utf-8 -*-
#
# Copyright © 2013 Kimmo Parviainen-Jalanko <k@77.fi>
#
# 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 right... | shed to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES O... | Y CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
version = '0.0.1'
|
ayys/siya | settings/templatetags/nepali.py | Python | gpl-3.0 | 2,133 | 0.002344 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import template
import string
from settings.models import Globals
from head.templatetags.bookFilters import to_bs
import datetime
register = template.Library()
@register.filter(name="no_to_np")
def no_to_np(value):
'''
convert ... | alue.lower().replace(" ", "_")
out_val = ""
for _ in value:
if _ in string.ascii_lowercase + string.ascii_uppercase or _ == "_":
out_val += _
while len(out_val) > 1 and out_val[0] not in string.ascii_lowercase + string.ascii_uppercase + "".join([unicode(_) for _ in ra... | nd the text correspondent
return text
else:
values = raw_value.split(" ")
out_val = []
for _ in values:
_ = "".join([char for char in _ if char in string.ascii_lowercase+string.ascii_uppercase+"".join([unicode(int) for int in range(0,10)]) or _ == ... |
nunataksoftware/anayluistango | contact_form/tests/forms.py | Python | mit | 2,154 | 0.001857 | from django.conf import settings
from django.core import mail
from django.test import RequestFactory
from django.test import TestCase
from django.contrib.sites.models import Site
from contact_form.forms import ContactForm
class ContactFormTests(TestCase):
def test_request_required(self):
"""
Can... | (self):
# """
# Sites integration works with or without installed
# contrib.sites.
# """
# old_installed = Site._meta.installed
# Site._meta.installed = | False
# request = RequestFactory().request()
# data = {'name': 'Test',
# 'email': 'test@example.com',
# 'message': 'Test message'}
# form = ContactForm(request=request, data=data)
# self.assertTrue(form.is_valid())
# form.save()
# self.as... |
andresriancho/w3af-webui | src/w3af_webui/tests/test_view.py | Python | gpl-2.0 | 6,559 | 0.002592 | #-*- coding: utf-8 -*-
from mock import patch
from django.conf import settings
from django.test import TestCase
from django_any.models import any_model
from django.utils import unittest
from django.contrib.auth.models import User
from django.test.client import Client
from django.test.client import RequestFactory
from ... | anTask
from w3af_w | ebui.models import Target
from w3af_webui.models import ScanProfile
from w3af_webui.models import Scan
from w3af_webui.models import Vulnerability
from w3af_webui.views import get_select_code
from w3af_webui.views import show_report
from w3af_webui.views import show_report_txt
from w3af_webui.views import user_settings... |
juanchopanza/pyhistuples | pyhistuples/pysequence.py | Python | lgpl-3.0 | 763 | 0.011796 | ''' Helpers functions and classes for sequence manipulation.
'''
__author__ = "Juan Palacios <juan.palacios@nikhef.nl>"
__all__ = ('isiterable',
'flattenList')
def isIterable(obj) :
'''
Test if an object is iterable but not a string type.
'''
return hasattr(obj, "__iter__") and not isinstanc... | on-iterable elements retrieved tree and tree's sub-trees.
"""
flatList = []
for member in tree :
if isIterable(member) :
flatList.extend(flattenList(member))
else :
flatList.append(member)
return flatList
| |
KaranToor/MA450 | google-cloud-sdk/lib/googlecloudsdk/command_lib/ml/local_predict.py | Python | apache-2.0 | 3,662 | 0.008738 | # Copyright 2016 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 ag... | xcept (NameError, AttributeError) as e:
eprint('Error while getting the installed Cloudml SDK version: ', e,
'\n', VERIFY_CLOUDML_VERSION)
packages_ok = False
return packages_ok
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model- | dir', required=True, help='Path of the model.')
args, _ = parser.parse_known_args()
if not _has_required_package():
sys.exit(-1)
instances = []
for line in sys.stdin:
instance = json.loads(line.rstrip('\n'))
instances.append(instance)
# pylint: disable=g-import-not-at-top
from google.cloud.ml ... |
mazaclub/mazabot-core | plugins/Factoids/config.py | Python | bsd-3-clause | 4,152 | 0.002649 | ###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2009, James Vega
# 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 copyri... | THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
import supybot.conf as conf
import supybot.registry as registry
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified himself as an ... | ating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Factoids', True)
class FactoidFormat(registry.TemplatedString):
"""Value must include $value, otherwise the factoid's value would be left
out."""
requiredTemplates = ['value']... |
google-research/google-research | psycholab/examples/prisoners_dilemma.py | Python | apache-2.0 | 3,208 | 0.015586 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | choice(range(env.num_actions), env.num_players)
# Environment step:
obs, rewards, done, info = env.step(actions)
new_state = env.discrete_state(obs)
transitions.append((state, new_state, rewards, actions, done, info))
state = new_state
# Sum rewards:
returns += rewards
if done:
# ... | s finished:
episode += 1
print('episode', episode, 'returns', returns)
# Reset env for new episode
obs = env.reset()
# state = env.discrete_state(obs)
returns = 0
# Close visualizer:
env.finish()
if __name__ == '__main__':
game_env = create_game()
run_game(game_env, max_ste... |
apinski-cavium/mcrouter | mcrouter/test/test_shadow.py | Python | bsd-3-clause | 7,398 | 0.000135 | # Copyright (c) 2015, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import absolute_... | ) == value)
if key i | n shadow_keys:
self.assertEqual(self.mc_foo_shadow.get(key), value)
self.assertEqual(self.mc_bar_shadow.get(key), value)
else:
self.assertIsNone(self.mc_foo_shadow.get(key))
self.assertIsNone(self.mc_bar_shadow.get(key))
def test_regional_... |
ATIX-AG/foreman-ansible-modules | plugins/modules/subscription_manifest.py | Python | gpl-3.0 | 5,027 | 0.002785 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Andrew Kofink <ajkofink@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | e_task_errors=True)
for error in result['humanized']['errors']:
if "same as existing data" in error:
# Nothing changed, but everything ok
break
if "older than existing data" in error:
... | Upload of the manifest failed: %s" % error)
else:
module.set_changed()
except IOError as e:
module.fail_json(msg="Unable to read the manifest file: %s" % e)
elif module.desired_absent and existing_manifest:
module.resource_actio... |
telegraphic/allantools | examples/gradev-demo.py | Python | gpl-3.0 | 1,437 | 0.059847 | import matplotlib.pyplot as plt
import numpy as np
import allantools as allan
def example1():
"""
Compute the GRADEV of a white phase noise. Compares two different
scenarios. 1) The original data and 2) ADEV estimate with gap robust ADEV.
"""
N = 1000
f = 1
y = np.random.randn(1,N)[0,:]
x = np.linspace(1,len(... | y white phase noise.
"""
N=1000 # number of samples
f = 1 # d | ata samples per second
s=1+5/N*np.arange(0,N)
y=s*np.random.randn(1,N)[0,:]
x = np.linspace(1,len(y),len(y))
x_ax, y_ax, err_l, err_h, ns = allan.gradev(y,f,x)
plt.loglog(x_ax, y_ax,'b.',label="No gaps")
y[int(0.4*N):int(0.6*N,)] = np.NaN # Simulate missing data
x_ax, y_ax, err_l, err, ns = allan.gradev(y,f,x)
... |
stefanw/froide | froide/foirequestfollower/forms.py | Python | mit | 1,957 | 0.000511 | from django import forms
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from froide.account.forms import user_extra_registry
from froide.foirequest.auth import can_read_foirequest
from froide.helper.spam import SpamProtectionMixin
from .models import FoiRequestFo... | email is None:
raise forms.Valida | tionError(_("Missing email address!"))
if not can_read_foirequest(self.foirequest, self.request):
raise forms.ValidationError(_("You cannot access this request!"))
if self.user == self.foirequest.user:
raise forms.ValidationError(_("You cannot follow your own requests."))
... |
Tythos/hypyr | data/__init__.py | Python | mit | 294 | 0.034014 | """Interface for package data stored in the "data" folder
"""
import os
def get_path(data_path):
return os.path.dirname(os.path | .realpath(__file__)) + os.sep + | data_path
def get_text(data_path):
p = get_full_path(data_path)
f = open(p, 'r')
content = f.read()
f.close()
return content
|
rudhir-upretee/Sumo17_With_Netsim | tools/trip/route2trips.py | Python | gpl-3.0 | 2,364 | 0.002961 | #!/usr/bin/env python
"""
@file route2trips.py
@author Michael Behrisch
@author Daniel Krajzewicz
@date 2008-03-19
@version $Id: route2trips.py 13811 2013-05-01 20:31:43Z behrisch $
This script converts SUMO routes back into SUMO trips which serve
as input to one of the routing applications.
It reads the route... | R (http://www.dlr.de/) and contributors
All rights reserved
"""
import sys, datetime
from xml.sax import parse, h | andler
class RouteReader(handler.ContentHandler):
def __init__(self):
self._vType = ''
self._vID = ''
self._vDepart = 0
self._routeID = ''
self._routeString = ''
self._routes = {}
def startElement(self, name, attrs):
if name == 'vehicle':
... |
0x0mar/the-backdoor-factory | intel/WinIntelPE32.py | Python | bsd-3-clause | 36,465 | 0.006637 | '''
Copyright (c) 2013-2014, Joshua Pitts
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 conditions and t... | strip("L")), 16))
else:
self.shellcode2 += struct.pack("<I", int(str(hex(0xffffffff - len(self.shellcode2) -
breakupvar + 241).rstrip("L")), 16))
else:
self.shellcode2 += struct.pack("<I", int(str(hex(... | self.shellcode2 = "\xE8\xB7\xFF\xFF\xFF"
#Can inject any shellcode below.
self.shellcode2 += ("\xFC\xE8\x89\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B\x52"
|
tjcsl/director | web3/apps/sites/migrations/0007_auto_20161119_1617.py | Python | mit | 544 | 0.001838 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-19 16:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
d | ependencies = [
('sites', '0006_auto_20161119_0044'),
]
operations = [
migrations.AlterField(
model_name='site',
name='purpose',
field=models.CharField(choices=[('legacy', 'legacy'), ('user', 'user'), ('activity', 'activity'), | ('other', 'other')], max_length=16),
),
]
|
ARM-software/bob-build | config_system/tests/test_type_strictness.py | Python | apache-2.0 | 5,231 | 0.000574 | # Copyright 2020 Arm Limited.
# SPDX-License-Identifier: Apache-2.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 a... | },
"Select option must have type bool but got type string instead"
),
(
{ # select with the right type (bool)
| "expr": "select OPTION_1",
},
None
),
(
{ # select with the wrong type (string)
"expr": "select OPTION_2 if OPTION_1",
},
"Select option must have type bool but got type string instead"
),
(
{ # select with the wrong type (int)
"e... |
soerendip42/rdkit | rdkit/sping/Pyart/pidPyart.py | Python | bsd-3-clause | 9,314 | 0.009878 | # lots to do:
# __ native drawLines
# __ add native drawCurve method
# __ native rectangle/round rect method
# __ native drawEllipse
# __ native drawArc
# __ drawImage support (work on Pyart side of things)
from __future__ import print_function
import pyart
from rdkit.sping.pid import *
from rdkit.sping... |
def __init__(self,size=(300,300),name='PyartCanvas.png'):
self._pycan = pyart.Canvas(size[0], size[1], dpi=72)
self.filename = name
Canvas.__init__(self, size, name)
# self.defaultFillC | olor = transparent
# now we need to setup our tracking of the defaults vs the current state
# see if the __setattr__ approach is any better than the _updateXX strategy
def __setattr__(self, name, value):
if name == 'defaultLineColor':
if value:
# print('setting defa... |
shaxbee/scnparse | grammar/node.py | Python | mit | 2,315 | 0.00432 | from pyparsing import *
from common import Identifier, UIntNum, DecimalNum, Position, FileName
# common
NodeTag = CaselessKeyword('node')
Name = Keyword('none').setParseAction(replaceWith(None)) | Identifier
Preamble = \
NodeTag + \
DecimalNum('max_dist') + \
DecimalNum('min_dist') + \
Name('name')
#... | DecimalNum('slope'))('ballast')
TrackMaterial = (VisTag + TrackMaterialParams('material')) | UnvisTag
Point = Position.setResultsName('point', True)
Roll = DecimalNum.setResultsName('roll', True)
Control = Position.setResultsName('control', True)
Radius = DecimalNum.setResultsName('ra | dius', True)
TrackGeometry = Point + Roll + Control + Control + Point + Roll + Radius
SwitchGeometry = TrackGeometry + TrackGeometry
Track = \
Preamble + \
TrackTag + \
CaselessKeyword('normal') + \
TrackPrefix + \
TrackMaterial + \
TrackGeometry('geometry') + \
TrackSuffix + \
EndTrac... |
orviz/ooi | ooi/api/network_link.py | Python | apache-2.0 | 5,041 | 0.000198 | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | lFound(pool=net_id)
# Allocate IP
ip = self.os_helpe | r.allocate_floating_ip(req, pool_name)
# Add it to server
self.os_helper.associate_floating_ip(req, server_id, ip["id"])
n = network.NetworkResource(title="network", id=net_id)
c = compute.ComputeResource(title="Compute", id=server_id)
l = os_network.OSNetworkInterface(c, n, "ma... |
702nADOS/sumo | tools/shapes/CSV2polyconvertXML.py | Python | gpl-3.0 | 1,565 | 0.001917 | #!/usr/bin/env python
"""
@file CSV2polyconvertXML.py
@author Daniel Krajzewicz
@author Michael Behrisch
@date 2008-07-17
@version $Id: CSV2polyconvertXML.py 22608 2017-01-17 06:28:54Z behrisch $
Converts a given CSV-file that contains a list of pois to
an XML-file that may be read by POLYCONVERT.
SUMO, Sim... | file are supposed to be divided by ';'.")
print(
" <VALUENAME>s give the attribute names in order of their appearence within the csv-file .")
exit()
names = sys.argv[3].split(',')
inpf = open(sys.argv[1])
outf = open(sys.argv[2], "w")
outf.write("<pois>\n")
for line in inpf:
if len(line) == 0 or l... | outf.write(' ' + n + '="' + vals[i] + '"')
outf.write("/>\n")
outf.write("</pois>\n")
inpf.close()
outf.close()
|
CodeForKuwait/reForm | reForm/functional_tests.py | Python | gpl-2.0 | 727 | 0.001376 | from selenium import webdriver
import unittest
class NewVisitorTest(unittest.TestCase):
|
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
# Fulan closes his browser
self.browser.quit()
def test_can_start_a_form_and_retrieve_it_later(self):
# Fulan has heard about an amazing service for filling out ... | # He notices the page title and the header say "reForm"
self.assertIn('reForm', self.browser.title)
self.fail("Finish the test!")
if __name__ == '__main__':
unittest.main()
|
hexcap/dpkt | dpkt/edp.py | Python | bsd-3-clause | 442 | 0.004525 | """ | Extreme Discovery Protocol."""
import dpkt
import sys
class EDP(dpkt.Packet):
__hdr__ = (
('v', 'B', 1),
('res', 'B', 0),
('hlen', 'H', 0),
('sum', 'H', 0),
('seq', 'H', 0),
('mid', 'H', 0),
('mac', '6s', '')
)
def __str__(self):
if ... | self.sum = dpkt.in_cksum(dpkt.Packet.__str__(self))
return dpkt.Packet.__str__(self)
|
developmentseed/slingshotSMS | pygsm/gsmcodecs/gsm0338.py | Python | bsd-3-clause | 19,653 | 0.020495 | # vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
""" Python Character Mapping Codec based on gsm0338 generated from './GSM0338.TXT' with gencodec.py.
With extra sauce to deal with the 'multibyte' extensions!
"""#"
import codecs
import re
### Codec APIs
#
# Shared funcs
#
def _encode(input,errors='strict'):
... | .Codec):
def encode(self,in | put,errors='strict'):
return _encode(input,errors)
def decode(self,input,errors='strict'):
# strip any trailing '\x00's as the standard
# says trailing ones are _not_ @'s and
# are in fact blanks
if input[-1]=='\x00':
input=input[:-1]
return _decode(inpu... |
bhunter/stopdroproll | src/dropbox-python-sdk-2.1.0/example/datastore_app/tasks.py | Python | isc | 7,334 | 0.002182 | """A simple tasks manager using the Dropbox Datastore API.
This example requires Python 2.7 (for OrderedDict).
This uses the same data model as the JavaScript tutorial example.
The code is somewhat uncharacteristic for Flask apps (e.g. it doesn't
use template files). The advantage of this style is that the entire
a... | return None
cache[access_token] = datastore
return datastore
# Dropbox auth routes and helper. Same as ../flask_app/. |
@app.route('/dropbox-auth-finish')
def dropbox_auth_finish():
try:
access_token, user_id, url_state = get_auth_flow().finish(request.args)
except DropboxOAuth2Flow.BadRequestException as e:
abort(400)
except DropboxOAuth2Flow.BadStateException as e:
abort(400)
except DropboxOAu... |
alphatwirl/alphatwirl | alphatwirl/collector/ToDataFrameWithDatasetColumn.py | Python | bsd-3-clause | 1,326 | 0.008296 | # Tai Sakuma <tai.sakuma@gmail.com>
import pandas as pd
from .ToTupleListWithDatasetColumn import ToTupleListWithDatasetColumn
##__________________________________________________________________||
class ToDataFrameWithDatasetColumn:
def __init__(self, summaryColumnNames,
datasetColumnName = 'co... | istWithDatasetColumn(
summaryColumnNames = summaryColumnNames,
datasetColumnName = datasetColumnName)
def __repr__(self):
name_value_pairs = (
('summaryColumnNames', self.summaryColumnNames),
('datasetColumnName', self.datasetColumnName),
| )
return '{}({})'.format(
self.__class__.__name__,
', '.join(['{} = {!r}'.format(n, v) for n, v in name_value_pairs]),
)
def combine(self, dataset_readers_list):
tuple_list = self.to_tuple_list.combine(dataset_readers_list)
if tuple_list is None:
... |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram/marker/pattern/_sizesrc.py | Python | mit | 424 | 0.002358 | import _plotly_utils.basevalidators
class SizesrcValidator(_plotly_utils.baseva | lidators.SrcValidator):
def __init__(
self, plotly_name="sizesrc", parent_name="histogram.marker.pattern", **kwargs
):
super(SizesrcValidator, self).__init__(
plotly_name=plotly_name,
pa | rent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
subramani95/neutron | neutron/agent/linux/iptables_manager.py | Python | apache-2.0 | 24,792 | 0.00004 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Locaweb.
# 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/license... | chain_set(self, wrap):
if wrap:
return self.chains
else:
return self.unwrapped_chains
def ensure_remove_chain(self, name, wrap=True):
"""Ensure the chain is removed.
This removal "cascades". A | ll rule in the chain are removed, as are
all rules in other chains that jump to it.
"""
name = get_chain_name(name, wrap)
chain_set = self._select_chain_set(wrap)
if name not in chain_set:
return
self.remove_chain(name, wrap)
def remove_chain(self, name,... |
praus/django-rssmailer | rssmailer/models.py | Python | bsd-3-clause | 662 | 0.007553 | from django.db import models
class EntryHash(models.Model):
'''Model for storing hashes of seen entries.'''
hash = models.CharField(max_le | ngth=255, primary_key=True)
class Channel(models.Model):
'''Model for channels to crawl.'''
url = models.URLField(max_length=255)
modified = models.DateTimeField(null=True, editable=False)
etag = models.CharField(max_length=255, null=True, editable=False)
def __unicode__(self):
return ... | rn self.email
|
ecotner/Learning-to-fly | Project Euler Python/Problem 04/problem4.py | Python | mit | 485 | 0.012397 | # -*- codi | ng: utf-8 -*-
"""
Created on Mon Sep 29 21:25:13 2014
@author: 27182_000
"""
# A palindromic number reads the same both ways. The largest palindrome made
# from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
import sys
ans = 1
for ... | s |
jiangzhonglian/MachineLearning | src/py3.x/16.RecommenderSystems/sklearn-RS-demo.py | Python | gpl-3.0 | 508 | 0 | #!/usr/bin/pytho | n
# coding:utf8
import numpy as np
from sklearn.decomposition import NMF
import matplotlib.pyplot as plt
RATE_MATRIX = np.array([[5, 5, 3, 0, 5, 5], [5, 0, 4, 0, 4, 4],
[0, 3, 0, 5, 4, 5], [5, 4, 3, 3, 5, 5]])
nmf = NMF(n_components=2) # 设有2个隐主题
user_distribution = nmf.fit_transform(RATE_MAT... | ('物品的主题分布:')
print(item_distribution)
|
adfinis-sygroup/timed-backend | timed/projects/migrations/0009_auto_20201201_1412.py | Python | agpl-3.0 | 38,360 | 0.000417 | # Generated by Django 2.2.15 on 2020-12-01 13:12
from django.db import migrations
import djmoney.models.fields
class Migration(migrations.Migration):
dependencies = [
("projects", "0008_auto_20190220_1133"),
]
operations = [
migrations.AddField(
model_name="project",
... | hilippine Peso"),
("XPT", "Platinum"),
("GBP", "Pound Sterling"),
("BWP", "Pula"),
("QAR", "Qatari Rial"),
("GTQ", "Quetzal"),
("ZAR", "Rand"),
("OMR", "Rial | Omani"),
("KHR", "Riel"),
("MVR", "Rufiyaa"),
("IDR", "Rupiah"),
("RUB", "Russian Ruble"),
("RWF", "Rwanda Franc"),
("XDR", "SDR"),
("SHP", "Saint Helena Pound"),
... |
kinverarity1/bruges | bruges/transform/timedepthconv.py | Python | apache-2.0 | 3,434 | 0 | from scipy.interpolate import interp1d
from numpy import arange, amax, amin, asarray, zeros, cumsum, \
transpose, gradient, mean, size
def __convert(data, vmodel, interval, interval_new, scale, mode):
"""
Generic function for converting between scales. Use either
time to depth or depth to time
""... | traces)]
v_avg = cumsum(vmodel, axis=0) / transpose(tr)
times = depths / v_avg
times *= scale
if size(dt) == 1:
times_lin = arange(amin(times), amax(times), dt)
else:
times_lin = dt
if ntraces == 1:
inter = interp1d(times | , data,
bounds_error=False,
fill_value=data[-1],
kind='nearest')
return inter(times_lin)
else:
output = zeros((times_lin.size, ntraces))
for i in range(ntraces):
inter = interp1d(times[:, i], data[:, i],
... |
Pabjimcas/produccionEcologica | ecologica/views.py | Python | mit | 158,738 | 0.059112 | # coding=utf-8
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.forms import AuthenticationForm,PasswordChangeForm
from django.s... | a.objects.filter(inspector = inspect)
else:
expediente = str(usInspector[0].expedientes).split()
planificadas = str(usInspector[0].p_visitas).split()
auditorias = str(usInspector[0].auditorias).split()
cliente = str(usInspector[0].clientes).split()
| riesgos = str(usInspector[0].ev_riesgos).split()
archivos = str(usInspector[0].archivos).split()
certifica = str(usInspector[0].certifica).split()
facturacion = str(usInspector[0].facturacion).split()
inspectores = str(usInspector[0].inspectores).split()
idExp = []
expedientesA = []
if len(expedi... |
brianmay/sshuttle | src/assembler.py | Python | lgpl-2.1 | 764 | 0.001309 | import sys, zlib
z = zlib.decompressobj()
mainmod = sys.modules[__name__]
while 1:
name = sys.stdin.readline().strip()
if name:
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
... | ent = z.decompress(sys.stdin.read(nbytes))
exec compile(content, name, "exe | c")
# FIXME: this crushes everything into a single module namespace,
# then makes each of the module names point at this one. Gross.
assert(name.endswith('.py'))
modname = name[:-3]
mainmod.__dict__[modname] = mainmod
else:
break
verbose = verbosity
sys.stderr.flush... |
zcwj/emacs | lisps/webkit/send_key.py | Python | gpl-3.0 | 3,676 | 0.013874 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 ~ 2014 Andy Stewart
#
# Author: Andy Stewart <lazycat.manatee@gmail.com>
# Maintainer: Andy Stewart <lazycat.manatee@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publ... | '#' is returned as "numbersign"
# the subsequent display.keysym_to_keycode("numbersign") is 0.
if ch in special_X_keysyms:
special = special_X_keysyms[ch]
keysym = Xlib.XK.string_to_keysym(special)
return keysym
def send_string(window, str, modifiers, press=True):
xlib_d... | if modifier == "Ctrl":
mask |= Xlib.X.ControlMask
elif modifier == "Alt":
mask |= Xlib.X.Mod1Mask
elif modifier == "Shift":
mask |= Xlib.X.ShiftMask
elif modifier == "Super":
mask |= Xlib.X.Mod4Mask
keycode = xlib_display.keysym_... |
dkobozev/tatlin | libtatlin/vector.py | Python | gpl-2.0 | 1,804 | 0.002217 | # -*- coding: utf-8 -*-
# Copyright (C) 2011 Denis Kobozev
#
# 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.
#
# This pr... | ns(angle)
c = math.cos(angle_r)
s = math.sin(angle_r)
C = 1 - c
matrix = numpy.require([
[x ** 2 * C + c, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, y ** 2 * C + c, y * z * C - x * s],
[x * z * C - y * s, y * | z * C + x * s, z ** 2 * C + c],
], 'f')
return matrix
def translate(vertices, x, y, z):
translated = vertices + numpy.array([x, y, z], 'f')
return translated
def rotate(vertices, angle, x, y, z):
key = (angle, x, y, z)
if key not in _rotation_matrix_cache:
_rotation_matrix_cache[key] =... |
bitcraft/pyglet | contrib/wydget/wydget/widgets/textline.py | Python | bsd-3-clause | 16,785 | 0 | import sys
import string
from pyglet.gl import *
from pyglet.window import key, mouse
from wydget import event, anim, util, element
from wydget.widgets.frame import Frame
from wydget.widgets.label import Label
from wydget import clipboard
# for detecting words later
letters = set(string.letters)
class Cursor(eleme... | ze=None, size=None,
x=0, y=0, z=0, width=None, height=None, border='black',
padding=2, bgcolor='white', color='black',
| focus_border=(.3, .3, .7, 1), **kw):
style = parent.getStyle()
if font_size is None:
font_size = style.font_size
else:
font_size = util.parse_value(font_size, None)
self.font_size = font_size
if size is not None:
size = util.parse_value(s... |
Princeton-CDH/winthrop-django | winthrop/common/models.py | Python | apache-2.0 | 2,609 | 0 | from django.db import models
from django.core.exceptions import ValidationError
# abstract models with common fields to be
# used as mix-ins
class Named(models.Model):
'''Abstract model with a 'name' field; by default, name is used as
the string display.'''
def __init__(self, | *args, **kwargs):
super().__init__(*args, **kwargs)
self.__initial = self.__dict__.copy()
#: unique name (required)
name = models.CharField(max_length=255, unique=True)
clas | s Meta:
abstract = True
ordering = ['name']
def __str__(self):
return self.name
@property
def name_changed(self):
'''Determine if the name of an object has changed on
current instance'''
return self.name != self.__initial['name']
class Notable(models.Model... |
tristan-hunt/UVaProblems | graph_theory/airline_comparison.py | Python | gpl-3.0 | 2,226 | 0.013926 | # Python program for transitive closure using Floyd Warshall Algorithm
#Complexity : O(V^3)
# http://www.geeksforgeeks.org/transitive-closure-of-a-graph/
from collections import defaultdict
import sys
#Class to represent a graph
class Graph:
def __init__(self, vertices):
self.V = vertices
# A u... | s.stdout.write("%7d\t" %(reach[i][j]))
sys.stdout.write("\n")
# Prints transitive closure of graph[][] using Floyd Warshall algorithm
def transitiveClosure(self,graph):
"""
reach[][] will be the output matrix that will finally
have reachability values.
Ini... | one to the set of intermediate
vertices.
---> Before start of a iteration, we have reachability value
for all pairs of vertices such that the reachability values
consider only the vertices in set
{0, 1, 2, .. k-1} as intermediate vertices.
----> After the end of an iter... |
peacekeeper/freedom-maker | freedommaker/vmdebootstrap.py | Python | gpl-3.0 | 8,089 | 0 | #
# This file is part of Freedom Maker.
#
# 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 distribute... | 'sudo', 'losetup', '-d', loop_device])
def process_variant(self):
"""Add paramaters for deboostrap variant."""
if self.builder.debootstrap_variant:
self.parameters += [
'--debootstrapopts',
'variant=' + self.builder.debootstrap_variant
]
... | ot in ('i386', 'amd64'):
self.parameters += ['--foreign', '/usr/bin/qemu-arm-static']
# Using taskset to pin build process to single core. This
# is a workaround for a qemu-user-static issue that causes
# builds to hang. (See Debian bug #769983 for details.)
... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/whoosh/legacy.py | Python | mit | 3,459 | 0 | # Copyright 2012 Matt Chaput. 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 conditions and the... | UMERIC field, so we have to change the
# classes the unpickler tries to load if we need to read an old schema
# Read the length of the pickled schema
picklen = stream.r | ead_varint()
if schema:
# If the user passed us a schema, use it and skip the one on disk
stream.seek(picklen, 1)
else:
# Remap the old classes and functions to their moved versions as we
# unpickle the schema
scuts = {"wf": "whoosh.fields",
"wsn": "whoos... |
Jawoll/automatchthreads | test3.py | Python | mit | 202 | 0.009901 | import zmq, time
port = "5550"
c | ontext = zmq.Context()
socket = context.socket(zmq.PAIR)
|
socket.connect("tcp://localhost:%s" % port)
while True:
socket.send_string("yo")
time.sleep(4) |
jigarkb/CTCI | LeetCode/687-E-LongestUnivaluePath.py | Python | mit | 1,382 | 0.003618 | # Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
#
# Note: The length of path between two nodes is represented by the number of edges between them.
#
# Example 1:
#
# Input:
#
# 5
# / \
# 4 5
# ... | x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.result = 0
self.recursive_helper(root)
return self.result
def r... | return 0, 0
l_max = max(self.recursive_helper(node.left))
r_max = max(self.recursive_helper(node.right))
l = l_max + 1 if node.left and node.left.val == node.val else 0
r = r_max + 1 if node.right and node.right.val == node.val else 0
self.result = max(self.result, ... |
cgqyh/pyalgotrade-mod | pyalgotrade/technical/highlow.py | Python | apache-2.0 | 2,660 | 0.001504 | # PyAlgoTrade
#
# Copyright 2011-2015 Gabriel Martin Becedillas Ruiz
#
# 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 ap... |
from pyalgotrade import technical
from pyalgotrade import dataseries
class HighLowEventWindow(technical.EventWindow):
def __init__(self, windowSize, useMin):
technical.EventWindow.__init__(self, windowSize)
self.__useMin = useMin
def getValue(self):
ret = None
if self.window... | ret = values.min()
else:
ret = values.max()
return ret
class High(technical.EventBasedFilter):
"""This filter calculates the highest value.
:param dataSeries: The DataSeries instance being filtered.
:type dataSeries: :class:`pyalgotrade.dataseries.DataSer... |
srfraser/services | src/releng_tooltool/releng_tooltool/api.py | Python | mpl-2.0 | 11,752 | 0.003319 | # -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
import datetime
import time
import flask
import flask_lo... | utils.is_valid_sha512(digest):
raise werkzeug.exceptions.BadRequest('Invalid sha512 digest')
row = releng_tooltool.models.File.query.filter(releng_tooltool.models.Fi | le.sha512 == digest).first()
if not row:
raise werkzeug.exceptions.NotFound
return row.to_dict(include_instances=True)
@backend_common.auth.auth.require_scopes(['project:releng:tooltool/manage'])
def patch_file(digest, body):
S3_REGIONS = flask.current_app.config['S3_REGIONS']
if type(S3_REGI... |
obulpathi/poppy | poppy/model/common.py | Python | apache-2.0 | 1,962 | 0 | # Copyright (c) 2014 Rackspace, 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 wr... | (self, attributes):
"""Convert a dictionary into a object/Or copy constructor
Update the current instance based on attribute->value items in
*attributes* dictionary.
"""
for attribute in attributes:
setattr(self, attribute, attributes[attribute])
return self
... | s is only meant to be used for converting a
response model into a model.
When converting a request-model into a model,
use to_dict.
"""
raise NotImplementedError
|
lawrennd/collab | python/restartNetflix7.py | Python | bsd-3-clause | 540 | 0.044444 | #!/usr/bin/env python
# Tr | y collaborative filtering on the netflix data.
import collab
import ndlml as nl
opt = collab.options()
o | pt.resultsBaseDir = "/local/data/results/netflix/"
try:
collab.restart(loadIter = 5,
startCount = 2620000,
loadUser = 2190625,
latentDim = 7,
dataSetName = 'netflix',
experimentNo = 7,
options=op... |
obi-two/Rebelion | data/scripts/templates/object/draft_schematic/food/shared_dish_thakitillo.py | Python | mit | 449 | 0.046771 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE | SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/food/shared_dish_thakitillo.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFIC | ATIONS ####
return result |
Doveps/mono | savant-web/forms.py | Python | mit | 4,267 | 0.003515 | import logging
from wtforms import Form, SelectField, SelectMultipleField, validators
import savant.comparisons
import savant.sets
import savant.diffs
class DiffForm(Form):
diffs = SelectMultipleField('Diffs', [validators.Required()], choices=[])
class DiffNamingForm(DiffForm):
action = SelectField('Action'... | .isdisjoint(set_ids_with_diff):
continue
set_id_count = str(len(set_ids_with_diff))
if diff.system != prev_system:
diff_choices.append(('Isystem', diff.system))
prev_system = diff.system
prev_action = ''
if diff.actio... | diff_choices.append(('I'+diff.action, '- '+diff.action))
prev_action = diff.action
diff_choices.append(
(diff.id, '--- '+diff.name+' ('+set_id_count+')'))
return(diff_choices)
def get_valid_choices(self, given_choices):
choices = []
for diff... |
thorrak/fermentrack | app/serial_integration.py | Python | mit | 4,779 | 0.006068 | import serial.tools.list_ports
import fermentrack_django.settings
import os
import pickle
# from . import udev_integration
DEVICE_CACHE_FILENAME = fermentrack_django.settings.ROOT_DIR / 'device.cache'
known_devices = {
'arduino': [
# Those with 'generic': False are virtually guaranteed to be Arduinos
... | 0x0036, 'name': "Arduino Leonardo Bootloader", 'generic': False},
{'vid': 0x2341, 'pid': 0x0043, 'name': "Arduino Uno", 'generic': False},
{'vid': 0x2341, 'pid': 0x0001, | 'name': "Arduino Uno", 'generic': False},
{'vid': 0x2a03, 'pid': 0x0010, 'name': "Arduino Mega2560", 'generic': False},
{'vid': 0x2a03, 'pid': 0x8036, 'name': "Arduino Leonardo", 'generic': False},
{'vid': 0x2a03, 'pid': 0x0036, 'name': "Arduino Leonardo Bootloader", 'generic': False},
... |
kelsoncm/suapwebconf | tests/__init__.py | Python | mit | 1,170 | 0.001709 | # -*- coding: utf-8 -*-
"""
| The MIT License (MIT)
Copyright 2015 Umbrella Tech.
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 right | s to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the... |
hyde/hyde | hyde/template.py | Python | mit | 4,633 | 0.000216 | # -*- coding: utf-8 -*-
# pylint: disable-msg=W0104,E0602,W0613,R0201
"""
Abstract classes and utilities for template engines
"""
from hyde._compat import with_metaclass
from hyde.exceptions import HydeException
import abc
from commando.util import getLoggerWithNullHandler, load_python_object
DEFAULT_TEMPLATE = 'hyd... | ing this object to match
the `settings` required for the template engines.
The engine is an informal protocol to provide access to some
hyde internals.
The preprocessor attribute must contain the function that trigger the
hyde plugins to preprocess the template after load.
... | with the appropriate variables
for the given path.
"""
return
def clear_caches(self):
"""
Clear all caches to prepare for regeneration
"""
return
def get_dependencies(self, text):
"""
Finds the dependencies based on the included
... |
HackBulgaria/Odin | statistics/urls.py | Python | agpl-3.0 | 1,240 | 0.008871 | from django.conf.urls import patterns, url
urlpatterns = patterns('statistics.views',
url(r'^dashboard/$', 'dashboard', name='dashboard'),
url(r'^partners/all/$', 'show_partners_stats', name='show_partners_stats'),
url(r'^partners/(?P<partner_id>[0-9]+)/$', 'show_partner_stats', name='show_partner_stats... | gnments_stats', name='show_assignm | ents_stats'),
url(r'^assignments/$', 'show_all_assignments_stats', name='show_all_assignments_stats'),
url(r'^assignments/all$', 'show_all_assignments_stats', name='show_all_assignments_stats'),
url(r'^assignments/active$', 'show_active_assignments_stats', name='show_active_assignments_stats'),
url(r'^a... |
Hiltronix/plugin.video.sickrage | resources/lib/show_filter.py | Python | gpl-2.0 | 1,116 | 0.008961 | import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
import sys
import urllib
import shows
import settings
def menu(handle):
total_items = 4
addDirectory(handle, 'All', 14, True, settings.addon_path + '/manage.png', total_items)
addDirectory(handle, 'Continuing', 14, True, settings.addon_path + '... | .pluginID, menu_number, urllib.quote_plus(menu_item_name))
list_item = xbmcgui.ListItem(menu_item_name)
list_item.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart': '', 'banner': '', 'clearart': '', 'clearlogo': '', 'landscape': ''})
xbmcplugin. | addDirectoryItem(handle=int(handle), url=return_url, listitem=list_item, isFolder=folder, totalItems=total_items)
|
pombredanne/anvil | anvil/components/configurators/neutron_plugins/__init__.py | Python | apache-2.0 | 676 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file exc | ept 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 | ble law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
|
karlorg/drunken-octo-avenger | migrations/versions/4623531fa2b_record_information_about_how_a_game_.py | Python | cc0-1.0 | 1,921 | 0.004685 | """Record information about how a game finished.
Revision ID: 4623531fa2b
Revises: 9aec2a74d9
Create Date: 2016-04-16 12:27:45.788322
"""
# revision identifiers, used by Alembic.
revision = '4623531fa2b'
down_revision = '9aec2a74d9'
from alembic import op
import sqlalchemy as sa
import app.go as go
# A kind of hyb... | =None) as batch_op:
batch_op.add_column(sa.Column('result', sa.Enum('WBR', 'WBC', 'BBR', 'BBC', 'D', ''), nullable=True))
| connection = op.get_bind()
for game in connection.execute(gamehelper.select()):
result = go.get_game_result(game.sgf).value
connection.execute(
gamehelper.update().where(
gamehelper.c.id == game.id
).values(result=result)
)
with op.batch_alter_... |
beni55/edx-platform | common/test/acceptance/tests/studio/test_import_export.py | Python | agpl-3.0 | 11,718 | 0.001195 | """
Acceptance tests for the Import and Export pages
"""
from abc import abstractmethod
from bok_choy.promise import EmptyPromise
from .base_studio_test import StudioLibraryTest, StudioCourseTest
from ...fixtures.course import XBlockFixtureDesc
from ...pages.studio.import_export import ExportLibraryPage, ExportCoursePa... | d(self):
"""
Scenario: I want to upload a course or library for import.
Given that I have a library or course to import into
And I have a valid .tar.gz file cont | aining data to replace it with
I can select the file and upload it
And the page will give me confirmation that it uploaded successfully
"""
self.import_page.upload_tarball(self.tarball_name)
self.import_page.wait_for_upload()
def test_landing_url(self):
"""
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_PolyTrend_Seasonal_MonthOfYear_AR.py | Python | bsd-3-clause | 163 | 0.04908 | import tests.model_control.te | st_ozone_custom_models_enabled as testmod
testmod.build_model( ['Difference' | ] , ['PolyTrend'] , ['Seasonal_MonthOfYear'] , ['AR'] ); |
googlefonts/statmake | tests/testutil.py | Python | mit | 3,392 | 0.00059 | import io
from pathlib import Path
from typing import Mapping
import fontTools.designspaceLib
import fontTools.ttLib
import fontTools.ttLib.tables._n_a_m_e
import fontTools.varLib
import ufo2ft
import ufoLib2
import statmake.classes
import statmake.lib
def dump_axes(font, axes_array):
dump_list = []
for axi... | font, axis.ValueNameID),
"Flags": axis.Flags,
}
if axis.Format == 1:
entry["AxisIndex"] = axis.AxisIndex
entry["Value"] = axis.Value
elif axis.Format == 2:
entry["AxisIndex"] = axis.AxisIndex
entry["NominalValue"] = axis.NominalValue
... | entry["RangeMinValue"] = axis.RangeMinValue
entry["RangeMaxValue"] = axis.RangeMaxValue
elif axis.Format == 3:
entry["AxisIndex"] = axis.AxisIndex
entry["Value"] = axis.Value
entry["LinkedValue"] = axis.LinkedValue
elif axis.Format == 4:
entry[... |
crash-g/BoardGameBot | test/test_output_formatter.py | Python | mit | 349 | 0.008596 | import os
import sys
sys.path.insert(0, os.path.abspath("../boardg | amebot"))
import html
from tools import output_formatter
import test_xml_parser
game = test_xml_parser.parseGame()
print(output_formatter.formatGame(game).formattedAnswer)
gameLis | t = test_xml_parser.parseGameList()
print(output_formatter.formatGameList(gameList).formattedAnswer)
|
ChinaQuants/bokeh | bokeh/server/tests/test_auth.py | Python | bsd-3-clause | 1,085 | 0.00553 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#----------------------------------------... | eh.server.models.user import User
from bokeh.server.views.decorators import login_required
@contextmanager
def patch_current_user(func):
old = bokeh_app.current_user
try:
bokeh_app.current_user = func
yield
finally:
bokeh_app.current_user = old
def test_login_required():
@login... | rized):
test()
with patch_current_user(lambda : User):
assert test(1) == 1
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_sean_trenwell.py | Python | mit | 444 | 0.047297 | ### | # NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_sean_trenwell.iff"
result.attribute_template_id = 9
resu... | sult |
rethumb/rethumb-examples | examples-cover/example-python2.py | Python | unlicense | 384 | 0.007813 | import urllib2
param_operation = "cover"
param_value = "150x200" # New WIDTHxHEIGHT in pixels.
image_url = "http://images.rethumb.com/image_coimbra_600x300.jpg"
image_filename | = "resized-image.jpg"
response = urllib2.urlopen("http://api. | rethumb.com/v1/{0}/{1}/{2}".format(param_operation, param_value, image_url))
fh = open(image_filename, "w")
fh.write(response.read())
fh.close() |
d-lee/airflow | airflow/operators/sensors.py | Python | apache-2.0 | 22,890 | 0.000743 | # -*- coding: utf-8 -*-
#
# 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
... | super(BaseSensorOperator, self).__init__(*args, **kwargs)
self.poke_interval = poke_interval
self.soft_fail = soft_fail
self.timeout = timeout
def poke(self, context):
'''
Function that the sensors defined while deriving this class should
override.
'''
... | xt):
started_at = datetime.now()
while not self.poke(context):
if (datetime.now() - started_at).total_seconds() > self.timeout:
if self.soft_fail:
raise AirflowSkipException('Snap. Time is OUT.')
else:
raise AirflowSenso... |
napo/poly2wkt | poly2wkt.py | Python | mit | 2,953 | 0.036912 | #!/usr/bin/python
import sys
import argparse
def loopfile(polyfile):
polyline=''
with open(polyfile,'r') as f:
read_data = f.readlines()
f.close()
polylines = []
polyline = ""
countend = 0
# countpoly = 0
for l in read_data:
s = l.strip()
if len(s) > 1:
try:
x = ''
y = ''
... | len(polylines) >0:
polygon = "POLYGON | ("
for p in polylines:
polygon += p +","
polygon = polygon[0:len(polygon)-1]
polygon += ")"
return polygon
parser = argparse.ArgumentParser(description='convert a .poly file in .wkt format')
parser.add_argument('infile', metavar='infile', type=str,
help='i... |
gnu-sandhi/sandhi | modules/gr36/gnuradio-core/src/python/gnuradio/gr/tag_utils.py | Python | gpl-3.0 | 1,704 | 0.005869 | #
# Copyright 2003-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)
# any later version... | hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; | see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
""" Conversion tools between stream tags and Python objects """
try: import pmt
except: from gruel import pmt
from gnuradio_core import gr_tag_t
class PythonTag(object):
" Python cont... |
heromod/migrid | mig/shared/init.py | Python | gpl-2.0 | 4,932 | 0.002636 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
#
# init - shared helpers to init functionality backends
# Copyright (C) 2003-2014 The MiG Project lead by Brian Vinter
#
# This file is part of MiG.
#
# MiG is free software: you can redistribute it and/or modify
# it under the terms of the GNU Genera... | ] = user_widgets
return (configuration, logger, output_objects, op_name)
def extract_menu(configuration, title_entry):
"""Extract the list of active menu items from title_entry. Useful to
detect if a particular feature should be enabled for this particular set
of default and user configured menu items... | ation.site_default_menu
return menu_items
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.