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
pavel-odintsov/ru_open_statistics
helpers/helperUnicode.py
Python
gpl-2.0
3,890
0.001028
# Copyright (C) 2013, Stefan Schwarzer # See the file LICENSE for licensing terms. """ tool.py - helper code """ from __future__ import unicode_literals import compat as compat __all__ = ["same_string_type_as", "as_bytes", "as_unicode", "as_default_string"] # Encoding to convert between byte string an...
type): r
eturn string.encode(encoding) else: return string def recursive_str_to_unicode(target): """ recursive function for convert all string in dict, tuple and list to unicode """ pack_result = [] if isinstance(target, dict): level = {} for key, val in target.iteritems(): ...
chris2727/BeastBot
src/inc/modules/suggest.py
Python
gpl-3.0
1,611
0.003724
from inc import * modFunc.addCommand('suggest', 'suggest', 'suggest') modFunc.addCommand('sug', 'suggest', 'suggest') modFunc.addCommand('issue', 'suggest', 'suggest') modFunc.addCommand('sug-read', 'suggest', 'read') modFunc.addCommand('sug-clear', 'suggest', 'clear') def suggest(line, irc): message, username, m...
botadmins').split(" "): if (ircFunc.isRegged(username, irc)): with open('suggestions.txt') as sugfile: print 'in with'
for sugline in sugfile: ircFunc.ircSay(msgto, sugline, irc) def clear(line, irc): message, username, msgto = ircFunc.ircMessage(line) if username.lower() in configFunc.getBotConf('botadmins').split(" "): if (ircFunc.isRegged(username, irc)): f = open('suggestions.txt',...
enjaz/enjaz
studentguide/migrations/0006_tag_image.py
Python
agpl-3.0
446
0.002242
#
-*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('studentguide', '0005_add_studentguide_clubs'), ] operations = [ migrations.AddField( model_name='tag', ...
lennax/util
util/atom_data.py
Python
gpl-3.0
6,616
0.000151
# Copyright 2013-2015 Lenna X. Peterson. All rights reserved. from .meta import classproperty class AtomData(object): # Maximum ASA for each residue # from Miller et al. 1987, JMB 196: 641-656 total_asa = { 'A': 113.0, 'R': 241.0, 'N': 158.0, 'D': 151.0, 'C': 140...
reate their own local scope """ return {o: cls.three_to_full[t.title()] for t, o in cls.three_to_one.iteritems()} res_atom_list = dict( ALA=['
C', 'CA', 'CB', 'N', 'O'], ARG=['C', 'CA', 'CB', 'CD', 'CG', 'CZ', 'N', 'NE', 'NH1', 'NH2', 'O'], ASN=['C', 'CA', 'CB', 'CG', 'N', 'ND2', 'O', 'OD1'], ASP=['C', 'CA', 'CB', 'CG', 'N', 'O', 'OD1', 'OD2'], CYS=['C', 'CA', 'CB', 'N', 'O', 'SG'], GLN=['C', 'CA', 'CB', 'CD', 'CG', 'N'...
ichi23de5/ichi_Repo
property/models/inspection.py
Python
gpl-3.0
2,328
0.007732
# -*- coding: utf-8 -*- from openerp import models, fields, api from datetime import datetime, timedelta, date from dateutil.relativedelta import relativedelta class Inspection(models.Model): _name = 'property.inspection' _order = 'date desc' _inherit = ['mail.thread', 'ir.needaction_mixin'] propert...
= fields.Text(string='product_memo', help='Koukan sita kiki wo kaitene') ### request ### request_id = fields.Many2one('property.inspection.request', string='Request') request_date = fields.Date(string='request_date', related='request_id.date', readon
ly=True) requester_name = fields.Char(string='requester_name', related='request_id.partner_id.name', readonly=True) request_note = fields.Text(string='request_note', related='request_id.request_note', readonly=True) responder_name = fields.Char(string='responder_name', related='request_id.user_id.name', rea...
fengren/python_koans
python2/koans/about_string_manipulation.py
Python
mit
2,781
0.000719
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutStringManipulation(Koan): def test_use_format_to_interpolate_variables(self): value1 = 'one' value2 = 2 string = "The values are {0} and {1}".format(value1, value2) self.assertEqual("The values are...
f.assertEqual(97, ord('a')) self.assertEqual(True, ord('b') == (ord('a') + 1)) def test_strings_can_be_split(self): string = "Sausage Egg Cheese" words = stri
ng.split() self.assertEqual(["Sausage", "Egg", "Cheese"], words) def test_strings_can_be_split_with_different_patterns(self): import re # import python regular expression library string = "the,rain;in,spain" pattern = re.compile(',|;') words = pattern.split(string) ...
saahil/MSSegmentation
dice.py
Python
gpl-2.0
1,199
0.010008
import numpy from PIL import Image import sys #if len(sys.argv) != 3: # sys.exit('usage: dice.py path_to_segmented_image path_to_ground_truth_image') pairs = [['/home/ognawala/data/PatientMS-R/20140120T143753/20140120T143753_annotated_rf.png', '/home/ognawala/data/Patient-Mask/20140120T143753-mask.png'], ['/home/o...
p[1] print truth_y.shape # flatten arrays truth_y = truth_y.flatten() y = y.flatten() print truth_y.shape print y.shape for i in range(len(y)): # both marked? if y[i]==200 and truth_y[i]==0: n_aib += 1 # y marked if y[i]==200: ...
2*n_aib)/float(n_y+n_truth) print dice
kambysese/mne-python
tutorials/preprocessing/plot_10_preprocessing_overview.py
Python
bsd-3-clause
11,702
0
# -*- coding: utf-8 -*- """ .. _tut-artifact-overview: Overview of artifact detection ============================== This tutorial covers the basics of artifact detection, and introduces the artifact detection tools available in MNE-Python. We begin as always by importing the necessary Python modules and loading som...
nsors picking up the field generated by unshielded headphones) # - Continuous oscillations at specific frequencies used by he
ad position # indicator (HPI) coils # - Random high-amplitude fluctuations (or alternatively, constant zero # signal) in a single channel due to sensor malfunction (e.g., in surface # electrodes, poor scalp contact) # # - Biological artifacts # - Periodic `QRS`_-like signal patterns (especiall...
kirpit/couchbasekit
couchbasekit/fields.py
Python
mit
6,692
0.002241
#! /usr/bin/env python """ couchbasekit.fields ~~~~~~~~~~~~~~~~~~~ :website: http://github.com/kirpit/couchbasekit :copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt. :license: MIT, see LICENSE.txt for details. * :class:`couchbasekit.fields.CustomField` * :class:`couchbasekit.fields.Choice...
be used when saving a custom field into :class:`couchbasekit.document.Document` instance. :returns: The value to be saved for t
he field within :class:`couchbasekit.document.Document` instances. :rtype: mixed """ if self._value is None: raise ValueError("%s's 'value' is not set." % type(self).__name__) return self._value @value.setter def value(self, value): """Propery set...
esikachev/scenario
sahara/plugins/mapr/plugin.py
Python
apache-2.0
2,850
0
# Copyright (c) 2015, MapR Technologies # # 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...
def scale_cluster(self, cluster, instances): v_handler = self._get_handler(cluster.hadoop_version) v_handler.scale_cluster(cluster, instances) def decommission_nodes(self, cluster, instances): v_handler = self._get_handler(cluster.hadoop_version) v_handler.decommission_nodes(c
luster, instances) def get_edp_engine(self, cluster, job_type): v_handler = self._get_handler(cluster.hadoop_version) return v_handler.get_edp_engine(cluster, job_type) def get_open_ports(self, node_group): v_handler = self._get_handler(node_group.cluster.hadoop_version) return...
matburt/ansible
lib/ansible/module_utils/openstack.py
Python
gpl-3.0
4,528
0.006846
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
(k, v) in addresses.iteritems(): if key_name and k == key_name: ret.extend([addrs['addr'] for addrs in v]) else: for interface_spec in v: if 'OS-EXT-IPS:type' in interface_spec and interface_spec['OS-EXT-IPS:type'] == ext_tag: ret.append(interf...
fault=None), auth=dict(default=None, no_log=True), region_name=dict(default=None), availability_zone=dict(default=None), verify=dict(default=True, aliases=['validate_certs']), cacert=dict(default=None), cert=dict(default=None), key=dict(default=None, no_log=True),...
raycarnes/account-financial-tools
account_journal_always_check_date/__openerp__.py
Python
agpl-3.0
2,081
0
# -*- encoding: utf-8 -*- ############################################################################## # # Account Journal Always Check Date module for OpenERP # Copyright (C) 2013-2014 Akretion (http://www.akretion.com) # @author Alexis de Lattre <[email protected]> # # This program is free so...
the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #...
ve received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Account Journal Always Check Date', 'version': '0.1', 'category': 'Accounting &...
crimoniv/odoo-module-tools
repository_management/vcs_wrapper/vcs_wrapper.py
Python
agpl-3.0
1,918
0
# -*- coding: utf-8 -*- # © 2016 Cristian Moncho <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import logging _logger = logging.getLogger(__name__) _LOADED_VCS = [] def load_vcs(vcs): vcs = vcs.lower() modname = 'vcs.%s' % (vcs,) clsname = vcs.title()....
S)[vcs](path, **kwargs) except KeyError: raise Exception('Unknown repository structure in %s' % (path,)) @classmethod def available_vcs(cls):
return zip(*_LOADED_VCS)[0] if _LOADED_VCS else () @classmethod def from_source(cls, vcs, path, source, branch=None, **kwargs): res = cls(vcs, path) res.init(source, branch=branch, **kwargs) res.load() return res @classmethod def from_dir(cls, vcs, path, **kwarg...
DavidAndreev/indico
indico/modules/events/timetable/models/entries.py
Python
gpl-3.0
13,696
0.001168
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
port NEVER_SET, NO_VALUE from indico.core.db import db from indico.core.db.sqlalchemy import UTCDateTime, PyIntEnum from indico.core.db.sqlalchemy.util.models import populate_one_to_one_backrefs from indico.util.date_time import overlaps from indico.util.locators i
mport locator_property from indico.util.string import format_repr, return_ascii from indico.util.struct.enum import TitledIntEnum from indico.util.i18n import _ class TimetableEntryType(TitledIntEnum): __titles__ = [None, _("Session Block"), _("Contribution"), _("Break")] # entries are uppercase since `break`...
dbrgn/mopidy
tests/mpd/test_translator.py
Python
apache-2.0
6,809
0
from __future__ import absolute_import, unicode_literals import unittest from mopidy.internal import path from mopidy.models import Album, Artist, Playlist, TlTrack, Track from mopidy.mpd import translator class TrackMpdFormatTest(unittest.TestCase): track = Track( uri='a uri', artists=[Artist(n...
sult) self.assertIn(('Title', ''), result) self.assertIn(('Album', ''), result) self.assertIn(('Track', 0), result) self.assertNotIn(('Date', ''), result) self.assertEqual(len(result), 6) def test_track_to_mpd_format_with_position(self): result = translator.track_to_...
self.assertNotIn(('Pos', 1), result) def test_track_to_mpd_format_with_tlid(self): result = translator.track_to_mpd_format(TlTrack(1, Track())) self.assertNotIn(('Id', 1), result) def test_track_to_mpd_format_with_position_and_tlid(self): result = translator.track_to_mpd_format( ...
dilawar/moose-full
moose-examples/snippets/funcReacLotkaVolterra.py
Python
gpl-2.0
5,043
0.029942
######################################################################### ## This program is part of 'MOOSE', the ## Messaging Object Oriented Simulation Environment. ## Copyright (C) 2013 Upinder S. Bhalla. and NCBS ## It is made available under the terms of the ## GNU Lesser General Public License version 2...
sub', x, 'reac' ) moose.connect( xreac, 'prd', z, 'reac' ) moose.connect( yreac, 'sub', y, 'reac' ) moose.connect( yreac, 'prd', z, 'reac' ) # Create the output tables graphs = moose.Neutral( '/model/grap
hs' ) xplot = moose.Table2 ( '/model/graphs/x' ) yplot = moose.Table2 ( '/model/graphs/y' ) # connect up the tables moose.connect( xplot, 'requestOut', x, 'getN' ); moose.connect( yplot, 'requestOut', y, 'getN' ); def main(): """ The funcReacLotkaVolterra example shows how to use function objects ...
stvstnfrd/edx-platform
openedx/core/djangoapps/xblock/runtime/blockstore_field_data.py
Python
agpl-3.0
16,343
0.003243
""" Key-value store that holds XBlock field data read out of Blockstore """ from collections import namedtuple from weakref import WeakKeyDictionary import logging from xblock.exceptions import InvalidScopeError, NoSuchDefinition from xblock.fields import Field, BlockScope, Scope, UserScope, Sentinel from xblock.fiel...
rence so that the memory will be freed when the XBlock is no # longer needed (e.g. at the end of a request) # The
key of this dictionary is on ID object owned by the XBlock itself # (see _get_active_block()) and the value is an ActiveBlock object # (which holds olx_hash and changed_fields) self.active_blocks = WeakKeyDictionary() super(BlockstoreFieldData, self).__init__() # lint-amnesty, pylint: ...
bertrandF/DictionaryDB
db.py
Python
gpl-2.0
8,296
0.008799
#!/usr/bin/python3.4 ############################################################################# # # Dictionnary DB managing script. Add/Del/Search definitions # Copyright (C) 2014 bertrand # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public L...
to dictionnary.") print(" del Remove definition from dictionnary.") print(" help Print general help or command specific help.") print(" search Search definit
ion in dictionnary.") print("") ########### ### ADD ### def add(): argc = len(sys.argv) if argc < 3: __help_cmd(sys.argv[1]) return req = { 'fields' : '', 'name' : '', 'def' : '', 'url' : '' } i=2 while i < argc: if sys.arg...
HorizonXP/python-react-router
react_router/render.py
Python
mit
5,105
0.003918
import os import sys import json from optional_django import staticfiles from optional_django.serializers import JSONEncoder from optional_django.safestring import mark_safe from optional_django import six from js_host.function import Function from js_host.exceptions import FunctionError from react.render import Rende...
anslate=None, # Prop handling json_encoder=None ): if not os.path.isabs(path): abs_path = staticfiles.find(path) if not abs_path: raise ComponentSourceFileNotFound(path) path = abs_path if not os.path.exists(path): raise ComponentSourceFileNotFound(path) ...
t_path: raise ComponentSourceFileNotFound(client_path) client_path = abs_client_path if not os.path.exists(client_path): raise ComponentSourceFileNotFound(client_path) bundled_component = None import re client_re = re.compile(r"client-(?:\w*\d*).js",re.IGNORECASE) serve...
attibalazs/nltk-examples
7.6_Relation_Extraction.py
Python
mit
332
0.006024
import nltk import re import pprint def main(): IN = re.compile(r'.*\bin\b(?!\b.+ing)') for doc in nltk.corpus.ieer.parsed_docs('NYT_1998031
5'): for rel in nltk.sem.extract_rels('ORG', 'LOC', doc, corpus='ieer', pattern=IN):
print nltk.sem.relextract.rtuple(rel) if __name__ == "__main__": main()
eeyorkey/ipac
tasks/__init__.py
Python
gpl-2.0
42
0.02381
__all__ =
["pval_task", "annotation_tas
k"]
bioidiap/bob.bio.spear
bob/bio/spear/utils/extraction.py
Python
gpl-3.0
4,798
0.002293
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Pavel Korshunov <[email protected]> # Tue 22 Sep 17:21:35 CEST 2015 # # Copyright (C) 2012-2015 Idiap Research Institute, Martigny, Switzerland # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General...
f c1 != []: return (numpy.mean(c0, 0) + numpy.mean(c1, 0)) / 2.0 else: return
numpy.mean(c0, 0) def calc_std(c0, c1=[]): """ Calculates the variance of the data.""" if c1 == []: return numpy.std(c0, 0) prop = float(len(c0)) / float(len(c1)) if prop < 1: p0 = int(math.ceil(1 / prop)) p1 = 1 else: p0 = 1 p1 = int(math.ceil(prop)) r...
kayhayen/Nuitka
nuitka/nodes/CoroutineNodes.py
Python
apache-2.0
4,498
0.001112
# Copyright 2021, Kay Hayen, mailto:[email protected] # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
ntBase): kind = "EXPRESSION_COROUTINE_OBJECT_BODY" __slots__ = ("qualname_setup", "needs_generator_return_exit") def __init__(self, provider, name, code_object, flags, auto_release, source_ref): ExpressionFunctionEntryPointBase.__init__( self, provider=provider, ...
code_object=code_object, code_prefix="coroutine", flags=flags, auto_release=auto_release, source_ref=source_ref, ) self.needs_generator_return_exit = False self.qualname_setup = None def getFunctionName(self): return self.name ...
xunmengfeng/engine
sky/tools/skypy/url_mappings.py
Python
bsd-3-clause
878
0.009112
# 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. import os class URLMappings(object): def __init__(self, src_root, build_dir): self.mappings = { 'dart:mojo.internal': os.path.join(s...
l.dart'), 'dart:sky': os.path.join(build_dir, 'gen/sky/bindings/dart_sky.dart'), 'dart:sky.internals': os.path.join(src_root, 'sky/engine/bindings/sky_internals.dart'), 'dart:sky_builtin_natives': os.path.join(src_root, 'sky/engine/bindings/builtin_natives.dart'), } s...
% item, self.mappings.items())
practo/federation
manage.py
Python
mit
1,415
0.002827
import urllib from flask import url_for from f
lask_script import Manager, Server, Shell, Command from config.app import create_app from config.db
import db from config.initializers.newrelic_monitoring import NewrelicMonitoring from federation_api.people.model import Person manager = Manager(create_app) server = Server(host='0.0.0.0', port=1786) NewrelicMonitoring(manager.app()) manager.add_command('runserver', server) def _make_context(): models = [Pers...
Spiderlover/Toontown
toontown/effects/Fireworks.py
Python
mit
9,697
0.004744
from direct.interval.IntervalGlobal import * from direct.particles import ParticleEffect from direct.particles import Particles from direct.particles import ForceGroup from pandac.PandaModules import * import random from FireworkGlobals import * colors = {WHITE: Vec4(1, 1, 1, 1), RED: Vec4(1, 0.2, 0.2, 1), BLUE: Vec4...
ter.setEmissionType(BaseParticleEmitter.ETRADIATE) p0.emitter.setAmplitude(0) p0.emitter.setAmplitudeSpread(0) f0 = ForceGroup.ForceGroup('gravity') force0 = LinearSourceForce(Point3(x, y, z), LinearDistanceForce.FTONEOVERR, 0.1, 1.1 * amp, 1) force0.setActive(1) f0.addForc
e(force0) force1 = LinearSinkForce(Point3(x, y, z), LinearDistanceForce.FTONEOVERR, 0.5, 2.0 * amp, 1) force1.setActive(1) f0.addForce(force1) f.addForceGroup(f0) p0.emitter.setRadius(4.0) f.addParticles(p0) f.setPos(x, y, z) f.setHpr(0, random.random() * 180, random.random() * 180) ...
draperlaboratory/user-ale
demo/dashboard/files/twisted_app.py
Python
apache-2.0
7,791
0.005391
# # Copyright 2016 The Charles Stark Draper Laboratory # # 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...
EATE', 5: 'WF_ENRICH', 6: 'WF_TRANSFORM' } def get_allow_origin(request): if 'allow_origin' not in settings or settings['allow_origin'] is None: return '*' elif isinstance(settings['allow_origin'], list): origin = request.getHeader('Origin') return 'null' if origin not in settin...
data) and (data ['useraleVersion'].split('.')[0] == '4'): logger_js.info(simplejson.dumps(data)) elif ('useraleVersion' in data) and (data['useraleVersion'].split('.')[0] == '3'): loggerv3.info(simplejson.dumps(data)) elif ('parms' in data) and ('wf_state' in data['parms']): data['wf_st...
mnubo/kubernetes-py
kubernetes_py/models/v1/DeleteOptions.py
Python
apache-2.0
3,140
0.002866
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is subject to the terms and conditions defined in # file 'LICENSE.md', which is part of this source code package. # import json import yaml from kubernetes_py.utils import is_valid_string class DeleteOptions(object): """ http://kubernetes.io/docs/...
on @api_version.setter def api_version(self, v=0): if not is_valid_string(v): raise SyntaxError("DeleteOptions: api_version: [ {0} ] is invalid.".format(v)) self._kind = v #
------------------------------------------------------------------------------------- grace period seconds @property def grace_period_seconds(self): return self._grace_period_seconds @grace_period_seconds.setter def grace_period_seconds(self, secs=0): if not isinstance(secs, int): ...
nickpack/reportlab
tools/pythonpoint/styles/standard.py
Python
bsd-3-clause
4,262
0.005631
from reportlab.lib import styles from reportlab.lib import colors from reportlab.lib.units import cm from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY from reportlab.platypus import Preformatted, Paragraph, Frame, \ Image, Table, TableStyle, Spacer def getParagraphStyles(): ""...
eBefore = 12 para.bulletFontName = 'Helvetica-BoldOblique' para.bulletFontSize = 24 stylesheet['Definition'] = para para = ParagraphStyle('Code', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.l
eftIndent = 36 stylesheet['Code'] = para para = ParagraphStyle('PythonCode', stylesheet['Normal']) para.fontName = 'Courier' para.fontSize = 16 para.leading = 18 para.leftIndent = 36 stylesheet['PythonCode'] = para para = ParagraphStyle('Small', stylesheet['Normal']) par...
olt/mapproxy
mapproxy/cache/geopackage.py
Python
apache-2.0
27,948
0.003936
# This file is part of the MapProxy project. # Copyright (C) 2011-2013 Omniscale <http://omniscale.de> # 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/LIC...
ITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations und
er the License. import hashlib import logging import os import re import sqlite3 import threading from mapproxy.cache.base import TileCacheBase, tile_buffer, REMOVE_ON_UNLOCK from mapproxy.compat import BytesIO, PY2, itertools from mapproxy.image import ImageSource from mapproxy.srs import get_epsg_num from mapproxy...
orbitfp7/nova
nova/api/ec2/__init__.py
Python
apache-2.0
25,652
0.000039
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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 ...
pache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissi...
om oslo_serialization import jsonutils from oslo_utils import importutils from oslo_utils import netutils from oslo_utils import timeutils import requests import six import webob import webob.dec import webob.exc from nova.api.ec2 import apirequest from nova.api.ec2 import ec2utils from nova.api.ec2 import faults from...
apark263/tensorflow
tensorflow/compiler/tests/image_ops_test.py
Python
apache-2.0
38,279
0.006923
# Copyright 2017 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...
# Convert to HSV and back, as a batch and individually with self.cached_session() as sess: batch0 = array_ops.placeholder(nptype, shape=shape) with self.test_scope(): batch1 = image_ops.rgb_to_hsv(batch0) batch2 = image_ops.hsv_to_rgb(batch1) split0 = array_ops.u...
self.test_scope(): split1 = list(map(image_ops.rgb_to_hsv, split0)) split2 = list(map(image_ops.hsv_to_rgb, split1)) join1 = array_ops.stack(split1) join2 = array_ops.stack(split2) batch1, batch2, join1, join2 = sess.run([batch1, batch2, join1, join2], ...
hcwiley/the-front
the_front/the_front/artist/migrations/0005_auto__del_field_artistmedia_is_default_image__del_field_artistmedia_na.py
Python
gpl-2.0
8,560
0.006075
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'ArtistMedia.is_default_image' db.delete_column(u'artist_artistmedia', 'is_default_image') ...
django.db.models.fields.BooleanField')(default=False), keep_default=False) # Adding field 'ArtistMedia.name' db.add_column(u'artist_artistmedia', 'name', self.gf('django.db.models.fields.CharField')(default='', max_length=100), keep_defa...
elds.CharField')(default='', max_length=255, null=True, blank=True), keep_default=False) # Adding field 'ArtistMedia.full_res_image' db.add_column(u'artist_artistmedia', 'full_res_image', self.gf('django.db.models.fields.files.ImageField')(default='', max_len...
chatelak/RMG-Py
rmgpy/tools/canteraTest.py
Python
mit
3,597
0.020573
import unittest import os import numpy from rmgpy.tools.canteraModel import findIgnitionDelay, CanteraCondition, Cantera from rmgpy.quantity import Quantity import rmgpy class CanteraTest(unittest.TestCase): def testIgnitionDelay(self): """ Test that findIgnitionDelay() works. """ ...
s[i],self.rmg_ctSpecies[i])) def testReactionConversion(self): """ Test that species objects convert properly """ from rmgpy.tools.cantera
Model import checkEquivalentCanteraReaction for i in range(len(self.ctReactions)): self.assertTrue(checkEquivalentCanteraReaction(self.ctReactions[i],self.rmg_ctReactions[i]))
InterestingLab/elasticmanager
cluster/models.py
Python
mit
1,207
0.000829
from django.db import models from django.utils.encoding import python_2_unicode_compatible from elasticsearch import Elasticsearch @python_2_unicode_compatible class ElasticCluster(models.Model): class Meta: db_table = 'cluster_elastic_cluster' # cluster name name = models.CharField(max_length=12...
def address(self): return '{host}:{port}'.format(host=self.hos
t, port=self.port) def client(self, timeout=30): return Elasticsearch(self.address(), timeout=timeout) def info(self): info = self.client().info() ret = { 'cluster_name': info['cluster_name'], 'elasticsearch_version': info['version']['number'], 'luce...
dripton/ampchat
chatserver.py
Python
mit
3,458
0.001446
#!/usr/bin/env python import sys from twisted.protocols import amp from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.python import usage from twisted.cred.checkers import FilePasswordDB from twisted.cred.portal import Portal from twisted.cred import credentials fro...
actory.username_to_protocol: if username != name: self.callRemote(commands.AddUser, user=username) return {} def login_failed(self, failure): raise commands.LoginError("Incorrect username or password") @commands.SendToUsers.responder def send_to_users(self, mess...
username_to_protocol.get(username) if protocol: protocol.callRemote(commands.Send, message=message, sender=self.username) # Also show it to the sender if self.username not in usernames: self.callRemote(commands.Send, message=message, ...
slgphantom/RocketMap
pogom/schedulers.py
Python
agpl-3.0
46,757
0.000021
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Schedulers determine how worker's queues get filled. They control which locations get scanned, in what order, at what time. This allows further optimizations to be easily added, without having to modify the existing overseer and worker thread code. Schedulers will recieve...
timestamp of when the pokemon next a
ppears - disappears_seconds is the unix timestamp of when the pokemon next disappears appears_seconds and disappears_seconds are used to skip scans that are too late, and wait for scans the worker is early for. If a scheduler doesn't have a specific time a location needs to be scanned, it shou...
lczub/TestLink-API-Python-client
test/conftest.py
Python
apache-2.0
2,865
0.008028
#! /usr/bin/python # -*- coding: UTF-8 -*- # Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers # # 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 appl
icable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ---------------------...
mpg-age-bioinformatics/bit
bit/config.py
Python
mit
9,252
0.016105
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import os import sys import getpass from os.path import expanduser import stat import shutil import bit.git as git structure="\n\ /file_system_a\n\ |\n\ '- data\n\ |\n\ '- p...
t_x\n\ | |\n\ | |- results\n\ | |- models\n\ | |- scripts\n\ | |- tmp\n\ | |- slurm_logs\n\ | '- wiki\n\ |\n\ '- Company_B\n\ |\n\ '- CB_p...
path to projects = /file_system_a/data/projects/" requirements=["owncloud_address","owncloud_upload_folder",\ "owncloud_download_folder","owncloud_user",\ "owncloud_pass","github_address",\ "github_organization","github_user",\ "github_pass","local_path", "user_group" ] special_reqs=["owncloud_user","owncloud_pass"...
christoffkok/auxi.0
src/tests.py
Python
lgpl-3.0
2,865
0.000349
#!/usr/bin/env python3 """ This module runs all the tests of the auxi package at once. """ import unittest from auxi.core.objects_test import ObjectUnitTester from auxi.core.objects_test import NamedObjectUnitTester from auxi.core.time_test import ClockUnitTester from auxi.tools.chemistry.stoichiometry_test import S...
IsothermalFlatSurfaceTester from auxi.tools.transportphenomena.dimensionlessquantities_test \ import DimensionlessQiantitiesTester from auxi.modelling.process.materials.chem_te
st \ import ChemMaterialUnitTester, ChemMaterialPackageUnitTester from auxi.modelling.process.materials.thermo_test \ import ThermoMaterialUnitTester # from auxi.modelling.process.materials.thermo_test \ # import ThermoMaterialPackageUnitTester from auxi.modelling.process.materials.psd_test \ import PsdMa...
vim-awesome/vim-awesome
web/api/api.py
Python
mit
7,261
0.001102
import itertools import json import re import flask from flask import request from web.cache import cache import rethinkdb as r import web.api.api_util as api_util import db import util api = flask.Blueprint("api", __name__, url_prefix="/api") r_conn = db.util.r_conn def _should_skip_get_plugins_cache(): ""
"Whether the current request to /api/plugins should not be cached."""
page = int(request.args.get('page', 1)) search = request.args.get('query', '') # Only cache empty searches for now. # TODO(david): Also cache simple category and tag searches. May also want # to actually use a proper cache backend like Redis so we can # arbitrarily cache (right now we ...
endlessm/chromium-browser
native_client/tools/checkdeps/checkdeps.py
Python
bsd-3-clause
17,715
0.008863
#!/usr/bin/env python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that files include headers from allowed directories. Checks DEPS files in the source tree for rules, and applie...
"foobar". self._rules = [x for x in self._rules if n
ot x.ParentOrMatch(rule_dir)] self._rules.insert(0, Rule(add_rule, rule_dir, source)) def DirAllowed(self, allowed_dir): """Returns a tuple (success, message), where success indicates if the given directory is allowed given the current set of rules, and the message tells why if the comparison failed....
hail-is/hail
gear/gear/clients.py
Python
mit
1,942
0.00206
from typing import Optional from gear.cloud_config import get_azure_config, get_gcp_config, get_global_config from hailtop.aiocloud import aioazure, aiogoogle from hailtop.aiotools.fs import AsyncFS, AsyncFSFactory def get_identity_client(credentials_file: Optional[str] = None): if credentials_file is None: ...
cloud == 'gcp', cloud project = get_gcp_config().project return aiogoogle.GoogleIAmClient(project, credentials_file=credentials_file) def get_compute_client(credentials_file: Optional[str] = None): if credentials_file is None: credentials_file = '/gsa-key/key.json' cloud = get_global_config()...
onfig.resource_group) assert cloud == 'gcp', cloud project = get_gcp_config().project return aiogoogle.GoogleComputeClient(project, credentials_file=credentials_file) def get_cloud_async_fs(credentials_file: Optional[str] = None) -> AsyncFS: if credentials_file is None: credentials_file = '/g...
nijinashok/sos
sos/plugins/dbus.py
Python
gpl-2.0
745
0
# This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted materi
al is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General Public License. # # See the LICENSE file in the source distribution for further information. from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin ...
s message bus""" plugin_name = "dbus" profiles = ('system',) packages = ('dbus',) def setup(self): self.add_copy_spec([ "/etc/dbus-1", "/var/lib/dbus/machine-id" ]) # vim: set et ts=4 sw=4 :
ntt-sic/nova
nova/api/openstack/compute/contrib/aggregates.py
Python
apache-2.0
8,962
0.000112
# Copyright (c) 2012 Citrix Systems, 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 ...
) except (exception.AggregateHostExists, exception.InvalidAggregateAction) as e: LOG.info(_('Cannot add host %(host)s in aggregate %(id)s'), {'host': hos
t, 'id': id}) raise exc.HTTPConflict(explanation=e.format_message()) return self._marshall_aggregate(aggregate) @get_host_from_body def _remove_host(self, req, id, host): """Removes a host from the specified aggregate.""" context = _get_context(req) authorize(context...
amcat/amcat-dashboard
dashboard/migrations/0023_auto_20180702_1140.py
Python
agpl-3.0
696
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-07-02 11:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrat
ions.Migration): dependencies = [ ('dashboard', '0022_query_amcat_options'), ] operations = [ migrations.AlterField( model_name='query', name='amcat_query_id', field=models.IntegerField(), ), migrations.AlterUniqueTogether( na...
ry_id')]), ), migrations.AlterModelTable( name='querycache', table=None, ), ]
levilucio/SyVOLT
GM2AUTOSAR_MM/MT_post__indirectLink_S.py
Python
mit
4,553
0.028992
""" __MT_post__indirectLink_S.py_____________________________________________________ Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY) Author: levi Modified: Sun Aug 9 23:46:05 2015 _________________________________________________________________________________ """ from ASGNode import * from...
s MT_post__indirectLink_S(ASGNode, ATOM3Type): def __init__(self, parent = None): ASGNode.__init__(self) ATOM3Type.__init__(self)
self.superTypes = [] self.graphClass_ = graph_MT_post__indirectLink_S self.isGraphObjectVisual = True if(hasattr(self, '_setHierarchicalLink')): self._setHierarchicalLink(False) if(hasattr(self, '_setHierarchicalNode')): self._setHierarchicalNode(False) self.parent = paren...
aerler/WRF-Tools
Python/wrfrun/generateStepfile.py
Python
gpl-3.0
4,142
0.021004
#! /usr/bin/env python # # python script to generate a valid stepfile for WRF cycling # import sys import pandas import calendar filename = 'stepfile' # default filename lleap = True # allow leap days (not used in some GCM calendars) lecho = False lperiod = False dateargs = [] # list of date arguments passed to date_...
to accomodate some GCM calendars elif arg == '-e' or arg == '--echo': lecho = True elif arg == '-h' or arg == '--help': print('') print("Usage: "+sys.argv[0]+" [-e] [-h] [--interval=interval] [--steps=steps] begin-date [end-date]") print(" Interval, begin-date and end-date or steps must be s...
-l | --noleap omit leap days (to accomodate some GCM calendars)") print(" -e | --echo print steps to stdout instead of writing to stepfile") print(" -h | --help print this message") print('') sys.exit(1) else: dateargs.append(arg) # output patterns lmonthly = False dateform = '...
RyanSkraba/beam
sdks/python/apache_beam/runners/dataflow/test_dataflow_runner.py
Python
apache-2.0
4,039
0.003714
# # 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 "License"); you may not us...
unner, self).run_pipeline( pipeline, options) if self.result.has_job: # TODO(markflyhigh)(BEAM-1890): Use print since Nose dosen't show logs # in some cases. print('Worker logs: %s' % self.build_console_url(options)) try: self.wait_until_in_state(PipelineState.RUNNING) if...
if on_success_matcher: from hamcrest import assert_that as hc_assert_that hc_assert_that(self.result, pickler.loads(on_success_matcher)) finally: if not self.result.is_in_terminal_state(): self.result.cancel() self.wait_until_in_state(PipelineState.CANCELLED) return se...
pydanny/django-admin2
example/files/tests/test_models.py
Python
bsd-3-clause
1,470
0
from os import path from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from files.models import CaptionedFile fixture_dir = path.join(path.abspath(path.dirname(__file__)), 'fixtures') class CaptionedFileTestCase(TestCase): def setUp(self): self...
",
publication=path.join('pubtest.txt') ) cf.save() self.assertEqual(CaptionedFile.objects.count(), 2) # Cause setup created one already def test_update(self): self.captioned_file.caption = "I like text files" self.captioned_file.save() cf = CaptionedFil...
pbabik/mainnav-reader
setup.py
Python
bsd-2-clause
1,980
0.002525
#!/usr/bin/env python # -*- coding: utf-8 -*- # # mainnav-reader - Version: 0.5.1 # # Copyright (c) 2009-2013, Dennis Keitzel # 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...
OLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMI
TED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOO...
levilucio/SyVOLT
RSS2ATOM/contracts/unit/HUnitConnectCAG_ConnectedLHS.py
Python
mit
1,301
0.032283
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HUnitConnectCAG_ConnectedLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HUnitConnectCAG_ConnectedLHS """ # Flag this instance as compiled now self.is_compiled...
nel(Channel) node self.add_node() self.vs[0]["MT_pre__attr1"] = """return True""" self.vs[0]["MT_label__"] = """1""" self.vs[0]["mm__"] = """MT_pre__Channel""" self.vs[0]["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'Channel') # Add the edges self.add_edges([ ]) # define evaluation methods for each ma...
return True # define evaluation methods for each match association. def constraint(self, PreNode, graph): return True
Havate/havate-openstack
proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/dashboards/project/vpn/workflows.py
Python
apache-2.0
19,939
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013, Mirantis 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 # #...
[('', _("Select a Subnet"))] try: tenant_id = request.user.tenant_id networks = api.neutron.network_list_for_tenant(request, tenant_id) except Exception: exceptions.handle(request, _('Unable to retrieve networks list.')) n
etworks = [] for n in networks: for s in n['subnets']: subnet_id_choices.append((s.id, s.cidr)) self.fields['subnet_id'].choices = subnet_id_choices return subnet_id_choices def populate_router_id_choices(self, request, context): router_id_choices = [('',...
nzlosh/st2
st2common/tests/unit/test_actionchain_schema.py
Python
apache-2.0
2,701
0.00037
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
in.vars), len(CHAIN_WITH_VARS["vars"])) def test_actionchain_with_publish(self): chain = actionchain.ActionChain(**CHAIN_WITH_PUBLISH) self.assertEqual(len(chain.chain), len(CHAIN_WITH_PUBLISH["chain"])) self.assertEqual(
len(chain.chain[0].publish), len(CHAIN_WITH_PUBLISH["chain"][0]["publish"]) ) def test_actionchain_schema_invalid(self): with self.assertRaises(ValidationError): actionchain.ActionChain(**MALFORMED_CHAIN)
jdavisp3/TigerShark
tigershark/facade/utils.py
Python
bsd-3-clause
88
0.011364
def first(l): try:
return l.pop() e
xcept Exception: return None
endlessm/chromium-browser
tools/grit/grit/tool/interface.py
Python
bsd-3-clause
1,507
0.011944
# Copyright (c) 2012 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. '''Base class and interface for tools. ''' from __future__ import print_function class Tool(object): '''Base class for all tools. Tools should use t...
(self): '''Returns a short description of the functionality of the tool.''' raise NotImplementedError() def Run(self, global_options, my_arguments): '''Runs the tool. Args: global_options: object grit_runner.Options my_arguments: [arg1 arg2 ...] Return: 0 for success, non-0 fo...
ror() # # Base class implementation # def __init__(self): self.o = None def ShowUsage(self): '''Show usage text for this tool.''' print(self.__doc__) def SetOptions(self, opts): self.o = opts def Out(self, text): '''Always writes out 'text'.''' self.o.output_stream.write(text)...
marekpetrik/RAAM
raam/examples/inventory/configuration.py
Python
mit
5,606
0.019265
""" Global configuration for the problem settings """ import numpy as np from scipy import stats horizon = 300 runs = 40 DefaultConfiguration = { "price_buy" : [1.2,2.1,3.3], "price_sell" : [1,2,3], "price_probabilities" : np.array([[0.8, 0.1, 0.1],[0.1, 0.8, 0.1],[0.1, 0.1, 0.8]]), "initial_capacity...
Constructs a definitions with a martingale definition of transition probabilities. The change in price is modeled as a normal distribution with zero mean and the specified variance. The capacity of the battery does in fact change Parameters ---------- prices : array **Sell...
of the normal distribution Returns ------- out : dict Configuration that corresponds to the martingale """ states = len(prices) # defines over how many states the probability is spread over spread = min(5,states-1) if type(prices) is not np.ndarray: pri...
tseaver/google-cloud-python
bigtable/tests/unit/test_instance.py
Python
apache-2.0
37,126
0.001104
# Copyright 2015 Google LLC # # 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, s...
play_name=self.INSTANCE_ID, type=instance_type, labels=self.LABELS, state=state, ) klass = self._get_target_class() instance = klass.from_pb(instance_pb, client) self.assertIsInstance(instance, klass) self.assertEqual(instance._client, client)...
STANCE_ID) self.assertEqual(instance.display_name, self.INSTANCE_ID) self.assertEqual(instance.type_, instance_type) self.assertEqual(instance.labels, self.LABELS) self.assertEqual(instance._state, state) def test_from_pb_bad_instance_name(self): from google.cloud.bigtable_a...
prarthitm/edxplatform
openedx/core/djangoapps/user_api/urls.py
Python
agpl-3.0
1,706
0.001758
""" Defines the URL routes for this app. """ from django.conf import settings from django.conf.urls import patterns, url from ..profile_images.views import ProfileImageView from .accounts.views import AccountDeactivationView, AccountViewSet from .preferences.views import PreferencesView, PreferencesDetailView fr
om .verification_api.views import PhotoVerificationStatusView ME = AccountViewSet.as_view({ 'get': 'get', }) ACCOUNT_LIST = AccountViewSet.as_view({ 'get': 'list', }) ACCOUNT_DETAIL = AccountViewSet.as_view
({ 'get': 'retrieve', 'patch': 'partial_update', }) urlpatterns = patterns( '', url(r'^v1/me$', ME, name='own_username_api'), url(r'^v1/accounts/{}$'.format(settings.USERNAME_PATTERN), ACCOUNT_DETAIL, name='accounts_api'), url(r'^v1/accounts$', ACCOUNT_LIST, name='accounts_detail_api'), url...
daisymax/nvda
source/NVDAObjects/IAccessible/sysTreeView32.py
Python
gpl-2.0
10,467
0.040222
#NVDAObjects/IAccessible/sysTreeView32.py #A part of NonVisual Desktop Access (NVDA) #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2007-2010 Michael Curran <[email protected]>, James Teh <[email protected]> from ctypes import * from ctypes.wintypes...
indowHandle,TVM_MAPHTREEITEMTOACCID,prevItem,0) if not newID: # Tree views from comctl < 6.0 use the hItem as the child ID. newID=prevItem return IAccessible(windowHandle=self.windowHandle,IAccessibleObject=self.IAccessibleObject,IAccessibleChildID=newID) def _get_children(self): children=[] chi...
return 0 childItem=watchdog.cancellableSendMessage(self.windowHandle,TVM_GETNEXTITEM,TVGN_CHILD,hItem) if childItem<=0: return 0 numItems=0 while childItem>0: numItems+=1 childItem=watchdog.cancellableSendMessage(self.windowHandle,TVM_GETNEXTITEM,TVGN_NEXT,childItem) return numItems def...
franklinsales/udacity-data-analyst-nanodegree
project3/class-works/data-wrangling/data-in-more-complex-formats/quiz-extracting-data-corrected.py
Python
mit
1,669
0.001797
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Mar 15 23:06:23 2017 @author: franklin """ # Your task here is to extract data from xml on authors of an article # and add it to a list, one item for an author. # See the provided data structure for the expected format. # The tags for first name, surna...
s def test(): solution = [{'fnm': 'Omer', 'snm': 'Mei-Dan', 'email': '[email protected]'}, {'fnm': 'Mike', 'snm': 'Carmont', 'email': '[email protected]'}, {'fnm': 'Lior', 'snm': 'Laver', 'email': '[email protected]'}, {'fnm': 'Meir', 'snm': 'Nyska', 'email': '[email protected]'}, {'fnm': 'Hagay', 's...
m': 'Kammar', 'email': '[email protected]'}, {'fnm': 'Gideon', 'snm': 'Mann', 'email': '[email protected]'}, {'fnm': 'Barnaby', 'snm': 'Clarck', 'email': '[email protected]'}, {'fnm': 'Eugene', 'snm': 'Kots', 'email': '[email protected]'}] root = get_root(article_file) data = get_author(root) a...
openilabs/falconlab
env/lib/python2.7/site-packages/falcon/cmd/bench.py
Python
mit
944
0
"""Benchmark runner. Copyright 2013 by Rackspace Hosting, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You m
ay obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless requir
ed by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys from falc...
EMS-TU-Ilmenau/fastmat
fastmat/version.py
Python
apache-2.0
245
0
#
-*- coding: utf-8 -*- # This file carries the module's version information which will be updated # during execution of the installation script, setup.py. Distribution tarballs # contain a pre-generated copy of this file. __version__ = '0
.2'
dadavidson/Python_Lab
Python-w3resource/Python_Basic/ex01.py
Python
mit
715
0.00979
# https://www.w3resource.com/python-exe
rcises/ # 1. Write a Python program to print the following string in a specific format (see the output). # Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond # in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output : # Twinkle, tw...
you are string = """ Twinkle, twinkle, little star, \t\tUp above the world so high, \t\tLike a diamond in the sky. Twinkle, twinkle, little star, \tHow I wonder what you are """ print string
inconvergent/differential_ani
differential.py
Python
mit
7,824
0.034126
#!/usr/bin/python # -*- coding: utf-8 -*- import cairo, Image import gtk, gobject from numpy import cos, sin, pi, sqrt, sort, square,array, zeros, diff,\ column_stack,ones, reshape, linspace, arctan2 from numpy import sum as npsum from numpy.random import random, seed from itertools import count ...
nd1,GRO
W_NEAR_LIMIT) #pyx_growth_branch(L,rnd1,rnd2,GROW_NEAR_LIMIT) L.update_zone_maps() if not render.steps%RENDER_ITT: show(render,L) print 'steps:',render.steps,'vnum:',L.vnum,'snum:',L.snum fn = '{:s}_nearl{:0.0f}_itt{:07d}.png' fn = fn.format(FNAME,FARL/ONE,render.steps) ren...
OriHoch/pysiogame
game_boards/game054.py
Python
gpl-3.0
7,891
0.034216
# -*- coding: utf-8 -*- import classes.level_controller as lc import classes.game_driver as gd import classes.extras as ex import classes.board import random import math import pygame class Board(gd.BoardGame): def __init__(self, mainloop, speaker, config, screen_w, screen_h): self.level = lc.Level(self...
.board.Door,"",self.col_k,"",0) self.board.units[-1].image.set_colorkey(None) self.board.add_door(7,0,2,data[1],classes.board.Door,"",self.col_k,"",0) self.board.units[-1].image.set_colorkey(None) for i in [5,6,7,8,9,10,11,12,13]: if i>7: self.board.u...
ey) self.board.all_sprites_list.move_to_back(self.board.units[i]) else: self.board.all_sprites_list.move_to_front(self.board.units[i]) self.canvas.set_outline((255,75,0),1) self.canv = [] for i in range(4): self.canv.append(pyg...
box/ClusterRunner
test/unit/project_type/test_git.py
Python
apache-2.0
13,290
0.004138
from os.path import join, expanduser from subprocess import Popen from unittest import skipIf from unittest.mock import ANY, call, MagicMock, Mock from genty import genty, genty_dataset import re from app.project_type.git import Git from app.util.conf.configuration import Configuration from app.util.process_utils imp...
ile_path_happy_path(self): git_env = Git("ssh://scm.dev.box.net/box/www/current", 'origin', 'refs/changes/78/151978/27') actual_timing_file_sys_path = git_env.timing_file_path('QUnit') expected_timing_file_sys_path = join( Configuration[
'base_directory'], 'timings', 'master', 'scm.dev.box.net', 'box', 'www', 'current', 'QUnit.timing.json', ) self.assertEquals(expected_timing_file_sys_path, actual_timing_file_sys_path) def test_execute_command_in_pr...
JeroenDeDauw/phpstat
src/phpstat/dirinfo.py
Python
gpl-3.0
4,098
0.006833
''' Created on Mar 22, 2011 @author: jeroen ''' import os from fileinfo import FileInfo from bytesize import ByteSize class DirInfo(object): ''' Simple class to represent a directory and obtain data about if when needed. ''' def __init__(self, path, recursive=False): ''' Construc...
it_if_needed() return self._codelines + self._commentlines + self._whitespacelines def get_filecount(self): self._init_if_needed() return self._filecount def get_dirc
ount(self): self._init_if_needed() return self._dircount
luoshao23/ML_algorithm
Decission_Tree/tree.py
Python
mit
7,395
0.002299
from math import log from PIL import Image, ImageDraw my_data = [['slashdot', 'USA', 'yes', 18, 'None'], ['google', 'France', 'yes', 23, 'Premium'], ['digg', 'USA', 'yes', 24, 'Basic'], ['kiwitobes', 'France', 'yes', 23, 'Basic'], ['google', 'UK', 'no', 21, 'Premium'], ...
'UK', 'no', 21, 'Basic'], ['google', 'USA', 'no', 24, 'Premium'], ['slashdot', 'France', 'yes', 19, 'None'], ['digg', 'USA', 'no', 18, 'None'],
['google', 'UK', 'no', 18, 'None'], ['kiwitobes', 'UK', 'no', 19, 'None'], ['digg', 'New Zealand', 'yes', 12, 'Basic'], ['slashdot', 'UK', 'no', 21, 'None'], ['google', 'UK', 'yes', 18, 'Basic'], ['kiwitobes', 'France', 'yes', 19, 'Basic']] class decisionno...
marineam/coil
coil/test/__init__.py
Python
mit
22
0
"""Test
s f
or coil."""
unicef/rhizome
rhizome/tests/test_agg.py
Python
agpl-3.0
38,994
0.001795
from django.contrib.auth.models import User from pandas import read_csv, notnull, DataFrame from numpy import isnan from django.test import TestCase from rhizome.models.campaign_models import Campaign, CampaignType, \ DataPointComputed, AggDataPoint from rhizome.models.location_models import Location, LocationType...
self.campaign_id = Campaign.objects.create( start_date='2016-01-01', end_date='2016-01-0
2', campaign_type_id=campaign_type1.id ).id document = Document.objects.create( doc_title='test', created_by_id=user_id, guid='test') self.ss = SourceSubmission.objects.create( document_id=document.id, submission_json='', ...
thaim/ansible
test/lib/ansible_test/_internal/cloud/aws.py
Python
mit
3,947
0.00228
"""AWS plugin for integration tests.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os from ..util import ( ApplicationError, display, is_shippable, ConfigParser, ) from . import ( CloudProvider, CloudEnvironment, CloudEnvironmentConfig, ...
Provider, self).setup() aws_config_path = os.path.expanduser('~/.aws') if os.path.exists(aws_config_path) and not self.args.docker and not self.args.remote: raise ApplicationError('Rename "%s" or us
e the --docker or --remote option to isolate tests.' % aws_config_path) if not self._use_static_config(): self._setup_dynamic() def _setup_dynamic(self): """Request AWS credentials through the Ansible Core CI service.""" display.info('Provisioning %s cloud environment.' % self....
googleapis/python-service-usage
samples/generated_samples/serviceusage_v1_generated_service_usage_list_services_async.py
Python
apache-2.0
1,497
0.000668
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not
use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS...
r express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for ListServices # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your ...
b0nk/botxxy
src/oauth2.py
Python
gpl-2.0
23,431
0.001536
""" The MIT License Copyright (c) 2007 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the right...
keep_blank_values=False) if not len(params): raise ValueError("Invalid parameter string.") try:
key = params['oauth_token'][0] except Exception: raise ValueError("'oauth_token' not found in OAuth request.") try: secret = params['oauth_token_secret'][0] except Exception: raise ValueError("'oauth_token_secret' not found in " "OAuth request...
torchhound/projects
python/ffi.py
Python
gpl-3.0
264
0
import ct
ypes libc = ctypes.CDLL("/usr/lib/libc.dylib") print(libc.rand()) print(libc.time()) cPrintF = libc.printf value = b"I'm a C function!" print(value) printValue = ctypes.c_char_p(value)
print(printValue.value) print(printValue) cPrintF("%s", printValue)
snim2mirror/openihm
src/openihm/model/database.py
Python
lgpl-3.0
949
0.002107
#!/usr/bin/env python """ A convinience wrapper around mysql connector. This file is part of open-ihm. open-ihm 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 y...
nse along with open-ihm. If not, see <http://www.gnu.org/licenses/>. """ import includes.mysql.connector as connector import data.database #
refactored to remove duplicate code while # providing same interface as before. class Database(data.database.Database): pass
kk1987/pycparser
tests/all_tests.py
Python
bsd-3-clause
294
0.006803
#!/usr/bin/env
python import sys sys.path.extend(['.', '..']) import unittest suite = unittest.TestLoader().loadTestsFromNames( [ 'test_c_lexer', 'test_c_ast', 'test_general', 'test_c_parser',
] ) unittest.TextTestRunner(verbosity=1).run(suite)
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/hostname/__init__.py
Python
apache-2.0
11,660
0.001286
# -*- coding: utf-8 -*- from operator import
attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtyp
es import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3...
ghaskins/obc-peer
openchain/peer/bddtests/environment.py
Python
apache-2.0
1,357
0.034635
from steps.bdd_test_util import cli_call def after_scenario(context, scenario): if 'doNotDecompose' in scenario.tags: print("Not going to decompose after scenario {0}, with yaml '{1}'".format(scenario.name, context.compose_yaml)) else: if 'compose_yaml' in context: print("Decomposing with yaml '{0}' after sc...
pose_output, context.compose_error, context.compose_returncode = \ cli_call(context, ["docker-compose", "-f", context.compose_yaml, "rm","-f"], expect_success=True) # now remove any other containers (chaincodes) context.compose_output, context.compose_error, context.compose_returncode = \ ...
Remove each container for containerId in context.compose_output.splitlines(): #print("docker rm {0}".format(containerId)) context.compose_output, context.compose_error, context.compose_returncode = \ cli_call(context, ["docker", "rm", containerId], expect_succes...
sid88in/incubator-airflow
airflow/utils/dates.py
Python
apache-2.0
9,508
0.000947
# -*- coding: utf-8 -*- # # 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 #...
re(datetime.min)): """ Returns the datetime of the form start_date + i * delta which is closest to dt for any non-negative integer i. Note that delta may be a datetime.timedelta or a dateutil.relativedelta >>> round_time(datetime(2015, 1, 1, 6), timedelta(days=1)) datetime.datetime(2015, 1, 1, 0...
datetime.datetime(2015, 1, 1, 0, 0) >>> round_time(datetime(2015, 9, 16, 0, 0), timedelta(1), datetime(2015, 9, 14, 0, 0)) datetime.datetime(2015, 9, 16, 0, 0) >>> round_time(datetime(2015, 9, 15, 0, 0), timedelta(1), datetime(2015, 9, 14, 0, 0)) datetime.datetime(2015, 9, 15, 0, 0) >>> round_time...
LockScreen/Backend
venv/lib/python2.7/site-packages/awscli/customizations/cloudsearchdomain.py
Python
mit
1,074
0.000931
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
IS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, ei
ther express or implied. See the License for the specific # language governing permissions and limitations under the License. """Customizations for the cloudsearchdomain command. This module customizes the cloudsearchdomain command: * Add validation that --endpoint-url is required. """ def register_cloudsearchd...
dspaccapeli/bus-arrival
visualization/plot_delay_evo.py
Python
gpl-3.0
1,979
0.016675
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Description: Plot the delay evolution during a run for multiple ones having the run_time (in seconds) shown on the X axis. @author: dspaccapeli """ #imports to manage the sql db import sqlite3 as lite import pandas as pd #to make the plot show-up from command l...
uffle(unq_dep) i=0 for x in unq_dep: i+=1 #for each run_code temp = df[df['begin'] == x] #plot evolution of the delay plt.plot(temp['time'], temp['delay'], alpha=0.6) #plt.scatter(temp['time'], temp['delay'], alpha=0.7) #up to a max of
5 lines if i==10: break plt.suptitle('Delay progression between %s and %s during the week' % (hh_start, hh_end)) plt.xlabel('run time') plt.ylabel('delay') plt.savefig(str(count), ext="png") plt.clf() #uncomment if you want to do it cumulatively #plt.suptitle('Delay progressio...
UnrememberMe/pants
contrib/node/src/python/pants/contrib/node/subsystems/package_managers.py
Python
apache-2.0
8,798
0.007729
# coding=utf-8 # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging from...
ype_option) package_version_option = { PackageInstallationVersionOption.EXACT: '--exact', PackageInstalla
tionVersionOption.TILDE: '--tilde', }.get(version_option) if package_version_option is None: LOG.warning( '{} does not support install with {} version, ignored'.format(self.name, version_option)) elif package_version_option: # Skip over '' entries return_args.append(package_version_optio...
darrenbilby/grr
lib/plist.py
Python
apache-2.0
5,402
0.004813
#!/usr/bin/env python """Shared classes between the client and the server for plist parsing.""" import calendar import datetime from binplist import binplist from grr.lib import lexer from grr.lib import objectfilter class PlistFilterParser(objectfilter.Parser): """Plist specific filter parser. Because we wil...
ttr_name, None) except AttributeError: # This is no dictionary... are we a list of dictionaries? return [item.get(attr_name, None) for item in obj] def _AtNonLeaf(self, attr_value, path): """Makes dictionaries expandable when dealing with plists.""" if isinstance(attr_value, dict): for ...
ld v class PlistFilterImplementation(objectfilter.BaseFilterImplementation): FILTERS = {} FILTERS.update(objectfilter.BaseFilterImplementation.FILTERS) FILTERS.update({"ValueExpander": PlistExpander}) def PlistValueToPlainValue(plist): """Takes the plist contents generated by binplist and returns a plain di...
leovoel/glc.py
examples/custom_rendering.py
Python
mit
473
0.002114
from math imp
ort cos, sin, pi from example_util import get_filename from glc import Gif def draw(l, surf, ctx, t): xpos = cos(t * 2 * pi) * 100 + surf.get_width() * 0.5 ypos = sin(t * 2 * pi) * 100 + surf.get_height() * 0
.5 w, h = 100, 100 ctx.set_source_rgb(0, 0, 0) ctx.translate(xpos, ypos) ctx.translate(-w * 0.5, -h * 0.5) ctx.rectangle(0, 0, w, w) ctx.fill() with Gif(get_filename(__file__), after_render=draw) as a: a.save()
sbrichards/rockstor-core
src/rockstor/storageadmin/views/share_iscsi.py
Python
gpl-3.0
4,001
0.00025
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 la...
v_name=dev_name, dev_size=options['dev_size']) iscsi_target.save() iscsi_serializer = IscsiSerializer(iscsi_target) return Re
sponse(iscsi_serializer.data) except Exception, e: handle_exception(e, request) @transaction.commit_on_success def delete(self, request, sname): try: share = Share.objects.get(name=sname) iscsi_target = IscsiTarget.objects.get(share=share) iscsi_...
arnovich/core
test/yahoo/py/extract_to_srv.py
Python
bsd-3-clause
2,381
0.025619
# small script for from optparse import OptionParser import sqlite3 import time import string import arnovich.core as core def parse_command_args(): parser = OptionParser() parser.add_option("-t", "--ticker", action="append", type="string", dest="tickers") parser.add_option("--from", action="store", type="string...
icker srv_id = connection.add_ticker(str(ticker_id[1])) srv_id_opt = connection.add_ticker(str(ticker_id[1])+"_options") if (fromdate == "") or (todate == ""): d.execute("select date, data from stocks_data where ticker_id="+str(ticker_id[0])+" ORDER BY date") else: d.execute("select date, data from stocks...
data = str(r[1]) rowtime = float(r[0]) if prevtime == 0: prevtime = rowtime connection.push_ticker(srv_id, rowdata) vcursor = conn.cursor() vcursor.execute("select data from options_data where ticker_id="+str(ticker_id[0])+" and date="+rowdate) for row in vcursor: connection.push_ticker(srv_id...
saai/codingbitch
twoPointers/minSubArrayLen.py
Python
mit
623
0.008026
class Solution: # @param {integer} s # @param {integer[]} nums # @return {integer} def minSubArrayLen(self, s, nums): i
= 0 j = -1 n = len(nums) t = 0 min_len = sys.maxint while(i<n and j <n): if t < s: j += 1 if j >=n : break t += nums[j] else: if min_len > (j-i+1): min_...
i += 1 if min_len == sys.maxint: return 0 else: return min_len
trueneu/swiss-knife
swk_plugins/swk_casp/swk_casp/version.py
Python
gpl-3.0
24
0
__v
ersion__ = "0.0.2a3"
mattjj/pyhsmm-autoregressive
autoregressive/util.py
Python
gpl-2.0
1,782
0.016835
from __future__ import division import numpy as np from numpy.lib.stride_tricks import as_strided as ast ### striding data for efficient AR computations def AR_striding(data,nlags): # I had some trouble with views and as_strided, so copy if
not contiguous data = np.asarray(data) if not data.flags.c_contiguous: data = data.copy(order='C') if data.ndim == 1: data = np.reshape(data,(-1,1)) sz = data.dtype.itemsize return ast( data, shape=(data.shape[0]-nlags,data.shape[1]*(nlags+1)), str...
a,nlags): sz = strided_data.dtype.itemsize return ast( strided_data, shape=(strided_data.shape[0]+nlags,strided_data.shape[1]//(nlags+1)), strides=(strided_data.shape[1]//(nlags+1)*sz,sz)) ### analyzing AR coefficient matrices def canonical_matrix(A): # NOTE: throws awa...
samueljackson92/metaopt
python_tests/simulated_annealing_test.py
Python
mit
1,038
0.000963
import unittest import numpy as np import
pyoptima as opt class SimulatedAnnealingTest(unittest.TestCase): def test_with_parabola(self): """ Test with a simple parabolic function with 2 variables """ def neighbour_func(params):
new_params = params params['x0'] += np.random.uniform(-1., 1.) params['x1'] += np.random.uniform(-1., 1.) return new_params hyper_params = { 'temperature_func': lambda t, i: t/np.log(i+2), 'neighbour_func': neighbour_func, 'initia...
angr/angr
tests/test_strcasecmp.py
Python
bsd-2-clause
780
0.00641
import angr import claripy import os test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests') def test_i386(): p = angr.Project(os.path.join(test_location, 'i386', 'test_strcasecmp'), auto_lo
ad_libs=False) arg1 = claripy.BVS('arg1', 20*8) s = p.factory.entry_state(args=("test_strcasecmp", arg1)) sm = p.factory.simulation_manager(s) sm.ex
plore() sm.move('deadended', 'found', filter_func=lambda s: b"Welcome" in s.posix.dumps(1)) assert len(sm.found) == 1 f = sm.found[0] sol = f.solver.eval(arg1, cast_to=bytes) assert b'\x00' in sol assert sol[:sol.index(b'\x00')].lower() == b'letmein' assert b'wchar works' in f.posix.dumps...
lowellbander/ngVote
priorityDB/priorityDB/admin.py
Python
gpl-2.0
418
0.014354
from d
jango.contrib import admin from priorityDB.models import * # Register your models here # For more information on this file, see # https://docs.djangoproject.com/en/dev/intro/tutorial02/ class TaskHistoryInline(admin.StackedInline): model = TaskHistory extra = 0 class EventAdmin(admin.ModelAdmin): inlin...
ter(Event, EventAdmin) admin.site.register(Task)
gomezsan/ochopod
examples/sanity.py
Python
apache-2.0
2,544
0.003931
# # Copyright (c) 2015 Autodesk 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 l...
ware # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ This script illustrates how we handle process level sanity che...
nt ochopod to know what you're running is healthy. You could curl the process or run some script for instance. Too many sanity check failures will turn the pod off (which can be seen in the CLI for instance). Just start a local standalone Zookeeper server and run "python sanity.py". """ from ochopod.bindings.generic....
workbandits/gamerocket-python-guide
1_create_player/src/app.py
Python
mit
837
0.016726
import gamerocket from flask import Flask, request, render_template app = Flask(__name__) gamerocket.Configuration.configure(gamerocket.Environment.Development, apiKey = "your_
apiKey", secretKey = "your_secretKey") @app.route("/") def form(): return render_template("form.html") @app.route("/create_player", met
hods=["POST"]) def create_player(): result = gamerocket.Player.create({ "name":request.form["name"], "locale":request.form["locale"] }) if result.is_success: return "<h1>Success! Player ID: " + result.player.id + "</h1>" else: return "<h1>Error " + result.error + ": ...
nyu-dl/WebNav
simple_parser.py
Python
bsd-3-clause
399
0.010025
''' Simple parse
r that extracts a webpage's content and hyperlinks. ''' import urllib2 import re class Parser(): def __init__(self): pass def parse(self, url):
f = urllib2.urlopen(url) text = f.read() # get page's contents. #use re.findall to get all the links links = re.findall('href=[\'"]?([^\'" >]+)', text) return text, links
nathanbjenx/cairis
cairis/core/ResponseParameters.py
Python
apache-2.0
1,469
0.008169
# 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 # "License"); you may...
espRisk,tags,cProps,rType): ObjectCreationParameters.ObjectCreationParameters.__init__(self) self.theName = respName self.theTags = tags self.theRisk = respRisk self.theEnvironmentProperties = cProps self.theResponseType = rType def name(self): return self.theName def tags(self): return sel...
ype
Azure/azure-sdk-for-python
sdk/synapse/azure-mgmt-synapse/azure/mgmt/synapse/operations/_spark_configuration_operations.py
Python
mit
6,172
0.004213
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
200]: map_error(status_code=response.status_code, res
ponse=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('SparkConfigurationResource', pipeline_resp...
scaphe/lettuce-dirty
tests/integration/django/couves/leaves/views.py
Python
gpl-3.0
872
0.001148
# -*- coding: utf-8 -*- # <Lettuce - Behaviour Driven Development for python> # Copyright (C) <2010-2011> Gabriel Falcão <[email protected]> # # This program is free software: you can redistribute it and/or modify # it
under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is dist
ributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If...
KAMI911/loec
examples/Sharpen/binaries-windows-python26/PcfFontFile.py
Python
gpl-3.0
6,642
0.004968
# # THIS IS WORK IN PROGRESS # # The Python Imaging Library # $Id: PcfFontFile.py 2134 2004-10-06 08:55:20Z fredrik $ # # portable compiled font file parser # # history: # 1997-08-19 fl created # 2003-09-13 fl fixed loading of unicode fonts # # Copyright (c) 1997-2003 by Secret Labs AB. # Copyright (c)...
pad data = fp.read(i32(fp.read(4))) for k, s, v in p: k = sz(data, k) if s: v = sz(data, v) properties[k] = v
return properties def _load_metrics(self): # # font metrics metrics = [] fp, format, i16, i32 = self._getformat(PCF_METRICS) append = metrics.append if (format & 0xff00) == 0x100: # "compressed" metrics for i in range(i...