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 |
|---|---|---|---|---|---|---|---|---|
wxgeo/geophar | wxgeometrie/sympy/series/tests/test_approximants.py | Python | gpl-2.0 | 962 | 0.007277 | from sympy.core.compatibility import range
from sympy.series import approximants
from sympy import lucas, fibonacci, symbols, binomial
def test_approximants():
x, t = symbols("x,t")
g = [lucas(k) for k in range(16)]
assert [e for e in approximants(g)] == (
[2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x ... | /(x - 1), (3*x - 3)/(2*x - 1), -3/(x**2 + x - 1)] )
g = [lucas(k)**2 for k in range(16)]
assert [e for e in approximants(g)] == (
[4, -16/(x - 4), (35*x - 4)/(9*x - 1), (37*x - 28)/(13*x**2 + 11*x - 7),
(50*x**2 + 63*x - 52)/(37*x**2 + 19*x - 13),
(-x**2 - 7*x + 4)/(x**3 - 2*x**2 - 2*x +... | for i in range(k+1)) for k in range(16)]
y = approximants(p, t, simplify=True)
assert next(y) == 1
assert next(y) == -1/(t*(x + 1) - 1)
|
edx/ecommerce | ecommerce/extensions/order/management/commands/tests/test_update_order_lines_partner.py | Python | agpl-3.0 | 2,921 | 0.001369 |
import ddt
from django.core.management import call_command
from django.core.management.base import CommandError
from mock import patch
from oscar.core.loading import get_model
from ecommerce.extensions.test.factories import create_order
from ecommerce.tests.factories import PartnerFactory
from ecommerce.tests.testca... | that command raises partner does not exist error."""
self.assert_error_log(
'No Partner exists for code {}.'.format(self.PARTNER_CODE),
'sku12345',
'--partner={}'.format(self.PARTNER_CODE)
)
def test_one_or_more_sku_required(self):
"""Test that command r... | error."""
self.assert_error_log(
'update_order_lines_partner requires one or more <SKU>s.',
'--partner={}'.format(self.PARTNER_CODE)
)
@ddt.data(True, False)
def test_update_order_lines_partner(self, yes_no_value):
"""Test that command works as expected."""
... |
jedie/PyHardlinkBackup | pyhardlinkbackup/backup_app/management/commands/add.py | Python | gpl-3.0 | 422 | 0 | from django.core.management.base import BaseCommand
# https://github.com/jedie/PyHardLinkBackup
from pyhardlinkbackup.phlb.add import add_all_backups
class Command(BaseCommand):
help = 'Scan all existing backup and add missing ones to database.'
def handle(self, *args | , **options):
self.stdout.write(f'\n\n{self.help}\n')
add_all_backups()
self.stdout.write(self.style.SUCCESS('done') | )
|
redfern314/amazedFirmware | bootloader/software/hellousb.py | Python | mit | 1,389 | 0.00504 |
import usb.core
class hellousb(object):
def __init__(self):
self.HELLO = 0
self.SET_VALS = 1
self.GET_VALS = 2
self.PRINT_VALS = 3
self.dev = usb.core.find(idVendor = 0x6666, idProduct = 0x0003)
if self.dev is None:
raise ValueError('no USB de... | st."
def set_vals(self, val1, val2):
try:
self.dev.ctrl_transfer(0x40, self.SET_VALS, int(val1), int(val2))
except usb.core.USBError:
prin | t "Could not send SET_VALS vendor request."
def get_vals(self):
try:
ret = self.dev.ctrl_transfer(0xC0, self.GET_VALS, 0, 0, 4)
except usb.core.USBError:
print "Could not send GET_VALS vendor request."
else:
return [int(ret[0])+int(ret[1])*256, in... |
nadege/food-organizer | backend/apps/project/views.py | Python | gpl-3.0 | 1,258 | 0 | import logging
import os
from django.shortcuts import render
f | rom django.views.generic import View
from django.http import HttpResponse
from django.conf import settings
class FrontendAppView(View):
"""
Serves the compiled frontend entry point (only works i | f you have run `make
build-frontend`).
"""
def get(self, request):
try:
with open(
os.path.join(settings.FRONTEND_DIR, 'build', 'index.html'),
) as frontend:
return HttpResponse(frontend.read())
except FileNotFoundError:
... |
Balannen/LSMASOMM | atom3/Formalisms/LSMASOMM/canNotCommunicateWith.py | Python | gpl-3.0 | 3,261 | 0.028519 | """
__canNotCommunicateWith.py_____________________________________________________
Automatically generated AToM3 syntactic obj | ect (DO NOT MODIFY DIRECTLY)
Author: bogdan
Modified: Fri Jul 1 01:29:28 2016
_______________________________________________________________________________
"""
from ASGNode import *
from ATOM3Type import *
from graph_canNotCommunicateWith import *
class canNotCommunicateWith(ASGNode, ATOM | 3Type):
def __init__(self, parent = None):
ASGNode.__init__(self)
ATOM3Type.__init__(self)
self.graphClass_ = graph_canNotCommunicateWith
self.isGraphObjectVisual = True
if(hasattr(self, '_setHierarchicalLink')):
self._setHierarchicalLink(False)
if(hasattr(self, '_setHier... |
awhittle3/pyBattleship | playAnchors.py | Python | apache-2.0 | 325 | 0.009231 | from playSounds import play
BEAT = 500
HALF = int(BEAT/2)
QUART = int(BEAT/4)
def playSong():
play('C4' ,BEAT*2)
play('E4', BEAT)
play('G4', BEAT)
play('A4', BEAT + 3*QUART)
play('E4', QUART)
play('A4', 2*BEAT)
play | ('C5', BEAT*2)
play('D5', BEAT)
play | ('G4', BEAT)
play('C5', BEAT*4)
|
lmazuel/azure-sdk-for-python | azure-mgmt-billing/azure/mgmt/billing/operations/invoices_operations.py | Python | mit | 11,810 | 0.002202 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | if skiptoken is not None:
query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int', maximum=100, minimum=1)
else:
url =... | header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.upd... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_file_system/codecs_bom_create_file.py | Python | apache-2.0 | 796 | 0 | import codecs
from codecs_to_hex import to_hex
# Pick the nonnative version of UTF-16 encoding
if codecs.BOM_UTF16 == codecs.BOM_UTF16_BE:
bom = codecs.BOM_UTF16 | _LE
encoding = 'utf_16_le'
else:
bom = codecs.BOM_UTF16_BE
encoding = 'utf_16_be'
print('Native order :', to_hex(codecs.BOM_UTF16, 2))
print('Selected order:', to_hex(bom, 2))
# Encode the text.
encoded_text = 'français'.encode(encoding)
print('{:14}: {}'.format(encoding, to_hex(encoded_text, 2)))
with ... | It is not included
# in the encoded text because the byte order was given
# explicitly when selecting the encoding.
f.write(bom)
# Write the byte string for the encoded text.
f.write(encoded_text)
|
NicolasDorier/bitcoin | qa/rpc-tests/wallet.py | Python | mit | 18,545 | 0.00615 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.... | ettxfee(fee_per_byte * 1000)
txid = self.nodes[2].sendtoaddress(address, 10, "", "", False)
self.nodes[2].generate(1)
self.sync_all()
node_2_bal = self.check_fee_amount(self.nodes[2].getbalance(), Decimal('84'), fee_per_byte, count_bytes(self.nodes[2].getrawtransaction(txid) | ))
assert_equal(self.nodes[0].getbalance(), Decimal('10'))
# Send 10 BTC with subtract fee from amount
txid = self.nodes[2].sendtoaddress(address, 10, "", "", True)
self.nodes[2].generate(1)
self.sync_all()
node_2_bal -= Decimal('10')
assert_equal(self.nodes[2].g... |
impallari/Impallari-Fontlab-Macros | IMP Testing/Save EPS from Glyph.py | Python | apache-2.0 | 436 | 0.009174 | #FLM: Save EPS from selected Glyph
# Description:
# Generate a EPS file for the Selected Glyph
# Credits:
# Pablo Impallari
# http://www.impallari.com
import os.path
from FL import *
from robofab.world import CurrentFont
# Get current Glyphs
f = CurrentFont()
g = fl.glyph
# Get path and file name
path = f.path
dir... | ame + '.eps'
# Generate EP | S file
g.SaveEPS( filename )
|
micha-shepher/oervoer-wizard | oervoer-django/oervoer/src/testimport.py | Python | gpl-3.0 | 490 | 0.004082 | import pprint
from wizard.importoervoer import ImportOrders, Credentials, ImportProds, ImportSmaak, ImportVlees
imp = ImportOrders(Credentials.user, Credentials.pw)
if imp.connect():
savecur = imp.get_cur()
imp.importtable()
imp = ImportProds(Credentials.user, Credentials.pw, savecur)
pprint.pprint(imp.importtab... | s.user, Credentials.pw, savecur)
imp.importtab | le()
|
asifpy/django-crudbuilder | crudbuilder/views.py | Python | apache-2.0 | 8,139 | 0.000491 | from django.forms.models import modelform_factory
from django.views.generic import (
DetailView,
CreateView,
UpdateView,
DeleteView,
TemplateView
)
from django_tables2 import SingleTableView
from crudbuilder.registry import registry
from crudbuilder.mixins import (
CrudBuilderMixin,
BaseLis... | n_required,
permissions=self.view_permission('detail'),
inlineformset=self.inlineformset,
permission_required=self.check_permission_required,
custom_detail_context= | self.custom_detail_context,
custom_postfix_url=self.custom_postfix_url
)
detail_class = type(name, (BaseDetailViewMixin, DetailView), detail_args)
self.classes[name] = detail_class
return detail_class
def generate_update_view(self):
"""Generate class based view ... |
fuzeman/trakt.py | tests/test_helpers.py | Python | mit | 519 | 0 | from __future__ import absolute_import, division, print_function
from trakt.core.h | elpers import from_iso8601_datetime, to_iso8601_datetime
from hamcrest import assert_that, equal_to
import pytest
try:
import arrow
except ImportError:
arrow = None
def test_datetime_conversion():
if arrow is None:
pytest.skip('arrow not installed, skipping')
d = arrow.utcnow().replace(micro... | e(d_str)
assert_that(d, equal_to(d2))
|
opennode/nodeconductor-assembly-waldur | src/waldur_mastermind/marketplace/migrations/0023_category_i18n.py | Python | mit | 917 | 0 | # Generated by Django 2.2.13 on 2020-09-30 11:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('marketplace', '0022_extend_description_limits'),
]
operations = [
migrations.AddField(
model_name='category',
name=... | _en',
field=models.TextField(blank=Tr | ue, null=True),
),
migrations.AddField(
model_name='category',
name='description_et',
field=models.TextField(blank=True, null=True),
),
migrations.AddField(
model_name='category',
name='title_en',
field=models.CharFi... |
cpennington/edx-platform | lms/djangoapps/courseware/tests/test_rules.py | Python | agpl-3.0 | 1,680 | 0.00119 | """
Tests for permissions defined in courseware.rules
"""
import ddt
import six
from django.test import TestCase
from opaque_keys.edx.locator import CourseLocator
from course_modes.tests.factories import CourseModeFactory
from student.models import Co | urseEnrollment
from student.tests.factories import UserFactory
@ddt.ddt
class PermissionTests(TestCase):
"""
Tests for permissions defined in courseware.rules
"""
def setUp(self):
super(PermissionTests, self).setUp()
self.user = UserFactory()
self.course_id = CourseLocator('MI... |
CourseModeFactory(mode_slug='professional', course_id=self.course_id)
CourseEnrollment.unenroll(self.user, self.course_id)
def tearDown(self):
super(PermissionTests, self).tearDown()
self.user.delete()
@ddt.data(
(None, False),
('audit', False),
('verif... |
zhangyage/Python-oldboy | my_request/img_request.py | Python | apache-2.0 | 414 | 0.014778 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
def download_img():
'''
@下载图片
'''
url = "https://www.jcd6.com/Public/Home/new/images/process_03.png"
response = requests.get(url,stream=True)
with open('demo.png','wb') as fd:
for chunk in respons | e.iter_content(128):
fd.write(chunk)
| if __name__ == '__main__':
download_img() |
expectocode/Telethon | telethon/hints.py | Python | mit | 1,562 | 0.00128 | import datetime
import typing
from . import helpers
from .tl import types, custom
Phone = str
Username = str
PeerID = int
Entity = typing.Union[types.User, types.Chat, types.Channel]
FullEntity = typing.Union[types.UserFull, types.messages.ChatFull, types.ChatFull, types.ChannelFull]
EntityLike = typing.Union[
| Phone,
Username,
PeerID,
types.TypePeer,
types.TypeInputPeer,
Entity,
FullEntity
]
EntitiesLike = typing.Union[EntityLike, typing.Sequence[EntityLike]]
ButtonLike = typing.Union[types.TypeKeyboardButton, custom.Button]
MarkupLike = typing.Union[
types.TypeReplyMarkup,
| ButtonLike,
typing.Sequence[ButtonLike],
typing.Sequence[typing.Sequence[ButtonLike]]
]
TotalList = helpers.TotalList
DateLike = typing.Optional[typing.Union[float, datetime.datetime, datetime.date, datetime.timedelta]]
LocalPath = str
ExternalUrl = str
BotFileID = str
FileLike = typing.Union[
LocalPath... |
SanchayanMaity/gem5 | configs/example/fs.py | Python | bsd-3-clause | 15,347 | 0.004496 | # Copyright (c) 2010-2013, 2016 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the fun... | OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Ali Saidi
# Brad Beckmann
import optparse
import sys
import m5
from m5.defines import buildEnv
from m5.objects import *
from m5.util import addToPath, fatal
addToPath('../')
from ruby import Ruby
from common.FSConfig import *
from common.SysPaths import *
fr... | port MemConfig
from common import CpuConfig
from common.Caches import *
from common import Options
# Check if KVM support has been enabled, we might need to do VM
# configuration if that's the case.
have_kvm_support = 'BaseKvmCPU' in globals()
def is_kvm_cpu(cpu_class):
return have_kvm_support and cpu_class != No... |
hpcugent/vsc-mympirun | test/mytaskprolog.py | Python | gpl-2.0 | 1,831 | 0.003277 | #
# Copyright 2019-2022 Ghent University
#
# This file is part of vsc-mympirun,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# the Flemish Research Foundat... | ils.
#
# You should have received a copy of the GNU General Public License
# along with vsc-mympirun. If not, see <http://www.gnu.org/licenses/>.
#
"""
End-to-end tests for mypmirun
"""
import os
import logging
logging.basicConfig(level=logging.DEBUG)
from pmi_utils import PMITest
from vs | c.utils.affinity import sched_getaffinity, sched_setaffinity
class TaskPrologEnd2End(PMITest):
def setUp(self):
"""Prepare to run test."""
super(TaskPrologEnd2End, self).setUp()
self.script = os.path.join(os.path.dirname(self.script), 'mytaskprolog.py')
def test_simple(self):
... |
BitWriters/Zenith_project | zango/lib/python3.5/site-packages/django/contrib/postgres/validators.py | Python | mit | 2,718 | 0.004415 | import copy
from django.core.exceptions import ValidationError
from django.core.validators import (
MaxLengthValidator, MaxValueValidator, MinLengthValidator,
MinValueValidator,
)
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
clas... | t__(self, keys, strict=False, messages=None):
self.keys = set(keys)
self.strict = strict
if messages is not None:
self.messages = copy.copy(self.messages)
self.messages.update(messages) |
def __call__(self, value):
keys = set(value.keys())
missing_keys = self.keys - keys
if missing_keys:
raise ValidationError(self.messages['missing_keys'],
code='missing_keys',
params={'keys': ', '.join(missing_keys)},
)
if self... |
SlashDK/OpenCV-simplestuff | vendors/microsoft.py | Python | mit | 1,684 | 0.00772 | import base64
import json
import requests
def call_vision_api(image_filename, api_keys):
api_key = api_keys['microsoft']
post_url = "https://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories,Tags,Description,Faces,ImageType,Color,Adult&subscription | -key=" + api_key
image_data = open(image_filename, 'rb').read()
result = requests.post(post_url, data=image_data, headers={'Content-Type': 'application/octet-stream'})
result.raise_for_status()
return result.text
# Return a dictionary of features to their scored values (represented as lists of tuples... | score), ...],
# 'feature_2' : ...
# }
#
# E.g.,
#
# {
# 'tags' : [('throne', 0.95), ('swords', 0.84)],
# 'description' : [('A throne made of pointy objects', 0.73)]
# }
#
def get_standardized_result(api_result):
output = {
'tags' : [],
'captions' : [],
# 'categories' : [],
# ... |
ivano666/tensorflow | tensorflow/contrib/testing/python/framework/test_util.py | Python | apache-2.0 | 4,116 | 0.007532 | # 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 a... | exist under base_dir.
"""
return [e for e in latest_events(base_dir) if e.HasField('summary')]
def simple_v | alues_from_events(events, tags):
"""Parse summaries from events with simple_value.
Args:
events: List of tensorflow.Event protos.
tags: List of string event tags corresponding to simple_value summaries.
Returns:
dict of tag:value.
Raises:
ValueError: if a summary with a specified tag does not co... |
mayankjohri/LetsExplorePython | Section 2 - Advance Python/Chapter S2.05 - REST API - Server & Clients/code/clients/old/6_Cookies_with_Authentication.py | Python | gpl-3.0 | 290 | 0.034483 | import requests
session = requests.session()
user ="mayank"
password = "test"
p = session.post("http://127.0.0.1:5000/api/users", {'user':user,'password':password})
print ('headers', p.headers)
print ('cookies', requests.utils.d | ict_from_cookiejar(session.cookies))
| print ('html', p.text) |
JPWKU/unix-agent | src/dcm/agent/tests/unit/test_backoff.py | Python | apache-2.0 | 7,619 | 0 | #
# Copyright (C) 2014 Dell, 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 wri... | ime.datetime.now()
ws.close()
self.assertEqual(1, m.connect.call_count)
def test_backoff_object_ready_immediately(self):
initial_backoff_second = 300.0
max_ba | ckoff_seconds = initial_backoff_second
backoff = websocket.Backoff(
max_backoff_seconds,
initial_backoff_second=initial_backoff_second)
self.assertTrue(backoff.ready())
def test_backoff_object_error_not_ready(self):
initial_backoff_second = 300.0
max_backoff_... |
couchbaselabs/celery | celery/tests/slow/test_buckets.py | Python | bsd-3-clause | 10,768 | 0.001022 | from __future__ import absolute_import
from __future__ import with_statement
import sys
import time
from functools import partial
from itertools import chain, izip
from Queue import Empty
from mock import Mock, patch
from celery.app.registry import TaskRegistry
from celery.task.base import Task
from celery.utils im... | f_disabled
def empty_queue_yields_QueueEmpty(self):
x = buckets.TokenBucketQueue(fill_rate=10)
with self.asser | tRaises(buckets.Empty):
x.get()
@skip_if_disabled
def test_bucket__put_get(self):
x = buckets.TokenBucketQueue(fill_rate=10)
x.put("The quick brown fox")
self.assertEqual(x.get(), "The quick brown fox")
x.put_nowait("The lazy dog")
time.sleep(0.2)
se... |
j-mracek/dnf_docker_test | features/steps/test_behave.py | Python | mit | 9,384 | 0.002558 | #!/usr/bin/python -tt
from behave import *
import os
import subprocess
import glob
import re
import shutil
DNF_FLAGS = ['-y', '--disablerepo=*', '--nogpgcheck']
RPM_INSTALL_FLAGS = ['-Uvh']
RPM_ERASE_FLAGS = ['-e']
def _left_decorator(item):
""" Removed packages """
return u'-' + item
def _right_decorator... | :
return [p.strip() for p in pkgs.split(',')]
@given('I use the repository "{repo}"')
def given_repo_condition(context, repo):
""" :type context: behave.runner.Context """
assert repo
context.repo = repo
assert os.path.exists('/var/www/html/repo/' + repo)
for root, dirs, files in os.walk('/rep... | f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
subprocess.check_call(['cp -rs /var/www/html/repo/' + repo + '/* /repo/'], shell=True)
with open('/etc/yum.repos.d/' + repo + '.repo', 'w') as f:
f.write('[' + repo + ']\nname=' + r... |
YeelerG/twilio-python | setup.py | Python | mit | 2,325 | 0.012043 | from __future__ import with_statement
import sys
from setuptools import setup, find_packages
__version__ = None
with open('twilio/version.py') as f:
exec(f.read())
# To install the twilio-python library, open a Terminal shell, then run this
# file by typing:
#
# python setup.py install
#
# You need to have the se... | :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Communications :: Telephony",
],
long_description =... | ilio Helper Library
----------------------------
DESCRIPTION
The Twilio REST SDK simplifies the process of making calls using the Twilio REST API.
The Twilio REST API lets to you initiate outgoing calls, list previous calls,
and much more. See https://www.github.com/twilio/twilio-python for more i... |
sameerparekh/pants | src/python/pants/backend/codegen/targets/java_protobuf_library.py | Python | apache-2.0 | 1,867 | 0.004821 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
from... | rsion
# and --gen-protoc-plugins into the fingerprint. Consider adding a custom FingeprintStrategy
# into ProtobufGen to get it.
payload.add_fields({
'import_specs': PrimitiveField(imports or ())
})
super(JavaProtobufLibrary, self).__init__(payload=payload, **kwargs)
if buildflags is not ... | finition at {address} sets attribute 'buildflags' which is "
"ignored and will be removed in a future release"
.format(address=self.address.spec))
self.add_labels('codegen')
@property
def imported_jar_library_specs(self):
"""List of JarLibrary specs to import.
Requi... |
anythingrandom/eclcli | eclcli/common/limits.py | Python | apache-2.0 | 3,896 | 0 | # Copyright 2012-2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | ", "Remain", "Unit",
"Next Available"]
return (columns, (utils.get_item_properties(s, columns)
for s in i | tertools.chain(compute_limits, volume_limits)))
else:
return ({}, {})
|
thurloat/django-postleware | postleware/tests.py | Python | bsd-3-clause | 1,561 | 0.000641 | from django.http import HttpResponse
from django.utils import unittest
from django.test.client import C | lient
from postleware import PostResponseCachebusterMiddleware
class PostResponseMiddleware(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_header_added_when_necessary(self):
# 'Cache-Control: no-cache' is added to POSTs
response = self.client.post('/test1', {'foo... | rtFalse(response.has_header('Cache-Control'))
def test_header_not_added_when_present(self):
middleware = PostResponseCachebusterMiddleware()
test_header_setting = 'test-setting'
raw_response = HttpResponse()
# 'Cache-Control' header isn't modified when present on POSTs
requ... |
RianFuro/vint | vint/linting/config/config_comment_source.py | Python | mit | 1,825 | 0.003836 | import re
from vint.linting.config.config_source import ConfigSource
from vint.ast.node_type import NodeType
CONFIG_COMMENT_PATTERN = re.compile(r'^\s*vint:\s*')
POLICY_SWITCH_PATTERN = re.compile(r'[-\+]\S+')
class ConfigCommentSource(ConfigSource):
""" A class for ConfigCommentSourcees.
This class provide ... | ype']) is not Nod | eType.COMMENT:
return False
comment_content = node['str']
return CONFIG_COMMENT_PATTERN.match(comment_content) is not None
def _parse_config_comment(self, comment_content):
striped_comment_content = CONFIG_COMMENT_PATTERN.sub('', comment_content)
policy_switches = POL... |
CrazyBBer/Python-Learn-Sample | gui.py | Python | mit | 433 | 0.04157 | # GUI
# python | for tkinter nature
from tkinter import *
class Application(Frame):
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.helloLabel=Label(self,text='Hello World')
self.helloLabel.pack()
self.quitButton = Button(self,text='Quit app')... | pp.mainloop() |
iot-factory/synapse | synapse/rest/client/v2_alpha/tokenrefresh.py | Python | apache-2.0 | 2,090 | 0.000478 | # -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | er express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from twisted.internet import defer
from synapse.api.errors import AuthError, StoreError, SynapseError
from synapse.http.servlet import RestServlet
from ._base import client_v2_pattern, parse_... | t_v2_pattern("/tokenrefresh")
def __init__(self, hs):
super(TokenRefreshRestServlet, self).__init__()
self.hs = hs
self.store = hs.get_datastore()
@defer.inlineCallbacks
def on_POST(self, request):
body = parse_json_dict_from_request(request)
try:
old_re... |
yuanagain/seniorthesis | venv/lib/python2.7/site-packages/scipy/io/matlab/mio.py | Python | mit | 8,793 | 0.000341 | """
Module for reading and writing matlab (TM) .mat files
"""
# Authors: Travis Oliphant, Matthew Brett
from __future__ import division, print_function, absolute_import
import numpy as np
from scipy._lib.six import string_types
from .miobase import get_matfile_version, docfiller
from .mio4 import MatFile4Reader, Ma... | efault, implying byte order guessed from mat
fi | le. Otherwise can be one of ('native', '=', 'little', '<',
'BIG', '>').
mat_dtype : bool, optional
If True, return arrays in same dtype as would be loaded into
MATLAB (instead of the dtype with which they are saved).
squeeze_me : bool, optional
Whether to squeeze unit matrix dimensio... |
krainet/Wordplease | users/api_urls.py | Python | mit | 320 | 0 | # -*- coding: utf-8 -*-
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from users.api import UserViewSet
router = DefaultRouter()
router.register('user', UserViewSet, base_name= | 'user')
urlpatterns = [
url(r'1.0/', include(r | outer.urls)), # include de las url's router
]
|
trhd/cmdln | test/cmdln_main1.py | Python | mit | 443 | 0.011287 | #!/usr/bin/env python
"""
$ python cmdln_main1.py foo
hello from foo
$ python cmdln_main1.py #expecttest: INTERACTIVE, PROMPT="shell> "
shell> | foo
hello from foo
shell> ^D
"""
import sys
import cmdln
class Shell(cmdln.RawCmdln):
"This is my shell."
name = "shell"
def do_foo(self, argv):
print("hello from foo")
if __name__ == "__main__":
sys.exit( Shell().main(loop=cmdln.LOOP_IF_EMPT | Y) )
|
tetherless-world/dco-viz | dco-stats/puStats.py | Python | lgpl-3.0 | 984 | 0.029472 | from dcoStats import DCOStats
query = "where { ?obj a dco:ProjectUpdate . ?obj dco:forReportingYear <http://info.deepcarbon.net/individual/n33426> . }"
objFile = "puObjs"
cntFile = "puCount"
rqFile = "pu.rq"
def printIt( uri, jObj ):
if jObj and len( jObj ) > 0 and "Name" in jObj[0]:
print( jObj[0]["Name... | Obj[0]:
print( " For Project: " | + jObj[0]["Project"]["value"] )
if "EnteredBy" in jObj[0]:
print( " Entered By: " + jObj[0]["EnteredBy"]["value"] )
else:
print( "Missing or no information for Project Update " + uri )
print( "" )
print( "Project Updates" )
stats = DCOStats()
stats.getNew( query, objFile, query,... |
j-coll/opencga | opencga-app/app/cloud/azure/arm/scripts/mount.py | Python | apache-2.0 | 7,799 | 0.003334 | import sys
import socket
import fcntl
import struct
import random
import os
import shutil
import subprocess
import time
import csv
import ipaddress
# Run `python3 -m unittest discover` in this dir to execute tests
default_mount_options_nfs = "nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0"
default_mount_option... | azure files connection details."""
)
print_help | ()
exit(2)
print("Mounting type: {}".format(sys.argv[1]))
print("Mounting data: {}".format(sys.argv[2]))
mount_point_permissions = 0o0777 # Todo: What permissions does this really need?
primary_mount_folder = "/media/primarynfs"
seconday_mount_folder_prefix = "/media/secondarynfs"
fst... |
nachandr/cfme_tests | cfme/test_framework/pytest_plugin.py | Python | gpl-2.0 | 985 | 0.001015 | """
cfme main plugin
This provides the option group and disables pytest logging plugin
Also provides uncollection stats during testrun/collection
"""
import pytest
@pytest.ho | okimpl(tryfirst=True)
def pytest_addoption(parser):
# Create the cfme option group for use in other plugins
parser.getgroup('cfme', 'cfme: options related to cfme/miq appliances')
def pytest_configure(config):
# also disable the pytest logging system since its triggering | issues with our own
config.pluginmanager.set_blocked('logging-plugin')
def pytest_collection_finish(session):
from cfme.fixtures.pytest_store import store
store.terminalreporter.write(
"Uncollection Stats:\n", bold=True)
for reason, value in store.uncollection_stats.items():
store.te... |
jodal/comics | comics/comics/lunche24.py | Python | agpl-3.0 | 607 | 0 | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Lunch (e24.no)"
language = "no"
url = "http:// | www.e24.no/lunch/"
start_date = "2009-10-21"
rights = "Børge Lund"
class Crawler(CrawlerBase):
history_capable_date = "2012-11-02"
schedule = "Mo,Tu,We,Th,Fr,Sa"
time_zone = "Europe/Oslo"
def crawl(self, pub_date):
url = "http://static.e24.no/images/comics/lunch_%s.gif" % | (
pub_date.strftime("%Y%m%d")
)
return CrawlerImage(url)
|
tph-thuering/vnetsource | ts_om_viz/forms.py | Python | mpl-2.0 | 571 | 0.010508 | # -*- coding: utf-8 -*-
from django import forms
class DocumentForm(forms.Form):
xmlfile = forms.FileField(label='Select the input xml file (scenario.xml)')
outputfile = forms.FileField(label='Select the survery output file (output.txt) if available', required=Fal | se)
ctsoutputfile = forms.FileField(label='Select the continuous file (ctsout.txt) if available', required=False)
save_to = forms.BooleanField(initial=False, label='Save to My | Scenarios', required=False)
scenario_label = forms.CharField(label="Scenario name (optional)", required=False) |
zubie7a/Algorithms | LeetCode/02_Medium/lc_435.py | Python | mit | 827 | 0.001209 | # 435 - Non Overlapping Intervals (Medium)
# https://leetcode.com/problems/non-overlapping-intervals/
# How many intervals have to be erased from a list so that all
# remaining intervals are not overlapping?
class Solution(object):
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: Li... | ased = 0
# Sort intervals by "end" key, and check that each interval's
# "start" is no lesser than the pr | eviously biggest "end" found.
# Those that are lesser then are overlapping.
for intv in sortIntervals:
if intv[0] >= end:
end = intv[1]
else:
erased += 1
return erased
|
evanunderscore/defopt | examples/short.py | Python | gpl-3.0 | 582 | 0 | """
Example showing short flags in defopt.
Y | ou can add alternative short flags to arguments by passing a
dictionary to `defopt.run` which maps flag names to single letters.
Code usage::
>>> | main(count=2)
Command line usage::
$ python short.py -C 2
$ python short.py --count 2
"""
import defopt
def main(*, count: int = 1):
"""
Example function which prints a message.
:param count: Number of times to print the message
"""
for _ in range(count):
print('hello!')
if _... |
frederica07/Dragon_Programming_Process | PyOpenGL-3.0.2/OpenGL/raw/GL/ARB/compressed_texture_pixel_storage.py | Python | bsd-2-clause | 743 | 0.004038 | '''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p
from OpenGL.GL import glget
EXTENSION_NAME = 'GL_ARB_compressed_texture_pixel_storage'
_p.unpack_constants( """GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127
GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128
GL_UNPACK_COMPRESSED_BLOCK_DEPTH... | cating whether this extension is availab | le'''
from OpenGL import extensions
return extensions.hasGLExtension( EXTENSION_NAME )
|
CloverHealth/temporal-sqlalchemy | temporal_sqlalchemy/tests/conftest.py | Python | bsd-3-clause | 1,589 | 0.000629 | """ pytest fixtures for test suite """
import pytest
import sqlalchemy as sa
import sqlalchemy.orm as orm
import testing.postgresql
import temporal_sqlalchemy as temporal
from . import models
@p | ytest.yield_fixture(scope='session')
def engine():
"""Creates a postgres database for testing, returns a sqlalchemy engine"""
db = testing.postgresql.Postgresql()
engine_ = sa.create_engine(db.url())
yield engine_
engine_.dispose()
db.stop()
@pytest.yield_fixture(scope='session')
def connec... | ."""
conn = engine.connect()
for extension in ['uuid-ossp', 'btree_gist']:
conn.execute("""\
CREATE EXTENSION IF NOT EXISTS "%s"
WITH SCHEMA pg_catalog
""" % extension)
for schema in [models.SCHEMA, models.TEMPORAL_SCHEMA]:
conn.execute('CREATE SCHEMA IF NOT ... |
armab/st2contrib | packs/sensu/actions/silence.py | Python | apache-2.0 | 833 | 0 | #!/usr/bin/python
from lib import sensu
import argparse
import json
import time
parser = argparse.ArgumentParser(description='Sensu Silence Actions')
parser.add_argument('--client', nargs='?', required=True)
parser.add_argument('--check', nargs='?', default=False) |
parser.add_argument('--expiration', nargs='?', default=False)
parser.add_argument('--message', default="Stash created by StackStorm")
args = parser.parse_args()
stashes = sensu.Stashes('config.yaml')
data = {}
data['message'] = args.message
current_time = time.time()
data['timestamp'] = int(curren | t_time)
if args.expiration:
data['expire'] = int(args.expiration)
else:
expiration = False
path = "silence/%s" % args.client
if args.check:
path = "%s/%s" % (path, args.check)
data['path'] = path
print(stashes.post_by_path(path, json.dumps(data)))
|
sipwise/repoapi | repoapi/models/__init__.py | Python | gpl-3.0 | 825 | 0 | # Copyright (C) 2015-2020 The Sipwise Team - http://sipwise.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)
# any later version.
#
# Th... | d warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PUR | POSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
from .gri import GerritRepoInfo # noqa
from .jbi import JenkinsBuildInfo # noqa
from .wni import WorkfrontNoteInfo... |
openqt/algorithms | projecteuler/pe598-split-divisibilities.py | Python | gpl-3.0 | 660 | 0.010606 | #!/usr/bin/env python
# coding=utf-8
"""598. Split Divis | ibilities
https://projecteuler.net/problem=598
Consider the number 48.
There are five pairs of integers $a$ and $b$ ($a \leq b$) such that $a \times
b=48$: (1,48), (2,24), (3,16), (4,12) and (6,8).
It can be seen that both 6 and 8 have 4 divisors.
So of those five pairs one consists of two integers with the same... | al:
Let $C(n)$ be the number of pairs of positive integers $a \times b=n$, ($a
\leq b$) such that $a$ and $b$ have the same number of divisors;
so $C(48)=1$.
You are given $C(10!)=3$: (1680, 2160), (1800, 2016) and (1890,1920).
Find $C(100!)$
"""
|
adaptive-learning/robomission | backend/learn/tests/test_mastery.py | Python | gpl-3.0 | 5,319 | 0.000188 | import pytest
from learn.models import Task, ProblemSet, Domain
from learn.models import Student, TaskSession, Skill
from learn.mastery import has_mastered, get_level
from learn.mastery import get_first_unsolved_mission
from learn.mastery import get_first_unsolved_phase
from learn.mastery import get_current_mission_ph... | ():
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
p2 = m1.add_part()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=m1, value=1)
Skill.objects.create(student=student, chunk=p1, value=1)
Skill.objects.create(student=student, chunk=p2, value=0)
assert ... | ects.create()
domain.problemsets.set([mission])
student = Student.objects.create()
assert get_first_unsolved_mission(domain, student) == mission
@pytest.mark.django_db
def test_get_first_unsolved_mission__all_unsolved():
mission1 = ProblemSet.objects.create(section='1')
mission2 = ProblemSet.objec... |
cislaa/prophy | prophyc/tests/test_model.py | Python | mit | 29,060 | 0.007123 | from prophyc import model
def test_typedef_repr(): |
typedef = model.Typedef("my_typedef", "u8")
assert str(typedef) == "u8 my_typedef"
def test_struct_repr():
struct = model.Struct("MyStruct", [
model.St | ructMember("a", "u8"),
model.StructMember("b", "u16", bound = 'xlen'),
model.StructMember("c", "u32", size = 5),
model.StructMember("d", "u64", bound = 'xlen', size = 5),
model.StructMember("e", "UU", unlimited = True),
model.StructMember("f", "UUUU", optional = True)
])
... |
thaim/ansible | lib/ansible/plugins/doc_fragments/oracle_display_name_option.py | Python | mit | 436 | 0.004587 | # Copyright (c) 2018, Oracle and/or its affiliates.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocF | ragment(object):
DOCUMENTATION = """
options:
display_name:
description: Use I(display_name) along with the other options to return only resources that match the given
dis | play name exactly.
type: str
"""
|
balazsdukai/batch3dfier | batch3dfier/db.py | Python | gpl-3.0 | 2,117 | 0 | # -*- codi | ng: utf-8 -*-
"""Database connection class."""
import psycopg2
class db(object):
"""A database connection class """
def __init__(self, dbname, host, port, user, password):
self.dbname = dbname
self.host = host
self.port = port
self.user = user
self.password = passwor... | self.conn = psycopg2.connect(
"dbname=%s host=%s port=%s \
user=%s password=%s" %
(dbname, host, port, user, password))
print("Opened database successfully")
except BaseException:
print("I'm unable to c... |
manassolanki/erpnext | erpnext/hr/doctype/expense_claim_type/test_expense_claim_type.py | Python | gpl-3.0 | 317 | 0.009464 | # -*- coding: | utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Expense Claim Type')
class TestExpenseCla | imType(unittest.TestCase):
pass
|
mbrucher/ATK-plugins | ATKStereoPhaser/update_version.py | Python | bsd-3-clause | 4,450 | 0.020449 | #!/usr/bin/python
# this script will update the versions in plist and installer files to match that in resource.h
import plistlib, os, datetime, fileinput, glob, sys, string
scriptpath = os.path.dirname(os.path.realpath(__file__))
def replacestrs(filename, s, r):
files = glob.glob(filename)
for line in filein... | rtas['CFBundleGetInfoString'] = CFBundleGetInfoString
# rtas['CFBundleVersion'] = CFBundleVersion
# rtas['CFBundleShortVersionString'] = CFBundleVersion
# plistlib.writePlist(rtas, plistpath)
# replacestrs(plistpath, "//Apple//", "//Apple Computer//");
#
# plistpath = scriptpath + "/resources/ATKStereoPhaser-AA... | FBundleGetInfoString
# aax['CFBundleVersion'] = CFBundleVersion
# aax['CFBundleShortVersionString'] = CFBundleVersion
# plistlib.writePlist(aax, plistpath)
# replacestrs(plistpath, "//Apple//", "//Apple Computer//");
# plistpath = scriptpath + "/resources/ATKStereoPhaser-IOSAPP-Info.plist"
# iosapp = plistlib.... |
zygmuntz/kaggle-bestbuy_small | train.py | Python | mit | 1,432 | 0.066341 | 'http://fastml.com/best-buy-mobile-contest/'
import sys, csv, re
def prepare( query ):
query = re.sub( r'[\W]', '', query )
query = query.lower()
return query
popular_skus = [9854804, 2107458, 2541184, 2670133, 2173065]
input_file = sys.argv[1]
test_file = sys.argv[2]
output_file = sys.argv[3]
i = open( input_f... | csv.writer( o, delimiter = " " )
n = 0 # all test cases
m = 0 # the ones we have mapping for
for line in reader:
n += 1
query = line[2]
query = prepare( query )
if query in mapping:
m += 1
skus = []
for sku in sorted( mapping[query], key=mapping[query].get, reverse = True ):
skus.append( sku )
#p... | skus = skus[0:5]
else:
skus = popular_skus
writer.writerow( skus )
print "Used mapping in %s / %s (%s)" % ( m, n, 1.0 * m / n ) |
LucidBlue/mykeepon-storyteller | src/realTimeAudio.py | Python | bsd-3-clause | 1,209 | 0.019024 | import ui_plot
import sys
import numpy
from PyQt4 import QtCore, QtGui
import PyQt4.Qwt5 as Qwt
from recorder import *
def plotSomething():
if SR.newAudio==False:
| return
xs,ys=SR.fft()
c.setData(xs,ys)
uiplot.qwtPlot.replot()
SR.newAudio=False
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win_plot = ui_plot.QtGui.QMainWindow()
uiplot = ui_plot.Ui_win_plot()
uiplot.setupUi(win_plot)
uiplot.btnA.clic | ked.connect(plotSomething)
#uiplot.btnB.clicked.connect(lambda: uiplot.timer.setInterval(100.0))
#uiplot.btnC.clicked.connect(lambda: uiplot.timer.setInterval(10.0))
#uiplot.btnD.clicked.connect(lambda: uiplot.timer.setInterval(1.0))
c=Qwt.QwtPlotCurve()
c.attach(uiplot.qwtPlot)
ui... |
CharlesGust/django-imagr | imagr_site/imagr_app/migrations/0003_auto_20141114_1441.py | Python | mit | 1,007 | 0 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('imagr_app', '0002_auto_20141106_1538'),
]
operations = [
migrations.AlterField(
m | odel_name='album',
name='date_published',
field=models.DateField(blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='album',
name='title',
field=models.CharField(max_length=60),
preserve_default=Tru... |
Qwaz/solved-hacking-problem | DEFCON/2020 Quals/ooo-flag-sharing/chal.original.py | Python | gpl-2.0 | 8,529 | 0.009849 | #!/usr/bin/env python3
import gensafeprime
import contextlib
import textwrap
import hashlib
import fuckpy3 #pylint:disable=unused-import
import random
import numpy as np
import ast
import os
import re
banner = r"""
___ ___ ___ _____ _
/ _ \ / _ \ / _ \ | ___|... | ])
def sanity_check(n=N, k=K, m=M):
def one_check(secret):
shares = split_secret(secr | et, n, k, m)
random.shuffle(shares)
new_secret = reconstitute_secret(shares[:k], m)
asser |
agconti/Ember-Demo | ember_demo/config/settings.py | Python | mit | 14,218 | 0.006119 | # -*- coding: utf-8 -*-
"""
Django settings for ember_demo project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.... | RATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = join(os.path.dirname(BASE_DIR), 'staticfiles')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfi... | join(BASE_DIR, 'static'),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
########## END STA... |
kyleabeauchamp/pysam | pysam/Pileup.py | Python | mit | 8,975 | 0.000557 | '''Tools for working with files in the samtools pileup -c format.'''
import collections
import pysam
PileupSubstitution = collections.namedtuple("PileupSubstitution",
" ".join((
"chromosome",
... | "consensus_quality",
"snp_quality",
| "mapping_quality",
"coverage",
"first_allele",
"second_allele",
"reads_first",
"reads_second"... |
DesertBot/DesertBot | desertbot/modules/commands/Join.py | Python | mit | 1,084 | 0.001845 | """
Created on Dec 20, 2011
@author: StarlitGhost
"""
from twisted.plugin import IPlugin
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import IModule
from desertbot.modules.commandinterface import BotCommand
from desertbot.response import IRCResponse, R... | 'join <channel> - makes the bot join the specified channel(s)'
def execute(self, message: IRCMessage):
if len(message.parameterList) > 0:
responses = []
for param in message.parameterList:
channel = param
if not chan | nel.startswith('#'):
channel = '#' + channel
responses.append(IRCResponse(f'JOIN {channel}', '', ResponseType.Raw))
return responses
else:
return IRCResponse(f"{message.user.nick}, you didn't say where I should join", message.replyTo)
join = Join()
|
mortbauer/openfoam-extend-Breeder-other-scripting-PyFoam | PyFoam/IPythonHelpers/Notebook.py | Python | gpl-2.0 | 6,200 | 0.013387 | # ICE Revision: $Id$
"""Read and create IPython-Notebooks
"""
import json
from copy import deepcopy
from time import asctime
from PyFoam.Error import error,warning
from PyFoam.ThirdParty.six import string_types,text_type,u
class Notebook(object):
"""Class that represents an IPython-notebook in memory"""
d... | for conveniently querying metadata"""
def __init__(self,classes=(),pyFoam={},**kwargs):
dict.__init__(self,deepcopy(kwargs))
if not u("metadata") in self:
| self[u("metadata")]={}
if len(classes)>0 or len(pyFoam)>0:
py=deepcopy(pyFoam)
if not "pyFoam" in self[u("metadata")]:
self[u("metadata")]["pyFoam"]=py
else:
self[u("metadata")]["pyFoam"].update(py)
if len(classes)>0:
if i... |
thomasjm/LyX | po/lyx_pot.py | Python | gpl-2.0 | 27,060 | 0.003806 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# file lyx_pot.py
# This file is part of LyX, the document processor.
# Licence details can be found in the file COPYING.
#
# \author Bo Peng
#
# Full author contact details are available in file CREDITS
# Usage: use
# lyx_pot.py -h
# to get usage message
# This scri... | NORECASE)
DescBegin = re.compile(r'^\s*#DescriptionBegin\s*$', re.IGNORECASE)
DescEnd = re.compile(r'^\s*#\s*DescriptionEnd\s*$', re.IGNORECASE)
Category = re.compile(r'^\s*#\s*Category | :\s+(.*\S)\s*$', re.IGNORECASE)
I18nPreamble = re.compile(r'^\s*((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
EndI18nPreamble = re.compile(r'^\s*End((Lang)|(Babel))Preamble\s*$', re.IGNORECASE)
I18nString = re.compile(r'_\(([^\)]+)\)')
CounterFormat = re.compile(r'^\s*PrettyFormat\s+"?(.*)"?\s*$', re.IG... |
myles/twtxt-cli | setup.py | Python | mit | 850 | 0.001176 | import os
from setuptools import setup
from twtxtcli import __version__, __project_name__, __project_link__
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name=__project_name__,
version=__v | ersion__,
author='Myles Braithwaite',
author_email='me@mylesbraithwaite.com',
description='',
license='BSD',
keywords='twtxt',
url=__project_lin | k__,
packages=['twtxtcli'],
long_description=read('README'),
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: MIT License",
],
install_requires=[
'requests',
'clint',
'humanize',
'iso8601'
]... |
jcarbaugh/python-rd | rd/core.py | Python | bsd-3-clause | 6,389 | 0 | import datetime
import logging
JRD_TYPES = ('application/json', 'application/xrd+json', 'text/json')
XRD_TYPES = ('application/xrd+xml', 'text/xml')
logger = logging.getLogger("rd")
def _is_str(s):
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
def loads(... | elf.href = href
self.template = template
self._titles = TitleList()
| self._properties = PropertyList()
def get_titles(self):
return self._titles
titles = property(get_titles)
def get_properties(self):
return self._properties
properties = property(get_properties)
#
# main RD class
#
class RD(object):
def __init__(self, xml_id=None, subject=N... |
wathsalav/xos | xos/openstack_observer/steps/sync_slivers.py | Python | apache-2.0 | 6,455 | 0.012239 | import os
import base64
import socket
from django.db.models import F, Q
from xos.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.sliver import Sliver
from core.models.slice import Slice, SlicePrivilege, ControllerSlice
from core.models.network import Network, NetworkSlice,... | host_filter = sliver.node.name.strip()
availability_zone_filter = 'nova:%s'%host_filter
sliver_name = '%s-%d'%(sliver.slice.name,sliver.id)
userData = self.get_userdata(sliver)
if sliver.userData:
userData = sliver.userData
controller = sliver.node.site_deploy... | 'admin_user': sliver.creator.email,
'admin_password': sliver.creator.remote_password,
'admin_tenant': sliver.slice.name,
'tenant': sliver.slice.name,
'tenant_description': sliver.slice.description,
'... |
Tesi-Luca-Davide/ryu | ryu/ofproto/oxm_fields.py | Python | apache-2.0 | 13,622 | 0.00022 | # Copyright (C) 2013-2015 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013-2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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
#
... | --------+
# | experimenter ID |
# +---------------------------------------------------------------+
# NOTE: EXT-256 had a variation of experimenter OXM header.
# It has been rectified since then. Currentl | y this implementation
# supports only the old version.
#
# ONF EXT-256 (old, exp_type = 2560)
# +-------------------------------+-------------+-+---------------+
# | class (OFPXMC_EXPERIMENTER) | ????? |m| length |
# +-------------------------------+-------------+-+---------------+
# | experimenter ID (O... |
apporc/neutron | neutron/extensions/quotasv2.py | Python | apache-2.0 | 5,333 | 0 | # Copyright 2011 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | 'POST requests are not supported on this resource.')
| raise webob.exc.HTTPNotImplemented(msg)
def index(self, request):
context = request.context
self._check_admin(context)
return {self._resource_name + "s":
self._driver.get_all_quotas(
context, resource_registry.get_all_resources())}
def tenant(sel... |
eloquence/unisubs | apps/subtitles/workflows.py | Python | agpl-3.0 | 18,336 | 0.000873 | # Amara, universalsubtitles.org
#
# Copyright (C) 2014 Participatory Culture 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 opti... | action_name:
retu | rn action
raise LookupError("No action: %s" % action_name)
def perform_action(self, user, language_code, action_name):
"""Perform an action on a subtitle set
This method is used to perform an action by itself, without new
subtitles being added.
"""
action = self.loo... |
agraubert/agutil | agutil/security/__init__.py | Python | mit | 452 | 0 | from .src.securesocket import SecureSocket
| from .src.connection import SecureConnection
from .src.files import encryptFile, decryptFile, encryptFileObj, decryptFileObj
from .src.server import | SecureServer
from .src.cipher import (
configure_cipher,
EncryptionCipher,
DecryptionCipher,
CipherHeader,
Bitmask,
CipherError,
HeaderError,
HeaderLengthError,
InvalidHeaderError,
EncryptionError,
DecryptionError
)
|
andreagrandi/toshl-python | toshl/category.py | Python | mit | 427 | 0 | class | Category(object):
def __init__(self, client):
self.client = client
def list(self):
response = self.client._make_request('/categories')
response = response.json()
return self.client._list_response(response)
def search(self, category_name):
categories = self.list()
... | d']
|
grg2rsr/xyt_movement_correction | lsm2tiff_batch_converter.py | Python | gpl-2.0 | 441 | 0.011338 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 14 13:13:02 2015
@author: georg
"""
import IOtools as io
import sys
import os
filelist_file = sys.argv[1]
with open(filelist_file,'r') as fH:
paths = [line.strip() for line in fH.readlines()]
|
for path in paths:
print "processing file: " + path
| outpath = os.path.splitext(path)[0] + '.tif'
io.lsm2tiff(path)
#sys.stdout.write("\n") # move the cursor to the next line |
djscheuf/Machikoro-Simulator | MachikoroSimulator/MachikoroSimulator/Simulator/BatchSimulator.py | Python | mit | 1,597 | 0.001252 | import concurrent.futures
from copy import deepcopy
from .SimulationResult import SimulationResult
class BatchSimulator:
def __init__(self, game, logger, count=1000, batch_size=5):
self._game = game
self._max = count
self._batch_size = batch_size
self._batches = self._max//self._ba... |
batch = []
for i in range(self._batch_size):
batch.append(executor.submit(self._run_a_game, deepcopy(self._game)))
for future in concurrent.futures.as_completed(batch):
game_result = future.result()
self._increme | nt_win_count(game_result.winner)
self._turns += game_result.turns
self._count += 1
@staticmethod
def _run_a_game(game):
game.reset()
game.run()
return game.get_result()
def _increment_win_count(self, winner):
name = winner.name
self._... |
MiroK/dolfin | demo/undocumented/extrapolation/python/demo_extrapolation.py | Python | gpl-3.0 | 1,227 | 0 | # Copyright (C) 2010 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... |
# First added: 2010-02-08
# Last changed: 2010-02-09
from dolfin import *
# Create mesh and function spaces
mesh = UnitSquareMesh(8, 8)
P1 = FunctionSpace(mesh, "CG", 1)
P2 = FunctionSpace(mesh, "CG", 2)
# Create exact dual
dual = Expression("s | in(5.0*x[0])*sin(5.0*x[1])")
# Create P1 approximation of exact dual
z1 = Function(P1)
z1.interpolate(dual)
# Create P2 approximation from P1 approximation
z2 = Function(P2)
z2.extrapolate(z1)
# Plot approximations
plot(z1, title="z1")
plot(z2, title="z2")
interactive()
|
jdemel/gnuradio | gnuradio-runtime/python/gnuradio/gru/seq_with_cursor.py | Python | gpl-3.0 | 1,933 | 0.008795 | #
# Copyright 2003,2004 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
# misc utilities
fro | m __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
| __slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
assert len (items) > 0, "seq_with_cursor: len (items) == 0"
self.items = items
self.set_index (initial_index)
if initial_value is not None:
self.set_index_by_valu... |
SickGear/SickGear | lib/enzyme/language.py | Python | gpl-3.0 | 15,177 | 0 | # -*- coding: utf-8 -*-
# enzyme - Video metadata parser
# Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com>
# Copyright 2003-2006 Dirk Meyer <dischi@freevo.org>
#
# This file is part of enzyme.
#
# enzyme is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public Lice... | Y; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License f | or more details.
#
# You should have received a copy of the GNU General Public License
# along with enzyme. If not, see <http://www.gnu.org/licenses/>.
import re
from six import string_types
__all__ = ['resolve']
def resolve(code):
"""
Transform the given (2- or 3-letter) language code to a human readable
... |
redhat-openstack/heat | heat/openstack/common/loopingcall.py | Python | apache-2.0 | 4,501 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | return self.done.wait()
class FixedIntervalLoopingCall(LoopingCallBase):
"""A fixed interval looping call."""
def start(self, interval, initial_delay=None):
self._running = True
done = event.Event()
def _inner():
if initial_delay:
greenthread.sleep(initi... | lf.f(*self.args, **self.kw)
end = timeutils.utcnow()
if not self._running:
break
delay = interval - timeutils.delta_seconds(start, end)
if delay <= 0:
LOG.warn(_LW('task run outlasted interval... |
dperconti/hexwick_python | hexwick/migrations/0001_initial.py | Python | agpl-3.0 | 3,992 | 0.002004 | # -*- 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),
]
operations = [
migrations.Create... | ('available_balance', models.CharF | ield(max_length=200)),
('_user', models.CharField(max_length=200)),
('_item', models.CharField(max_length=200)),
('_id', models.CharField(max_length=200)),
('access_token', models.CharField(max_length=200)),
],
options={
... |
lxy235/lserver | src/Common/Lang/zh_cn.py | Python | apache-2.0 | 1,569 | 0.026793 | # !/usr/bin/python
# coding=utf-8
#
# @Author: LiXiaoYu
# @Time: 2013-10-17
# @Info: lang
_lang = {
'_MODULE_NOT_EXIST_':'无法加载模块',
'_ERROR_ACTION_':'非法操作 | ',
'_LANGUAGE_NOT_L | OAD_':'无法加载语言包',
'_TEMPLATE_NOT_EXIST_':'模板不存在',
'_MODULE_':'模块',
'_ACTION_':'操作',
'_ACTION_NOT_EXIST_':'控制器不存在或者没有定义',
'_MODEL_NOT_EXIST_':'模型不存在或者没有定义',
'_VALID_ACCESS_':'没有权限',
'_XML_TAG_ERROR_':'XML标签语法错误',
'_DATA_TYPE_INVALID_':'非法数据对象!',
'_OPERATION_WRONG_':'操作出现错误',
'_NOT_... |
rbaumg/trac | trac/web/tests/api.py | Python | bsd-3-clause | 31,977 | 0.000125 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2019 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consi... | def process_request(self, req):
self.assertTrue(self.req_handler.match_request(req))
return self.req_handler.process_request(req)
def _make_environ(scheme='http', server_name='example.org',
server_port=80, method='GET', script_name='/trac',
**kwargs):
environ ... | AME': server_name,
'SERVER_PORT': server_port, 'SCRIPT_NAME': script_name}
environ.update(kwargs)
return environ
def _make_req(environ, authname='admin', chrome=None, form_token='A' * 40,
locale=None, perm=MockPerm(), tz=utc, use_xsendfile=False,
xsendfile_header='X-... |
shoopio/shoop | shuup/discounts/migrations/0007_delete_fields.py | Python | agpl-3.0 | 2,742 | 0.001459 | # Generated by Django 2.2.18 on 2021-07-28 20:41
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('discounts', '0006_migrate_discounts'),
]
operations = [
migrations.Remove... | ,
),
migrations.RemoveField(
model_name='discount',
name='coupon_code',
),
migrations.RemoveField(
model_name='discount',
name='exclude_selected_contact_group',
),
migrations.RemoveField(
model_na | me='discount',
name='shops',
),
migrations.RemoveField(
model_name='happyhour',
name='shops',
),
migrations.AlterField(
model_name='discount',
name='created_by',
field=models.ForeignKey(blank=True, null=True, on_dele... |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/testscript.py | Python | bsd-3-clause | 50,708 | 0.008381 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/TestScript) on 2017-03-22.
# 2017, SMART Health IT.
from . import domainresource
class TestScript(domainresource.DomainResource):
""" Describes a set of tests.
A structured set of... | of `TestScriptVariable` items (represented as `dict` in JSON). """
self.version = None
""" Business version of the test script.
Type `str | `. """
super(TestScript, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(TestScript, self).elementProperties()
js.extend([
("contact", "contact", contactdetail.ContactDetail, True, None, False),
("copyright", "cop... |
reschly/cryptopals | prob3.py | Python | apache-2.0 | 2,592 | 0.021991 | #!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 3
# The hex encoded string:
# 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736
# has been XOR'd against a single character. Find the key, decrypt
# the message.
# Some of the 'magic' in this comes from a college crypto... | tterFrequency['S'] = .063;
letterFrequency['T'] = .091;
letterFrequency['U'] = .028;
letterFrequency['V'] = .010;
letterFrequency['W'] = .023;
letterFrequency['X'] = .001;
letterFrequency['Y'] = .020;
letterFrequency['Z'] = .001;
letterFrequenc | y[' '] = .200;
# See page 35, Stinson
def calculateMG(plain):
counts = [];
for i in range(256):
counts.append(0);
for i in range(len(plain)):
if (plain[i] < 128):
counts[ord(chr(plain[i]).upper())] += 1;
result = 0.0;
for i in string.ascii_uppe... |
the13fools/Bokeh_Examples | plotting/file/relative_paths.py | Python | bsd-3-clause | 1,023 | 0.00391 | # All of the other examples directly embed the Javascript and CSS code for
# Bokeh's client-side runtime into the HTML. This leads to the HTML files
# being rather large. An alternative is to ask Bokeh to produce HTML that
# has a relative link to the Bokeh Javascript and CSS. This is easy to
# do; you just pass in ... | p.pi, N)
y = np.sin(x)
output_file("relative_paths.html", title="Relative path example", mode="relative")
scatter(x,y, color="#FF00FF", tools="pan,wheel_zoom,box_zoom,reset,previewsave")
show()
# By default, the URLs for the Javascript and CSS will be relative to
# the current directory, i.e. th | e directory in which the HTML file is
# generated. You can provide a different "root" directory from which
# the relative paths will be computed:
#
# output_file("scatter.html", title="scatter.py example",
# resources="relative", rootdir="some/other/path")
|
ckclark/leetcode | py/valid-triangle-number.py | Python | apache-2.0 | 931 | 0.003222 | from collections import Counter
class Solution(object):
def triangleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
| nums = filter(None, nums)
if not nums:
return 0
c = Counter(nums)
N = max(nums)
buckets = [0] * (N + 1)
for k, cnt in c.iteritems():
buckets[k] += cnt
for i in xrange(1, N + 1):
buckets[i] += buckets[i - 1]
s = sorted(c)... | ans += c[n1] * c[n2] * (buckets[min(n1_n2 - 1, N)] - buckets[n1])
ans += c[n2] * (c[n1] - 1) * c[n1] / 2
ans += c[n1] * (c[n1] - 1) * (c[n1] - 2) / 6
ans += c[n1] * (c[n1] - 1) / 2 * (buckets[min(n1 * 2 - 1, N)] - buckets[n1])
return ans
|
ChristopherGS/sensor_readings | app/sensors/models.py | Python | bsd-3-clause | 3,951 | 0.004303 | from datetime import datetime
from app.data import CRUDMixin, db
class Experiment(CRUDMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
hardware = db.Column(db.Text)
t_stamp = db.Column(db.DateTime)
label = db.Column(db.Text)
sensors = db.relationship('Sensor', backref='experiment',... | Z_AXIS
self.LINEAR_ACCELERATION_X = LINEAR_ACCELERATION_X
| self.LINEAR_ACCELERATION_Y = LINEAR_ACCELERATION_Y
self.LINEAR_ACCELERATION_Z = LINEAR_ACCELERATION_Z
self.GYROSCOPE_X = GYROSCOPE_X
self.GYROSCOPE_Y = GYROSCOPE_Y
self.GYROSCOPE_Z = GYROSCOPE_Z
self.ORIENTATION_Z = ORIENTATION_Z
self.ORIENTATION_X = ORIENTATION_X
... |
azverkan/scons | test/Deprecated/SourceCode/CVS/CVS.py | Python | mit | 11,399 | 0.005527 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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 use, copy, modify, merge, publish,
... | cvs, arguments = 'init')
test.write(['import', 'aaa.in'], "import/aaa.in\n")
test.write(['import', 'bbb.in'], "import/bbb.in\n")
test.write(['import', 'ccc.in'], "i | mport/ccc.in\n")
test.write(['import', 'sub', 'SConscript'], """\
Import("env")
env.Cat('ddd.out', 'ddd.in')
env.Cat('eee.out', 'eee.in')
env.Cat('fff.out', 'fff.in')
env.Cat('all', ['ddd.out', 'eee.out', 'fff.out'])
""")
test.write(['import', 'sub', 'ddd.in'], "import/sub/ddd.in\n")
test.write(['import', 'sub', 'eee... |
tylertian/Openstack | openstack F/cinder/cinder/api/openstack/volume/views/limits.py | Python | apache-2.0 | 3,478 | 0.000288 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-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... | e": rate_limits,
"absolute": absolute_limits,
},
}
return output
def _build_absolute_limits(self, absolute_limits):
"""Builder for absolute limits
absolute_limits should be given as a dict of limits.
For example: {"ram": 512, "gigabytes": 1024}.... | "cores": ["maxTotalCores"],
"gigabytes": ["maxTotalVolumeGigabytes"],
"volumes": ["maxTotalVolumes"],
"key_pairs": ["maxTotalKeypairs"],
"floating_ips": ["maxTotalFloatingIps"],
"metadata_items": ["maxServerMeta", "maxImageMeta"],
"injected_file... |
zero-rp/miniblink49 | third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/mock_drt.py | Python | apache-2.0 | 12,040 | 0.002243 | # Copyright (c) 2012 Google Inc. 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
# notice, this list of conditions and the ... | ys.executable,
path_to_this_file,
self.__delegate.name())
return driver
@staticmethod
def _overriding_cmd_line(original_cmd_line, driver_pat | h, python_exe, this_file, port_name):
def new_cmd_line(pixel_tests, per_test_args):
cmd_line = original_cmd_line(pixel_tests, per_test_args)
index = cmd_line.index(driver_path)
cmd_line[index:index + 1] = [python_exe, this_file, '--platform', port_name]
return cmd... |
IEEEDTU/CMS | Course/migrations/0006_auto_20160410_1530.py | Python | mit | 572 | 0.001748 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-04-10 10:00
from __future__ import unicode_liter | als
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Course', '0005_coursegroup'),
]
operations = [
migrations.AlterField(
model_name='department',
name='hod',
| field=models.ForeignKey(default=False, on_delete=django.db.models.deletion.CASCADE, related_name='head_of_dept', to='Profiler.Faculty'),
),
]
|
skitazaki/python-school-ja | src/datestring_convert.py | Python | mit | 783 | 0 | #!/usr/bin/env python
# | -*- coding: utf-8 -*-
import datetime
def datestring_convert(s):
"""Convert datetime string which appears in subversion commit log.
"""
assert type(s) == str, "Argument must be string"
dt = s.split()
year, month, day = map(int, dt[0].split("-"))
hour, minute, second = map(int, dt[1].split(":... |
d1 = datestring_convert(TEST_1)
d2 = datestring_convert(TEST_2)
diff = d1 - d2
print("{} ==> {}".format(TEST_1, TEST_2))
print("DIFF: days={}, seconds={}".format(diff.days, diff.seconds))
# vim: set et ts=4 sw=4 cindent fileencoding=utf-8 :
|
Bekt/tweetement | src/tqueue.py | Python | mit | 4,586 | 0 | import logging
import service
import webapp2
from models import (Query, Status, Method)
from collections import Counter
from google.appengine.api import mail
from google.appengine.ext import ndb
class QueueHandler(webapp2.RequestHandler):
def pop(self):
"""Pops a query from the queue and performs query ... | {}'.format(q, hashtags[0], q, keywords[0])
m6 = serv.fetch(q6, limit=195)
| counter = Counter()
for tweet in m6:
for token in set(tweet.text.split()):
ok, text = service._token_okay(token)
if ok and (text in hashtags or text in keywords):
counter[tweet.id] += 1
m6 = counter.most_common(10)
if m6:
... |
Rastagong/A-Scholar-In-The-Woods | Releases/Post Compo/Windows build/play.py | Python | mit | 507 | 0.00789 | # -*-coding:iso-8859-1 -*
try: #If needed, the _path module must add the path to the Narro directory to sys.path so that the Narro Engine can be imported as a package
import _path
except:
pass
from constantes import *
from narro.main import *
from narro.constantes import *
from gestionnaireEvenements import *
... | u = Narro()
jeu.inclureGestionnaire(MonGestionnaireEvenements(jeu))
jeu.execu | ter()
if REDIRECTION_FICHIER_ERREURS:
sys.stderr.close()
|
laurentb/weboob | modules/bred/module.py | Python | lgpl-3.0 | 3,023 | 0.000662 | # -*- coding: utf-8 -*-
# Copyright(C) 2012-2014 Romain Bignon
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the L... | self.BROWSER = self.BROWSERS[self.config['website'].get()]
return self.create_browser(
self.config['accnum'].get().replace(' ', '').zfill(11),
self.config['login'].get(),
self.config['password'].get(),
weboob=self.weboob,
)
def iter_accounts(self):... | self.browser.get_accounts_list()
def get_account(self, _id):
return find_object(self.browser.get_accounts_list(), id=_id, error=AccountNotFound)
def iter_history(self, account):
return self.browser.get_history(account)
def iter_coming(self, account):
return self.browser.get_histo... |
etingof/talks | pyvo-optional-static-typing/code/12-add-annotations.py | Python | gpl-3.0 | 331 | 0 | """
This code will fail at runtime...
Could you help `mypy` catching the problem at compile time?
"""
def sum_numbers(*n) -> float:
"""Sums up any number of numbers"""
return sum(n)
if __name__ == '__main__':
sum_numbers(1, 2.0) # | this is not a bug
sum_numbers('4', 5) | # this is a bug - can `mypy` catch it?!
|
TwilioDevEd/api-snippets | rest/messages/sms-handle-callback/sms-handle-callback.7.x.py | Python | mit | 452 | 0 | from flask import Flask, request
import logging
logging.basicConfig(level=logging.INFO)
app = Flask(__name__)
@app | .route("/MessageStatus", methods=['POST'])
def incoming_sms():
message_si | d = request.values.get('MessageSid', None)
message_status = request.values.get('MessageStatus', None)
logging.info('SID: {}, Status: {}'.format(message_sid, message_status))
return ('', 204)
if __name__ == "__main__":
app.run(debug=True)
|
sknepneklab/SAMoS | configurations/MakeConfigurations/TissueWithObstacle/circle.py | Python | gpl-3.0 | 826 | 0.021792 | from obstacle import *
class Circle(Obstacle):
def __init__(self, Rc, dens, R):
Obstacle.__init__(self,Rc,dens)
if R <= 0:
raise Exception('Circle radius has to be positive')
self.R = R
def make(self, offset = 0):
N = int(np.round(2*np.pi*self.R*s | elf.dens))
phi = np.linspace(0,2*np.pi*(1-1/N),N)
x = self.Rc[0] + self.R*np.cos(phi)
y = self.Rc[1] + self.R*np.sin(phi)
z = np.zeros(N)
for i in range(N):
p = Particle(i + offset)
p.radius = 1.0
p.type = self.obstacle_type
p.r = ... | np.array([0,0,0])
p.n = np.array([0,0,0])
p.in_tissue = 0
p.boundary = 0
self.pos.append(p)
|
usrix/alfred-verbizr-workflow | verbizr.py | Python | gpl-2.0 | 1,716 | 0.020979 | # Library from https://github.com/nikipore/alfred-python
import alfred
import re
import unicodedata
import xml.dom
import xml.dom.minidom
import time
# XML verbs db
conjFR = xml.dom.minidom.parse('conjugation-fr.xml')
verbsFR = xml.dom.minidom.parse('verbs-fr.xml')
conjList = conjFR.getElementsByTagName('template')
v... | e value
if (template != None) :
templateSplit = template.split(':')
radical = usrInput.replace(templateSplit[1], "")
termina = templateSplit[1]
# loop to check conj list
for v in conjList :
line = v.attributes | ['name'].value
if template == line:
# we are in the verb
# we need to extract the verb
# from
momentoNode = v.getElementsByTagName('indicative')
# get each conj
for tiempoNode in momentoNode :
#for present
personas = tiempoNode.getElementsByTagName('present')
for personaNode ... |
virtuald/exaile | plugins/ipconsole/ipconsoleprefs.py | Python | gpl-2.0 | 1,656 | 0.006039 | # | Copyright (C) 2012 Brian Parma
#
# 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 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it w... | CULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from xlgui.preferences import widg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.