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 |
|---|---|---|---|---|---|---|---|---|
spuriousdata/logrok | logrok/logrok.py | Python | mit | 8,948 | 0.004582 | #!/usr/bin/env python
"""Query and aggregate data from log files using SQL-like syntax"""
import sys
import argparse
import os
import re
import ast
import readline
import atexit
import time
import inspect
from multiprocessing import cpu_count
try:
from collections import OrderedDict
except ImportError:
# pyth... | tring (requires -T)')
cmd.add_argument('-T', '--ctype', help='type-name for LogFormat from specified httpd.conf file (only works with -c)')
cmd.add_argument('-j', '--processes', action='store', type=int, help='Number of proces | ses to fork for log crunching (default: smart)', default=parallel.SMART)
cmd.add_argument('-l', '--lines', action='store', type=int, help='Only process LINES lines of input')
interactive = cmd.add_mutually_exclusive_group(required=False)
interactive.add_argument('-i', '--interactive', action='store_true', h... |
sopython/kesh | kesh/api/__init__.py | Python | bsd-3-clause | 39 | 0.025641 | from .con | nection import MongoConnection | |
damianpv/skeleton_django | sk_django/sk_django/settings/staging.py | Python | gpl-3.0 | 86 | 0.023256 | # Config | uracion para una versin semi-privada en el servidor de produccion. Beta - A | lfa |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2016_12_01/operations/security_rules_operations.py | Python | mit | 18,911 | 0.002327 | # 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 ... | network_security_group_name, security_rule_name, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = '/subscriptions/{subsc | riptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecu... |
sgiavasis/C-PAC | CPAC/GUI/interface/pages/vmhc.py | Python | bsd-3-clause | 3,737 | 0.025957 | import wx
import wx.html
from ..utils.generic_class import GenericClass
from ..utils.constants import control, dtype
from ..utils.validator import CharValidator
import pkg_resources as p
class VMHC(wx.html.HtmlWindow):
def __init__(self, parent, counter = 0):
from urllib2 import urlopen
wx.html.H... | package available on the Install page of the User Guide.\n\nIt is not necessary to change this path unless you intend to use a non-standard symmetric templ | ate.")
self.page.set_sizer()
parent.get_page_list().append(self)
def get_counter(self):
return self.counter
|
tjsavage/sfcsdatabase | sfcs/django/http/__init__.py | Python | bsd-3-clause | 23,818 | 0.002393 | import datetime
import os
import re
import time
from pprint import pformat
from urllib import urlencode, quote
from urlparse import urljoin
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
try:
# The mo | d_python version is more efficient, so try importing it first.
from mod_python.util import parse_qsl
except ImportError:
try:
# Python 2.6 and greater
from urlpars | e import parse_qsl
except ImportError:
# Python 2.5, 2.4. Works on Python 2.6 but raises
# PendingDeprecationWarning
from cgi import parse_qsl
# httponly support exists in Python 2.6's Cookie library,
# but not in Python 2.4 or 2.5.
import Cookie
if Cookie.Morsel._reserved.has_key('httponl... |
google-research/scenic | scenic/projects/baselines/clip/tokenizer.py | Python | apache-2.0 | 1,853 | 0.008095 | """Simple CLIP tokenizer wrapper."""
from absl import logging
import functools
from typing import Any, Callable, Optional, Sequence, Union
from clip.simple_tokenizer import SimpleTokenizer
import jax.numpy as jnp
import numpy as np
from scenic.projects.baselines.clip import download
# pylint: disable=line-too-long
... | TH,
bpe_url: str = DEFAULT_BPE_URL,
download_dir: str = download.DEFAULT_DOWNLOAD_DIR
) -> Callable[[Union[str, Sequence[str]]], np.ndarray]:
"""Returns CLIP's tokenization function."""
if bpe_path is None:
bpe_path = download.download(bpe_url, download_dir)
logging.info('Downloaded vocabulary from ... | length=MAX_TEXT_LENGTH)
return tokenizer_fn
|
jashort/SmartFileSorter | smartfilesorter/actionplugins/renameto.py | Python | bsd-3-clause | 2,257 | 0.004431 | import shutil
import os
import re
import logging
class RenameTo(object):
"""
Renames a given file. Performs a case sensitive search and replace on the filename, then renames it.
Also supports regular expressions.
"""
config_name = 'rename-to'
def __init__(self, parameters):
self.logge... | self.logger.error("Error renaming file {0} to {1}".format(target, new_filename))
raise IOError
else:
self. | logger.error("Destination file already exists: {0}".format(new_filename))
raise IOError
return destination
|
michealcarrerweb/LHVent_app | stock/models.py | Python | mit | 4,911 | 0.007738 | from __future__ import unicode_literals
from django.db import models
import datetime
from django.db.models.signals import pre_save
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from source_utils.starters import CommonInfo, GenericCategor... | ompany_list")
def get_absolute_url(self):
return reverse(
"product:base_product_detail",
kwargs={'slug': self.slug}
)
def pre_save_category(sender, instance, *args, **kwargs):
instance.slug = slugify(i | nstance.category)
pre_save.connect(pre_save_category, sender=Base)
class Product(CommonInfo):
"""
This model describes the specific product related to the category.
"""
base = models.ForeignKey(
Base,
on_delete=models.CASCADE
)
supplier = models.ForeignKey(
'company... |
vFense/vFense | tp/src/server/oauth/token.py | Python | lgpl-3.0 | 484 | 0.006198 | from hashlib import sha512
from uuid import uuid4
from vFense.db.client import validate_session
class TokenManager():
def __init__(self, session):
self.session = session # DB sessio | n
def save_access_token(self, token):
self.session = validate_session(self.session)
self.session.add(token)
self.session.commit()
self.session | .close()
def generate_token(self, length=24):
return sha512(uuid4().hex).hexdigest()[0:length]
|
BloodyD/django-dbbackup | dbbackup/settings.py | Python | bsd-3-clause | 2,525 | 0.005149 | # DO NOT IMPORT THIS BEFORE django.configure() has been run!
import os
from django.conf import settings
DATABASES = getattr(settings, 'DBBACKUP_DATABASES', list(settings.DATABASES.keys()))
BACKUP_DIRECTORY = getattr(settings, 'DBBACKUP_BACKUP_DIRECTORY', os.getcwd())
# Days to keep backups
CLEANUP_KEEP = getattr(se... | DBBACKUP_DATE_FORMAT_REGEX', r"\d{4}-\d{2}-\d{2}-\d{6}")
SERVER_NAME = getattr(settings, 'DBBACKUP_SERVER_NAME', '')
FORCE_ENGINE = getattr(settings, 'DBBACKUP_FORCE_ENGINE', '')
FILENAME_TEMPLATE = getattr(settings, 'DBBACKUP_FILENAME_TEMPLATE', '{databasename}-{servername}-{datetime}.{extension | }')
READ_FILE = '<READ_FILE>'
WRITE_FILE = '<WRITE_FILE>'
# Environment dictionary
BACKUP_ENVIRONMENT = {}
RESTORE_ENVIRONMENT = {}
# TODO: Unify backup and restore commands to support adding extra flags instead
# of just having full statements.
SQLITE_BACKUP_COMMANDS = getattr(settings, 'DBBACKUP_SQLITE_BACKUP_COM... |
NikNitro/Python-iBeacon-Scan | sympy/printing/conventions.py | Python | gpl-3.0 | 2,504 | 0 | """
A few practical conventions common to all printers.
"""
from __future__ import print_function, division
import re
import collections
_name_with_digits_p = re.compile(r'^([a-zA-Z]+)([0-9]+)$')
def split_super_sub(text):
"""Split a symbol name into a name, superscripts and subscripts
The first part ... | 2')
('var', ['sup'], ['sub1', 'sub2'])
"""
if len(text) == 0:
return text, [], []
pos = 0
name = None
supers = []
subs = []
while pos < len(text):
start = pos + 1
if text[pos:pos + 2] == "__":
start += 1
pos_hat = text.find("^", start)
... | _usc < 0:
pos_usc = len(text)
pos_next = min(pos_hat, pos_usc)
part = text[pos:pos_next]
pos = pos_next
if name is None:
name = part
elif part.startswith("^"):
supers.append(part[1:])
elif part.startswith("__"):
supers.appen... |
alseambusher/SemanticTyping | lib/utils.py | Python | mit | 1,139 | 0.005268 | import re
from main import sc
__author__ = 'minh'
class Utils:
def __init__(self):
pass
not_allowed_chars = '[\/*?"<>|\s\t]'
numeric_regex = r"\A( | (\\-)?[0-9]{1,3}(,[0-9]{3})+(\\.[0-9]+)?)|((\\-)?[0-9]*\\.[0-9]+)|((\\-)?[0-9]+)|((\\-)?[0" \
r"-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?)\Z"
@staticmethod
def is_number(example):
matches = re.match(Utils.numeric_regex, example.s | trip())
if matches and matches.span()[1] == len(example.strip()):
return True
return False
@staticmethod
def clean_examples_numeric(examples):
return sc.parallelize(examples).map(lambda x: float(x) if Utils.is_number(x) else "").filter(
lambda x: x).collect()... |
viswimmer1/PythonGenerator | data/python_files/32677285/views.py | Python | gpl-2.0 | 15,766 | 0.000698 | import logging
import traceback
from django.conf import settings
from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseServerError, Http404
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from django.template.loader i... | ion)
if file['force_interdiff']:
interfilediff = file['interfilediff']
if interfilediff:
key += 'interdiff- | %s-%s' % (filediff.pk, interfilediff.pk)
else:
key += 'interdiff-%s-none' % filediff.pk
else:
key += str(filediff.pk)
if chunkindex:
chunkindex = int(chunkindex)
num_chunks = len(file['chunks'])
if chunkindex < 0 or chunkindex >= num_chunks:
... |
noman798/dcny | lib/f42/f42/ob.py | Python | mpl-2.0 | 1,570 | 0.000639 | #!/usr/bin/env python
# coding:utf-8
class Ob(object):
def __init__(self, *args, **kwds):
for i in args:
self.__dict__.update(args)
self.__dict__.update(kwds)
def __getattr__(self, name):
return self.__dict__.get(name, '')
def __setattr__(self, name, value):
... | elf):
for k, v in self.__dict__.item | s():
yield k, v
def __contains__(self, name):
return self.__dict__.__contains__(name)
def __eq__(self, other):
return self.__dict__ == other.__dict__
class StripOb(Ob):
def __init__(self, *args, **kwds):
super(StripJsOb, self).__init__(*args, **kwds)
d = self... |
quietcoolwu/python-playground | imooc/python_advanced/8_1_multi_threading.py | Python | mit | 4,077 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import tarfile
from io import BytesIO
from queue import Queue
from threading import Event, Thread
from xml.etree.ElementTree import Element, ElementTree
import requests
import unicodecsv as csv
class DownloadThread(Thread):
def __init__(self, stock_id, que... | self.cvt_event.set()
self.tar_event.wait()
self.tar_event.clear()
count = 0
# Armor Thread
class TarThread(Thread):
def __init__(self, cvt_event, tar_event):
Thread.__init__(self)
self.count = 0
| self.cvt_event = cvt_event
self.tar_event = tar_event
self.setDaemon(True)
def tarXML(self):
self.count += 1
tfname = '{}.tgz'.format(self.count)
tf = tarfile.open(tfname, 'w:gz')
for fname in os.listdir('.'):
if fname.endswith('.xml'):
... |
DarkFenX/Pyfa | gui/builtinContextMenus/ammoToDmgPattern.py | Python | gpl-3.0 | 1,296 | 0.002315 | # noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFr | ame = gui.ma | inFrame.MainFrame.getInstance()
def display(self, callingWindow, srcContext, mainItem):
if srcContext not in ("marketItemGroup", "marketItemMisc") or self.mainFrame.getActiveFit() is None:
return False
if mainItem is None:
return False
for attr in ("emDamage", "the... |
FelixLoether/flask-uploads | flask_uploads/models.py | Python | mit | 458 | 0.002183 | from .extensions import db, resizer
class Upload(db.Model):
__tablename__ = 'upload'
id = db.Column(db.Integer, autoincrement=True, primary_key=True)
name = db.Column(db.Unicode(255), nullable=False)
url = db.Column(db.Unicode(255), nullable=False)
if resizer:
for size in resizer.sizes.iterkeys(... | ||
papaloizouc/migrants | migrants/base/models.py | Python | gpl-2.0 | 1,356 | 0 | from django.db import models
class DataCategory(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=150)
year = models.IntegerField()
def __unicode__(self):
# Ideadlly would be title but its too big
return u"{} - {}".format(self.year, self.id)... | ield()
class Meta:
unique_together = ('destination', 'origin', 'category')
def __unicode__(self):
fields = [self.origin, " -> ", self.destination, self.category]
return u" ". | join(map(repr, fields))
|
jpapon/minimal_ros_nodes | cnn_classifier/src/cnn_classifier/tensorflow_fcn/fcn16_vgg.py | Python | bsd-3-clause | 16,410 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
from math import ceil
import sys
import numpy as np
import tensorflow as tf
VGG_MEAN = [103.939, 116.779, 123.68]
class FCN16VGG:
def __init__(self, vgg16_npy_path=None):
... | ._conv_layer(self.pool2, "conv3_1")
self.conv3_2 = self._conv_layer(self.conv3_1, "conv3_2")
self.conv3_3 = self._conv_layer(self.conv3_2, "conv3_3")
self.pool3 = self._max_pool(self.conv3_3, 'pool3', debug)
self.conv4_1 = self._conv_layer(self.pool3, "conv4_1 | ")
self.conv4_2 = self._conv_layer(self.conv4_1, "conv4_2")
self.conv4_3 = self._conv_layer(self.conv4_2, "conv4_3")
self.pool4 = self._max_pool(self.conv4_3, 'pool4', debug)
self.conv5_1 = self._conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self._conv_layer(self.conv5_1, "co... |
kura/batfish | tests/test_client_authorize.py | Python | mit | 1,645 | 0 | import collections
import json
import unittest
import responses
from requests import HTTPError
from mock import patch
from batfish import Client
from batfish.__about__ import __version__
class TestClientAuthorize(unittest.TestCase):
def setUp(self):
with patch('batfish.client.read_token_from_conf',
... | content_type="app | lication/json")
auth = self.cli.authorize("test_token")
self.assertEquals(auth, "OK")
self.assertEquals(responses.calls[0].response.status_code, 200)
|
mobb-io/django-erp | djangoerp/menus/signals.py | Python | mit | 2,406 | 0.007897 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file | is part of the django ERP project.
T | HE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN A... |
OpenDataCordoba/codigo-postal-argentino | alembic/versions/f5195fe91e09_agrega_alturas_codprov_y_alturas_cp.py | Python | gpl-2.0 | 796 | 0.001256 | """Agrega alturas.codprov y alturas.cp
Revision ID: f5195fe91e09
Revises: fccbcd8362d7
Create Date: 2017-07-09 22:01:51.280360
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f5195fe91e09'
down_revision = 'fccbcd8362d7'
branch_labels = Non | e
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('alturas', sa.Column('codprov', sa.String(length=1), nullable=True))
op.add_column('alturas', sa.Column('cp', sa.Integer(), nullable=True))
# ### end Alembic commands ###
def downgrade():
... | op_column('alturas', 'codprov')
# ### end Alembic commands ###
|
simontakite/sysadmin | pythonscripts/practicalprogramming/gui/mainloop.py | Python | gpl-2.0 | 78 | 0 | import tkinter
window = t | kinter.Tk()
window.mainloop()
print('Anybod | y home?')
|
Thermi/ocfs2-tools | ocfs2console/ocfs2interface/process.py | Python | gpl-2.0 | 4,541 | 0.002202 | # OCFS2Console - GUI frontend for OCFS2 management and debugging
# Copyright (C) 2002, 2005 Oracle. All rights reserved.
#
# 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 th... | .parent = parent
self.spin_now = spin_now
self.pipe = popen2.Popen4(self.command)
def reap(self):
self.success = False
self.killed = False
self.count = TIMEOUT // INTERVAL
self.threshold = self.count - INTERVAL * 10
self.dialog = None
if self.spi... | self.count = TIMEOUT * 60
self.make_progress_box()
timeout_id = gobject.timeout_add(INTERVAL, self.timeout)
fromchild = self.pipe.fromchild
fileno = fromchild.fileno()
flags = fcntl.fcntl(fileno, fcntl.F_GETFL, 0)
flags = flags | os.O_NONBLOCK
fcntl.fcn... |
aalekperov/Task1 | fixture/db.py | Python | apache-2.0 | 2,534 | 0.005919 | import mysql
import pymysql
from model.group import Group
from model.contact import Contact
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=ho... | "company, title, address, "
"home, mobile, work, fax, "
"email, email2, email3, homepage, "
"bday, bmonth, byear, "
"aday, amonth, ayear, "
"address2, phone2, n... | id, firstname, middlename, lastname, nickname,
company, title, address,
home, mobile, work, fax,
email, email2, email3, homepage,
bday, bmonth, byear,
aday, amonth, ayear,
address2, phone2, notes) = row
... |
parthapritam2717/CodeChef | FCTRL2.py | Python | gpl-3.0 | 283 | 0.038869 | from sys import stdin as sin
list_index=[]
list=dict()
def fn(n):
f=1
#check if a value less that that has already been calculated
for i | in range(1,n+1):
f*=i
return f
t=int(input())
for i i | n range(t):
n=int(sin.readline().rstrip())
print(fn(n)) |
Ragowit/fireplace | fireplace/managers.py | Python | agpl-3.0 | 7,048 | 0.027667 | from hearthstone.enums import GameTag
from . import enums
class Manager(object):
def __init__(self, obj):
self.obj = obj
self.observers = []
def __getitem__(self, tag):
if self.map.get(tag):
return getattr(self.obj, self.map[tag], 0)
raise KeyError
def __setitem__(self, tag, value):
setattr(self.obj... | meTag.CARDTYPE: "type",
GameTag.CHARGE: "charge",
GameTag.CLASS: "card_class",
GameTag.COMBO: "has_combo",
GameTag.CONTROLLER: "controller",
GameTag.COST: "cost",
GameTag.CREATOR: "creator",
GameTag.DAMAGE: "damage",
GameTag.DEATHRATTLE: "has_deathrattle",
GameTag.DEFENDING: "defending",
GameTag.DIVIN | E_SHIELD: "divine_shield",
GameTag.DURABILITY: "max_durability",
GameTag.EMBRACE_THE_SHADOW: "healing_as_damage",
GameTag.ENRAGED: "enrage",
GameTag.EXHAUSTED: "exhausted",
GameTag.EXTRA_DEATHRATTLES: "extra_deathrattles",
GameTag.FORGETFUL: "forgetful",
GameTag.FROZEN: "frozen",
GameTag.HEALING_DOUBLE: "healin... |
nickhand/nbodykit | nersc/example.py | Python | gpl-3.0 | 578 | 0.012111 | from nbodykit.lab import *
f | rom nbodykit import setup_logging
setup_logging("debug")
# initialize a linear power spectrum class
cosmo = cosmology.Planck15
Plin = cosmology.LinearPower(cosmo, redshift=0.55, transfer='CLASS')
# get some lognormal particles
source = LogNormalCatalog(Plin=Plin, nbar=3e-7, BoxSize=1380., Nmesh=8, seed=42)
# apply ... | ut = "./nbkit_example_power.json"
result.save(output)
|
eyaler/tensorpack | examples/FasterRCNN/model_box.py | Python | apache-2.0 | 7,519 | 0.001197 | # -*- coding: utf-8 -*-
# File: model_box.py
import numpy as np
from collections import namedtuple
import tensorflow as tf
from tensorpack.tfutils.scope_utils import under_name_scope
from config import config
@under_name_scope()
def clip_boxes(boxes, window, name=None):
"""
Args:
boxes: nx4, xyxy
... | hors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2))
anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y2, 2, axis=1)
waha = anchors_x2y2 - anchors_x1y1
xaya = (anchors_x2y2 + anchors_x1y1) * 0.5
boxes_x1y1x2y2 = tf.reshape(boxes, (-1, 2, 2))
boxes_x1y1, boxes_x2y2 = tf.split(boxes_x1y1x2y2, 2, axis=1... | txty = (xbyb - xaya) / waha
twth = tf.log(wbhb / waha) # may contain -inf for invalid boxes
encoded = tf.concat([txty, twth], axis=1) # (-1x2x2)
return tf.reshape(encoded, tf.shape(boxes))
@under_name_scope()
def crop_and_resize(image, boxes, box_ind, crop_size, pad_border=True):
"""
Aligned ... |
jhsenjaliya/incubator-airflow | airflow/executors/local_executor.py | Python | apache-2.0 | 2,991 | 0 | # -*- 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
... | ocalExecutor executes tasks locally in parallel. It uses the
multiprocessing Python library and queues to parallelize the execution
| of tasks.
"""
def start(self):
self.queue = multiprocessing.JoinableQueue()
self.result_queue = multiprocessing.Queue()
self.workers = [
LocalWorker(self.queue, self.result_queue)
for _ in range(self.parallelism)
]
for w in self.workers:
... |
xuender/test | testAdmin/itest/migrations/0007_auto__chg_field_test_content.py | Python | apache-2.0 | 1,756 | 0.006834 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Test.content'
db.alter_column(u'itest_test', 'content'... | o.db.models.fields.CharField', [], {'max_length': '450', 'null': 'True', 'blank': 'True'}),
'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'tests'", 'symmetrical': 'False', 'to': "orm['ite | st.Tag']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '150'})
}
}
complete_apps = ['itest'] |
gleicher27/Tardigrade | moose/gui/mesh_info/ExodusIIMeshInfo.py | Python | lgpl-2.1 | 1,654 | 0.015719 | from MeshInfo import *
''' Provides Informatio | n about ExodusII meshes '''
class ExodusIIMeshInfo(MeshInfo):
def __init__(self, mesh_ite | m_data, file_name):
MeshInfo.__init__(self, mesh_item_data)
self.file_name = file_name
import vtk
reader = vtk.vtkExodusIIReader()
reader.SetFileName(self.file_name)
reader.UpdateInformation()
num_nodesets = reader.GetNumberOfNodeSetArrays()
num_sidesets = reader.GetNumberOfSideSetArrays... |
rmenegaux/bqplot | bqplot/colorschemes.py | Python | apache-2.0 | 2,813 | 0.003199 |
# These color schemes come from d3: http://d3js.org/
#
# They are licensed under the following license:
#
# Copyright (c) 2010-2015, Michael Bostock
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#: 10 colors that work well together as data category colors
CATEGORY10 = ['#1f77b4', '#ff7f0e', '#2ca02c', '# | d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
#: 20 colors that work well together as data category colors
CATEGORY20 = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
'#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
... |
thinkopensolutions/odoo-saas-tools | saas_portal_tagging/models/__init__.py | Python | lgpl-3.0 | 79 | 0 | # - | *- coding: utf-8 -*-
from . import saas_portal_taggin | g
from . import wizard
|
ianyh/heroku-buildpack-python-opencv | vendor/.heroku/lib/python2.7/test/test_robotparser.py | Python | mit | 6,753 | 0.003998 | import unittest, StringIO, robotparser
from test import test_support
from urllib2 import urlopen, HTTPError
class RobotTestCase(unittest.TestCase):
def __init__(self, index, parser, url, good, agent):
unittest.TestCase.__init__(self)
if good:
self.str = "RobotTest(%d, good, %s)" % (inde... | sertEqual(parser.can_fetch("*", robots_url), False)
def testPythonOrg(self):
test_support.requires('network')
with test_support.transient_internet('www.python.org'):
parser = robotparser.RobotFileParser(
"http://www.python.org/robots.txt")
parser.read()
... | parser.can_fetch("*", "http://www.python.org/robots.txt"))
def test_main():
test_support.run_unittest(tests)
test_support.run_unittest(NetworkTestCase)
if __name__=='__main__':
test_support.verbose = 1
test_main()
|
BigBart/2sync | 2sync.py | Python | gpl-3.0 | 1,089 | 0.01011 | #! /usr/bin/env python3
from gi.repository import Gtk, GObject
import gui
import logging
import argparse
import threading
# Commandline arguments
parser = argparse.ArgumentParser(description='2-way syncronisation for folders')
parser.add_argument('config', help='name of the configuration file')
parser.add_argument('-d... | rgs = parser.parse_args()
# Config logging
# Set loglevel für logfile
if args.debug == True:
log_level = logging.DEBUG
else:
log_level = logging.INFO
# Logging to file
logging.basicConfig(level=log_level, filename='2sync.log', filemode='a', format='%(levelname)s: %(asctime)s - 2sync - %(message)s')
# define a Hand... | setLevel(logging.WARNING)
logging.getLogger('').addHandler(console)
# Needed for running threads
GObject.threads_init()
thread = threading.Thread(target=gui.TwoSyncGUI, args=[args.config])
thread.daemon = True
thread.start()
try:
Gtk.main()
except:
Gtk.main_quit() |
quattor/aquilon | tests/broker/test_add_rack.py | Python | apache-2.0 | 11,937 | 0.001508 | #!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compl... | t --row g --column 4"
err = self.badoptiontest(command.split(" "))
self.matchoutput(err, "no such option: --rackid", command)
def test_150_addut10(self):
command = "add rack --building ut --row g --column 4"
out = self.commandtest(command.sp | lit(" "))
self.matchoutput(out, "ut10", command)
def test_151_add_rack_fail_name_format(self):
command = "add rack --force_rackid 012 --building ut --row g --column 4"
err = self.badrequesttest(command.split(" "))
self.matchoutput(err, "Invalid rack name ut012. Correct name format: ... |
ppwwyyxx/tensorflow | tensorflow/python/tpu/tpu_test_wrapper_test.py | Python | apache-2.0 | 6,679 | 0.005989 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi | s file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY... | her express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
"""Tests for tpu_test_wrapper.py."""
from __future__ import absolute_import
from __future__ import division
from... |
QISKit/qiskit-sdk-py | qiskit/pulse/commands/instruction.py | Python | apache-2.0 | 9,538 | 0.001887 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | ls)
return self.insert(time, schedule, buffer=buffer, name=name)
def draw(self, dt: float = 1, style: Optional['SchedStyle'] = None,
filename: Optional[str] = None, interp_method: Optional[Callable] = None,
scaling: float = 1, channels_to_plot: Optional[List[Channel]] = None,
... | interactive: bool = False, table: bool = True,
label: bool = False, framechange: bool = True):
"""Plot the instruction.
Args:
dt: Time interval of samples
style: A style sheet to configure plot appearance
filename: Name required to save pulse ... |
tkruse/rosinstall | test/local/test_setupfiles.py | Python | bsd-3-clause | 14,673 | 0.002726 | # Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, 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... | ss GenerateTest(AbstractFakeRosBasedTest):
def test_gen_setup(self):
try:
config = Config([PathSpec(os.path.join("test", "example_dirs", "ros_comm")),
PathSpec("bar")],
self.test_root_path,
None)
ro... | self.ros_path),
PathSpec(os.path.join("test", "example_dirs", "ros_comm")),
PathSpec("bar")],
self.test_root_path,
None)
rosinstall.setupfiles.generate_setup(config)
self.assertTrue(os.path.isfile(os.path.j... |
LockScreen/Backend | venv/lib/python2.7/site-packages/boto3/s3/transfer.py | Python | mit | 27,752 | 0.000036 | # Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | e fine grained control over the
transfer. For example:
.. code-block:: python
client = boto3.client('s3', 'us-west-2')
config = TransferConfig(
multipart_threshold=8 * 1024 * 1024,
max_concurrency=10,
num_download_attempts=10,
)
transfer = S3Transfer(client, config)
transf... | /tmp/foo', 'bucket', 'key')
"""
import os
import math
import functools
import logging
import socket
import threading
import random
import string
import boto3
from concurrent import futures
from botocore.compat import six
from botocore.vendored.requests.packages.urllib3.exceptions import \
ReadTimeoutError
from b... |
akrherz/iem | scripts/dbutil/set_wfo.py | Python | mit | 2,127 | 0 | """Assign a WFO to sites in the metadata tables that have no WFO set."""
from pyiem.util import get_dbconn, logger
LOG = logger()
def main():
"""Go Main"""
mesosite = get_dbconn("mesosite")
postgis = get_dbconn("postgis")
mcursor = mesosite.cursor()
mcursor2 = mesosite.cursor()
pcursor = pos... | (row[3], row[4]),
)
wfo, dist = pcursor.fetchone()
if dist > 3:
LOG.info(
" closest CWA %s found >3 degrees away %.2f",
| wfo,
dist,
)
continue
else:
row2 = pcursor.fetchone()
wfo = row2[0][:3]
LOG.info(
"Assinging WFO: %s to IEMID: %s ID: %s NETWORK: %s",
wfo,
iemid,
sid,
network,
... |
nsdont/dotfiles | bin/omnifocus_export_dayone.py | Python | mit | 6,596 | 0 | #!/usr/local/bin/python3
"""OmniFocus export to Dayone.
Usage:
omnifocus_export_dayone.py
omnifocus_export_dayone.py <date> [--show]
omnifocus_export_dayone.py (-s | --show)
Options:
-h --help Show this screen.
--version Show version.
-s --show Only echo to screen.
"""
import sys
import sqlit... | G.info('Start generate monthly...')
today_timestamp = (today - | timedelta(30)).timestamp() - base_timestamp
tomorrow_timestamp = tomorrow.timestamp() - base_timestamp
query_and_export_data(today_timestamp, tomorrow_timestamp, now,
'Monthly', only_show=only_show)
LOG.info('Finish generate monthly...')
# 生成日报
LOG.info('S... |
gvizquel/comunidad | comunidad/1settings.py | Python | gpl-3.0 | 3,105 | 0.001288 | """
Django settings for comunidad project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import ... | .CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middle | ware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'comunidad.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
... |
tjnapster555/django-edu | djangoedu/core/generic_views.py | Python | mit | 264 | 0.015152 | """
=============
G | eneric Views
=============
Class based helper views.
"""
class GenericManyToMany(object):
"""Generic view to edit many to many relations with extra fields."""
left_table = None
right_table = None
allow_multiple = True
| |
mapix/utknows | examples/test_world.py | Python | bsd-3-clause | 860 | 0.004651 | # -*- coding:utf-8 -*-
import random
import unittest
class TestSequenceFunctionsWorld(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle | (self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
# should raise an exception for an immutable sequence
self.assertRaises(TypeError, random.shuffle, (1,2,3))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)... |
def test_sample(self):
with self.assertRaises(ValueError):
random.sample(self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
|
daviskirk/climatecontrol | climatecontrol/ext/pydantic.py | Python | mit | 2,447 | 0.001226 | """Climatecontrol extension for using pydantic schemas as source."""
from typing import Generic, Mapping, Type, TypeVar
from pydantic import BaseModel
from climatecontrol.core import Climate as BaseClimate
from climatecontrol.core import SettingsItem as BaseSettingsItem
from climatecontrol.fragment import FragmentPa... | es.
Args:
*args, **kwargs: See :class:`climateontrol.Climate`
model: Additional argument specific to the model to use for the settings.
Examples:
>>> from climatecontrol.ext.pydantic import Climate
>>>
>>> class SettingsSubSchema(BaseModel):... | a: str = 'test'
... b: bool = False
... c: SettingsSubSchema = SettingsSubSchema()
...
>>> climate = Climate(model=SettingsSchema)
>>> # defaults are initialized automatically:
>>> climate.settings.a
'test'
>>> ... |
mehulsbhatt/easyengine | ee/cli/plugins/clean.py | Python | mit | 4,861 | 0.000823 | """Clean Plugin for EasyEngine."""
from ee.core.shellexec import EEShellExec
from ee.core.aptget import EEAptGet
from ee.core.services import EEService
from ee.core.logging import Log
from cement.core.controller import CementBaseController, expose
from cement.core import handler, hook
import os
import urllib.request
... | he()
if self.app.pargs.pagespeed:
self.clean_pagespeed()
if self.app.pargs.redis:
self.clean_redis()
@expose(hide=True)
def clean_redis(self):
"""This function clears Redis cache"""
if(EEAptGet.is_installed(self, "redis-server")):
Log.info(sel... | not installed")
@expose(hide=True)
def clean_memcache(self):
"""This function Clears memcache """
try:
if(EEAptGet.is_installed(self, "memcached")):
EEService.restart_service(self, "memcached")
Log.info(self, "Cleaning MemCache")
else:
... |
Endika/account-financial-tools | account_move_batch_validate/account.py | Python | agpl-3.0 | 6,169 | 0 | # -*- coding: utf-8 -*-
###############################################################################
# #
# Author: Leonardo Pistone
# Copyright 2014 Camptocamp SA
# ... | context = {}
self.write(cr, uid, move_ids, {'to_post': False}, context=context)
self._cancel_jobs(cr, uid, context=context)
@job(default_channel='root.account_move_batch_validate')
def validate_one_move(session, model_name, move_id):
"""Validate a move, and leave the job reference in place."""
... | e_pool.exists(session.cr, session.uid, [move_id]):
move_pool.button_validate(
session.cr,
session.uid,
[move_id]
)
else:
return _(u'Nothing to do because the record has been deleted')
|
Buggaarde/youtube-dl | youtube_dl/extractor/kontrtube.py | Python | unlicense | 2,732 | 0.002276 | # encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_duration,
)
class KontrTubeIE(InfoExtractor):
IE_NAME = 'kontrtube'
IE_DESC = 'KontrTube.ru - Труба зовёт'
_VALID_URL = r'http://(?:www\.)?kontrtube\.ru/... | rl': 'http://www.kontrtube.ru/videos/2678/nad-olimpiyskoy-derevney-v-sochi-podnyat-rossiyskiy-flag/',
'm | d5': '975a991a4926c9a85f383a736a2e6b80',
'info_dict': {
'id': '2678',
'display_id': 'nad-olimpiyskoy-derevney-v-sochi-podnyat-rossiyskiy-flag',
'ext': 'mp4',
'title': 'Над олимпийской деревней в Сочи поднят российский флаг',
'description': 'md5:80edc4c... |
euccas/CodingPuzzles-Python | leet/source/pickone/recordered_power_of_2.py | Python | mit | 690 | 0.010145 | class Solution:
def reorderedPowerOf2(self, N):
"""
:type N: int
:rtype: bool
"""
if N is None or N == 0:
return False
binary = []
while N > 0:
binary.append(N%2)
N = N//2
binary.sort()
binary.pop() # remov... | for n in binary:
if n == 0:
zero += 1
return zero == len(binary) - zero
if __name__ == "__main__":
sln = Solution()
#res = sln.reorderedPowerOf2(10)
#assert(res == False)
res = sln.reorderedPowerOf2(46)
assert(res == True) | |
RIPE-NCC/ripe.atlas.sagan | ripe/atlas/sagan/http.py | Python | gpl-3.0 | 3,498 | 0 | # Copyright (c) 2016 RIPE NCC
#
# 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 Fo | undation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General P | ublic 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 .base import Result, ParsingDict
class Response(ParsingDict):
def __init__(self, data, **kwargs):
ParsingDict.__init__(self,... |
rahulunair/nova | nova/tests/functional/wsgi/test_services.py | Python | apache-2.0 | 19,683 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | en(services))
# Make sure the host was removed from the aggregate.
aggregate = self.admin_api.api_get(
'/os-aggregates/%s' % aggregate['id']).body['aggregate']
self.assertEqual([], aggregate['hosts'])
| # Trying to get the hypervisor should result in a 404.
self.admin_api.api_get(
'os-hypervisors?hypervisor_hostname_pattern=%s' % service['host'],
check_response_status=[404])
# The host mapping should also be gone.
self.assertRaises(exception.HostMappingNotFound,
... |
aodag/asbool | tests/test_it.py | Python | mit | 2,013 | 0 | import pytest
class TestAsBoolConverter(object):
@pytest.fixture
def target(self):
from asbool.converter import AsBoolConverter
return AsBoolConverter
@pytest.mark.parametrize(
"true_values, false_values, input, expected",
[
(['t'], ['f'], 't', True),
... | input)
assert result == expected
@pytest.mark.parametrize(
"input, expected",
[
('TRUE', True | ),
('t', True),
('y', True),
('yes', True),
(1, True),
('FALSE', False),
('f', False),
('n', False),
('no', False),
(0, False),
]
)
def test_asbool(input, expected):
from asbool import asbool
result = asbool(input)
assert result == ... |
sdpython/pyquickhelper | _unittests/ut_pycode/test_missing_function_pycode.py | Python | mit | 3,947 | 0.000507 | """
@brief test log(time=8s)
@author Xavier Dupre
"""
import sys
import os
import unittest
import shutil
from contextlib import redirect_stdout
from io import StringIO
from pyquickhelper.pycode import ExtTestCase
from pyquickhelper.pycode import process_standard_options_for_setup_help, get_temp_folder
from pyq... | @unittest.skipIf(sys.platform != 'win32', reason="not available")
def test_process_standard_options_for_setup(self):
| temp = get_temp_folder(
__file__, "temp_process_standard_options_for_setup")
os.mkdir(os.path.join(temp, '_unittests'))
f = StringIO()
with redirect_stdout(f):
process_standard_options_for_setup(
['build_script'], file_or_folder=temp, project_var_name=... |
r-darwish/pushjournal | pushjournal/_compat.py | Python | bsd-3-clause | 128 | 0 | import sys
PY2 = sy | s.version_info[0] == 2
if PY2:
from urllib import urlopen
else:
from urllib.request import | urlopen
|
jmetzen/skgp | examples/plot_gp_learning_curve.py | Python | bsd-3-clause | 3,042 | 0.001644 | #!/usr/bin/python
# -*- coding: utf-8 -*-
r"""
==========================================================
Comparing different variants of squared exponential kernel
==========================================================
Three variants of the squared exponential covariance function are compared:
* Isotropic squar... | Xtrain, ytrain, scoring="mean_squa | red_error",
cv=10, n_jobs=4)
test_scores = -test_scores # Scores correspond to negative MSE
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_min = np.min(test_scores, axis=1)
test_scores_max = np.max(test_scores, axis=1)
plt.plot(train_sizes, test_scores_mean, lab... |
MadsJensen/CAA | calc_itc_ali.py | Python | bsd-3-clause | 2,791 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 20:51:31 2017
@author: mje
"""
import numpy as np
import mne
import matplotlib.pyplot as plt
from mne.stats import permutation_cluster_test
from my_settings import (subjects_select, tf_folder, epochs_folder)
d_ali_ent_right = []
for subject i... | 1e3
plt.close('all')
plt.subplot(211)
plt.title("Ctl left v right")
plt.plot(
times,
d_ali_ent_left.mean(axis=0) - d_ali_ent_right.mean(axis=0),
label="ERF Contrast (Event 1 - Event 2)")
plt.ylabel("MEG (T / m)")
plt.legend()
plt.subplot(212)
for i_c, c in enumerate(clusters):
c = c[0]
if cluster_p... | e:
plt.axvspan(
times[c.start],
times[c.stop - 1],
color=(0.3, 0.3, 0.3),
alpha=0.3)
hf = plt.plot(times, T_obs, 'g')
plt.legend((h, ), ('cluster p-value < 0.05', ))
plt.xlabel("time (ms)")
plt.ylabel("f-values")
plt.show()
|
cysuncn/python | spark/crm/PROC_A_R_ENT_CRE_COUNT.py | Python | gpl-3.0 | 3,402 | 0.015805 | #coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_A_R_ENT_CRE_COUNT').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)
sc.... | strftime("%Y-%m-%d")
V_STEP = 0
#保留当天及月末数据
if V_DT_LD | != V_DT_LMD :
ret = os.system("hdfs dfs -rm -r /"+dbname+"/ACRM_A_ENT_CRE_COUNT/"+V_DT_LD+".parquet")
#删除当天的
ret = os.system("hdfs dfs -rm -r /"+dbname+"/ACRM_A_ENT_CRE_COUNT/"+V_DT+".parquet")
ACRM_F_CUS_DEV_CONFIG = sqlContext.read.parquet(hdfs+'/ACRM_F_CUS_DEV_CONFIG/*')
ACRM_F_CUS_DEV_CONFIG.registerTempTable("A... |
davilajose23/ProjectCobra | functions_dir.py | Python | mit | 10,907 | 0.004034 | """Modulo que contiene la clase directorio de funciones
-----------------------------------------------------------------
Compilers Design Project
Tec de Monterrey
Julio Cesar Aguilar Villanueva A01152537
Jose Fernando Davila Orta A00999281
-----------------------------------------------------------------
DOCUM... | va a leer variable con funcion read
self.r | eading = False
# Ultimo token ID, usado para el read
self.last_id = Stack()
# Ultimo token de tipo que fue leido por el directorio de funciones
self.last_type = None
'''Funciones que estan siendo llamadas.
Se utiliza una pila para llamadas nesteadas a funciones'''
... |
callowayproject/django-viewpoint | viewpoint/urls_defaultblog.py | Python | apache-2.0 | 2,705 | 0.026248 | """
URL routing for blogs, entries and feeds
"""
from django.conf.urls.defaults import patterns, url
from django.conf import settings
from feeds import LatestEntriesByBlog, LatestEntries #, EntryComments
from models import Blog
from views import generic_blog_entry_view, blog_detail
from viewpoint.settings import USE_C... | # Listing of blog entries for a given week of the year
url(
regex = r'^(?P<year>\d{4})/(?P<week>\d{1,2})/$',
view = generic_blog_entry_view,
name = 'viewpoint_blog_archive_week'
),
# Listing of blog entries for a given day
url(
regex = r'^(? | P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/$',
view = generic_blog_entry_view,
name = 'viewpoint_blog_archive_day'
),
# Listing of blog entries for the current date
url(
regex = r'^today/$',
view = generic_blog_entry_view,
name='viewpoint_blog_archive_today'
... |
RealTimeWeb/datasets | datasets/python/state_fragility/setup.py | Python | gpl-2.0 | 198 | 0.005051 | from setuptools import setup
import os.path
se | tup(
name='State Fragility',
version='1',
py_modules=['state_fragility'],
data_file | s=[('', [
"./state_fragility.db"
])]
)
|
jtk1rk/xsubedit | gcustom/cellRendererText.py | Python | gpl-3.0 | 923 | 0.004334 | import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from .textEditDialog import cTextEditDialog
class cCellRendererText(Gtk.CellRendererText):
""" Label entry cell which calls TextEdit_Dialog upon editing """
__gtype_name__ = 'CellRendererCustomTe | xt'
def __init__(self, parent):
super(cCellRendererText, self).__init__()
self.parentWindow = parent
def do_start_editing(
self, event, treeview, path, background_area, cell_area, flags):
| if not self.get_property('editable'):
return
sub = treeview.get_model()[path][0]
entry = Gtk.Entry()
dialog = cTextEditDialog(self.parentWindow, sub, 'vo', treeview.thesaurus)
response = dialog.run()
if response == Gtk.ResponseType.OK:
entry.set_text(dia... |
yawd/django-sphinxdoc | sphinxdoc/admin.py | Python | bsd-3-clause | 659 | 0 | # encoding: utf-8
"""
Admin interface for the sphinxdoc app.
"""
from django.contrib import admin
from sphinxdoc.models import Project, Document
class ProjectAdmin( | admin.ModelAdmin):
"""Admin interface for :class:`~sphinxdoc.models.Project`."""
list_display = ('name', 'path',)
prepopulated_fields = {'slug': ('name',)}
class DocumentAdmin(admin.ModelAdmin):
"""
Admin interface for :class:`~sphinxdo | c.models.Document`.
Normally, you shouldn’t need this, since you create new documents via
the management command.
"""
pass
admin.site.register(Project, ProjectAdmin)
admin.site.register(Document, DocumentAdmin)
|
yvaucher/account-financial-tools | __unported__/account_compute_tax_amount/__openerp__.py | Python | agpl-3.0 | 1,342 | 0.003726 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville. Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# | published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. S... | License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
"name" : "Recompute tax_amount",
"version" : "1... |
lucienfostier/gaffer | python/GafferUI/ButtonPlugValueWidget.py | Python | bsd-3-clause | 3,794 | 0.03611 | ##########################################################################
#
# Copyright (c) 2017, Image Engine Design 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:
#
# * Redistrib... |
self.__button = GafferUI.Button()
GafferUI.PlugValueWidget.__init__( self, self.__button, plug, **kw )
self.__button.clickedSignal().connect( Gaffer.WeakMethod( self.__clicked ) | , scoped = False )
Gaffer.Metadata.plugValueChangedSignal().connect( Gaffer.WeakMethod( self.__plugMetadataChanged ), scoped = False )
self.setPlug( plug )
def hasLabel( self ) :
return True
def setPlug( self, plug ) :
GafferUI.PlugValueWidget.setPlug( self, plug )
self.__nameChangedConnection = None
... |
mhoffma/micropython | tests/extmod/ure_split_notimpl.py | Python | mit | 138 | 0 | import ure as re
r = re.compile('( )')
| try:
s = r.split("a b | c foobar")
except NotImplementedError:
print('NotImplementedError')
|
LorenzoBi/courses | UQ/rand_gen.py | Python | mit | 286 | 0.003497 | import numpy as np
import matplotlib.pyp | lot as plt
def generate_random(a, M, c, seed):
for i in range(1000 * seed // 10):
seed = (a | * seed + c) % M
return seed / M
y = [generate_random(45, 989993, 12, i) for i in range(1000)]
plt.plot(np.arange(1000), y)
plt.show()
|
UmSenhorQualquer/pythonVideoAnnotator | base/pythonvideoannotator/setup.py | Python | mit | 2,475 | 0.013737 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import re, os
PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(PACKAGE_PATH, 'pythonvideoannotator','__init__.py'), 'r') as fd:
content = fd.read()
version = re.search(
r'^__versio... | "python-video-annotator-models-gui==0.7.63",
"python-video-annotator-models==0.8.82",
"python-video-annotator-module-timeline==0.6.26",
"python-video-annotator-module-eventstats==0.5.15",
"python-video-annotator-module-virtual-object-generator==0. | 6.26",
"python-video-annotator-module-deeplab==0.902.21",
"python-video-annotator-module-contours-images==0.5.28",
"python-video-annotator-module-tracking==0.6.38",
"python-video-annotator-module-smooth-paths==0.5.19",
"python-video-annotator-module-distances==0.5.18",
"python-video-annotator-module-path-map==0.6... |
izhaohui/gardener | controller/home/flower/models.py | Python | gpl-3.0 | 2,048 | 0.001953 | from django.db import models
import socket,logging
# Create your models here.
class Sensor(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
env_light = models.IntegerField()
env_humid = models.IntegerField()
env_raindrop = models.IntegerField()
env_temperature = models.IntegerFie... | ef valve(seconds):
seconds = seconds if 0 <= seconds <= 10 else 2
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
| conn.connect(("192.168.33.58", 80))
conn.send("ST,%d" % seconds)
content = conn.recv(10240)
if content and content.find("&") > 0:
data = {k: v for k, v in [tuple(i.split('=')) for i in content.split("&")]}
sensor = Sensor()
sensor.env_light = data['env_li... |
jfischer/micropython-iot-hackathon | example_code/server_mqtt_to_influx.py | Python | mit | 2,908 | 0.003783 | # Read from an MQTT queue and write events to Influxdb
import argparse
import asyncio
import time
import sys
from collections import namedtuple
from thingflow.base import Scheduler, SensorEvent
from thingflow.adapters.mqtt import MQTTReader
import thingflow.filters.select # adds select() method
import thingflow.filte... | help="Ho | stname or IP address of MQTT broker (defaults to localhost)")
parser.add_argument('--topic-name', type=str, default='sensor-data',
help="Topic for subscription (defaults to sensor-data)")
parser.add_argument('--influx-host', type=str, default='localhost',
help="In... |
jedp/oakland_pm | core/models.py | Python | mit | 8,624 | 0.007189 | from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django_countries import CountryField
from django.contrib.localflavor.us.models import *
from django.contrib.localflavor.us.us_states im... | None
def time_until(self):
return "hi"
def __unicode__(self):
return self.name
class ProgramStatus(models.Model):
program_status = models.CharField(max_length=200)
description = models.TextField(blank=True, null=True)
class ProgramType(models.Model):
program_type = models.Ch... | ield(max_length=200)
description = models.TextField(blank=True, null=True)
class WatchList(models.Model):
profile = models.ForeignKey('Profile', related_name="watchlist_profile")
program = models.ForeignKey('Program', related_name="watchlist_program")
date_added = models.DateTimeField(auto_now_add=Tru... |
rienafairefr/pynYNAB | pynYNAB/scripts/helpers.py | Python | mit | 2,659 | 0.001128 | from __future__ import print_function
import os
import argparse
import re
import six
import yaml
DEFAULT_CONFIG_FILE = 'ynab.yaml'
class ConfigEnvArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
super(ConfigEnvArgumentParser, self).__init__(*args, **kwargs)
try:
... | _config_from_yaml(nominal)
# cli-passed > cli-passed-config > ynab.yaml > ENV
merged_config = merge(ynab_yaml_config, env_config)
if hasattr(arguments, 'config') and arguments.config:
cli_passed_config = get_config_from_yaml(arguments.config)
merged_config = merge(cli_passed_config, merged_... | ed_config, default_flow_style=False), end='',)
print('------------')
return merged_config
def merge(user, default):
if isinstance(user, dict) and isinstance(default, dict):
for key, value in six.iteritems(default):
if key not in user:
user[key] = value
else:... |
DVegaCapital/zipline | tests/test_exception_handling.py | Python | apache-2.0 | 3,339 | 0 | #
# Copyright 2013 Quantopian, 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... | 'Algo exception in handle_data')
def test_zerodivision_exception_in_handle_data(self):
# Simulation
# ----------
self.zipline_test_conf | ig['algorithm'] = \
DivByZeroAlgorithm(
self.zipline_test_config['sid'],
sim_params=factory.create_simulation_parameters()
)
zipline = simfactory.create_test_zipline(
**self.zipline_test_config
)
with self.assertRaises(ZeroDivisio... |
timthelion/FreeCAD | src/Mod/Fem/_CommandBeamSection.py | Python | lgpl-2.1 | 2,767 | 0.001084 | # ***************************************************************************
# * *
# * Copyright (c) 2015 - Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * Th... | but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for m | ore details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Bo... |
BioRoboticsUNAM/pyRobotics | setup.py | Python | mit | 513 | 0.017578 | # -*- coding: utf-8 -*-
from distutils.core import setup
from pyrobotics.BB import __ver | sion__
setup(name='pyRobotics',
version=__version__,
author='Adrián Revuelta Cuauhtli',
author_email='adrianrc.89@gmail.com',
url='http://bioroboticsunam.github.io/pyRobotics',
| license='LICENSE.txt',
data_files=[('', ['README', 'LICENSE.txt'])],
description="A Python API to create modules that connect to our message-passing and shared varaibels hub 'BlackBoard'.",
packages=['pyrobotics'])
|
himanshu-dixit/oppia | core/controllers/learner_playlist_test.py | Python | apache-2.0 | 14,127 | 0.001628 | # Copyright 2017 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | to the learner playlist.
| response = self.post_json(
'%s/%s/%s' % (
feconf.LEARNER_PLAYLIST_DATA_URL,
constants.ACTIVITY_TYPE_EXPLORATION,
self.EXP_ID_4), {}, csrf_token)
self.assertEqual(
response['belongs_to_subscribed_activities'], True)
self.assertE... |
avocado-framework/avocado-vt | virttest/libvirt_xml/devices/audio.py | Python | gpl-2.0 | 1,707 | 0 | """
audio device support class(es)
https://libvirt.org/formatdomain.html#audio-devices
"""
from virttest.libvirt_xml import accessors
from virttest.libvirt_xml.devices import base
class Audio(base.UntypedDeviceBase):
__slots__ = ('id', 'type', 'attrs', 'input_attrs',
'input_settings', 'output_... | t')
accessors.XMLElementDict('input_settings', self,
parent_xpath='/input',
tag_name='settings')
accessors.XMLElementDict('output_attrs', self,
parent_xpath='/',
tag_name='... | t_xpath='/output',
tag_name='settings')
super(Audio, self).__init__(device_tag='audio',
virsh_instance=virsh_instance)
|
billhoffman/drake | drake/bindings/python/pydrake/test/testRBTIK.py | Python | bsd-3-clause | 1,165 | 0.006009 | import unittest
import numpy as np
import pydrake
from pydrake.solvers import ik
import os.path
class TestRBTIK(unittest.TestCase):
def testPostureConstraint(self):
r = pydrake.rbtree.RigidBodyTree(os.path.join(pydrake.getDrakePath(), "examples/Pendulum/Pendulum.urdf"))
q = -0.9
posture_con... | 0.8147))
q_nom = np.vstack((np.zeros((6,1)),
0.))
options = ik.IKoptions(r)
results = ik.inverseKinSimple(r,
q_seed,
q_nom,
[posture_constraint],
... | .main()
|
matthew-brett/bibstuff | bibstuff/bibstyles/default.py | Python | mit | 4,900 | 0.02102 | #File: default.py
"""
Provides a default style for bib4txt.py
Produces a list of citations that to be included in a reStructuredText document.
(In very simple documents, can also provide citation reference formatting
by substituting in the document text for the citation references.)
A style includes:
- citation templ... | to substitute inline for citation references.
"""
style_logger.debug('default: enter CitationManager.format_inline_cite')
#:note: need entry to be None if cite_key not found, so discard=Fa | lse
entry_list = self.find_entries(cite_key_list,discard=False)
"""
for entry in entry_list:
print entry
"""
return format_inline_cite(entry_list, self)
################### CITATION FORMATTING ########################
def get_citation_label(self,entry,citation_template=None):
return '.. [' + entry.cit... |
xfumihiro/powerline | powerline/lint/imp.py | Python | mit | 1,573 | 0.028043 | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
from powerline.lint.selfcheck import havemarks
class WithPath(object):
def __init__(self, import_paths):
self.import_paths = import_paths
def __enter__(self):
self.oldpath = sys.path
... |
def impo | rt_segment(*args, **kwargs):
return import_function('segment', *args, **kwargs)
|
javierwilson/forocacao | forocacao/app/migrations/0006_auto_20160808_1041.py | Python | bsd-3-clause | 1,212 | 0.0033 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0005_question_event'),
]
operations = [
migrations.CreateModel(
name='Topic',
fields=[
... | lize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200, verbose_name='Nombre')),
('weight', models.IntegerField()),
],
options={
'ordering': ['weight'],
'verbose_name': 'Tema',
'v... | ,
name='type',
field=models.CharField(blank=True, max_length=1, null=True, choices=[('O', 'Organizador'), ('E', 'Exhibidor'), ('S', 'Speaker')]),
),
migrations.AddField(
model_name='organization',
name='topic',
field=models.ForeignKey(verbose_n... |
mahabs/nitro | nssrc/com/citrix/netscaler/nitro/resource/config/authentication/authenticationwebauthpolicy_systemglobal_binding.py | Python | apache-2.0 | 5,383 | 0.036597 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | nt']
return 0
except Exception as e:
raise e
@classmethod
def count_filtered(cls, service, name, filter_) :
""" Use this API to count the filtered set of authenticationwebauthpolicy_systemglobal_binding resources.
Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
"""
try :
obj... | e, option_)
if response :
return response[0].__dict__['___count']
return 0
except Exception as e:
raise e
class authenticationwebauthpolicy_systemglobal_binding_response(base_response) :
def __init__(self, length=1) :
self.authenticationwebauthpolicy_systemglobal_binding = []
self.errorcode = 0
s... |
ZeitOnline/zeit.cms | src/zeit/cms/tagging/testing.py | Python | bsd-3-clause | 5,795 | 0 | import collections
import lxml.objectify
import mock
import zeit.cms.repository.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.tagging.tag
import zope.component
import zope.interface
NAMESPACE = "http://namespaces.zeit.de/CMS/tagging"
KEYWORD_PROPERTY = ('testtags', NAMESPACE)
class DummyTagger(objec... | y_autocomplete(self, text, form_prefix='form'):
self.add_by_autocomplete(
text, 'id=%s.keywords.add' % | form_prefix)
def add_topicpage_link(self, tag):
tag.link = 'thema/%s' % tag.label.lower()
|
madhav-datt/kgp-hms | src/workers/mess_manager.py | Python | mit | 2,480 | 0.000806 | #
# IIT Kharagpur - Hall Management System
# System to manage Halls of residences, Warden grant requests, student complaints
# hall worker attendances and salary payments
#
# MIT License
#
"""
@ authors: Madhav Datt, Avikalp Srivastava
"""
from ..database import db_func as db
from ..database import password_validatio... | tter
def password(self, password):
self._password = pv.hash_password(password)
db.update("worker", self.worker_ID, "password", self.password)
# monthly_salary getter and setter functions
@property
def monthly_salary(self):
return self._monthly_salary
@monthly_salary.setter
... | lf.worker_ID, "monthly_salary", self.monthly_salary)
def compute_mess_payment(self, student_table):
"""
Compute total money due to hall in form of mess payments
Sum of each student resident's mess charge
Pass parameter student_table = dbr.rebuild("student")
"""
mess... |
leighpauls/k2cro4 | third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base_unittest.py | Python | bsd-3-clause | 22,390 | 0.002635 | # Copyright (C) 2010 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 f... | a\xac\u1234\u20ac\U00008000', 'act.txt')
port.d | iff_text('exp' + chr(255), 'act', 'exp.txt' |
cloudera/hue | desktop/core/ext-py/Django-1.11.29/tests/gis_tests/gdal_tests/test_raster.py | Python | apache-2.0 | 21,062 | 0.000902 | """
gdalinfo tests/gis_tests/data/rasters/raster.tif:
Driver: GTiff/GeoTIFF
Files: tests/gis_tests/data/rasters/raster.tif
Size is 163, 174
Coordinate System is:
PROJCS["NAD83 / Florida GDL Albers",
GEOGCS["NAD83",
DATUM["North_American_Datum_1983",
SPHEROID["GRS 1980",6378137,298.2572221010002... | file
from django.contrib.gis.gdal import GDAL_VERSION, GDALRaster
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.raster.band import GDALBand
from django.contrib.gis.shortcuts import numpy
from django.test import SimpleTestCase
from django.utils import six
from django.utils._os imp... | .
"""
def setUp(self):
self.rs_path = os.path.join(os.path.dirname(upath(__file__)),
'../data/rasters/raster.tif')
self.rs = GDALRaster(self.rs_path)
def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name)
self.assertRege... |
crf1111/Bio-Informatics-Learning | Bio-StrongHold/src/Constructing_a_De_Bruijn_Graph.py | Python | mit | 685 | 0.013139 | import os
import sys
from Bio.Seq import Seq
def main(*a | rgs, **kwargs):
fpath = os.path.join(os.getcwd(), args[-2])
tmp = []
with open(fpath,'r') as f:
for line in f:
txt = line.strip()
tmp.append(txt)
S1 = set(tmp)
S2 = set([str(S | eq(s).reverse_complement()) for s in tmp])
S = S1.union(S2)
res = []
for s in S:
res.append((s[:-1],s[1:]))
for t1,t2 in res:
print '(%s, %s)' % (t1,t2)
out = os.path.join(os.getcwd(),args[-1])
f = open(out, 'w')
for t1,t2 in res:
txt = '(%s, %s)\n' % (t1,t2)
... |
mozilla/popcorn_maker | popcorn_gallery/reports/views.py | Python | bsd-3-clause | 1,003 | 0 | from django.contrib import messages
from django.shortcuts import render, redirect
from django.templ | ate.loader import render_to_string
from tower import ugettext as _
from .forms import ReportForm
from ..base.utils import notify_admins
from ..base.decorators import throttle_view
@throttle_view(methods=['POST'], duration=30)
def report_form(request):
if request.method == 'POST':
form = ReportForm(reques... | subject = render_to_string('reports/email_subject.txt', context)
subject = ''.join(subject.splitlines())
body = render_to_string('reports/email_body.txt', context)
notify_admins(subject, body)
messages.success(request, _('Report sent successfully'))
retur... |
memsharded/conan | conans/test/functional/old/package_integrity_test.py | Python | mit | 2,451 | 0.00204 | import os
import unittest
from conans.model.ref import ConanFileReference, PackageReference
from conans.test.utils.conanfile import TestConanFile
from conans.test.utils.tools import TestClient, TestServe | r,\
NO_SETTINGS_PACKAGE_ID
from conans.util.files import set_dirty
class PackageIngrityTest(unittest.TestCase):
def remove_locks_test(self):
client = TestClient()
client.save({"conanf | ile.py": str(TestConanFile())})
client.run("create . lasote/testing")
self.assertNotIn('does not contain a number!', client.out)
ref = ConanFileReference.loads("Hello/0.1@lasote/testing")
conan_folder = client.cache.package_layout(ref).base_folder()
self.assertIn("locks", os.list... |
JulienMcJay/eclock | windows/kivy/kivy/core/__init__.py | Python | gpl-2.0 | 4,391 | 0 | '''
Core Abstraction
================
This module defines the abstraction layers for our core providers and their
implementations. For further information, please refer to
:ref:`architecture` and the :ref:`providers` section of the documentation.
In most cases, you shouldn't directly use a library that's already cove... | ortant error: {1!r}'.format(
category.capitalize(), e.message))
raise
except Exception as e:
libs_ignored.append(modulename)
Logger.trace('{0}: Unable to use {1}'.format(
category.capitalize(), option, category))
Logger.trace('... | gger.critical(
'{0}: Unable to find any valuable {1} provider at all!'.format(
category.capitalize(), category.capitalize()))
def core_register_libs(category, libs, base='kivy.core'):
if 'KIVY_DOC' in os.environ:
return
category = category.lower()
libs_loaded = []
libs_igno... |
brechtm/rinohtype | tests/test_pdf_reader.py | Python | agpl-3.0 | 3,238 | 0 | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gn | u.org/licenses/.
import pytest
from io import BytesIO
from rinoh.backend.pdf import cos
from rinoh.backend.pdf.reader import PDFObjectReader
def test_read_bool | ean():
def test_boolean(bytes_boolean, boolean):
reader = PDFObjectReader(BytesIO(bytes_boolean))
result = reader.next_item()
assert isinstance(result, cos.Boolean) and bool(result) == boolean
test_boolean(b'true', True)
test_boolean(b'false', False)
def test_read_integer():
d... |
jbradberry/django-diplomacy | setup.py | Python | mit | 915 | 0.001093 | import setuptools
with open("README.rst") as f:
long_description = f.read()
setuptools.setup(
name='django-diplomacy',
version="0.8.0",
author='Jeff Bradberry',
author_ema | il='jeff.bradberry@gmail.com',
description='A play-by-web app for Diplomacy',
long_description=long_description,
long_description_content_type='test/x-rst',
url='http://github.com/j | bradberry/django-diplomacy',
packages=setuptools.find_packages(),
entry_points={
'turngeneration.plugins': ['diplomacy = diplomacy.plugins:TurnGeneration'],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Framework :: Django',
... |
rboman/progs | sandbox/pyopengl/ball_glut.py | Python | apache-2.0 | 1,601 | 0.021861 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# OK anaconda2 + freeglut+pyopengl
# sous windows:
# - telecharger freeglut ici: http://freeglut.sourceforge.net/
# - renommer freeglut.dll en freeglut64.vc14.dll et la mettre dans le path
# en cas de non chargement regarder ce qui se passe dans C:\Python37\Lib\site-pac... | fv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor)
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1)
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05)
glEnable(GL_LIGHT0)
glutDisplayFunc(display)
glMatrixMode(GL_PROJECTION)
gluPerspective(40.,1.,1.,40.)
glMatrixMode(GL_MODELVIEW)
gluLookAt(0,0,10,... | glPushMatrix()
color = [1.0,0.,0.,1.]
glMaterialfv(GL_FRONT,GL_DIFFUSE,color)
glutSolidSphere(2,20,20)
glPopMatrix()
glutSwapBuffers()
return
if __name__ == '__main__': main() |
mambocab/python-driver | tests/integration/cqlengine/statements/test_update_statement.py | Python | apache-2.0 | 3,975 | 0.001761 | # Copyright DataStax, 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/lic | enses/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 sp | ecific language governing permissions and
# limitations under the License.
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
from cassandra.cqlengine.columns import Column, Set, List, Text
from cassandra.cqlengine.operators import *
from cassandra.cqlengine.statements import (Update... |
sl2017/campos | campos_activity/wizards/campos_activity_signup_wiz.py | Python | agpl-3.0 | 10,652 | 0.008261 | # -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import api, fields, models, _, exceptions
import logging
_logger = logging.getLogger(__name__)
class CamposActivitySignupMembers(mode | ls.TransientModel):
_name = 'campos.activity.signup.members'
_description = 'Activity Signup Members'
name = fields.Char('Name', size=64)
camp_age = fields.Integer(related='par_id.camp_age')
own_note = fields.Char(related='par_id.own_note')
par_id = fields.Many2one('campos.event.p | articipant', 'Participation', ondelete='cascade')
reg_id = fields.Many2one('event.registration', 'Registration', ondelete='cascade')
wiz_id = fields.Many2one('campos.activity.signup.wiz', 'Wizard', ondelete='cascade')
class CamposActivitySignupWiz(models.TransientModel):
_name = 'campos.activity.signup.... |
pandeydivesh15/AVSR-Deep-Speech | util/data_set_helpers_RHL.py | Python | gpl-2.0 | 7,982 | 0.004009 |
import pandas
import tensorflow as tf
from threading import Thread
from math import ceil
from six.moves import range
from util.audio import audiofile_to_input_vector
from util.gpu import get_available_gpus
from util.text_RHL import ctc_label_dense_to_sparse, text_to_char_array
class DataSets(object):
def __init_... | if files is None:
files = file
else:
files = files.append(file)
return files
train_files = read_csvs(train_csvs)
dev_files = read_csvs(dev_csvs)
test_files = read_csvs(test_csvs)
# Create train DataSet from all the train archives
train ... | n)
# Create dev DataSet from all the dev archives
dev = _read_data_set(dev_files, thread_count, dev_batch_size, numcep, numcontext, stride=stride, offset=offset, next_index=lambda i: next_index('dev', i), limit=limit_dev)
# Create test DataSet from all the test archives
test = _read_data_set(test_file... |
mediatum/mediatum | core/test/test_containertype.py | Python | gpl-3.0 | 581 | 0.008606 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2014 b | y the mediaTUM authors
:license: GPL3, see COPYING for details
"""
from core.test.asserts import assert_deprecation_warning
def test_getContainerChildren(some_node):
container_children = assert_deprecation_warning(some_node.getContainerChildren)
assert len(container_children) == 1
assert container_chi... | assert content_type == "directory"
|
balloob/netdisco | netdisco/discoverables/spotify_connect.py | Python | mit | 355 | 0 | """Discover devices that implement the Spotify Connect platform."""
from . import MDNSDiscoverable
class Discoverable(MDNSDiscoverable):
"""Add support for discovering Spotify Connect serv | ice."""
def __init__(self, nd):
"""Initialize the Cast discovery."""
| super(Discoverable, self).__init__(nd, '_spotify-connect._tcp.local.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.