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 |
|---|---|---|---|---|---|---|---|---|
dianafprieto/SS_2017 | scripts/07_NB_StreamTubes.py | Python | mit | 4,407 | 0.00295 | import vtk
reader = vtk.vtkRectilinearGridReader()
reader.SetFileName("D:/Notebooks_Bogota2017/SS_2017/data/jet4_0.500.vtk")
reader.Update()
output = reader.GetOutput()
xmi, xma, ymi, yma, zmi, zma = output.GetBounds()
# Color Transfer Function and LookUpTable
# Create transfer mapping scalar value to color
colorTra... | )
# A | dd the outline of the data set
gOutline = vtk.vtkRectilinearGridOutlineFilter()
gOutline.SetInputData(output)
gOutlineMapper = vtk.vtkPolyDataMapper()
gOutlineMapper.SetInputConnection(gOutline.GetOutputPort())
gOutlineActor = vtk.vtkActor()
gOutlineActor.SetMapper(gOutlineMapper)
gOutlineActor.GetProperty().SetColor(0... |
GirlsCodePy/girlscode-coursebuilder | modules/review/review_tests.py | Python | gpl-3.0 | 68,643 | 0.000131 | # coding: utf-8
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... | , step.state)
self.assertFalse(step.removed)
self.assertEqual(1, summary.assigned_count)
def test_add_reviewer_removed_unremoves_completed_step(self):
summary_key = peer.ReviewSummary(
reviewee_key=self.reviewee_key, reviewer_key=self.reviewer_key,
submission_key=se... | ).put()
step_key = peer.ReviewStep(
assigner_kind=domain.ASSIGNER_KIND_AUTO, removed=True,
|
chunweiyuan/xarray | xarray/backends/rasterio_.py | Python | apache-2.0 | 12,619 | 0 | import os
import warnings
from collections import OrderedDict
from distutils.version import LooseVersion
import numpy as np
from .. import DataArray
from ..core import indexing
from ..core.utils import is_scalar
from .common import BackendArray
from .file_manager import CachingFileManager
from .locks import Serializa... | sterio array.
Parameter
---------
key: tuple of int |
Returns
-------
band_key: an indexer for the 1st dimension
window: two tuples. Each consists of (start, stop).
squeeze_axis: axes to be squeezed
np_ind: indexer for loaded numpy array
See also
--------
indexing.decompose_indexer
"""
... |
GENI-NSF/gram | src/vmoc/register_controller.py | Python | mit | 2,320 | 0.003879 | #!/usr/bin/python
#----------------------------------------------------------------------
# Copyright (c) 2013-2016 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without rest... | an controller ....] [unregister]
if len(sys.argv) < 2:
print "Usage: register_controller.py slice [vlan controller ...] [unregister]"
sys.exit()
print sys.argv[1]
print sys.argv[2]
slice_id = sys.argv[1]
vlan_controllers = json.loads(sys.argv[2 | ])
vlan_configs = []
for i in range(len(vlan_controllers)):
if i == 2*(i/2):
vlan_tag = vlan_controllers[i]
controller_url = vlan_controllers[i+1]
vlan_config = \
VMOCVLANConfiguration(vlan_tag=vlan_tag, \
controller_url=controller_url)
... |
michaelmontano/snowflakepy | src/snowflakeserver.py | Python | bsd-3-clause | 1,494 | 0.014726 | import sys
sys.path = ['..'] + sys.path
import zope
from twisted.internet import reactor
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.transport import TTwisted
from thrift.protocol import TBinaryProtocol
from lib.genpy.snowflake import Snowflake
from lib.genpy.snowflake.tt... | r_id(self):
return self.worker.get_datacenter_id()
d | ef get_timestamp(self):
return self.worker.get_timestamp()
def get_id(self):
return self.worker.get_id()
def print_usage():
print 'python snowflakeserver.py <port> <worker_id> <datacenter_id>'
print 'e.g. python snowflakeserver.py 1111 1 1'
def main():
if len(sys.argv) != 4:
... |
goodcrypto/goodcrypto-libs | reinhardt/templatetags/data_img.py | Python | gpl-3.0 | 828 | 0.014493 | '''
Convert an image file to a data uri.
Copyright 2012 GoodCrypto
Last modified: 2013-11-13
This file is open source, licensed under GPLv3 <http://www.gnu.org/licenses/>.
'''
import os.path
from django import template
import reinhardt.data_image
register = template.Library()
@reg... | lename is relative to settings.STATIC_URL/settings.STATIC_ROOT.
If the datauri is too large or anything goes wrong,
retur | ns the url to the filename.
Example:
<img alt="embedded image" src="{{ 'images/myimage.png'|data_img:browser }}">
'''
return reinhardt.data_image.data_image(filename, browser=browser)
|
endlessm/chromium-browser | third_party/catapult/common/py_vulcanize/py_vulcanize/resource_loader.py | Python | bsd-3-clause | 7,961 | 0.006657 | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""ResourceFinder is a helper class for finding resources given their name."""
import codecs
import os
from py_vulcanize import module
from py_vulcaniz... | to file resources.
"""
def __init__(self, project):
self.project = project
self.stripped_js_by_filename = {}
self.loaded_modules = {}
self.loaded_raw_scripts = {}
self.loaded_style_sheets = {}
self.loaded_images = {}
@property
def source_paths(self):
"""A list of base directories ... | return self.project.source_paths
def FindResource(self, some_path, binary=False):
"""Finds a Resource for the given path.
Args:
some_path: A relative or absolute path to a file.
Returns:
A Resource or None.
"""
if os.path.isabs(some_path):
return self.FindResourceGivenAbsolut... |
google-research/google-research | tf3d/utils/voxel_utils.py | Python | apache-2.0 | 21,191 | 0.004672 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | pped_start_coordinates,
size=(clipped_end_coordinates -
clipped_start_coordinates))
top_and_left_padding = tf.m | aximum(0, -start_coordinates)
bottom_and_right_padding = tf.maximum(0, end_coordinates - voxels.shape)
padding = tf.stack([top_and_left_padding, bottom_and_right_padding], axis=1)
return tf.pad(cropped_voxels, padding)
def pointcloud_to_voxel_grid(points,
features,
... |
kho/mr-cdec | python/pkg/cdec/sa/compile.py | Python | apache-2.0 | 5,575 | 0.003587 | #!/usr/bin/env python
import argparse
import os
import logging
import cdec.configobj
import cdec.sa
from cdec.sa._sa import monitor_cpu
import sys
MAX_PHRASE_LENGTH = 4
def precompute(f_sa, max_len, max_nt, max_size, min_gap, rank1, rank2, tight_phrases):
lcp = cdec.sa.LCP(f_sa)
stats = sorted(lcp.compute_stat... | nitor_cpu()
logger.info('Compiling target data array')
if args.bitext:
e = cdec.sa.DataArray(from_text=args.bitext, side='target')
else:
e = cdec.sa.DataArray(from_text=args.target)
e.write_binary(e_bin)
stop_time = monitor_cp | u()
logger.info('Compiling target data array took %f seconds', stop_time - start_time)
start_time = monitor_cpu()
logger.info('Precomputing frequent phrases')
precompute(f_sa, *params).write_binary(precomp_bin)
stop_time = monitor_cpu()
logger.info('Compiling precomputations took %f seconds', s... |
zenodo/invenio | invenio/base/views.py | Python | gpl-2.0 | 947 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014 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 Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT AN... | ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Define base Bl... |
veltri/DLV2 | tests/parser/bkunstrat3.bk.test.py | Python | apache-2.0 | 69 | 0 | input = """
x | -x.
y | | -y.
"""
output = """
x | -x.
y | -y.
" | ""
|
detly/webcavate | webcavate/app.py | Python | gpl-3.0 | 3,132 | 0.000958 | """
Copyright 2014 Jason Heeris, jason.heeris@gmail.com
This file is part of the dungeon excavator web interface ("webcavate").
Webcavate is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the L... | from dungeon.excavate import render_room
HELP_TEXT = """\
Web interface to the dungeon excavator."""
app = Flask('d | ungeon.web')
app.secret_key = str(uuid.uuid4())
@app.route("/")
def root():
""" Web interface landing page. """
return render_template('index.html')
@app.route("/error")
def error():
""" Display errors. """
return render_template('error.html')
def make_map(request, format):
tile_size = int(requ... |
galaxy-iuc/parsec | parsec/commands/libraries/create_library.py | Python | apache-2.0 | 859 | 0.001164 | import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, json_output
@click.command('create_library')
@click.argument("name", type=str)
@click.option(
"--description",
help="Optional dat | a library description",
type=str
)
@click.option(
"--synopsis",
help="Optional data library synopsis",
type=str
)
@pass_context
@custom_exception
@json_output
def cli(ctx, name, description="", synopsis=""):
"""Create a data library with the properties defined in the arguments.
Output:
Details... | om bioblend',
'url': '/api/libraries/f740ab636b360a70'}
"""
return ctx.gi.libraries.create_library(name, description=description, synopsis=synopsis)
|
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/lib/galaxy/tools/parameters/dataset_matcher.py | Python | gpl-3.0 | 6,314 | 0.01758 | import galaxy.model
from logging import getLogger
log = getLogger( __name__ )
ROLES_UNSET = object()
INVALID_STATES = [ galaxy.model.Dataset.states.ERROR, galaxy.model.Dataset.states.DISCARDED ]
class DatasetMatcher( object ):
""" Utility class to aid DataToolParameter and similar classes in reasoning
about... | not dataset.state in INVALID_STATES
return state_valid and ( not check_security or self.__can_access_dataset( dataset ) )
def valid_hda_match( self, hda, check_implicit_conversions=True, check_security=False ):
""" Return False of this parameter can not be matched to | a the supplied
HDA, otherwise return a description of the match (either a
HdaDirectMatch describing a direct match or a HdaImplicitMatch
describing an implicit conversion.)
"""
if self.filter( hda ):
return False
formats = self.param.formats
if hda.dat... |
lechat/jenkinsflow | test/prefix_test.py | Python | bsd-3-clause | 1,965 | 0.005598 | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from jenkinsflow.flow import serial
from .framework import api_select
prefixed_jobs = """
serial flow: [
job: 'top_quick1'
serial flow: [
job: 'top_x_quick2-1'
]
... | voke('quick3')
with ctrl1.parallel(timeout=40, report_interval=3, job_name_prefix='y_') as ctrl2:
with ctrl2.serial(timeout=40, report_interval=3, job_name_prefix='z_') as ctrl3a:
ctrl3a.invoke('quick4a')
# Reset prefix
with ctrl2.seri... | = capsys.readouterr()
assert prefixed_jobs.strip() in sout
|
jolyonb/edx-platform | common/test/acceptance/fixtures/course.py | Python | agpl-3.0 | 15,531 | 0.002447 | """
Fixture to create a course and course components (XBlocks).
"""
import datetime
import json
import mimetypes
from collections import namedtuple
from textwrap import dedent
from opaque_keys.edx.keys import CourseKey
from path import Path
from common.test.acceptance.fixtures import STUDIO_BASE_URL
from common.test... | lf, category, display_name, data=None,
metadata=None, grader_type=None, publish='make_public', **kwargs):
"""
Configure the XBlock to be created by the fixture.
These arguments have the same meaning as in the Studio REST API:
* `category`
* `display_name`... | category
self.display_name = display_name
self.data = data
self.metadata = metadata
self.grader_type = grader_type
self.publish = publish
self.children = []
self.locator = None
self.fields = kwargs
def add_children(self, *args):
"""
Ad... |
prudnikov/python-oauth2 | oauth2/_version.py | Python | mit | 438 | 0.004566 | # This is the vers | ion of this source code.
manual_verstr = "1.5"
auto_build_num = "212"
verstr = manual_verstr + "." + auto_build_num
try:
from pyutil.version_class import Version as pyutil_Version
__version__ = pyutil_Version(verstr)
except (ImportError, ValueError):
# Maybe there is no pyutil installed.
from dis... | _ = distutils_Version(verstr)
|
joadavis/rpi-coding | minecraft/oliverboom.py | Python | mit | 907 | 0.016538 | import mcpi.minecraft as minecraft
import mcpi.block as block
import random
import time
mc = minecraft.Minecraft.create()
#mc.postToChat("Heat Vision!")
pos = mc.player.getTilePos()
#mc.postToChat(pos)
#rot = mc.player.getRotation()
#pitch = mc.player.getPitch()
#direct = mc.player.getDirection()
#mc.postToChat(ro... | for zi in range (-4, 4):
for yi in range (-1, 3):
| thisblock = mc.getBlock(x + xi, y + yi, z + zi)
#print thisblock
if thisblock == 46:
mc.setBlock(x + xi, y + yi, z+zi, 46, 1)
print "setting on"
#mc.setBlock(x + xi, y + 1, z+zi, 46, 1)
time.sleep(1)
|
jroeland/teapot | project/web/app/products/urls.py | Python | mit | 489 | 0.010225 | '''
Created on Oct 19, 2016
@author: jaime
'''
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt
from products import views
url | patterns = [
url(r'^categories/$', csrf_exempt(views.ProductCategoryView.as_view())),
url(r'^categories/(?P<uid>\w+)/$ | ', csrf_exempt(views.ProductCategoryView.as_view())),
url(r'^$', csrf_exempt(views.ProductView.as_view())),
url(r'^(?P<uid>\w+)/$', csrf_exempt(views.ProductView.as_view())),
] |
yac/rdoupdate | rdoupdate/shell.py | Python | apache-2.0 | 5,901 | 0 | # -*- encoding: utf-8 -*-
import argparse
import os
import sys
import yaml
from . import VERSION
import actions
import core
import exception
from utils import log
def error(errtype, msg, code=42):
sys.stderr.write("{t.red}[ERROR] {t.yellow}{er}: {msg}"
"{t.normal}\n".format(er=errtype, msg=... | e file(s) to move')
move_parser.add_argument(
'-d', '--dir', type=str, metavar='DIR',
help="move update file(s) to this directory instead of using "
"update.group")
move_parse | r.set_defaults(action=do_move)
list_parser = subparsers.add_parser(
'list-bsources', help="show available build sources",
description="show available build sources")
list_parser.set_defaults(action=do_list_bsources)
return parser
def _get_update_files(args):
if args.files and args.git... |
google/material-design-icons | update/venv/lib/python3.9/site-packages/fontTools/ttLib/tables/S__i_l_f.py | Python | apache-2.0 | 33,326 | 0.003691 | from fontTools.misc.py23 import byteord
from fontTools.misc import sstruct
from fontTools.misc.fixedTools import floatToFixedToStr
from fontTools.misc.textTools import safeEval
# from itertools import *
from . import DefaultTable
from . import grUtils
from array import array
from functools import reduce
import struct, ... | METRIC", "Bbb"),
("PUSH_I | SLOT_ATTR", "Bbb"),
("PUSH_IGLYPH_ATTR", "Bbb"),
("POP_RET", 0), # x30
("RET_ZERO", 0),
("RET_TRUE", 0),
("IATTR_SET", "BB"),
("IATTR_ADD", "BB"),
("IATTR_SUB", "BB"),
("PUSH_PROC_STATE", "B"),
("PUSH_VERSION", 0),
("PUT_SUBS", ">bHH"),
("PUT_SUBS2", 0),
("PUT_SUBS3",... |
libvirt/libvirt-test-API | libvirttestapi/repos/checkpoint/checkpoint_get_xml.py | Python | gpl-2.0 | 2,134 | 0.000937 | # Copyright (C) 2010-2012 Red Hat, Inc.
# This work is licensed under the GNU GPLv2 or later.
import libvirt
import re
from libvirt import libvirtError
from libvirttestapi.utils import utils
required_params = {'guestname', 'checkpoint_name'}
optional_params = {'flags': None}
def checkpoint_get_xml(params):
logg... | d = open(checkpoint_xml_path, 'r')
checkpoint_xml = cp_fd.read()
checkpoint_xml = re.sub(r'<!--\n.*\n-->\n\n', '', checkpoint_xml, flags=re.S)
if flag == libvirt.VIR_DOMAIN_CHECKPOINT_XML_NO_DOMAIN:
cp_xml = cp_xml.replace('</domaincheckpoint>\n', '')
if cp_xml in checkpoint_xml:
... | essful.")
else:
logger.error("FAIL: check checkpoint xml failed.")
return 1
elif flag == libvirt.VIR_DOMAIN_CHECKPOINT_XML_SIZE:
logger.info("Don't support this flag.")
elif flag == libvirt.VIR_DOMAIN_CHECKPOINT_XML_SECURE or flag == 0:
if cp_xml == checkpoint_xml... |
zamonia500/PythonTeacherMythenmetz | 과외숙제/factorial.py | Python | gpl-3.0 | 86 | 0 | def fac | torial(c | ount):
return count * factorial(count - 1)
answer = factorial(6)
|
iotile/coretools | iotilesensorgraph/test/test_devicemodel.py | Python | gpl-3.0 | 693 | 0 | import pytest
from iotile.core.exceptions import ArgumentError
from iotile.sg.model import DeviceModel
def test_default_values():
"""Make sure we can get properties with default values."""
model = DeviceModel()
assert model.get('max_nodes') == 32
assert model.get(u'max_nodes') == 32
| model.set('max_nodes', 16)
assert model.get('max_nodes') == 16
assert model.get(u'max_nodes') == 16
model.set(u'max_nodes', 17)
assert model.get('max_nodes') == 17
assert model.get(u'max_nodes') == 17
with pytest.raises(ArgumentError):
model.get('unknown_parameter')
with | pytest.raises(ArgumentError):
model.set('unknown_parameter', 15)
|
zerog2k/stc_diyclock | post_extra_script.py | Python | mit | 392 | 0.015306 | ''' custom script for platformio '''
from os.path import join
from SCons.Script import DefaultEnvironment
env = DefaultEnvironment()
#print "post_extra_script running..."
#print env.Dump()
# compiler and linker flags dont work very well in build_flags of platformio.ini | - need to set them here
env.Append(
| LINKFLAGS = [
"--data-loc", 0x30
],
STCGALCMD="/stcgal.py"
)
|
JensTimmerman/radical.pilot | docs/architecture/api_draft/unit_manager.py | Python | mit | 3,311 | 0.017215 |
from a | ttributes import *
from constants import *
# ------------------------------------------------------------------------- | -----
#
class UnitManager (Attributes) :
"""
UnitManager class -- manages a pool
"""
# --------------------------------------------------------------------------
#
def __init__ (self, url=None, scheduler='default', session=None) :
Attributes.__init__ (self)
# -----------------... |
mixmastamyk/flask-skeleton | src/timezones.py | Python | unlicense | 371 | 0.002703 | import pytz
priorities = ('US/Pacific', 'US/Mountain', 'US/Central', 'US/Eastern',
'Brazil/East', 'UTC')
all_tz = pytz.all_timezones_set.copy()
for priori | ty in priorities:
all_tz.remove(priority)
all_tz = sorted(list(all_tz))
all_tz[:0] = priorities # prepends list to list
# tuples for selection widget
all_tz = tuple((tz, tz) for | tz in all_tz)
|
eduNEXT/edx-platform | openedx/core/djangoapps/oauth_dispatch/tests/factories.py | Python | agpl-3.0 | 1,383 | 0 | # pylint: disable=missing-docstring
from datetime import datetime, timedelta
import factory
import pytz
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyText
from oauth2_provider.models import AccessToken, Application, RefreshToken
from openedx.core.djangoapps.oauth_dispatch.models impor | t ApplicationAccess
from common.djangoapps.student.tests.factories import UserFactory
class ApplicationFactory(DjangoModelFactory):
class Meta:
model = Application
user = factory.SubFactory(UserFactory)
client_id = factory.Sequence('client_{}'.format)
client_secret = 'some_secret'
c | lient_type = 'confidential'
authorization_grant_type = Application.CLIENT_CONFIDENTIAL
name = FuzzyText(prefix='name', length=8)
class ApplicationAccessFactory(DjangoModelFactory):
class Meta:
model = ApplicationAccess
application = factory.SubFactory(ApplicationFactory)
scopes = ['grades... |
yelizariev/addons-yelizariev | delivery_sequence/__manifest__.py | Python | lgpl-3.0 | 295 | 0 | {
"name": "Delivery Sequence",
"vesion": "12.0.1.0.0",
"author": "IT-Proje | cts LLC, Ivan Yelizarie | v",
"license": "LGPL-3",
"category": "Custom",
"website": "https://yelizariev.github.io",
"depends": ["delivery"],
"data": ["views.xml"],
"installable": False,
}
|
theoj2/Nibbletex | nibblegen/nibblegen.py | Python | gpl-3.0 | 19,283 | 0.02733 | '''
Nibblegen: A script to convert LaTex text to html usable in Nibbleblog Forked from the latex2wp project (the licenceing for which is below).
Copyright (C) 2014 Theodore Jones
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publis... | "
changes $$ ... $$ into \[ ... \] and reformats
eqnarray* environments as regular array environments
"""
doubledollar = re.compile("\\$\\$")
L=doubledollar.split(m)
m=L[0]
for i in range(1,(len(L)+1)/2) :
m = m+ "\\[" + L[2*i-1] + "\\]" + L[2*i]
m=m.replace("\\begin{e | qnarray*}","\\[ \\begin{array}{rcl} ")
m=m.replace("\\end{eqnarray*}","\\end{array} \\]")
return m
def convertsqb(m) :
r = re.compile("\\\\item\\s*\\[.*?\\]")
Litems = r.findall(m)
Lrest = r.split(m)
m = Lrest[0]
for i in range(0,len(Litems)) :
s= Litems[i]
s=s.replace("\\it... |
vuolter/pyload | src/pyload/plugins/downloaders/VeehdCom.py | Python | agpl-3.0 | 2,189 | 0.000914 | # -*- coding: utf-8 -*-
import re
from ..base.downloader import BaseDownloader
class VeehdCom(BaseDownloader):
__name__ = "VeehdCom"
__type__ = "downloader"
__version__ = "0.29"
| __status__ = "testing"
__pattern__ = r"http://veehd\.com/video/\d+_\S+"
__config__ = [
("enabled", "bool", "Activated", True),
("filename_spaces", "bool", "Allow spaces in filename", False),
("replacement_char", "str", "Filename replacement character", "_"),
| ]
__description__ = """Veehd.com downloader plugin"""
__license__ = "GPLv3"
__authors__ = [("cat", "cat@pyload")]
def setup(self):
self.multi_dl = True
self.req.can_continue = True
def process(self, pyfile):
self.download_html()
if not self.file_exists():
... |
SmartElect/SmartElect | bulk_sms/tasks.py | Python | apache-2.0 | 7,112 | 0.001547 | import csv
import datetime
import logging
import os
from celery.task import task
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.timezone import now
from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \
REMINDER_LAST_REPORT, REMINDER_CLOSE
fr... | expected report yet.
"""
logger.debug("Start message_reminder_ | task")
if audience not in ('whitelist', 'registered'):
raise ValueError("Unknown audience type %s - expected whitelist or registered" % audience)
# Batches need to be owned by somebody - pick a non-random superuser
user = get_user_model().objects.filter(is_active=True, is_superuser=True)[0]
b... |
mefly2012/platform | src/parse/qyxx_ck.py | Python | apache-2.0 | 1,153 | 0.00272 | # -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from common import public
import time
import re
|
class qyxx_ck():
"""采矿许可证"""
need_check_ziduan = ['valid_from',
'v | alidto'
]
def check_valid_from(self, indexstr, ustr):
"""有效期限自"""
ret = None
validdate = indexstr['validdate'].strip()
if validdate and len(validdate):
err, time = public.get_date(validdate, 0)
if err:
ret = err
... |
laurentb/assnet | assnet/filters.py | Python | agpl-3.0 | 2,171 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2011 Romain Bignon, Laurent Bachelier
#
# This file is part of assnet.
#
# assnet 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.
#
# assnet is distributed in the hope that it will be us | eful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with assnet. If not, see <http://www.gnu.org/li... |
sims1253/coala-bears | bears/python/RadonBear.py | Python | agpl-3.0 | 1,902 | 0.003155 | import radon.complexity
import radon.visitors
from coalib.bears.LocalBear import LocalBear
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
from coalib.results.SourceRange import SourceRange
from coalib.settings.Setting import typed_list
class RadonBear(LocalBear):
... | yield Result(self, me | ssage, severity=severity,
affected_code=(visitor_range,))
|
jscott1989/happening | src/plugins/__init__.py | Python | mit | 43 | 0 | """P | lace all plugins in | this directory."""
|
amatkivskiy/baidu | baidu/utils/msbuilder.py | Python | apache-2.0 | 1,654 | 0.002418 | import os
import datetime
from utils.util import run_command
__author__ = 'maa'
class MsBuilder:
def __init__(self, msbuild):
if msbuild == None:
self.msbuild = r"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe"
else:
self.msbuild = msbuild
def build_with... | = datetime.datetime.now()
print('STAR | TED BUILD - ' + start.strftime('%Y-%m-%d %H:%M:%S'))
params = [self.msbuild, csprojPath] + list(args)
return run_command(params)
def get_files_from_project_bin_folder(self, csproj, configuration, do_return_full_paths=False):
name = os.path.dirname(os.path.realpath(csproj))
bin_con... |
nicolashainaux/mathmaker | tests/01_core_objects/test_110_polygons.py | Python | gpl-3.0 | 4,579 | 0.003494 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | .7\n'\
' "A" A 227.3 deg, font("sffamily")\n'\
' "G" G 318.7 deg, font("sffamily")\n'\
| ' "O" O 54.3 deg, font("sffamily")\n'\
' "Y" Y 142.7 deg, font("sffamily")\n'\
'end\n\n'\
'label\n'\
' G, A, Y simple\n'\
' O, G, A simple\n'\
' Y, O, G simple\n'\
' A, Y, O simple\n'\
'end\n'
|
spiricn/libIDL | idl/Enum.py | Python | mit | 3,126 | 0.011836 | from idl.Annotatable import Annotatable
from idl.IDLSyntaxError import IDLSyntaxError
from idl.Type import Type
class EnumField(Annotatable):
'''
Object that represents a single enumeration field.
'''
def __init__(self, enum, name, value):
Annotatable.__init__(self)
self.... | :
'''
Enumeration type this field is associated with.
'''
return self._enum
@property
def name(self):
'''
Field name.
'''
return self._name
@property
def value(self):
'''
Integer field value.
... | :
def __init__(self, module, desc):
Type.__init__(self, module, Type.ENUM, desc.name)
self._desc = desc
self._fields = []
for field in self._desc.fields:
if field.value:
# Evaluate value
value = eval(field.va... |
SolusOS-discontinued/pisi | pisi/signalhandler.py | Python | gpl-2.0 | 1,553 | 0.001932 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006, TUBITAK/UEKAE
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later v | ersion.
#
# Please read the COPYING file.
#
import signal
exception = {
signal.SIGINT:KeyboardInterrupt
}
class Signal:
def __init__(self, sig):
self.signal = sig
self.oldhandler = signal.get | signal(sig)
self.pending = False
class SignalHandler:
def __init__(self):
self.signals = {}
def signal_handler(self, sig, frame):
signal.signal(sig, signal.SIG_IGN)
self.signals[sig].pending = True
def disable_signal(self, sig):
if sig not in self.signals.keys():
... |
kyleabeauchamp/mdtraj | mdtraj/formats/netcdf.py | Python | lgpl-2.1 | 21,654 | 0.002448 | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
#
# Authors: Robert McGibbon
# Contributors:
#
# MDTraj is free software: y... | ER NetCDF files. This is a
file-like object, t | hat supports both reading or writing depending
on the `mode` flag. It implements the context manager protocol,
so you can also use it with the python 'with' statement.
Parameters
----------
filename : str
The name of the file to open
mode : {'r', 'w'}, default='r'
The mode in wh... |
google-research/uda | image/randaugment/augmentation_transforms.py | Python | apache-2.0 | 14,832 | 0.007821 | # coding=utf-8
# Copyright 2019 The Google UDA Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | mg[amount:img.shape[0] + amount, amount:
img.shape[1] + amount, :] = img
top = np.random.randint(low=0, high=2 * amount)
left = np.random.randint(low=0, high=2 * amount)
new_img = padded_img[top:top + img.shape[0], left:left + img.shape[1], | :]
return new_img
def create_cutout_mask(img_height, img_width, num_channels, size):
"""Creates a zero mask used for cutout of shape `img_height` x `img_width`.
Args:
img_height: Height of image cutout mask will be applied to.
img_width: Width of image cutout mask will be applied to.
num_channels:... |
sysadminmatmoz/ingadhoc | project_description/__openerp__.py | Python | agpl-3.0 | 1,639 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | ven the implied warr | anty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public 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/>.
#
###############################... |
zhushuchen/Ocean | 组件/zookeeper-3.3.6/src/contrib/zkpython/src/test/delete_test.py | Python | agpl-3.0 | 2,872 | 0.006964 | #!/usr/bin/python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Lic... | etetest", "node | contents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
self.assertEqual(ret, "/zk-python-adeletetest")
self.cv = threading.Condition()
self.callback_flag = False
self.rc = -1
def callback(handle, rc):
self.cv.acquire()
self.callback_flag = True
... |
OrangeTux/MafBot | mafbot/__init__.py | Python | gpl-3.0 | 106 | 0 | from selenium im | port webdriver
import logging
logger = logging.getLogger()
driver | = webdriver.Firefox()
|
youtube/cobalt | third_party/skia/infra/bots/recipe_modules/checkout/api.py | Python | bsd-3-clause | 5,928 | 0.006748 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=W0201
from recipe_engine import recipe_api
from recipe_engine import config_types
class CheckoutApi(recipe_api.RecipeApi):
@propert... | ully build.
if checkout_flutter and main_name == 'engine':
main_name = 'src/flutter'
main = gclient_cfg.solutions.add()
main.name = main_name
main.managed = False
main.url = main_repo
main.revision = self.m.properties.get('revision') or 'origin/master'
m = gclient_cfg.got_revi | sion_mapping
m[main_name] = 'got_revision'
patch_root = main_name
patch_repo = main.url
if self.m.properties.get('patch_repo'):
patch_repo = self.m.properties['patch_repo']
patch_root = patch_repo.split('/')[-1]
if patch_root.endswith('.git'):
patch_root = patch_root[:-4]
... |
htwenhe/DJOA | env/Lib/site-packages/tablib/formats/_df.py | Python | mit | 1,040 | 0.000962 | """ Tablib - DataFrame Support.
"""
import sys
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
try:
from pandas import DataFrame
except ImportError:
DataFrame = None
import tablib
from tablib.compat import unicode
title = 'df'
extensions = ('df'... | return False
def export_set(dset, index=None): |
"""Returns DataFrame representation of DataBook."""
if DataFrame is None:
raise NotImplementedError(
'DataFrame Format requires `pandas` to be installed.'
' Try `pip install tablib[pandas]`.')
dataframe = DataFrame(dset.dict, columns=dset.headers)
return dataframe
def ... |
RoboWoodhouse/RoboButler | python/scanlibrary.py | Python | mit | 2,231 | 0.037203 | import os
from lxml import etree
class device:
def __init__(self,ipadress,name):
self.ipadress=str(ipadress)
self.name=str(name)
self.status="off"
def turn_on(self):
self.status="on"
def turn_off(self):
self.status="off"
def getstatus(devices):
ips=[]
for ins... | th open("./log/scanlog.txt","a") as log:
log.write(str(localtime[3])+':'+str(localtime[4])+'on the'+str(localti | me[2])+'.'+str(localtime[1])+'.'+str(localtime[0])[-2:])
log.write("Scanned Wifi for my Devices")
|
fusionbox/django-darkknight | setup.py | Python | bsd-2-clause | 1,503 | 0.002661 | #!/usr/bin/env python
import os
from setuptools import setup
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as f:
return f.read()
setup(name='django-darkknight',
version='0.9.0',
li | cense="BSD",
description="He's a silent guardian, a watchful protector",
long_description=read('README.rst'),
author="Fusionbox, Inc",
author_email="programmers@fusionbox.com",
url='http://github.com/fusionbox/django-darkknight',
packages=['darkknight', 'darkknight_gpg'],
in... | =[
'django-dotenv',
'Django>=1.5',
'pyOpenSSL',
'django-localflavor',
'django-countries',
],
extras_require = {
'gpg': ['gnupg>=2.0.2,<3', 'django-apptemplates'],
},
classifiers=[
"Development Status :: 4 - Beta",
"... |
yacoma/auth-boilerplate | server/permissions.py | Python | mit | 959 | 0 | from .app import App
from .model import User, Group, ResetNonce
class ViewPermission:
pass
class EditPermission:
pass
@App.permission_rule(model=object, | permission=object)
def admin_has_global_permission(identi | ty, model, permission):
user = User.get(email=identity.userid)
return Group.get(name="Admin") in user.groups
@App.permission_rule(model=User, permission=object)
def user_has_self_permission(identity, model, permission):
user = User.get(email=identity.userid)
if user is not None and Group.get(name="Adm... |
dalejung/trtools | trtools/io/common.py | Python | mit | 109 | 0.009174 |
def _filename(obj):
| try:
return obj.__filename__()
except:
| pass
return str(obj)
|
Southpaw-TACTIC/Team | src/python/Lib/site-packages/win32com/client/dynamic.py | Python | epl-1.0 | 21,580 | 0.031279 | """Support for dynamic COM client support.
Introduction
Dynamic COM client support is the ability to use a COM server without
prior knowledge of the server. This can be used to talk to almost all
COM servers, including much of MS Office.
In general, you should not use this module directly - see below.
... | h with no type info"
IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx)
if createClass is None:
createClass = CDispatch
return createClass(IDispatch, buil | d.DispatchItem(), userName,UnicodeToString)
class CDispatch:
def __init__(self, IDispatch, olerepr, userName = None, UnicodeToString=NeedUnicodeConversions, lazydata = None):
if userName is None: userName = "<unknown>"
self.__dict__['_oleobj_'] = IDispatch
self.__dict__['_username_'] = userName
self._... |
toobaz/pandas | pandas/tests/sparse/test_indexing.py | Python | bsd-3-clause | 38,613 | 0.000829 | import numpy as np
import pytest
import pandas as pd
from pandas.core.sparse.api import SparseDtype
import pandas.util.testing as tm
@pytest.mark.filterwarnings("ignore:Sparse:FutureWarning")
@pytest.mark.filterwarnings("ignore:Series.to_sparse:FutureWarning")
class TestSparseSeriesIndexing:
def setup_method(sel... | oc["C":], orig.loc["C":].to_sparse(fill_value=0)
)
def test_loc_slice_fill_value(self):
orig = pd.Series([1, np.nan, 0, 3, 0])
sparse = orig.to_sparse(fill_value=0)
tm.assert_sp_series_equal(sparse.loc[2:], orig.loc[2:].to_sparse(fill_value=0))
def test_iloc(self):
orig... | isnan(sparse.iloc[2])
result = sparse.iloc[[1, 3, 4]]
exp = orig.iloc[[1, 3, 4]].to_sparse()
tm.assert_sp_series_equal(result, exp)
result = sparse.iloc[[1, -2, -4]]
exp = orig.iloc[[1, -2, -4]].to_sparse()
tm.assert_sp_series_equal(result, exp)
with pytest.rai... |
k4rtik/alpo | quotes/admin.py | Python | mit | 243 | 0.00823 | from quotes.models import Quote
from django.contrib import admin
c | lass QuoteAdmin(admin.ModelAdmin):
list_display = ('message', 'name', 'program', 'class_of',
'submission_time')
admin.site.register( | Quote, QuoteAdmin)
|
gryzz/uCall | utils/asterisk-connector/ami2stomp-get.py | Python | gpl-3.0 | 972 | 0.005144 | #!/usr/bin/env python
# vim: set expandtab shiftwidth=4:
# http://www.voip-info.org/wiki/view/asterisk+manager+events
import sys,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
config = ConfigParser.ConfigParser()
devel_config = ConfigParser.ConfigParser()
config.read('/opt/ucall/... | int 'Stomp host:', stomp_host
print 'Stomp username:', stomp_username
print 'Stomp password:', stomp_password
print 'Stomp queue:', stomp_queue
print '='*80
stomp = Client(stomp_host)
st | omp.connect(stomp_username, stomp_password)
stomp.subscribe("jms.queue.msg.ctrl")
while True:
message = stomp.get()
print message.body
stomp.disconnect()
|
xbot/alfred-pushbullet | lib/pushbullet/filetype.py | Python | mit | 373 | 0 | def _magic_get_file_type(f, _):
file_type = magic.from_buffer(f.read(1024), mime=True)
| f.seek(0)
return file_type.decode('utf-8')
def _guess_file_type(_, filename):
return mimetypes.guess_type(filename)[0]
try:
import magic
except ImportError:
import mimetypes
get_file_ty | pe = _guess_file_type
else:
get_file_type = _magic_get_file_type
|
eltonkevani/tempest_el_env | tempest/api/compute/floating_ips/test_floating_ips_actions.py | Python | apache-2.0 | 7,990 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | client.disassociate_floating_ip_from_server(
self.floating_ip,
self.server_id)
self.assertEqual(202, resp.status)
@attr(type=['negative', 'gate'])
def test_delete_nonexistant_floating_ip(self):
# Negative test:Deletion of a nonexistent floating IP
# from project ... | the non existent floating IP
self.assertRaises(exceptions.NotFound, self.client.delete_floating_ip,
self.non_exist_id)
@attr(type=['negative', 'gate'])
def test_associate_nonexistant_floating_ip(self):
# Negative test:Association of a non existent floating IP
#... |
sunyihuan326/DeltaLab | Andrew_NG_learning/class_two/week_three/Dxq_1.py | Python | mit | 3,691 | 0.00246 | # coding:utf-8
'''
Created on 2017/11/7.
@author: chk01
'''
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
from class_two.week | _three.tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict
np.random.seed(1)
def exam1():
y_hat = tf.constant(36, name='Y-hat')
y = tf.constant(39, name='y')
loss = tf.Variable((y - y_hat) ** 2, name='loss')
init = tf.global_variables_initializer()
with tf.S | ession() as sess:
sess.run(init)
print(sess.run(loss))
def exam2():
a = tf.constant(2)
b = tf.constant(3)
c = tf.multiply(a, b)
return c
def exam3(x_input):
with tf.Session() as sess:
x = tf.placeholder(tf.int64, name='x')
y = 2 * x
print(sess.run(y, feed_... |
nikolas/raven-python | raven/processors.py | Python | bsd-3-clause | 3,988 | 0 | """
raven.core.processors
~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import re
from raven.utils import varmap
from raven.utils import six
class Processor(object):
def _... | for | value in data['exception'].get('values', []):
if 'stacktrace' in value:
self.filter_stacktrace(value['stacktrace'])
if 'request' in data:
self.filter_http(data['request'])
if 'extra' in data:
data['extra'] = self.filter_extra(data['e... |
HEPData/hepdata3 | hepdata/factory.py | Python | gpl-2.0 | 2,063 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of HEPData.
# Copyright (C) 2016 CERN.
#
# HEPData is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later... | Data 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
# G | eneral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with HEPData; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immu... |
Joergen/zamboni | apps/comm/models.py | Python | bsd-3-clause | 6,495 | 0.001232 | from datetime import datetime
from django.db import models
from uuidfield.fields import UUIDField
from access import acl
import amo.models
from translations.fields import save_signal
from mkt.constants import comm as const
class CommunicationPermissionModel(amo.models.ModelBase):
# Read permissions imply writ... | c = CommunicationThreadCC.objects.filter(
user=profile, thread=thread)
if user_post.exists() or user_cc.exists():
return True
# User is a developer of the add-on and has the permission to read.
user_is_author = profile.addons.filter(pk=thread.addon_id)
if thread.read_permission_develop... | heck if the user has read/write permissions on the given note.
Developers of the add-on used in the note, users in the CC list,
and users who post to the thread are allowed to access the object.
Moreover, other object permissions are also checked agaisnt the ACLs
of the user.
"""
if note.autho... |
ericxlive/abstract-data-types | abstract-data-types/adt_queue.py | Python | mit | 2,361 | 0.002541 | """ This class represents a Queue Node to store values and also
links others Nodes with values."""
class Node:
""" It starts with a value at all times. A note can not be
created without a value associated. """
def __init__(self, value):
| self.value = value
self.next = None
""" This class represents a Queue to store values. The Queue starts
with a node called head. Every single element is going to be added
after the last node entered."""
class Queue:
""" The Queue is created with it's size zero and the head element
head is ... | lue is going to be added always after the
last value added. If the Queue has no elements, the value added is
going to be the head/head and also the last/tail value."""
def enqueue(self, value):
if (self.head is None):
self.head = Node(value)
self.size += 1
els... |
updatengine/updatengine-server | adminactions/__init__.py | Python | gpl-2.0 | 1,648 | 0.002427 | NAME = 'django-adminactions'
VERSION = __version__ = (0, 4, 0, 'final', 0)
__author__ = 'sax'
import subprocess
import datetime
import os
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
... | en('git log --pretty=form | at:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except Va... |
Donkyhotay/MoonPy | zope/app/apidoc/browser/skin.py | Python | gpl-3.0 | 1,074 | 0.003724 | ##############################################################################
#
# Copyright (c) 2004 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy | of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, A | ND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""`APIdoc` skin.
$Id$
"""
__docformat__ = "reStructuredText"
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
class ... |
tsg-/pyeclib | pyeclib/__init__.py | Python | bsd-2-clause | 1,348 | 0 | # Copyright (c) 2013, Kevin Greenan (kmgreen2@gmail.com)
# 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 c... | ING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 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.
|
plaidml/plaidml | mlperf/backend_tflite.py | Python | apache-2.0 | 1,874 | 0.001601 | """
tflite backend (https://github.com/tensorflow/tensorflow/lite)
"""
# pylint: disable=unused-argument,missing-docstring,u | seless-super-delegation
from threading import Lock
try:
# try dedicated tflite package first
import tflite_runtime
import tflite_runtime.interpreter as tflite
_version = tflite_runtime.__version__
_git_version = tflite_runtime.__git_version__
except:
# fall back to tflite bundled in tensorflow... | sion = tf.__version__
_git_version = tf.__git_version__
import backend
class BackendTflite(backend.Backend):
def __init__(self):
super(BackendTflite, self).__init__()
self.sess = None
self.lock = Lock()
def version(self):
return _version + "/" + _git_version
def nam... |
lidavidm/mathics-heroku | venv/lib/python2.7/site-packages/sympy/core/tests/test_sympify.py | Python | gpl-3.0 | 14,157 | 0.000212 | from __future__ import with_statement
from sympy import Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda, \
Function, I, S, sqrt, srepr, Rational, Tuple, Matrix, Interval
from sympy.abc import x, y
from sympy.core.sympify import sympify, _sympify, SympifyError, kernS
from sympy.core.decorators import _sympi... | t sympify(['.3', '.2'], rational=True) == ans
assert sympify(set(['.3', '.2']), rational=True) == set(ans)
assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans)
assert sympify(dict(x=0, y=1)) == {x: 0, y: 1}
assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]]
def test_symp... | def _sympy_(self):
return Symbol("x")
a = A()
assert _sympify(a)**3 == x**3
assert sympify(a)**3 == x**3
assert a == x
def test_sympify_text():
assert sympify('some') == Symbol('some')
assert sympify('core') == Symbol('core')
assert sympify('True') is True
assert ... |
JasonKessler/scattertext | scattertext/viz/__init__.py | Python | apache-2.0 | 329 | 0.009119 | from .Scatterplot | Structure import ScatterplotStructure
from .BasicHTMLFromScatterplotStructure import BasicHTMLFromScatterplotStructure
from scattertext.viz.PairPlotFromScattertextStructure import PairPlotFromScatterplotStructure
from .VizDataAdapter import VizDataAdapter
from .HTMLSemioticSquareViz import | HTMLSemioticSquareViz |
colaftc/webtool | top/api/rest/PictureIsreferencedGetRequest.py | Python | mit | 318 | 0.028302 | '''
Created by auto_sdk on 2013.11.26
'''
from top.api.base import RestApi
class PictureIsreferencedGetRequest(RestApi):
| def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi | .__init__(self,domain, port)
self.picture_id = None
def getapiname(self):
return 'taobao.picture.isreferenced.get'
|
pp-mo/iris | docs/iris/example_code/Meteorology/__init__.py | Python | lgpl-3.0 | 78 | 0 | """
Meteorolo | gy visualisation examples
=============== | ===================
"""
|
wilas/lab-ci | samples/py_garden/py_simple_tdd/test_nose_flat_play.py | Python | apache-2.0 | 137 | 0.021898 | def test_assert():
assert 'soup' == 'soup'
def test_pass():
pass
def test_fail():
assert | False
test_fail.wi | ll_fail = True
|
brigittebigi/proceed | proceed/src/TagPDF/name.py | Python | gpl-3.0 | 3,002 | 0.003331 | #! /usr/bin/env python
# -*- coding: UTF-8 -*-
# ---------------------------------------------------------------------------
# ___ __ ___ ___ ____ ____ __
# | \ | \ | | / | | | \ Automatic
# |__/ |__/ | | | |__ |__ | | Conference
# | ... | ion=""):
self.name = "/"
while (os.path.exists(self.name)==True):
self.set_name(extension)
|
def set_name(self, extension):
"""
Set a new file name.
"""
# random float value
randval = str(int(random.random()*10000))
# process pid
pid = str(os.getpid())
# today's date
today = str(date.today())
# filename
filen... |
mwgit00/poz | poz.py | Python | mit | 3,487 | 0.000287 | """
POZ Development Application.
"""
import numpy as np
# import cv2
import pozutil as pu
import test_util as tpu
def perspective_test(_y, _z, _ele, _azi):
print "--------------------------------------"
print "Perspective Transform tests"
print
cam = pu.CameraHelper()
# som... | .float32([0, _y, _z])
p8 = np.float32([1., _y, _z])
# 3x3 grid array
ppp = np.array([p0, p1, p2, p3, p4, p5, p6, p7, p8])
print "Here are some landmarks in world"
print ppp
puv_acc = []
quv_acc = []
for vp in ppp:
# original view of landmarks
u, v = cam.proj... | puv_acc.append(np.float32([u, v]))
# rotated view of landmarks
xyz_r = pu.calc_xyz_after_rotation_deg(vp, _ele, _azi, 0)
u, v = cam.project_xyz_to_uv(xyz_r)
quv_acc.append(np.float32([u, v]))
puv = np.array(puv_acc)
quv = np.array(quv_acc)
# 4-pt "diamond" arra... |
Yelp/pysensu-yelp | setup.py | Python | apache-2.0 | 480 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='pysen | su-yelp',
version='0.4.4',
provides=['pysensu_yelp'],
description='Emits Yelp-flavored Sensu events to a Sensu Client',
| url='https://github.com/Yelp/pysensu-yelp',
author='Yelp Operations Team',
author_email='operations@yelp.com',
packages=find_packages(exclude=['tests']),
install_requires=['six'],
license='Copyright Yelp 2014, all rights reserved',
)
|
shendo/peerz | peerz/messaging/base.py | Python | gpl-3.0 | 2,720 | 0.002941 | # Peerz - P2P python library using ZeroMQ sockets and gevent
# Copyright (C) 2014-2015 Steve Henderson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | es.setdefault(self.state, 0.0)
self.times[self.state] += (now - self.last_change)
self.last_change = now
def duration(self):
return time.time() * 1000 - self.start
def laten | cy(self):
return self.times.setdefault('waiting response', 0.0)
def _send_query(self):
pass
def _completed(self):
pass
|
rubiconjosh/aoc-2015 | day4-part2.py | Python | mit | 345 | 0 | import hashlib
puzzle_input = 'iwrupvqb'
cu | rrent = 0
done = False
while not done:
combined_input = puzzle_input + str(current)
solution = hashlib.md5(combined_input.encode())
solution = str(solution.hexdigest())
print(solution)
if solution.startswith('000000'):
done = True
print(current)
c | urrent += 1
|
glemaitre/scikit-learn | sklearn/tests/test_calibration.py | Python | bsd-3-clause | 23,376 | 0 | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD 3 clause
import pytest
import numpy as np
from numpy.testing import assert_allclose
from scipy import sparse
from sklearn.base import BaseEstimator
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import Leave... | 2 * y_train - 1, sample_weight=sw_train)
prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1]
assert_array_almost_equal(prob_p | os_cal_clf, prob_pos_cal_clf_relabeled)
# Check invariance against relabeling [0, 1] -> [1, 0]
cal_clf.fit(this_X_train, (y_train + 1) % 2, sample_weight=sw_train)
prob_pos_cal_clf_relabeled = cal_clf.predict_proba(this_X_test)[:, 1]
if method == "sigmoid":
assert_array_almo... |
cscott/wikiserver | mwlib/serve.py | Python | gpl-2.0 | 19,146 | 0.004805 | #! /usr/bin/env python
"""WSGI server interface to mw-render and mw-zip/mw-post"""
import os
import re
import shutil
import signal
import StringIO
import subprocess
import time
import urllib2
try:
from hashlib import md5
except ImportError:
from md5 import md5
try:
import json
except ImportError:
impo... | renderlog_filename = 'mw-render.log'
def __init__(self, cache_dir,
mwrender_cmd, mwrender_logfile,
mwzip_cmd, mwzip_logfile,
mwpost_cmd, mwpost_logfile,
queue_dir,
default_writer='rl',
report_from_mail=None,
report_recipients=None,
):
self.cac... | nder_logfile
self.mwzip_cmd = mwzip_cmd
self.mwzip_logfile = mwzip_logfile
self.mwpost_cmd = mwpost_cmd
self.mwpost_logfile = mwpost_logfile
if queue_dir:
self.queue_job = filequeue.FileJobQueuer(utils.ensure_dir(queue_dir))
else:
self.queue_job = ... |
foxbunny/Timetrack | tt.py | Python | gpl-3.0 | 7,554 | 0.003574 | #!/usr/bin/env python
"""
Simple-stupid time tracker script
=================================
Timetrack
opyright (C) 2010, Branko Vukelic <studio@brankovukelic.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 Soft... | on, pidfilter)
print "Closing connection to database"
connection.close()
sys.exit(1)
if __name__ == '__main__':
main(sys. | argv[1:])
|
data-refinery/data_refinery | common/data_refinery_common/models/jobs.py | Python | bsd-3-clause | 8,068 | 0.001363 | from typing import Dict, Set
from django.db import transaction
from django.db import models
from django.utils import timezone
from data_refinery_common.models.models import Sample, Experiment, OriginalFile
class SurveyJob(models.Model):
"""Records information about a Surveyor Job."""
class Meta:
db... | he end time of the job
end_time = models.DateTimeField(null=True)
# This field represents how many times this job has been
# retried. It starts at 0 and each time the job has to be retried
# it will be incremented.
num_retries = models.IntegerField(default=0)
# This field indicates whether or ... | ey failed.
failure_reason = models.TextField(null=True)
created_at = models.DateTimeField(editable=False, default=timezone.now)
last_modified = models.DateTimeField(default=timezone.now)
def save(self, *args, **kwargs):
""" On save, update timestamps """
current_time = timezone.now()
... |
DGA-MI-SSI/YaCo | deps/swig-3.0.7/Examples/test-suite/python/cpp11_decltype_runme.py | Python | gpl-3.0 | 347 | 0.011527 | import cpp11_decltype
a = cp | p11_decltype.A()
a.i = 5
if a.i != 5:
raise RuntimeError, "Assignment t | o a.i failed."
a.j = 10
if a.j != 10:
raise RuntimeError, "Assignment to a.j failed."
b = a.foo(5)
if b != 10:
raise RuntimeError, "foo(5) should return 10."
b = a.foo(6)
if b != 0:
raise RuntimeError, "foo(6) should return 0."
|
lre/deeppy | deeppy/loss.py | Python | mit | 3,134 | 0 | import numpy as np
import cudarray as ca
from .base import PickleMixin
_FLT_MIN = np.finfo(ca.float_).tiny
class Loss(PickleMixin):
# abll: I suspect that this interface is not ideal. It would be more
# elegant if Loss only provided loss() and grad(). However, where should
# we place the logic from fpro... | :
"""
Softmax + cross entropy (aka. multinomial logistic loss)
"""
def __init__(self):
self.name = 'softmaxce'
self._tmp_x = None
self._tmp_y = None
self._tmp_target = None
self._tmp_one_hot = None
self.n_classes = None
def _setup(self, x_shape):
... | not x:
self._tmp_y = ca.nnet.softmax(x)
self._tmp_x = x
return self._tmp_y
def _one_hot(self, target):
# caching wrapper
if self._tmp_target is not target:
self._tmp_one_hot = ca.nnet.one_hot_encode(target, self.n_classes)
self._tmp_target = ... |
mnazim/django-rest-kickstart | helpers/serializers.py | Python | mit | 206 | 0.004854 | from rest_framework import | serializers
class BaseModelSerializer(serializers.ModelSerializer):
id = serializers.SerializerMethodField()
def get_id(self, instance):
return str(inst | ance.id)
|
zachjanicki/osf.io | website/addons/mendeley/serializer.py | Python | apache-2.0 | 155 | 0.006452 | from website.addons.base.serializer import CitationsAddonSe | rializer
class MendeleySerializer(CitationsAddonSerializer | ):
addon_short_name = 'mendeley'
|
hackebrot/pytest | src/_pytest/cacheprovider.py | Python | mit | 13,931 | 0.00079 | """
merged implementation of the cache provider
the name cache was not chosen to ensure pluggy automatically
ignores the external pytest-cache
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import os
from collections import OrderedDict
imp... | cachedir.joinpath("CACHEDIR.TAG")
if not cachedir_tag_path.is_file():
cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)
class LFPlugin(object):
""" Plugin which implements the --lf (run last-failing) option """
def | __init__(self, config):
self.config = config
active_keys = "lf", "failedfirst"
self.active = any(config.getoption(key) for key in active_keys)
self.lastfailed = config.cache.get("cache/lastfailed", {})
self._previously_failed_count = None
self._no_failures_behavior = sel... |
jungla/ICOM-fluidity-toolbox | 2D/U/plot_Div_spec.py | Python | gpl-2.0 | 3,442 | 0.049099 | import os, sys
import myfun
import numpy as np
import matplotlib as mpl
mpl.use('ps')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import interpolate
import lagrangian_stats
import scipy.fftpack
## READ archive (too many points... somehow)
# args: name, dayi, dayf, days
#label ... | rgv[4])
#days = int(sys.argv[5])
path = './Velocity_CG/'
try: os.stat('./plot/'+label)
except OSError: os.mkdir('./plot/'+label)
# dimensions archives
# ML exp
Xlist = np.linspace(0,2000,161)
Ylist = np.linspace(0,2000,161)
Zlist = np.l | inspace(0,-50,51)
dl = [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
Zlist = np.cumsum(dl)
xn = len(Xlist)
yn = len(Ylist)
zn = len(Zlist)
dx = np.diff(Xlist)
z = 1
for time in range(dayi,dayf,days):
print 'time:', time
tlabel = str(time)
while len(... |
MathieuDuponchelle/django-sortedm2m | sortedm2m/__init__.py | Python | bsd-3-clause | 48 | 0 | # -*- c | oding: utf-8 -*-
__version__ = '0.7. | 0'
|
infoxchange/barman | barman/xlog.py | Python | gpl-3.0 | 14,318 | 0 | # Copyright (C) 2011-2017 2ndQuadrant Limited
#
# This file is part of Barman.
#
# Barman is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | segment
It can handle either a full file path or a simple file name.
:param str path: the file name to decode
:rtype: list[int]
"""
name = | os.path.basename(path)
match = _xlog_re.match(name)
if not match:
raise BadXlogSegmentName(name)
return [int(x, 16) if x else None for x in match.groups()]
def encode_segment_name(tli, log, seg):
"""
Build the xlog segment name based on timeline, log ID and segment ID
:param int tli:... |
apyrgio/ganeti | lib/http/__init__.py | Python | bsd-2-clause | 28,992 | 0.007243 | #
#
# Copyright (C) 2007, 2008, 2010, 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list ... | ly be used for internal error reporting.
"""
class HttpSocketTimeout(Exception):
"""Internal exception for socket timeouts.
This should only be used for internal error reporting.
"""
class HttpException(Exception):
code = None
message = None
def __init__(self, message=None, headers=None):
Exce... | .1: The request could not be understood by the server
due to malformed syntax. The client SHOULD NOT repeat the request
without modifications.
"""
code = 400
class HttpUnauthorized(HttpException):
"""401 Unauthorized
RFC2616, section 10.4.2: The request requires user
authentication. The response MUST ... |
tomprince/gemrb | gemrb/GUIScripts/bg1/GUICG22.py | Python | gpl-2.0 | 3,963 | 0.028261 | # GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later versi... |
from GUIDefines import *
from ie_stats import *
import CharGen | Common
import GUICommon
import CommonTables
KitWindow = 0
TextAreaControl = 0
DoneButton = 0
SchoolList = 0
ClassID = 0
def OnLoad():
global KitWindow, TextAreaControl, DoneButton
global SchoolList, ClassID
if GUICommon.CloseOtherWindow(OnLoad):
if(KitWindow):
KitWindow.Unload()
KitWindow = None
return... |
sebastian-steinmann/kodi-repo | src/service.library.video/resources/lib/date_utils.py | Python | mit | 1,538 | 0.001951 | """ Class to handle date-parsing and formatting """
# Workaround for http://bugs.python.org/issue8098
import _strptime # pylint: disable=unused-import
from datetime import datetime
import time
class DateUtils(object):
""" Class to h | andle date-parsing and formatting """
date_format = '%Y-%m-%dT%H:%M:%SZ'
json_date_format = '%Y-%m-%dT%H:%M:%S.%fZ'
kodi_date_format = '%Y-%m-%d %H:%M'
def get_str_date(self, date):
| """
Formats datetime to str of format %Y-%m-%dT%H:%M:%SZ
Arguments
date: datetime
"""
return datetime.strftime(date, self.date_format)
def parse_str_date(self, str_date):
"""
Parse a date of format %Y-%m-%dT%H:%M:%SZ to date
Arguments
st... |
umitproject/network-admin | netadmin/networks/urls.py | Python | agpl-3.0 | 2,718 | 0.002575 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# 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 Sof... | twork/delete/(?P<object_id>\d+)/$',
'network_delete', name="network_delete"),
url(r'^network/events/(?P<object_id>\d+)/$',
'network_events', name='network_events'),
url(r'^network/netmask-create/$',
'subnet_network', name='subnet_network'),
url(r'/update/(?P<object_id>\ | d+)/$',
'network_select', name='network_select'),
url(r'share/list/(?P<object_type>host|network)/(?P<object_id>\d+)/',
'share_list', name="share_list"),
url(r'share/(?P<object_type>host|network)/(?P<object_id>\d+)/',
'share', name="share"),
url(r'shar... |
yoannMoreau/Evapo_EraInterim | python/utils.py | Python | cc0-1.0 | 20,707 | 0.026002 | #-*- coding: utf-8 -*-
'''
Created on 16 déc. 2013
@author: yoann Moreau
All controls operations :
return true if control ok
'''
import os
import errno
from datetime import date,datetime,timedelta
import ogr,osr
import re
import gdal
import osr
import numpy as np
import numpy.ma as ma
import | subprocess
impor | t shutil
import math
from pyspatialite._spatialite import Row
import scipy.ndimage as ndimage
import pyproj as pp
def checkForFile(pathToFile):
if os.path.isfile(pathToFile):
return True
else:
return False
def createParamFile(pathFile,user,key):
f = open(pathFile, 'w+')
f.writ... |
miguelgrinberg/heat | heat/engine/clients/os/trove.py | Python | apache-2.0 | 4,752 | 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
# ... | import constraints
class TroveClientPlugin(client_plugin.ClientPlugin):
exceptions_module = exceptions
service_types = [DATABASE] = ['database']
def _create(self):
con = self.context
endpoint_type = self._get_client_option('trove', 'endpoint_type')
args = {
| 'service_type': self.DATABASE,
'auth_url': con.auth_url or '',
'proxy_token': con.auth_token,
'username': None,
'password': None,
'cacert': self._get_client_option('trove', 'ca_file'),
'insecure': self._get_client_option('trove', 'insecure'),... |
hephestos/pythos | discovery/tasks.py | Python | gpl-3.0 | 3,656 | 0.000274 | # import python modules
import os
import time
import logging
import multiprocessing
# import django modules
# import third party modules
# import project specific model classes
from config.models import Origin
# import app specific utility classes
# import app specific utility functions
from .utils import packet_c... | process = multiprocessing.Process(target=run_capture,
args=(interface,
duration,
packets
| )
)
logging.info("Starting live capture on: " + interface)
discovery_process.start()
logging.info("Starting " + str(num_processes) + " worker processes.")
while discovery_process.is_alive() or not packets.empty():
... |
ptorrestr/t2db_buffer | t2db_buffer/tests/test_buffer.py | Python | gpl-2.0 | 11,583 | 0.003367 | import unittest
import time
import _thread as thread
from threading import Barrier
from threading imp | ort Lock
from threading import Event
from t2db_buffer.buffer import GlobalBuffer
from t2db_buffer.buffer import BufferServer
from t2db_objects.objects import Tweet
from t2db_objects.objects import User
from t2db_objects.objects impor | t TweetStreaming
from t2db_objects.objects import TweetSearch
from t2db_objects.objects import Streaming
from t2db_objects.objects import Search
from t2db_objects.objects import ObjectList
from t2db_objects.tests.common import randomInteger
from t2db_objects.tests.common import randomTweetStreaming
from t2db_objects.te... |
wpjesus/codematch | ietf/community/management/commands/update_doc_change_dates.py | Python | bsd-3-clause | 1,440 | 0.002083 | import sys
from django.core.management.base import BaseCommand
from ietf.community.constants import SIGNIFICANT_STATES
from ietf.community.models import DocumentChangeDates
from ietf.doc.models import Document
class Command(BaseCommand):
help = (u"Update drafts in community lists by reviewing their rules")
... | ormal_change = doc.latest_event()
significant_change = None
for event in doc.docevent_set.filter(type='changed_document'):
for state in SIGNIFICANT_STATES:
if ('<b>%s</b>' % state) in event.desc:
significant_change = event
... | w_version.time.date()
changes.normal_change_date = normal_change and normal_change.time.date()
changes.significant_change_date = significant_change and significant_change.time.date()
changes.save()
sys.stdout.write('Document %s/%s\r' % (index, total))
sys.st... |
okfn/owslib | owslib/wfs.py | Python | bsd-3-clause | 930 | 0.008602 | # -*- coding: ISO-8859-15 -*-
# =============================================================================
# Copyright (c) 2004, 2006 Sean C. Gillies
# Copyright (c) 2009 STFC <http://www.stfc.ac.uk>
#
# Authors :
# Dominic Lowe <dominic.lowe@stfc.ac.uk>
#
# Contact email: dominic.lowe@stfc.ac.uk
# =======... | specific WebFeatureService object '''
if version in ['1.0', '1.0.0']:
return wfs100.WebFeatureService_1_0_0.__new__(wfs100.Web | FeatureService_1_0_0, url, version, xml)
elif version in ['2.0', '2.0.0']:
return wfs200.WebFeatureService_2_0_0.__new__(wfs200.WebFeatureService_2_0_0, url, version, xml)
|
alexeiramone/django-default-template | manage.py | Python | mit | 348 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
if __name__ == "__main__":
settings_name = "settings.local" if os.na | me == 'nt' else "settings | .remote"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_name)
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
MonicaHsu/truvaluation | venv/lib/python2.7/site-packages/pymysql/tests/test_basic.py | Python | mit | 12,154 | 0.003291 | import pymysql.cursors
from pymysql.tests import base
from pymysql import util
from pymysql.err import ProgrammingError
import time
import datetime
__all__ = ["TestConversion", "TestCursor", "TestBulkInserts"]
class TestConversion(base.PyMySQLTestCase):
def test_datatypes(self):
""" test every data typ... | # check sequence type
c.execute("insert into test_datatypes (i, l) values (2,4), (6,8), (10,12)")
c.execute("select l from test_datatypes where i in %s order by i", ((2,6),))
r = c.fetchall()
self.assertEqual(((4,),(8,)), r)
finally:
c.execute("d... | f):
""" test dict escaping """
conn = self.connections[0]
c = conn.cursor()
c.execute("create table test_dict (a integer, b integer, c integer)")
try:
c.execute("insert into test_dict (a,b,c) values (%(a)s, %(b)s, %(c)s)", {"a":1,"b":2,"c":3})
c.execute("s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.