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 |
|---|---|---|---|---|---|---|---|---|
pfalcon/ScratchABlock | tests_unit/test_liveness.py | Python | gpl-3.0 | 2,105 | 0.003325 | import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
def make_arg(a):
if a is None:
return None
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(add... | LV_entry = {
1: set(),
2: set(),
3: {REG("y")},
4: {REG("x | "), REG("y")},
5: {REG("y")},
6: {REG("y")},
7: {REG("z")},
}
LV_exit = {
1: set(),
2: {REG("y")},
3: {REG("x"), REG("y")},
4: {REG("y")},
5: {REG("z")},
6: {REG("z")},
7: set(),
}
GEN_LV = {
1: set(),
2: s... |
raspearsy/bme590hrm | test_hr.py | Python | mit | 2,111 | 0.000947 | from ecgmeasure import ECGMeasure
import pandas as pd
import numpy as np
# need to test what happens when have too little data to create a chunk
# need to throw an exception if have too little data
def get_raw_data():
""".. function :: get_raw_data()
Creates dataframe with raw data.
"""
times = [x*0.... | eartRate']).all()
assert | (biomeasure.data['B/T'] == test_hr1['B/T']).all()
|
respondcreate/django-versatileimagefield | tests/post_processor/models.py | Python | mit | 559 | 0 | from django.db import models
from versatileimagefield.fields import VersatileImageField
from versatileimagefield.placeholder import OnStoragePlaceholderImage |
class VersatileImagePostProcessorTestModel(models.Model):
"""A model for testing VersatileImageFields."""
image = VersatileImageField(
upload_to='./',
blank=True,
| placeholder_image=OnStoragePlaceholderImage(
path='on-storage-placeholder/placeholder.png'
)
)
class Meta:
verbose_name = 'foo'
verbose_name_plural = 'foos'
|
DolphinDream/sverchok | tests/ui_tests.py | Python | gpl-3.0 | 2,714 | 0.004422 |
from os import walk
from os.path import basename, splitext, dirname, join, exists
from glob import glob
import importlib
from inspect import getmembers, isclass
import sverchok
from sverchok.utils.testing import *
from sverchok.utils.logging import debug, info, error
from sverchok.node_tree import SverchCustomTreeNod... | 'SvIterationNode',
'SvExMinimalScalarFieldNode',
'SvExScalarFieldGraphNode',
'SvMeshSurfaceFieldNode',
'SvExMeshNormalFieldNode',
'SvExMinimalVectorFieldNode',
'SvSolidCenterOfMassNode',
... | 'SvIsSolidClosedNode',
'SvRefineSolidNode',
'SvSolidValidateNode'
]
sv_init = sverchok.__file__
nodes_dir = join(dirname(sv_init), "nodes")
def check_category(directory):
category = basename(directory)
fro... |
MasLinoma/test | kyzs/kyzs/pipelines.py | Python | gpl-2.0 | 258 | 0 | # Define your item pipelines here
#
# Don't forget to a | dd your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class KyzsPipeline(object):
def process_item(self, item, spider):
return i | tem
|
ATT-JBO/RPICameraRemote | RPICamera/RPICamera/RPICameraRemote.py | Python | mit | 7,821 | 0.009973 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#important: before running this demo, make certain that you import the library
#'paho.mqtt.client' into python (https://pypi.python.org/pypi/paho-mqtt)
#also make certain that ATT_IOT is in the same directory as this script.
import traceback ... |
IOT.addAsset(PictureId, "Picture", "take a picture (max resoution) and store on sd-card", True, "boolean")
IOT.addAsset(StreamServerId, "Stream server", "se | t the ip address of the server that manages the video", True, "string")
# get any previously defined settings
streamer.streamServerIp = IOT.getAssetState(StreamServerId)
if streamer.streamServerIp:
streamer.streamServerIp = streamer.streamServerIp['state']['value']
logging.info("sending str... |
mcornelio/synapse | synapse/__init__.py | Python | mit | 29,118 | 0.033141 | import sys
import os
import time
import logging
import socket
import string
import collections
import logging
import atexit
__version__ = "1.1.26"
__all__ = ['main','amqp']
class client_interface(object):
def get_cell(self, key, value=None):
"""Returns the contents of the cell"""
raise NotImple... | ""
if msg:
print msg
os._exit(status)
def trace_log_info(f, *args, **kw):
"""Trace function invocation"""
logger.info("calling %s with args %s, %s" % (f.__name__, args, kw))
return f(*args, **kw)
class base_dictionary(collections.MutableMapping):
"""A dictionary that applies an arbitrary key-alteri... | def __getitem__(self, key):
return self.store[self.__keytransform__(key)]
def __setitem__(self, key, value):
self.store[self.__keytransform__(key)] = value
def __delitem__(self, key):
del self.store[self.__keytransform__(key)]
def __iter__(self):
return iter(self.store)
def __len__(self):
... |
brchiu/tensorflow | tensorflow/python/data/experimental/kernel_tests/optimization/map_vectorization_test.py | Python | apache-2.0 | 20,093 | 0.004977 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Mod", math_ops.floor_mod),
("Greater", math_ops.greater),
("GreaterEqual", math_ops.greater_equal),
("Igamma", math_ops.igamma),
("Igammac", math_ops.igammac),
("IgammaGradA", math_ops.igamma_grad_a),
("Less", math_ops.less),
("LessEqual", math_ops.less_equal),
("Maximum"... | mum),
("Minimum", math_ops.minimum),
("Mod", math_ops.mod),
("Mul", math_ops.multiply),
("NotEqual", math_ops.not_equal),
("Polygamma", safe_polygamma),
("Pow", math_ops.pow),
("RealDiv", math_ops.divide),
("SquareDifference", math_ops.squared_difference),
("Sub", m... |
ashishnitinpatil/dota2api_scripts | dota2api_scripts/historical_data.py | Python | bsd-2-clause | 2,542 | 0.00236 | """
Script to fetch historical data (since 2011) for matches (global, public).
Gives results in a chronological order (ascending), as they happened.
"""
from __future__ import print_function
from dota2py import api
from time import sleep as wait_for_next_fetch
def public_match_history(start_at_match_seq_num=None, mat... | :
# successful data fetch
cur_matches = cur_response['result']['matches']
if len(cur_response['result']['matches']) >= 1:
if not match_history:
# very first fetch
match_history.extend(cur_matches)
matches_fet... | lse:
# 2nd fetch onwards, ignore the first common match
match_history.extend(cur_matches[1:])
matches_fetched += len(cur_matches) - 1
if len(cur_matches) == 1 and cur_matches[0]['match_id'] == last_match_id:
break
... |
caio2k/RIDE | src/robotide/searchtests/__init__.py | Python | apache-2.0 | 608 | 0.001645 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a | pplicable 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 th | e specific language governing permissions and
# limitations under the License.
|
ecolitan/fatics | venv/lib/python2.7/site-packages/twisted/mail/pop3client.py | Python | agpl-3.0 | 24,412 | 0.00168 | # -*- test-case-name: twisted.mail.test.test_pop3client -*-
# Copyright (c) 2001-2004 Divmod Inc.
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
POP3 client protocol implementation
Don't use this module directly. Use twisted.mail.pop3 instead.
@author: Jp Calderone
"""
import re
from h... | if args:
self.sendLine(cmd + ' ' + args)
else:
self.sendLine(cmd)
self.state = 'LONG_INITIAL'
self._xform = xform
self._consumer = consumer
self._waiting = defer.Deferred()
return self._waiting
# Twisted protocol callback
d | ef connectionMade(self):
if self.timeout > 0:
self.setTimeout(self.timeout)
self.state = 'WELCOME'
self._blockedQueue = []
def timeoutConnection(self):
self._timedOut = True
self.transport.loseConnection()
def connectionLost(self, reason):
if self.t... |
mineo/dnf-plugins-core | plugins/config_manager.py | Python | gpl-2.0 | 9,979 | 0.000701 | #
# Copyright (C) 2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be... | repo file into first reposdir which exists or create it
myrep | odir = None
for rdir in self.base.conf.reposdir:
if os.path.exists(rdir):
myrepodir = rdir
break
if not myrepodir:
myrepodir = self.base.conf.reposdir[0]
dnf.util.ensure_dir(myrepodir)
for url in self.opts.add_repo:
... |
ThreeDRadio/playlists | backend/catalogue/migrations/0002_auto_20160628_1024.py | Python | mit | 342 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('catal | ogue', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Cd',
new_name= | 'Release',
),
]
|
jashandeep-sohi/aiohttp | aiohttp/web_urldispatcher.py | Python | apache-2.0 | 26,407 | 0 | import abc
import asyncio
import keyword
import collections
import mimetypes
import re
import os
import sys
import inspect
import warnings
from collections.abc import Sized, Iterable, Container
from pathlib import Path
from urllib.parse import urlencode, unquote
from types import MappingProxyType
from . import hdrs
... | rn route
def register_route(self, route):
assert isinstance(route, ResourceRoute), \
'Instance of Route class is required, got {!r}'.format(route)
self._routes.append(route)
@asyncio.coroutine
def resolve(self, method, path):
allowed_methods = set()
match_dict ... | one:
return None, allowed_methods
for route in self._routes:
route_method = route.method
allowed_methods.add(route_method)
if route_method == method or route_method == hdrs.METH_ANY:
return UrlMappingMatchInfo(match_dict, route), allowed_methods
... |
lkluft/python-toolbox | scripts/matrixoperationen.py | Python | gpl-3.0 | 599 | 0 | # -*- coding: utf-8 -*-
"""Umgang mit mehrdimensionalen Arrays.
Im Folgenden w | ird der Umgang mit mehrdimensionalen Arrays
veranschaulicht. Die Beispiele zeigen zweidimensionale Arrays
(Matrizen), das Verhalten lässt sich jedoch auf Arrays höherer
Dimensionen übertragen.
"""
import numpy as np
# Definition zufälliger Matrizen
A = np.random.random_integers(0, 10, (3, 3))
B = np.random.random_... | n
A @ B # Matrixmultiplikation
np.cross(A, B) # Kreuzprodukt
A.T # Transponieren einer Matrix
|
onshape-public/onshape-clients | python/onshape_client/oas/models/bt_default_unit_info.py | Python | mit | 4,695 | 0 | # coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | noqa: E501
"""
self._data_store = {}
s | elf._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
if (
var_name not in self.attribute_map
and self._configur... |
insomnia-lab/calibre | src/calibre/ebooks/docx/fields.py | Python | gpl-3.0 | 4,524 | 0.0042 | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import re
from calibre.ebooks.docx.names import XPath, get
class Field(obje... | )
if typ == 'begin':
stack.append(Field(elem))
self.fields.append(stack[-1])
els | e:
try:
stack.pop().end = elem
except IndexError:
pass
elif elem.tag.endswith('}instrText'):
if stack:
stack[-1].add_instr(elem)
else:
if stack:
... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/google/appengine/api/files/records.py | Python | bsd-3-clause | 11,204 | 0.006426 | #!/usr/bin/env python
#
# Copyright 2007 Google 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 o... | ing = BLOCK_SIZE - self.__reader.tell() % BLOCK_SIZE
if block_remaining < HEADER_LENGTH:
return ('', RECORD_TYPE_NONE)
header = self.__reader.read(HEADER_LENGTH)
if len(header) != HEADER_LENGT | H:
raise EOFError('Read %s bytes instead of %s' %
(len(header), HEADER_LENGTH))
(masked_crc, length, record_type) = struct.unpack(HEADER_FORMAT, header)
crc = _unmask_crc(masked_crc)
if length + HEADER_LENGTH > block_remaining:
raise |
philgyford/django-spectator | spectator/events/views.py | Python | mit | 8,037 | 0.000249 | from django.db.models import Min
from django.http import Http404
from django.utils.encoding import force_str
from django.utils.translation import gettext as _
from django.views.generic import DetailView, YearArchiveView
from django.views.generic.detail import SingleObjectMixin
from spectator.core import app_settings
f... | 'movie', 'Movie', and 'Movies' respectively:
kind = self.get_work_kind()
kind_name = Work.get_kind_name(kind)
ki | nd_name_plural = Work.get_kind_name_plural(kind)
context["page_title"] = kind_name_plural
context["breadcrumb_list_title"] = kind_name_plural
context["work_kind"] = kind
context["work_kind_name"] = kind_name
context["work_kind_name_plural"] = kind_name_plural
context["... |
danrschlosser/eventum | eventum/forms/CreateProfileForm.py | Python | mit | 1,023 | 0 | """
.. module:: CreateProfileForm
:synopsis: A form for completing a user's profile.
.. moduleauthor:: Dan Schlosser <dan@schlosser.io>
"""
from flask.ext.wtf import Form
from wtforms import StringField, Hid | denField
from wtforms.validators import URL, Email, Required
EMAIL_ERROR = ' | Please provide a valid email address.'
class CreateProfileForm(Form):
"""A form for completing a :class:`~app.models.User` profile after they
login to Eventum for the first time.
:ivar email: :class:`wtforms.fields.StringField` - The user's email
address.
:ivar name: :class:`wtforms.fields.St... |
achapkowski/ArcREST | src/arcrest/common/geometry.py | Python | apache-2.0 | 20,189 | 0.009114 | import os
import json
import arcpy
import types
import general
from .._ab | stract import abstract
########################################################################
class SpatialReference(abstract.AbstractGeometry):
""" creates a spatial reference instance """
_wkid = None
#----------------------------------------------------------------------
def __init__(self, wkid) | :
"""Constructor"""
self._wkid = wkid
#----------------------------------------------------------------------
@property
def wkid(self):
""" get/set the wkid """
return self._wkid
@wkid.setter
def wkid(self, wkid):
""" get/set the wkid """
self._wkid = ... |
stryder199/RyarkAssignments | Assignment2/ttt/archive/_old/KnR/KnR_1-7b.py | Python | mit | 689 | 0.015965 | game_type = 'input_output'
parameter_list = [['$x1','int'], ['$y0','int'], ['$y1','int']]
tuple_list = [
['KnR_1-7b_',[-3,None,None]]
]
global_code_template = '''\
d #include <st | dio.h>
x #include <stdio.h>
dx
dx /* power: raise base to n-th power; n >= 0 */
dx /* (old-style version) */
dx power(base, n)
dx int base, n;
dx {
dx int i, p;
dx
dx p = 1;
dx for (i = 1; i <= n; ++i)
dx p = p * base;
dx return p;
dx }
dx
dx /* test power function */
'''
main_code_template = '''\
dx int i;... | '\
0 1 1
1 2 $y0
2 4 $y1
'''
|
ComputerNetworks-UFRGS/OpERA | python/experiment_design/transmission_config.py | Python | apache-2.0 | 3,622 | 0.004694 | __author__ = 'jtsreinaldo'
from radio_constants import *
from validation_constants import *
class TXConfigRadioGenerator(object):
"""
A class for the reception configuration of a radio.
"""
def __init__(self):
"""
CTOR
"""
pass
@staticmethod
def tx_generator(... | try:
modulator = "digital.gmsk_mod(samples_per_symbol={samples_per_symbol}, | bt={bt})"
modulator = modulator.format(samples_per_symbol=samples_per_symbol, bt=bt)
except:
modulator = DEFAULTS[TX][GMSK][MODULATOR]
tx_arch = "PacketGMSKTx(modulator={modulator})"
tx_arch = tx_arch.format(modulator=modulator)
ip = radio... |
lujinda/iotop | iotop/ui.py | Python | gpl-2.0 | 24,215 | 0.000991 | # 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 ve | rsion 2 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 Library General Public License for more details.
#
#... | n, MA 02110-1301 USA
#
# See the COPYING file for license information.
#
# Copyright (c) 2007 Guillaume Chazarain <guichaz@gmail.com>
# Allow printing with same syntax in Python 2/3
from __future__ import print_function
import curses
import errno
import locale
import math
import optparse
import os
import select
impo... |
jferreir/mbed | workspace_tools/host_tests/host_registry.py | Python | apache-2.0 | 1,214 | 0.004942 | """
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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... | itations under the License.
"""
class HostRegistry:
""" Class stores registry with host tests and objects representing them
"""
HOST_TESTS = {} # host_test_name -> host_test_ojbect
def register_host_test(self, ht_name, ht_object):
if ht_name not in self.HOST_TESTS:
self.HOST_TESTS... |
def unregister_host_test(self):
if ht_name in HOST_TESTS:
self.HOST_TESTS[ht_name] = None
def get_host_test(self, ht_name):
return self.HOST_TESTS[ht_name] if ht_name in self.HOST_TESTS else None
def is_host_test(self, ht_name):
return ht_name in self.HOST_TESTS
... |
matthewrmshin/isodatetime | metomi/isodatetime/tests/test_datetimeoper.py | Python | lgpl-3.0 | 15,759 | 0 | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright (C) 2013-2019 British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published ... | datetimeoper.process_time_point_s | tr(point_str, ['-P1D']))
# offsets that cancel out
self.assertEqual(
point_str,
datetimeoper.process_time_point_str(point_str, ['PT1H', '-PT60M']))
# Multiple offsets in 1 string
point_str_3 = str(seconds2point(1234567890 - 86400 - 3600))
self.assertEqual(... |
artefactual/archivematica-storage-service | storage_service/locations/south_migrations/0006_duracloud.py | Python | agpl-3.0 | 25,555 | 0.001722 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Duracloud'
db.create_table(
u"locations_duracloud",
(
(u"i... | roup']", "symmetrical": "False", "blank": "True"},
),
u"id": ("django.db.models.fields.AutoField", [], {"primary_key": "True"}),
"is_active": (
"django.db.models.fields.BooleanField",
[],
{"default": "True"},
),
... | django.db.models.fields.BooleanField",
[],
{"default": "False"},
),
"is_superuser": (
"django.db.models.fields.BooleanField",
[],
{"default": "False"},
),
"last_login": (
"djan... |
macosforge/ccs-calendarserver | contrib/performance/benchmarks/event_move.py | Python | apache-2.0 | 2,708 | 0 | ##
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | erformance.httpclient import StringProducer
from contrib.performance.benchlib import initialize, sample
from contrib.performance.benchmarks.event import makeEvent
@inlineCallbacks
def measure(host, port, dtrace, attendeeCount, samples):
organizerSequence = 1
user = password = " | user%02d" % (organizerSequence,)
root = "/"
principal = "/"
# Two calendars between which to move the event.
fooCalendar = "event-move-foo-benchmark"
barCalendar = "event-move-bar-benchmark"
authinfo = HTTPDigestAuthHandler()
authinfo.add_password(
realm="Test Realm",
uri="... |
sjsucohort6/openstack | python/venv/lib/python2.7/site-packages/cliff/formatters/shell.py | Python | mit | 1,337 | 0 | """Output formatters using shell syntax.
"""
from .base import SingleFormatter
import argparse
import six
class ShellFormatter(SingleFormatter):
def add_argument_group(self, parser):
group = parser.add_argument_group(
title='shell formatter',
description='a format a UNIX shell c... | ='variables',
metavar='VARIABLE',
help=argparse.SUPPRESS,
)
group.add_argument(
'--prefix',
action='store',
default='',
dest='prefix',
help='add a prefix to all variable names',
)
def emit_one(self, column_n... | e_names = [c.lower().replace(' ', '_')
for c in column_names
]
desired_columns = parsed_args.variables
for name, value in zip(variable_names, data):
if name in desired_columns or not desired_columns:
if isinstance(value, six... |
myint/language-check | test.py | Python | lgpl-3.0 | 5,483 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test suite for language_check."""
from __future__ import unicode_literals
import unittest
import warnings
from collections import namedtuple
import language_check
class TestLanguageTool(unittest.TestCase):
CheckTest = namedtuple('CheckTest', ('text', 'matches'))... | LanguageTool. '
'notez que LanguageTool ne comporte pas '
'de correcteur orthographique.'),
[
Match(0, 0, 'SE_CE'),
Match(0, 3, 'TE_NV'),
M | atch(0, 24, 'FRENCH_WORD_REPEAT_RULE'),
Match(0, 82, 'UPPERCASE_SENTENCE_START'),
]
),
CheckTest(
'je me rappelle de tout sans aucun soucis!',
[
Match(0, 0, 'UPPERCASE_SENTENCE_START'),
Ma... |
yeleman/uninond | uninond/tools.py | Python | mit | 6,367 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import re
import unicodedata
import datetime
import subprocess
from py3compat import string_types, text_type
from django.utils impo... | kup
clean_number = re.sub(r'[^\d\+]', '', number)
if phonenumber_isint(clean_number):
h, indicator, clean_number = \
clean_number.partition(phonenumber_indicator(clean_number))
return (indicator, clean_number)
return (None, clean_number)
def join_phonenumber(prefix, number, f... | +{prefix}{number}".format(prefix=prefix, number=number)
def phonenumber_repr(number, skip_indicator=str(COUNTRY_PREFIX)):
''' properly formated for visualization: (xxx) xx xx xx xx '''
def format(number):
if len(number) % 2 == 0:
span = 2
else:
span = 3
# use N... |
abhirevan/Yelp-Rate-my-Review | src/review_stats.py | Python | mit | 2,318 | 0.004745 | import csv
from numpy import histogram
def review_stats(count_ratings, length):
# print "in extract_rows"
ip_csv = "data\input\yelp_academic_dataset_review_ext.csv"
with open(ip_csv, "rb") as source:
rdr = csv.reader(source)
firstline = True
for r in rdr:
if firstline: ... | star", count_ratings[5]
length.sort()
sum = 0.0
for i in length:
sum += i
print "Min length: ", min(length), "Max length: ", max(length)
print "Avg length: ", sum / len(length), "Median: ", length[len(length) / 2]
hist,bin_edges = histogram(a=length,bins=20)
print hist
print... | categories", len(categories)
print "Reviews per category:"
for c in categories:
print c + "?" + str(category_count[c])
'''
|
kubeflow/code-intelligence | py/notifications/notifications.py | Python | mit | 6,630 | 0.008748 | from code_intelligence import graphql
import fire
import github3
import json
import logging
import os
import numpy as np
import pprint
import retrying
import json
TOKEN_NAME_PREFERENCE = ["INPUT_GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_TOKEN"]
for token in TOKEN_NAME_PREFERENCE:
if os.... | s which aren't assigned to the user.
if n.reason == "mention":
if n.subject.get("type") != "PullRequest":
return
title = n.subject.get("title")
logging.info("Marking as read: type: %s reason: %s title: %s",
n.subject.get("type"), n.reason, title)
n.mark()
def process_issue_results(da... | t of dicts; each dict is the data for some of
the results
"""
edges = data.get("data").get("repository").get("issues").get("edges")
issues = []
for e in edges:
issues.append(e["node"])
return issues
class NotificationManager(object):
def mark_read(self, user):
token = os.getenv(TOKEN_NAME)
... |
jacobajit/ion | intranet/apps/notifications/urls.py | Python | gpl-2.0 | 483 | 0.008282 | # -*- coding: | utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^/android/setup$", views.android_setup_view, name="notif_android_setup"),
url(r" | ^/chrome/setup$", views.chrome_setup_view, name="notif_chrome_setup"),
url(r"^/chrome/getdata$", views.chrome_getdata_view, name="notif_chrome_getdata"),
url(r"^/gcm/post$", views.gcm_post_view, name="notif_gcm_post"), url(r"^/gcm/list$", views.gcm_list_view, name="notif_gcm_list")
]
|
erasche/galactic-radio-telescope | api/migrations/0001_initial.py | Python | agpl-3.0 | 3,931 | 0.003561 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-04 09:25
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
... | odels.CharField(max_length=256)),
('value', models.TextField()),
('instance', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.GalaxyInstance')),
],
),
migrations.CreateModel(
name='MetricNumeric',
fields=[
... | ls.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('external_job_id', models.IntegerField(default=-1)),
('plugin', models.CharField(max_length=256)),
('name', models.CharField(max_length=256)),
('value', models.Decimal... |
kadhikari/navitia | source/jormungandr/tests/stif_tests.py | Python | agpl-3.0 | 7,989 | 0.005007 | # Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | override_scenario=new_default" \
"&min_nb_journeys=1&_min_journeys_calls=1&_final_line_filter=true&_max_successive_physical_mode=3"\
.format(from_sp="stopA", to_sp="stopB", datetime="20140614T075500")
response = self.query_region(query)
assert len(resp | onse['journeys']) == 1
assert response['journeys'][0]['arrival_date_time'] == '20140614T100000'
def test_stif_override_final_line_filter(self):
"""
Test of simple request :
* we want to make at least 2 journey calls (not only the best journey, but also try next)
* we deactiv... |
toha10/python-cudet | cudet/flock.py | Python | gpl-2.0 | 3,884 | 0 | # The MIT License (MIT)
# Copyright (c) 2009 Max Polk
# Permission i | s 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, distribute, sublicense | , and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDE... |
liuxu0703/lx_bash_script | android_script/keyword_manager.py | Python | mit | 5,470 | 0.006764 | #!/usr/bin/python
# AUTHOR : liuxu-0703@163.com
# used to extract keyword sets from xml
# used by aplog_helper.sh and adblogcat.sh
import os
import sys
import getopt
from xml.dom.minidom import parse, parseString
#=======================================
class KeywordSet:
def __init__(self, xml_node):
... | f.readKeywo | rds(xml_node.getElementsByTagName('keywords')[0])
def getText(self, text_node):
'''get text from xml node
$text_node should be a node with type NODE_TEXT
return str of the text
'''
ret = ''
for n in text_node.childNodes:
ret = ret + n.nodeValue
... |
gdsfactory/gdsfactory | gdsfactory/samples/20_components.py | Python | mit | 482 | 0 | """# Components.
You can adapt | some component functions from the `gdsfactory.components` module.
Each function there returns a Component object
Here are two equivalent functions
"""
import gdsfactory as gf
def straight_wide1(width=10, **kwargs) -> gf.Component:
return gf.components.straight(width=width, **kwargs)
straight_wide2 = gf.parti... | de1()
c = straight_wide2()
c.show()
|
yipenggao/moose | python/peacock/Input/BlockHighlighterPlugin.py | Python | lgpl-2.1 | 3,928 | 0.001527 | from PyQt5 import QtCore, QtWidgets
import chigger
import peacock
from peacock.ExodusViewer.plugins.ExodusPlugin import ExodusPlugin
from MeshBlockSelectorWidget import MeshBlockSelectorWidget
class BlockHighlighterPlugin(peacock.base.PeacockCollapsibleWidget, ExodusPlugin):
"""
Widget for controlling the visi... | info = self._result[0].getCurrentVariableInformation()
if varinfo:
if varinfo.object_type == chigger.exodus.ExodusReader.ELEMENTAL:
self.SidesetSelector.setEnabled(False)
self.NodesetSelector.setEnabled(False)
else:
self.SidesetSelector.set... | r.setEnabled(True)
|
CNR-Engineering/ModelerTools | common/qt_log_in_textbrowser.py | Python | gpl-3.0 | 788 | 0.002538 | " | ""
Handle logging in a Message Box?
"""
from PyQt4 import QtGui, QtCore
import logging
import sys
class MyQWidget(QtGui.QWidget):
def center(self):
| frameGm = self.frameGeometry()
screen = QtGui.QApplication.desktop().screenNumber(QtGui.QApplication.desktop().cursor().pos())
centerPoint = QtGui.QApplication.desktop().screenGeometry(screen).center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft())
class ConsoleWin... |
formencode/formencode | src/formencode/htmlfill.py | Python | mit | 23,202 | 0.000431 | """
Parser for HTML forms, that fills in defaults and errors. See ``render``.
"""
from __future__ import absolute_import
import re
from formencode.rewritingparser import RewritingParser, html_quote
import six
__all__ = ['render', 'htmlliteral', 'default_formatter',
'none_formatter', 'escape_formatter',
... | living='no',
... nice_guy=0)
>>> parser = FillingParser(defaults)
>>> parser.feed('''<input type="text" name="name" value="fill">
... <select name="occupation"> <option value="">Default</o | ption>
... <option value="Crazy Cultist">Crazy cultist</option> </select>
... <textarea cols="20" style="width: 100%" name="address">
... An address</textarea>
... <input type="radio" name="living" value="yes">
... <input type="radio" name="living" value="no">
... <input ... |
disappearedgod/stokeScrapy | stokeScrapy/pipelines.py | Python | gpl-2.0 | 1,353 | 0.031042 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
# import codecs
# import json
# class stokeScrapyPipeline(object):
# def __init__(self):
# self.file=codecs.open... | scrapy.conf import settings
f | rom scrapy.exceptions import DropItem
from scrapy import log
#MongoDBPipeline
class MongoDBPipeline( object ):
def __init__( self ):
connection = pymongo.MongoClient(
settings[ 'MONGODB_SERVER' ],
settings[ 'MONGODB_PORT' ]
)
db = connection[settings[ 'MONGODB_DB' ]]
self .collecti... |
BrainPad/FindYourCandy | robot-arm/calibration/adjust.py | Python | apache-2.0 | 4,494 | 0.00267 | # Copyright 2017 BrainPad 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... | se:
out_data.update({new_key: None})
try:
out_data_json = os.path.join(os.path.dirname(__file__), 'adjust_data.json')
f = open(out_data_json, 'w')
f.write(json.dumps(out_data, sort_keys=True, indent=4))
f.close()
except Exception as e:
... | <= x <= 1 and -1.5 <= y <= 1.5:
pass
else:
message = "Error: x=%s y=%s coordinate is out of range in sheet." % (x, y)
raise Exception(message)
x_round = round(x, 1)
y_round = round(y, 1)
if x_round == -0.0:
x_round = 0.0
if y_ro... |
jacobajit/ion | intranet/apps/eighth/forms/admin/blocks.py | Python | gpl-2.0 | 1,644 | 0.003041 | # -*- coding: utf-8 -*-
from django import forms
from django.core.validators import RegexValidator
from ...models import EighthBlock
block_letter_validator = RegexValidator(r"^[a-z A-Z0-9_-]{1,10}$",
"A block letter must be less than 10 characters long, and include only alphan... | obj):
return "{}: {}".format(obj.id, str(obj))
class BlockSelectionForm(forms.Form):
def __init__(self, label="Block", exclude_before_date=None, only_locked=False, *args, **kwargs):
super(BlockSelectionForm, self).__init__(*args, **kwargs)
filter_params = {}
if exclude_before_da... | .filter(**filter_params)
self.fields["block"] = BlockDisplayField(queryset=queryset, label=label, empty_label="Select a block")
class QuickBlockForm(forms.ModelForm):
block_letter = forms.CharField(max_length=10, validators=[block_letter_validator])
class Meta:
model = EighthBlock
fi... |
wangybgit/Chameleon | hostapd-OpenWrt/tests/hwsim/test_bgscan.py | Python | apache-2.0 | 6,284 | 0.003024 | # bgscan tests
# Copyright (c) 2014, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import time
import logging
logger = logging.getLogger()
import os
import hostapd
def test_bgscan_simple(dev, apdev):
"""bgscan_simple"""
hostapd... | freq="2412",
bgscan="simple:0:0")
dev[2].request("REMOVE_NETWORK all")
dev[2].wait_disconnected()
dev[2].connect("bgscan", key_mgmt="NONE", scan_freq="2412",
bgscan="simple")
dev[2].request("REMOVE | _NETWORK all")
dev[2].wait_disconnected()
dev[2].connect("bgscan", key_mgmt="NONE", scan_freq="2412",
bgscan="simple:1")
dev[2].request("REMOVE_NETWORK all")
dev[2].wait_disconnected()
ev = dev[0].wait_event(["CTRL-EVENT-SIGNAL-CHANGE"], timeout=10)
if ev is None:
ra... |
Ecotrust/COMPASS | mp/wsgi.py | Python | apache-2.0 | 378 | 0 | """
WSGI confi | g for lot project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "s | ettings")
application = get_wsgi_application()
|
iliawnek/SystematicReview | systematic_review/settings.py | Python | mit | 2,999 | 0 | """
Django settings for systematic_review project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DI... | honanywhere.com', '127.0.0.1', 'localhost']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contr | ib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.formtools',
'sysrev',
'registration',
'bootstrapform'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddl... |
skosukhin/spack | var/spack/repos/builtin/packages/r-speedglm/package.py | Python | lgpl-2.1 | 1,759 | 0.000569 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ls and generalized linear models to
large data sets by updating algorithms."""
homepage = "https://cran.r | -project.org/package=speedglm"
url = "https://cran.rstudio.com/src/contrib/speedglm_0.3-2.tar.gz"
list_url = "https://cran.rstudio.com/src/contrib/Archive/speedglm"
version('0.3-2', 'c4874d4c2a677d657a335186ebb63131')
depends_on('r-mass', type=('build', 'run'))
depends_on('r-matrix', type=('b... |
gramps-project/addons-source | SetAttributeTool/SetAttributeTool.gpr.py | Python | gpl-2.0 | 1,411 | 0.02197 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2009 Douglas S. Blank <doug.blank@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License... | Douglas S. Blank"],
authors | _email = ["doug.blank@gmail.com"],
category = TOOL_DBPROC,
toolclass = 'SetAttributeWindow',
optionclass = 'SetAttributeOptions',
tool_modes = [TOOL_MODE_GUI],
)
|
HiSPARC/station-software | user/python/Lib/unittest/signals.py | Python | gpl-3.0 | 2,411 | 0.002074 | import signal
import weakref
from functools import wraps
__unittest = True
class _InterruptHandler(object):
def __init__(self, default_handler):
self.called = False
self.original_handler = default_handler
if isinstance(default_handler, (int, long)):
if default_handler == sign... | # if we aren't the installe | d handler, then delegate immediately
# to the default handler
self.default_handler(signum, frame)
if self.called:
self.default_handler(signum, frame)
self.called = True
for result in _results.keys():
result.stop()
_results = weakref.WeakKeyDictio... |
numenta/nupic.research | projects/imagenet/experiments/sparse_r1.py | Python | agpl-3.0 | 5,411 | 0.00037 | # Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software you can redistribute it and/or modify
# it under... | auto_sparse_ | activation_params(in_channels, out_channels, kernel_size):
"""
A custom auto sparse params function.
:return: a dict to pass to `KWinners2d` as params.
"""
percent_on = 1.0
if kernel_size != 1:
if out_channels >= 128:
percent_on = 0.3
if percent_on >= 1.0:
retur... |
radical-software/mongrey | mongrey/web/worker.py | Python | bsd-3-clause | 1,033 | 0.003872 | #!/ | usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import multiprocessing
import gunicorn.app.base
from gunicorn.six import iteritems
def number_of_workers():
return (multiprocessing.cpu_count() * 2) + 1
class StandaloneApplication(gunicorn.app.base.BaseApplication | ):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(StandaloneApplication, self).__init__()
def load_config(self):
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.set... |
matthiask/feincms3 | feincms3/plugins/__init__.py | Python | bsd-3-clause | 269 | 0 | # flake8: noqa
from . import html, ric | htext, snippet
try:
import requests
except ImportError: # pragma: no cover
pass
else:
from . import external
try:
import | imagefield
except ImportError: # pragma: no cover
pass
else:
from . import image
|
PYPIT/arclines | arclines/scripts/match.py | Python | bsd-3-clause | 3,106 | 0.007727 | #!/usr/bin/env python
"""
Match input spectrum to ID lines
"""
from __future__ import (print_function, absolute_import, division, unicode_literals)
import pdb
try: # Python 3
ustr = unicode
except NameError:
ustr = str
def parser(options=None):
import argparse
# Parse
parser = argparse.ArgumentP... | pargs.debug:
pdb.set_trace()
if pargs.fit:
| ltu.savejson(pargs.outroot+'_fit.json', ltu.jsonify(final_fit), easy_to_read=True, overwrite=True)
|
cocofree/azkaban_assistant | schedule/webapp/handler/job_update.py | Python | apache-2.0 | 2,583 | 0.021624 | #!/usrbin/python
#encoding:utf-8
'''
Author: wangxu
Email: wangxu@oneniceapp.com
任务更新
'''
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import logging
import tornado.web
import json
import os
import time
CURRENTPATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(CURRENTPATH, '... | e(dependencies_box)))
logging.info('>>>>>>>>>>>'+str(dependencies_box))
job = Job()
#动态加载字段,默认均为字符串
for attr in attr_list:
value = str(self.get_argument(attr,'')).strip()
if value!='':
setattr(job,attr,value)
logging.info(attr+':'+v... | te_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
if job.creator == '':
job.creator = job.updater
job.create_time = job.update_time
#更新
job.update_job()
#列表
jobs = Job.get_alljobs(query_name,query_project_name,query_server_host,query_user,log... |
paulocheque/epub-meta | setup.py | Python | agpl-3.0 | 1,554 | 0.001931 | #from distutils.core import | setup
from setuptools import setup, find_packages
# http://guide.python-distribute.org/quickstart.html
# python setup.py sdist
# python setup.py register
# python setup.py sdist upload
# pip install epub_meta
# pip install epub_meta --upgrade --no-deps
# Manual upload to PypI
# http://pypi.python.org/pypi/epub_meta
# ... | equirements
# install_requires = parse_requirements('requirements.txt')
# tests_require = parse_requirements('requirements-dev.txt')
setup(name='epub_meta',
url='https://github.com/paulocheque/epub-meta',
author='Pluralsight',
keywords='python epub metadata',
description='',
license='MIT'... |
jcfr/mystic | examples2/g09.py | Python | bsd-3-clause | 1,961 | 0.009179 | #!/usr/bin/env python
#
# Problem definition:
# A-R Hedar and M Fukushima, "Derivative-Free Filter Simulated Annealing
# Method for Constrained Continuous Global Optimization", Journal of
# Global Optimization, 35(4), 521-549 (2006).
#
# Original Matlab code written by A. Hedar (Nov. 23, 2005)
# http://www-optima.amp.... | + x6**4 - 4*x5*x6 - 10*x5 - 8*x6
bounds = [(-10.,10.)]*7
# with penalty='penalty' applied, solution is:
xs = [2.330499, 1.951372, -0.4775414, 4.365726, -0.6244870, 1.038131, 1.594227]
ys = 680.6300573
from mystic.symbolic import generate_constrain | t, generate_solvers, solve
from mystic.symbolic import generate_penalty, generate_conditions
equations = """
2*x0**2 + 3*x1**4 + x2 + 4*x3**2 + 5*x4 - 127.0 <= 0.0
7*x0 + 3*x1 + 10*x2**2 + x3 - x4 - 282.0 <= 0.0
23*x0 + x1**2 + 6*x5**2 - 8*x6 - 196.0 <= 0.0
4*x0**2 + x1**2 - 3*x0*x1 + 2*x2**2 + 5*x5 - 11*x6 <= 0.0
"""... |
leosartaj/pymarkdown | setup.py | Python | bsd-3-clause | 599 | 0.001669 | #!/usr/bin/env python
import os
from setuptools import setup
setup(name='pymarkdown',
version='0.1.4',
description='Evaluate code in markdown',
url='http://github.com/mrocklin/pymarkdown',
aut | hor='Matthew Rocklin',
author_email='mrocklin@gmail.com',
license='BSD',
keywords='markdown documentation',
packages=['pymarkdown'],
install_requires=['toolz'],
long_description=(open('README.rst').read() if os.path.exists('README.rst')
else ''),
zip_saf... | oin('bin', 'pymarkdown')])
|
mtill/MailWebsiteChanges | mwcfeedserver.py | Python | gpl-2.0 | 1,039 | 0.002887 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright: (2013-2017) Michael Till Beck <Debianguru@gmx.de>
# License: GPL-2.0+
import http.server
import socketserver
import importlib
import sys
import getopt
bind = 'localhost'
port = 8000
configMod = 'config'
try:
opts, args = getopt.getopt(sys.argv[1:], ... | topt.GetoptError:
print('Usage: FeedServer.py --config=config --port=8000 --bind=localhost')
sys.exit(1)
for opt, arg in opts:
if opt == '-h':
print('Usage: | FeedServer.py --config=config --bind=localhost --port=8000')
exit()
elif opt in ('-c', '--config'):
configMod = arg
elif opt in ('-b', '--bind'):
bind = arg
elif opt in ('-p', '--port'):
port = int(arg)
config = importlib.import_module(configMod)
handler = http.server.Simp... |
infinigrove/TerminalRoastDB | cmds/Roaster_Set_Time.py | Python | gpl-3.0 | 324 | 0.003086 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# TerminalRoastDB, released under GPLv3
# Roaster Set Time
import Pyro | 4
import sys
new_roaster_time = sys.argv[1]
roast_control = Pyro4.Proxy("PYRONAME:roaster.sr700")
if int(new_roaster_time) > 0 and int( | new_roaster_time) <1200:
roast_control.set_time(new_roaster_time)
|
coopsource/taiga-back | taiga/searches/migrations/0001_initial.py | Python | agpl-3.0 | 1,689 | 0.002368 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wiki', '00 | 01_initial'),
('userstories', '0009_remove_userstory_is_archived'),
('issues', '0005_auto_20150623_1923'),
('tasks', '0006_auto_20150623_1923'),
]
operations = [
migrations.RunSQL(
"""
| CREATE INDEX "userstories_full_text_idx" ON userstories_userstory USING gin(to_tsvector('simple', coalesce(subject, '') || ' ' || coalesce(ref) || ' ' || coalesce(description, '')));
""",
reverse_sql="""DROP INDEX IF EXISTS "userstories_full_text_idx";"""
),
migrations.RunSQL... |
michaelnetbiz/mistt-solution | config.py | Python | mit | 1,994 | 0.005015 | import os
import json
from urlparse import urlparse
from pymongo import uri_parser
def get_private_key():
with open('mistt-solution-d728e8f21f47.json') as f:
return json.loads(f.read()).items()
# Flask
CSRF_SESSION_KEY = os.getenv('FLASK_SESSION_KEY', 'notsecret')
SECRET_KEY = os.getenv('FLASK_SECRET_KEY'... | _EMAIL = os.getenv('ADMIN_EMAIL', 'notsecret')
ADMIN_USERNAME = os.getenv('ADMIN_USERNAME', 'notsecret')
ADMIN_PASSWORD = os.getenv('ADMIN_PASSWORD', 'notsecret')
SECURITY_PASSWORD_SALT = os.getenv('SECURITY_PASSWORD_SALT', 'notsecret')
# postgres
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_MIGRATE_REPO = os.pat... | ASE_URI = os.getenv('DATABASE_URL', 'postgres://localhost:5432/mistt')
# dumps
PAGE_DUMP_PATH = os.getenv('PAGE_DUMP_PATH', 'page_dump_110116')
PATH_TO_CASE_EXPORTS = os.getenv('PATH_TO_CASE_EXPORTS')
# Drupal
DRUPAL_URL = os.getenv('DRUPAL_URL')
DRUPAL_LOGIN = os.getenv('DRUPAL_LOGIN')
DRUPAL_PASSWORD = os.getenv('D... |
srinath-chakravarthy/ovito | tests/scripts/test_suite/python_data_plot_overlay.py | Python | gpl-3.0 | 1,873 | 0.034704 | from ovito import *
from ovito.io import *
from ovito.modifiers import *
from ovito.vis import *
import matplotlib
# Activate 'agg' backend for off-screen plotting.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import PyQt5.QtGui
node = import_file("../../files/CFG/fcc_coherent_twin.0.cfg")
node.modifiers.a... | emory buffer
res_x, res_y = buf[1]
img = PyQt5.QtGui.QImage(buf[0], res_x, res | _y, PyQt5.QtGui.QImage.Format_RGBA8888)
# Paint QImage onto rendered viewport
painter.drawImage(0,0,img)
print("Overlay function was executed")
overlay = PythonViewportOverlay()
overlay.function = render
vp.overlays.append(overlay)
if ovito.headless_mode:
ovito.dataset.render_settings.renderer = TachyonRen... |
juliarizza/web2courses | languages/ro.py | Python | mit | 29,001 | 0.024039 | # -*- coding: utf-8 -*-
{
'\n\nThank you!': '\n\nThank you!',
'\n\nWe will wait and let you know when your payment is confirmed.': '\n\nWe will wait and let you know when your payment is confirmed.',
'\n- %s from %s to %s': '\n- %s from %s to %s',
'\nAmount: R$%.2f': '\nAmount: R$%.2f',
"\nSomething happened and we cou... | : 'crează fișier cu numele:',
'Create new app | lication': 'Creați aplicație nouă',
'create new application:': 'crează aplicație nouă:',
'crontab': 'crontab',
'Current request': 'Cerere curentă',
'Current response': 'Răspuns curent',
'Current session': 'Sesiune curentă',
'currently saved or': 'în prezent salvat sau',
'customize me!': 'Personalizează-mă!',
'DASHBOARD... |
samabhi/pstHealth | venv/lib/python2.7/site-packages/requests/packages/urllib3/_collections.py | Python | mit | 4,119 | 0.000243 | # urllib3/_collections.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from collections import deque
from threading import RLock
__all__ = ['RecentlyUsedContai... | _valid]
self.access_log_lock.release()
return r
def __getitem__(self | , key):
item = dict.get(self, key)
if not item:
raise KeyError(key)
# Insert new entry with new high priority, also implicitly invalidates
# the old entry.
self._push_entry(key)
if len(self.access_log) > self.access_log_limit:
# Heap is getting ... |
keithhendry/treadmill | tests/runtime_test.py | Python | apache-2.0 | 4,097 | 0 | """Unit test for treadmill.runtime.
"""
import errno
import socket
import unittest
import mock
import treadmill
import treadmill.rulefile
import treadmill.runtime
from treadmill import exc
class RuntimeTest(unittest.TestCase):
"""Tests for treadmill.runtime."""
@mock.patch('socket.socket.bind', mock.Mock... | = socket.error(errno.EADDRINUSE,
'In use')
with self.assertRaises(exc.ContainerSetupError):
treadmill.runtime._allocate_sockets(
'prod', '0.0.0.0', socket.SOCK_STREAM, 3
| )
@mock.patch('socket.socket', mock.Mock(autospec=True))
@mock.patch('treadmill.runtime._allocate_sockets', mock.Mock())
def test_allocate_network_ports(self):
"""Test network port allocation.
"""
# access protected module _allocate_network_ports
# pylint: disabl... |
maneeshd/Algorithms-and-Data-Structures | algorithms/QuickSort.py | Python | mit | 1,581 | 0 | """
Author: Maneesh Divana <mdaneeshd77@gmail.com>
Interpreter: Python 3.6.8
Quick Sort
Worst Case: O(n^2)
Average Case: O(nlog n)
Best Case: O(nlog n)
"""
from random import shuffle
def partition(arr: list, left: int, right: int) -> int:
"""Partitions the given array based on a pivot element,
then sorts the... | n index
p_idx = partition(arr, left, right)
# Recursively partition and sort the sub-arrays
qsort(arr, left, p_idx - 1)
qsort(arr, p_idx + 1, right)
if __name__ == "__main__":
ARR = list(range(0, 10))
shuffle(ARR)
LEFT = 0
RIGHT = len(ARR) - 1
print("\nQuickSort\n"... | rt(ARR, LEFT, RIGHT)
print("\nSorted array:", ARR, "\n")
|
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/base/shared_base_sleeve_both.py | Python | mit | 465 | 0.045161 | ## | ## NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/base/shared_base_sleeve_both.iff"
result.attribute_template... | d = 11
result.stfName("wearables_name","default_sleeves")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
cohadar/learn-python-the-hard-way | ex51.py | Python | mit | 13 | 0.076923 | # see ex50. | py | |
fasihahmad/django-rest-framework-related-views | rest_framework_related/py2_3.py | Python | gpl-3.0 | 239 | 0 | # Python 2 and 3:
try:
# Python 3 only:
| from urllib.parse import urlencode, urlsplit, parse_qs, unquote
except ImportError:
# Python 2 only:
from urlparse import pa | rse_qs, urlsplit
from urllib import urlencode, unquote
|
nikesh-mahalka/cinder | cinder/tests/unit/fake_hp_client_exceptions.py | Python | apache-2.0 | 3,077 | 0 | # (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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/LI... | ing += " (2: '%s')" % self._debug2
return formatted_string
class HTTPConflict(Exceptio | n):
http_status = 409
message = "Conflict"
def __init__(self, error=None):
if error and 'message' in error:
self._error_desc = error['message']
def get_description(self):
return self._error_desc
class HTTPNotFound(Exception):
http_status = 404
message = "Not found... |
ErwanAliasr1/syslinux | com32/cmenu/menugen.py | Python | gpl-2.0 | 10,693 | 0.033947 | #!/usr/bin/env python
import sys, re, getopt
class Menusystem:
types = {"run" : "OPT_RUN",
"inactive" : "OPT_INACTIVE",
"checkbox" : "OPT_CHECKBOX",
"radiomenu": "OPT_RADIOMENU",
"sep" : "OPT_SEP",
"invisible": "OPT_INVISIBLE",
"rad... | tem(self,name,value):
if name not in self.entry:
msg = ["Unknown attribute %s in line %d" % (name,self.lineno)]
msg.append(" | REASON: Attribute must be one of %s" % self.vattrs)
return "\n".join(msg)
if name=="type" and value not in self.types:
msg = [ "Unrecognized type %s in line %d" % (value,self.lineno)]
msg.append("REASON: Valid types are %s" % self.vtypes)
return "\n".join(msg)
if na... |
mava-ar/sgk | src/turnos/migrations/0005_auto_20160816_2140.py | Python | apache-2.0 | 415 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-17 00:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('turnos', '0004_auto_20160519_0134'),
]
operations = [
migrations.RenameField('Turno'... | sistio' | ),
migrations.RenameField('Turno', 'aviso', 'no_aviso')
]
|
mrnamingo/vix4-34-enigma2-bcm | lib/python/Screens/TimerEntry.py | Python | gpl-2.0 | 25,002 | 0.027718 | # -*- coding: utf-8 -*-
from time import localtime, mktime, time, strftime
from datetime import datetime
from enigma import eEPGCa | che
from Screens.Screen import Screen
import | ChannelSelection
from ServiceReference import ServiceReference
from Components.config import config, ConfigSelection, ConfigText, ConfigSubList, ConfigDateTime, ConfigClock, ConfigYesNo, getConfigListEntry
from Components.ActionMap import NumberActionMap, ActionMap
from Components.ConfigList import ConfigListScreen
fro... |
usc-isi/extra-specs | nova/tests/rpc/test_dispatcher.py | Python | apache-2.0 | 3,730 | 0.001072 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, 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
#
... | self.test_method_arg1 = arg1
def setUp(self):
self. | ctxt = context.RequestContext('fake_user', 'fake_project')
super(RpcDispatcherTestCase, self).setUp()
def tearDown(self):
super(RpcDispatcherTestCase, self).tearDown()
def _test_dispatch(self, version, expectations):
v2 = self.API2()
v3 = self.API3()
disp = dispatcher.R... |
lucasdavid/grapher | tests/parsers/query_test.py | Python | mit | 1,148 | 0.000871 | from unittest import TestCase
from unittest.mock import Mock
from grapher import errors
from grapher.parsers import QueryParser
from grapher.parsers import query
from nose_parameterized import parameterized
class QueryParserTest(TestCase):
def setUp(self):
r = Mock()
r.args = Mock()
r.arg... | ({},
{'query': {}, 'skip': 0, 'limit': None}),
({'skip': '2'},
{'query': {}, 'skip': 2, 'limit': None}),
({
'query': '{"test":"test 1"}',
'skip': '0',
'limit': '10'
},
{'query': {'test': 'test 1'}, 'skip': 0, 'limit': 10}),
... | test_parse(self, request_query, expected):
query.request.args.get.side_effect = lambda e: request_query[e] if e in request_query else None
actual = QueryParser.parse()
self.assertEqual(actual, expected)
def test_invalid_query(self):
query.request.args.get.return_value = 'invalid$... |
mathieugouin/tradesim | demo/demo_ystockquote.py | Python | gpl-3.0 | 998 | 0.001002 | # To make print working for Python2/3
from __future__ import print_function
import ystockquote as ysq
def _main():
for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
print("=============================================")
print("s: {}".format(s))
print("get_name: {}".for... | {}".format(ysq.get_market_cap(s)))
print("get_dividend_yield: {}".format(ysq.get_dividend_yield(s)) | )
print("get_price_earnings_ratio: {}".format(ysq.get_price_earnings_ratio(s)))
print("get_52_week_low: {}".format(ysq.get_52_week_low(s)))
print("get_52_week_high: {}".format(ysq.get_52_week_high(s)))
print("get_currency: {}".format(ysq.get_currency(s)))
if __name__ == '__main__':
... |
dbrgn/django-simplepaginator | simple_paginator/__init__.py | Python | lgpl-3.0 | 4,672 | 0.001712 | # coding=utf-8
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from urllib import urlencode
try:
from urlparse import parse_qs
except ImportError:
from cgi import parse_qs
class SimplePaginator(object):
"""A simple wrapper around the Django paginator."""
def __init__(self, request... | request -- The request object
prefix -- The prefix for the controls' css-class
data -- Elements to paginate
columns -- A tuple of tuples containing column name and key (default None)
per_page -- How many elements to display per page (default 20)
orphans -- Whether to move o... | lumns
self.per_page = per_page
self.orphans = orphans
def get_base_url(self):
'''Get query string from request, remove all necessary parts and return
two variants - one for the page suffix, one for the order suffix.
'''
# Get querystring and path, initialize variabl... |
Lucretiel/genetics | genetics/simulation/__init__.py | Python | lgpl-2.1 | 41 | 0 | from .dis | crete | import DiscreteSimulation
|
lgrahl/scripthookvpy3k | python/scripts/metadata.py | Python | mit | 857 | 0.002334 | import asyncio
import gta.utils
# The following metadata will not be processed but is recommended
# Author name and E-Mail
__author__ = 'Full Name <email@example.com>'
# Status of the script: Use one of 'Prototype', 'Development', 'Production'
__status__ = 'Development'
# The following metadata will be parsed and sh... | ment-specifiers
__dependencies__ = ('aiohttp>=0.15.3',)
@asyncio.coroutine
def main():
"""
Does absolute | ly nothing but show you how to provide metadata.
"""
logger = gta.utils.get_logger('gta.metadata')
logger.debug('Hello from the metadata example')
|
jessicalucci/TaskManagement | taskflow/task.py | Python | apache-2.0 | 9,682 | 0 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 Rackspace Hosting Inc. All Rights Reserved.
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | E(harlowja): in the case where a set is given we will not be
# able to determine the numeric ordering in a reliable way (since it is
# a unordered set) so the only way for us to easily ma | p the result of
# the task will be via the key itself.
return dict((key, key) for key in save_as)
raise TypeError('Task provides parameter '
'should be str, set or tuple/list, not %r' % save_as)
def _build_rebind_dict(args, rebind_args):
if rebind_args is None:
retu... |
flavour/eden | controllers/disease.py | Python | mit | 8,481 | 0.008843 | # -*- coding: utf-8 -*-
"""
Disease Case Tracking and Contact Tracing
"""
if not settings.has_module(c):
raise HTTP(404, body="Module disabled: %s" % c)
# -----------------------------------------------------------------------------
def index():
"Module's Home Page"
module_name = settings.modules[c]... | "summary_btn"]
return output
s3.postp = postp
return s3_rest_controller(rheader = s3db.disease_rheader)
# -----------------------------------------------------------------------------
def person():
""" Delegated person-controller for case tab """
def prep(r):
resource = r.resource
... | vtablename, record_id = get_vars["viewing"].split(".")
except ValueError:
return False
if vtablename == "disease_case":
# Get the person_id from the case
ctable = s3db[vtablename]
query = (ctable.id == record_id)
... |
jleclanche/fireplace | tests/full_game.py | Python | agpl-3.0 | 577 | 0.025997 | #!/usr/bin/env python
import sys
from fireplace import cards
from fireplace.exceptions import GameOver
from fireplace.utils import play_full_game
| sys.path.append("..")
def test_full_game():
try:
play_full_game()
except GameOver:
print("Game completed normally." | )
def main():
cards.db.initialize()
if len(sys.argv) > 1:
numgames = sys.argv[1]
if not numgames.isdigit():
sys.stderr.write("Usage: %s [NUMGAMES]\n" % (sys.argv[0]))
exit(1)
for i in range(int(numgames)):
test_full_game()
else:
test_full_game()
if __name__ == "__main__":
main()
|
IfcOpenShell/IfcOpenShell | src/blenderbim/test/bim/bootstrap.py | Python | lgpl-3.0 | 15,500 | 0.003032 | # BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on 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 Foundati... | ame_exists(name2).BIMObjectProperties.ifc_definition_id)
assert element1 != element2, f"Objects {name1} and {name2} have same elements {element1} and {element2}"
def the_file_name_should_contain_value(name, value):
with open(name, "r") as f:
assert value in f.read()
def the_object_name1_has_ | a_boolean_difference_by_name2(name1, name2):
obj = the_object_name_exists(name1)
for modifier in obj.modifiers:
if modifier.type == "BOOLEAN" and modifier.object and modifier.object.name == name2:
return True
assert False, "No boolean found"
def the_object_name1_has_no_boolean_differen... |
chrismattmann/girder | tests/cases/api_describe_test.py | Python | apache-2.0 | 4,148 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You may obtain a cop... | tatusOk(resp)
for routeDoc in resp.json['apis']:
self.assertHasKeys(('path', 'operations'), routeDoc)
self.assertTrue(len(routeDoc['operations']) > 0)
# Request an unknown resource's description to get an error
resp = self.request(path='/describe/unknown', method='GET')
... | perations are listed in the order we
# expect
resp = self.request(path='/describe/foo', method='GET')
self.assertStatusOk(resp)
listedRoutes = [(method['httpMethod'], route['path'])
for route in resp.json['apis']
for method in route['operat... |
SDSG-Invenio/invenio | invenio/legacy/bibindex/engine.py | Python | gpl-2.0 | 101,575 | 0.002648 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009,
# 2010, 2011, 2012, 2013, 2014, 2015 CERN.
#
# Invenio 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 Sof... | brec_" + bibXXx
query = """SELECT bb.field_number, b.tag, b.value FROM %s AS b, %s AS bb
WHERE bb.id_bibrec=%%s AND bb.id_bibxxx=b.id AND tag LIKE
%%s%%""" % (bibXXx, bibrec_bibXXx)
res = run_sql(query, (recID, tag[:-1]))
field_number = -1
for row in res:
if row[1] ... | == value:
field_number = row[0]
if field_number > 0:
for row in res:
if row[0] == field_number and row[1] == tag[:-1] + associated_subfield_code:
out = row[2]
break
return out
def get_author_canonical_ids_for_recid(recID):
"""
Return list... |
samuelmaudo/yepes | tests/validators/tests.py | Python | bsd-3-clause | 13,740 | 0.00102 | # -*- coding:utf-8 -*-
from __future__ import unicode_literals
from django import test
from django.core.exceptions import ValidationError
from yepes.validators import (
CharSetValidator,
ColorValidator,
FormulaValidator,
IdentifierValidator,
PhoneNumberValidator,
PostalCodeValidator,
Rest... | Valid('dadadada')
assertNotValid('aBcDeF')
assertNotValid('DADADADA')
assertNotValid('uy')
assertNotValid('a- | f')
validator = CharSetValidator('a-fA-F')
def assertValid(value):
self.assertTrue(validator.validate(value))
validator(value)
def assertNotValid(value):
self.assertFalse(validator.validate(value))
with self.assertRaises(ValidationError):
... |
radical-cybertools/radical.ensemblemd.mdkernels | setup.py | Python | mit | 5,031 | 0.015703 | #!/usr/bin/env python
"""Setup file for HT-BAC Tools.
"""
__author__ = "Ole Weidner"
__email__ = "ole.weidner@rutgers.edu"
__copyright__ = "Copyright 2014, The RADICAL Project at Rutgers"
__license__ = "MIT"
""" Setup script. Used by easy_install and pip. """
import os
import sys
import subprocess
from s... | d.mdkernel | s',
'radical.ensemblemd.mdkernels.configs'],
'package_dir' : {'': 'src'},
'package_data' : {'': ['*.sh', '*.json', 'VERSION', 'VERSION.git']},
'install_requires' : ['radical.utils', 'setuptools>=1'],
'test_suite' : 'radical.ensemblemd.mdkernels.tests',
... |
devs1991/test_edx_docmode | lms/djangoapps/ccx/api/v0/views.py | Python | agpl-3.0 | 30,649 | 0.002545 | """ API v0 views. """
import datetime
import json
import logging
import pytz
from django.contrib.auth.models import User
from django.db import transaction
from django.http import Http404
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.generics impo... | import CourseKey, UsageKey
from open | edx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.lib.api import permissions
from student.models import CourseEnrollment
from student.roles import CourseCcxCoachRole
from lms.djangoapps.ccx.models import CcxFieldOverride, CustomCourseForEdX
from lms.djangoapps.ccx.overrides i... |
CybOXProject/python-cybox | cybox/objects/win_service_object.py | Python | bsd-3-clause | 2,132 | 0.002814 | # Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.bindings.win_service_object as win_service_binding
from cybox.common import HashList
from cybox.objects.win_process_object import WinProcess
from | cybox.common import ObjectProperties, String
class ServiceDescriptionList(entities.EntityList):
_binding = win_service_binding
_binding_class = win_service_binding.ServiceDescriptionListType
_namespace = "http:// | cybox.mitre.org/objects#WinServiceObject-2"
description = fields.TypedField("Description", String, multiple=True)
class WinService(WinProcess):
_binding = win_service_binding
_binding_class = win_service_binding.WindowsServiceObjectType
_namespace = "http://cybox.mitre.org/objects#WinServiceObject-2"... |
winnerineast/Origae-6 | origae/download_data/cifar100.py | Python | gpl-3.0 | 5,218 | 0.002491 |
import cPickle
import os
import tarfile
import PIL.Image
from downloader import DataDownloader
class Cifar100Downloader(DataDownloader):
"""
See details about the CIFAR100 dataset here:
http | ://www.cs.toronto.edu/~kriz/cifar.html
"""
def urlList(self):
return [
'http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz',
]
def uncompressData(self):
filename = 'cifar-100-python.tar.gz'
filepath = os.path.join(sel | f.outdir, filename)
assert os.path.exists(filepath), 'Expected "%s" to exist' % filename
if not os.path.exists(os.path.join(self.outdir, 'cifar-100-python')):
print "Uncompressing file=%s ..." % filename
with tarfile.open(filepath) as tf:
tf.extractall(self.outdi... |
rich-pixley/zoo-animals | statlog-rollup.py | Python | apache-2.0 | 3,874 | 0.004388 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2012 Hewlett-Packard Development Company, L.P.
#
# 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/... | = ['maximum', 'minimum']
for s in this.stamps:
if s in minmax:
continue
if s in old.stamps:
total_weight = this.stamp | s[s].weight + old.stamps[s].weight
weighted_average_time = (this.stamps[s].weighted_time() + old.stamps[s].weighted_time()) / total_weight
new.stamps[s] = stamp(weighted_average_time, total_weight)
else:
new.stamps[s] = this.stamps[stamp]
for s in ol... |
DrChat/thermoctrl | thermoctrl/urls.py | Python | mit | 645 | 0.006202 | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib import auth
admin.autodiscover()
import templog.urls
import control.urls
from thermoctrl import views
urlpatterns = [
# Examples:
# url(r'^$', 'the | rmoctrl.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', views.index, name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^log/', include(templog.urls), name='log'),
url(r'^control/', include(co | ntrol.urls), name='control'),
url(r'^login/', auth.views.login, {"SSL": True, "template_name": "main/login.html"}, name='login'),
]
|
tomkralidis/geonode | geonode/monitoring/__init__.py | Python | gpl-3.0 | 3,733 | 0.000804 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# 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 ... | functools import wraps
from six import string_types
from geonode.notifications_helper import NotificationsAppConfigBase, has_notifications
from django.db.models.signals import post_migrate
log = logging.getLogger(__name__)
def run_setup_hooks(*args, **kwargs):
if not has_notifications:
| log.warning("Monitoring requires notifications app to be enabled. "
"Otherwise, no notifications will be send")
from geonode.monitoring.models import populate
populate()
class MonitoringAppConfig(NotificationsAppConfigBase):
name = 'geonode.monitoring'
NOTIFICATION_NAME = 'monitori... |
SylvainCecchetto/plugin.video.catchuptvandmore | plugin.video.catchuptvandmore/resources/lib/channels/fr/francetv.py | Python | gpl-2.0 | 14,146 | 0.001344 | # -*- coding: utf-8 -*-
"""
Catch-up TV & More
Original work (C) JUL1EN094, SPM, SylvainCecchetto
Copyright (C) 2016 SylvainCecchetto
This file is part of Catch-up TV & More.
Catch-up TV & More is free software; you can redistribute it and/or modify
it under the terms of the GNU General Publi... | args):
# Channels
item = Listitem()
item.label = Script.localize(30006)
item.set_callback(channels)
item_post_treatment(item)
yield item
# Categories
item = Listitem()
item.label = Script.localize(30725)
item.set_callback(categories)
item_post_treatment(item)
yield item
... | ture
item = Listitem.search(search)
item_post_treatment(item)
yield item
@Route.register
def channels(plugin, **kwargs):
"""
List all france.tv channels
"""
# (item_id, label, thumb, fanart)
channels = [
('channels/france-2', 'France 2', 'france2.png', 'france2_fanart.jpg'),
... |
johncheetham/jcchess | chess/pgn.py | Python | gpl-3.0 | 32,586 | 0.00043 | # -*- coding: utf-8 -*-
#
# This file is part of the python-chess library.
# Copyright (C) 2012-2016 Niklas Fiekas <niklas.fiekas@backscattering.de>
#
# 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 Foundat... | f.variations[i] = self.variations[i], self.variations[i + 1]
def remove_variation(self, move):
"""Removes a variation by move."""
self.variations.remove(self.variation(move))
def add_variation(self, move, comment="", | starting_comment="", nags=()):
"""Creates a child node with the given attributes."""
node = GameNode()
node.move = move
node.nags = set(nags)
node.parent = self
node.comment = comment
node.starting_comment = starting_comment
self.variations.append(node)
... |
EmreAtes/spack | var/spack/repos/builtin/packages/astyle/package.py | Python | lgpl-2.1 | 2,548 | 0.000392 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Liv | ermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can red... | # published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Pu... |
kinow-io/kinow-python-sdk | test/test_subtitle_file.py | Python | apache-2.0 | 747 | 0.001339 | # coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 2.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absol | ute_import
import os
import sys
import unittest
import kinow_client
from | kinow_client.rest import ApiException
from kinow_client.models.subtitle_file import SubtitleFile
class TestSubtitleFile(unittest.TestCase):
""" SubtitleFile unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testSubtitleFile(self):
"""
Test Subtit... |
MichaelCurrin/twitterverse | app/lib/trends.py | Python | mit | 3,038 | 0 | """
Trends library module.
"""
import datetime
from lib import database as db
from lib.twitter_api import authentication
# Global object to be used as api connection. During execution of the insert
# function, this can be setup once with default app then reused later,
# to avoid time calling Twitter API. It can be l... | stance(
woeid, int
| ), f"Expected WOEID as type `int` but got type `{type(woeid).__name__}`."
if userApi:
# Use user token.
api = userApi
else:
# Use app token.
if not appApi:
# Set it if necessary and then reuse it next time.
appApi = authentication.getAPIConnection()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.