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
avian2/jsonmerge
tests/test_jsonmerge.py
Python
mit
69,662
0.001349
# vim:ts=4 sw=4 expandtab softtabstop=4 import unittest import warnings from collections import OrderedDict import jsonmerge import jsonmerge.strategies from jsonmerge.exceptions import ( HeadInstanceError, BaseInstanceError, SchemaError ) from jsonmerge.jsonvalue import JSONValue import jsonschema try: ...
': "b"}, schema) self.assertEqual(base, {'a': "b"}) def test_merge_objclass(self): schema = {'mergeStrategy': 'objectMerge', 'mergeOptions': { 'objClass': 'OrderedDict'
}} merger = jsonmerge.Merger(schema) base = None base = merger.merge(base, OrderedDict([('c', "a"), ('a', "a")])) self.assertIsInstance(base, OrderedDict) self.assertEqual([k for k in base], ['c', 'a']) base = merger.merge(base, {'a': "b"}) self.assertIsInstanc...
puhoy/storedDict
storedDict/storedDict.py
Python
mit
2,106
0.001425
import json import logging class AutoVivification(dict): """Implementation of perl's autovivification feature. based on http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python """ def __init__(self, storedDict, **kwargs): super(AutoVivification,...
super(StoredDict,self).__init__({}) except IOError as e: logging.info('new file') super(StoredDict, self).__init__({}) def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: self[item] = AutoVivification(...
urn self[item] def __setitem__(self, key, value): super(StoredDict, self).__setitem__(key, value) if self.autocommit: self.commit() def commit(self, indent=None): try: with open(self.filename, 'w+') as f: json.dump(self, f, indent=indent) ...
robclark/shadertoy-render
shadertoy-render.py
Python
bsd-3-clause
7,005
0.004711
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015, Alex J. Champandard # Copyright (c) 2015, Vispy Development Team. # Copyright (c) 2015, Rob Clark # # Distributed under the (new) BSD License. from __future__ import (unicode_literals, print_function) import sys import argparse import datetime impor...
px, self.size[1] - py) self.program['iMouse'] = imouse def on_timer(self, event): self.update() def on_resize(self, event): self.activate_zoom() def activate_zoom(sel
f): gloo.set_viewport(0, 0, *self.physical_size) self.program['iResolution'] = (self.physical_size[0], self.physical_size[1], 0.) if __name__ == '__main__': vispy.set_log_level('WARNING') vispy.use(app='glfw') parser = argparse.ArgumentParser(description='Render a ShaderToy script.') ...
scripnichenko/nova
nova/api/openstack/compute/legacy_v2/versions.py
Python
apache-2.0
1,026
0
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this f
ile except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-
2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # un...
coursemdetw/2014django
wsgi/openshift/settings.py
Python
gpl-2.0
2,745
0.00147
""" Django settings for openshift project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) ...
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(os.environ['OPENSHIFT_
DATA_DIR'], 'db.sqlite3'), } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIM...
bashtage/statsmodels
statsmodels/tsa/base/prediction.py
Python
bsd-3-clause
6,163
0
import numpy as np import pandas as pd from scipy import stats class PredictionResults(object): """ Prediction results Parameters ---------- predicted_mean : {ndarray, Series, DataFrame} The predicted mean values var_pred_mean : {ndarray, Series, DataFrame} The variance of the...
im == 1: values = np.sqrt(self._var_pred_mean) elif ndim == 3: values = np.sqrt(self._var_pred_mean.T.diagonal()) else: raise NotImplementedError
("var_pre_mean must be 1 or 3 dim") return self._wrap_pandas(values, "mean_se") @property def tvalues(self): """The ratio of the predicted mean to its standard deviation""" val = self.predicted_mean / self.se_mean if isinstance(val, pd.Series): val.name = "tvalues" ...
orvi2014/kitsune
kitsune/forums/forms.py
Python
bsd-3-clause
3,129
0
from django import forms from tower import ugettext_lazy as _lazy from kitsune.forums.models import Thread, Post from kitsune.sumo.form_fields import StrippedCharField MSG_TITLE_REQUIRED = _lazy(u'Please provide a title.') MSG_TITLE_SHORT = _lazy( u'Your title is too short (%(show_value)s characters). It must b...
80}), error_messages={'required': MSG_CONTENT_REQUIRED, 'min_length': MSG_CO
NTENT_SHORT, 'max_length': MSG_CONTENT_LONG}) class Meta: model = Post fields = ('content', ) class NewThreadForm(forms.Form): """Form to start a new thread.""" title = StrippedCharField(min_length=5, max_length=255, widget=forms.TextI...
RokKos/FRI_Programiranje
OUI/planet-lia/rokkos/core/bot.py
Python
mit
112
0
class Bot: def setup(self, initi
al_d
ata): pass def update(self, state, response): pass
AstroPrint/AstroBox
src/astroprint/network/mac_dev.py
Python
agpl-3.0
5,835
0.033248
# coding=utf-8 __author__ = "Daniel Arroyo <daniel@astroprint.com>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' import logging import threading import time import os from octoprint.server import eventManager from octoprint.events import Events from octoprint.settings import...
rue eventManager.fire(Events.NETWORK_STATUS, 'online') def _goOffline(sel
f): self._online = False eventManager.fire(Events.NETWORK_STATUS, 'offline') def _setActiveWifi(self, network): self.logger.info("Selected WiFi: %s" % network['name']) for n in self._storedWiFiNetworks: n['active'] = False self._storedWiFiNetworks.append({ 'id': network['id'], 'name': network['nam...
digwiz/engrss
write_rss_xml.py
Python
mit
1,634
0.002448
import os from lxml import etree # write_rss_xml writes name and date data for podcast RSS feeds to XML files # contained in the relative path ./feeds. It is currently assumed that each # podcast will have its data stored in a separate file. def write_rss_xml( feed, feed_url, latest_title, latest_date ):
# the function currently assumes that the storage location will be file_path = "feeds" feed_name = feed file_name = feed_name + "_rss.xml" # Open the file to write binary data. write_rss_xml will currently only # operate by re-writing the xml file every time; this will be improved in # a later ...
podcast") # subElements of root. Right now there should only be four of these, # corresponding to the podcast name, feed url, latest episode name, and # latest episode date. pageElement = etree.SubElement(root, "name").text = feed_name pageElement = etree.SubElement(root, "url"...
cournape/numscons
numscons/scons-local/scons-local-1.2.0/SCons/Tool/m4.py
Python
bsd-3-clause
2,350
0.004255
"""SCons.Tool.m4 Tool-specific initialization for m4. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # Permissio...
re is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EX
PRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT O...
RedhawkSDR/integration-gnuhawk
components/conjugate_cc/tests/test_conjugate_cc.py
Python
gpl-3.0
4,067
0.006885
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by ...
e # Foundation, either version 3 of the License, or (at your option) any later # version. # # GNUHAWK is distr
ibuted 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. I...
deapplegate/wtgpipeline
dump_cat_filters.py
Python
mit
3,166
0.00916
#!/usr/bin/env python ######################### # Read a catalog, and dump all filters that match # Instrum-config-chipid-filter pattern ######################### import utilities, sys, ldac, re from optparse import OptionParser ########################## __cvs_id__ = "$Id: dump_cat_filters.py,v 1.6 2010-10-05 ...
ilters(cat, appendAppers = False): filters = [] for fluxkey in cat.keys(): filter = extractFilter(fluxkey) if _isNotValidFilter(filter): print "_isNotValidFilter" continue print "filter=",filter," fluxkey=",fluxkey if appendAppers: nApers ...
for i in xrange(nApers): filter = '%s_A%d' % (filter, i) if filter not in filters: filters.append(filter) elif filter not in filters: filters.append(filter) return filters #cat1 = ldac.openObjectFile(fl1) #cat2 = ldac.openObjectFile(fl2) #a...
MounirMesselmeni/django
django/contrib/admin/sites.py
Python
bsd-3-clause
21,392
0.001309
from functools import update_wrapper from django.apps import apps from django.conf import settings from django.contrib.admin import ModelAdmin, actions from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django.core.urlresolvers import NoRe...
red( "Put 'django.contrib.admin' in your INSTALLED_APPS " "setting in order to use the admin application.") if not apps.is_installed('django.contrib.contenttypes'): raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS "...
engine = Engine.get_default() except Exception: # Skip this non-critical check: # 1. if the user has a non-trivial TEMPLATES setting and Django # can't find a default template engine # 2. if anything goes wrong while loading template engines, in # ...
3dfxsoftware/cbss-addons
webdemo/__init__.py
Python
gpl-2.0
16
0.0625
#i
mpor
t webdemo
viliusl/dockery
objects/myparser.py
Python
apache-2.0
246
0.01626
import sys, argparse class MyParser(
argparse.ArgumentParser): def error(self, message): '''Wraps error and prints in a shorter way''' sys.stderr.write('error: %s\n' % message)
#self.print_help() sys.exit(2)
cinepost/Copperfield_FX
copper/core/parameter/parameter.py
Python
unlicense
6,311
0.036286
import logging from PyQt5 import QtCore from collections import OrderedDict from copper.core.utils.copper_string import CopperString from .parm_template import ParmTemplate, ParmLookScheme, ParmNamingScheme, ParmTemplateType, StringParmType logger = logging.getLogger(__name__) CopperLinear = 0 CopperBezier = 2 #C...
n needed, because some parameter was changed def setKeyfram
e(self, keyframe): self.__keyframes__.append(keyframe) #def __str__(self): # return self.value
Azure/azure-sdk-for-python
sdk/storage/azure-storage-queue/tests/settings/settings_fake.py
Python
mit
647
0
# ------------------------------------------------------------------------- # C
opyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------
------------ STORAGE_ACCOUNT_NAME = "fakename" STORAGE_ACCOUNT_KEY = "fakekey" TENANT_ID = "00000000-0000-0000-0000-000000000000" CLIENT_ID = "00000000-0000-0000-0000-000000000000" CLIENT_SECRET = "00000000-0000-0000-0000-000000000000" ACCOUNT_URL_SUFFIX = 'core.windows.net' RUN_IN_LIVE = "False" SKIP_LIVE_RECORDING...
viblo/pymunk
pymunk/pyglet_util.py
Python
mit
8,494
0.001766
# ---------------------------------------------------------------------------- # pymunk # Copyright (c) 2007-2016 Victor Blomqvist # # 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 with...
>>> s = pymunk.Space() >>> options = pymunk.pyglet_util.DrawOptions(batch=my_batch) >>>
s.debug_draw(options) >>> my_batch.draw() See pyglet_util.demo.py for a full example :Param: kwargs : You can optionally pass in a pyglet.graphics.Batch If a batch is given all drawing will use this batch to draw on. If no batch i...
izberg-marketplace/django-izberg
django_iceberg/templatetags/iceberg.py
Python
mit
1,539
0.005198
# -*- coding: utf-8 -*- import json from django import template from django.conf import settings register = template.Library() from django_iceberg.auth_utils import init_iceberg @register.inclusion_tag('django_iceberg/javascript_sdk.html', takes_context=True) def iceberg_javascript_sdk(context): """ To Fi...
['request']) if hasattr(api_handler, '_sso_response'): return { 'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE, "sso_data": json.dumps(api_handler._sso_response) } else: return {} @register.inclusion_tag('django_iceberg/sso.html', takes_context=...
it_iceberg(context['request']) if hasattr(api_handler, '_sso_response'): return { "modules": json.dumps(['client', 'seller']), 'appNamespace': api_handler.conf.ICEBERG_APPLICATION_NAMESPACE, "sso_data": json.dumps(api_handler._sso_response), "seller": json.du...
zsiki/ulyxes
pyapi/angle.py
Python
gpl-2.0
7,587
0.002636
#!/usr/bin/python # -*- coding: UTF-8 -*- """ .. module:: angle.py :platform: Unix, Windows :synopsis: Ulyxes - an open source project to drive total stations and publish observation results. GPL v2.0 license Copyright (C) 2010- Zoltan Siki <siki.zoltan@epito.bme.hu> .. moduleauthor:: dr. Zoltan ...
:returns: difference of the two angles (Angle) """ return Angle(self.value - a.GetAngle('RAD'), 'RAD') def __isub__(self, a): """ substract an agle from current :param a: Angle to substract """ self.value -=
a.GetAngle('RAD') return self if __name__ == "__main__": a = Angle(-0.01112, "DEG") print(a.GetAngle("DMS")) a1 = Angle("204-55-28", "DMS") print(a1.GetAngle('DMS')) a1 += Angle(180, 'DEG') print(a1.Normalize().GetAngle('DMS')) a2 = Angle('280-03-24', 'DMS') print(a2.GetAngle('...
c2corg/v6_api
c2corg_api/models/common/sortable_search_attributes.py
Python
agpl-3.0
4,890
0
# coding: utf-8 # enum mappers: To be able to search e.g. a route with a rating between # 'AD' an
d 'ED', certain enum values are converted to integers using the # mappers listed below, and stored as number in ElasticSearch. This allows # to do range queries. sortable_quality_types = { 'empty': 0, 'draft': 1,
'medium': 2, 'fine': 3, 'great': 4 } sortable_access_times = { '1min': 0, '5min': 1, '10min': 2, '15min': 3, '20min': 4, '30min': 5, '45min': 6, '1h': 7, '1h30': 8, '2h': 9, '2h30': 10, '3h': 11, '3h+': 12 } sortable_climbing_ratings = { '2': 0, '...
briancurtin/python-openstacksdk
openstack/cluster/v1/_proxy.py
Python
apache-2.0
52,340
0.000611
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
node as _node from openstack.cluster.v1 import policy as _policy from openstack.cluster.v1 import policy_type as _policy_type from openstack.cluster.v1 import profile as _profile from openstack.cluster.v1 import profile_type as _profile_type from openstack.cluster.v1 import receiver as _receiver from openstack.cluster...
f get_build_info(self): """Get build info for service engine and API :returns: A dictionary containing the API and engine revision string. """ return self._get(build_info.BuildInfo, requires_id=False) def profile_types(self, **query): """Get a generator of profile types. ...
s0x90/python-mailchimp
mailchimp3/entities/template.py
Python
mit
887
0.001127
from ..baseapi import BaseApi class Template(BaseApi): def __init__(self, *args, **kwargs): super(Template, self).__init__(*args, **kwargs) se
lf.endpoint = 'templates' self.list_id = None def all(self): """ returns a list of available template
s. """ return self._mc_client._get(url=self.endpoint) def get(self, template_id): """ returns a specific template. """ return self._mc_client._get(url=self._build_path(template_id)) def update(self, template_id, data): """ updates a specific temp...
endlessm/chromium-browser
third_party/angle/src/libANGLE/gen_overlay_widgets.py
Python
bsd-3-clause
11,216
0.002496
#! /usr/bin/python # Copyright 2019 The ANGLE Project Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # gen_overlay_widgets.py: # Code generation for overlay widgets. Should be run when the widgets declaration file, # overlay_widg...
dget.negative_alignment[0] is_top_aligned = not widget.negative_alignment[1] # We have offset_x, offset_y, width and height which together determine the bounding box. If # offset_x_is_left, the bounding box X would be in [offset_x, offset_x + width], otherwise it # would be in [offset_x - width, offse...
ean aligned to the right side of the screen, we need to make s
camilonova/django
tests/gis_tests/relatedapp/tests.py
Python
bsd-3-clause
14,177
0.001904
from django.contrib.gis.db.models import Collect, Count, Extent, F, Union from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import over...
ctually correspond to the centroid of the border. c1 = b1.centroid c2 = c1.transform(2276, clone=True) Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1) # Should return the second Parcel, which has the center within the # border. ...
len(qs)) self.assertEqual('P2', qs[0].name) if connection.features.supports_transform: # This time center2 is in a different coordinate system and needs # to be wrapped in transformation SQL. qs = Parcel.objects.filter(center2__within=F('border1')) self....
materialsproject/MPContribs
mpcontribs-io/mpcontribs/io/core/components/sdata.py
Python
mit
1,600
0.00125
# -*- coding: utf-8 -*- from mpcontribs.io.core import mp_level01_titles from mpcontribs.io.core.recdict import RecursiveDict from IPython.display import display_html class Structures(RecursiveDict): """class to hold and display list of pymatgen structures for single mp-id""" def __init__(self, content): ...
cursiveDict): """class to hold and display all pymatgen structures in MPFile""" def __init__(s
elf, document): super(StructuralData, self).__init__( (identifier, Structures(content)) for identifier, content in document.items() ) def _ipython_display_(self): for identifier, sdata in self.items(): if identifier != mp_level01_titles[0] and sdata: ...
pinterest/kingpin
kingpin/kazoo_utils/utils.py
Python
apache-2.0
1,118
0
#!/usr/bin/python # # Copyright 2016 Pinterest, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
hostname() def _escape_path_for_stats_name(path): # Do some formatting the file path. if path is None: return None if path.startswith("/"): path = path[1:] return path.replace("/", "_") class DummyStatsdClient: def __init__(self, *args, **kwar
gs): pass def increment(self, stats, sample_rate=1, tags={}): pass def gauge(self, stats, value, sample_rate=1, tags={}): pass dummy_statsd = DummyStatsdClient()
cloudbase/neutron-virtualbox
neutron/extensions/l3agentscheduler.py
Python
apache-2.0
7,118
0
# Copyright (c) 2013 OpenStack Foundation. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
smethod def get_name(cls): return "L3 Agent Scheduler" @classmethod def get_alias(cls): return constants.L3_AGENT_SCHEDULER_EXT_ALIAS @classmethod def get_descripti
on(cls): return "Schedule routers among l3 agents" @classmethod def get_namespace(cls): return "http://docs.openstack.org/ext/l3_agent_scheduler/api/v1.0" @classmethod def get_updated(cls): return "2013-02-07T10:00:00-00:00" @classmethod def get_resources(cls): ...
hoechenberger/psychopy
psychopy/misc.py
Python
gpl-3.0
1,519
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2018 Jonathan Peirce # Distributed under the terms of the GNU General Public License (GPL). """Wrapper for all miscellaneous functions and classes from psychopy.tools """ # pylint: disable=W0611 # W0611 = Unused import %s f...
extendArr, makeRadialMatrix, ratioRange, shuffleArray, val2array) from psychop
y.tools.attributetools import (attributeSetter, setAttribute, logAttrib) from psychopy.tools.colorspacetools import (dkl2rgb, dklCart2rgb, hsv2rgb, lms2rgb, rgb2dklCart, rgb2lms) from psy...
cangencer/hazelcast-python-client
hazelcast/protocol/codec/queue_is_empty_codec.py
Python
apache-2.0
1,041
0.000961
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.queue_message_type import * REQUEST_TYPE = QUEUE_ISEMPTY RESPONSE_TYPE = 101 RETRYABLE = Fa...
0 data_s
ize += calculate_size_str(name) return data_size def encode_request(name): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str...
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Tools/Scripts/webkitpy/common/system/executive_mock.py
Python
gpl-3.0
7,994
0.001251
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
self._should_throw_when_run.intersection(args): raise ScriptError("Exception for %s" % args, output="MOCK command output") if self._should_throw: raise ScriptError("MOCK ScriptError", output=self._output) if return_exit_code and self.
_should_return_zero_when_run.intersection(args): return 0 return self._output def cpu_count(self): return 2 def kill_all(self, process_name): pass def kill_process(self, pid): pass def popen(self, args, cwd=None, env=None, **kwargs): assert all(is...
laurentluce/lfu-cache
lfucache/test/all_tests.py
Python
mit
539
0.001855
"""Run all of the tests.""" import sys import unittest2 as unittest def main(args=None): unittest_dir = '.' unittest_suite = unittest.defaultTestLoader.discover(unittest_dir) kwargs = {} if args and '-v' in args: kw
args['verbosity'] = 2 runner = unittest.TextTestRunner(sys.stdout, "Unittests", **kwargs) results = runner.run(unittest_suite) return results.wasSuccessful() if __name__ == '__main__':
status = main(sys.argv[1:]) sys.exit(int(not status))
HHSIDEAlab/DDOD-HealthData.gov
data_json_counts.py
Python
gpl-2.0
11,117
0.011882
#!/usr/bin/env python # -*- coding: utf-8 -*- ###################### ## 2016-02-20 Created by David Portnoy ###################### import os import glob # Wildcard search import json import os import csv def support_old_schema(dataset_list): if isinstance(dataset_list, dict): return dataset_list["d...
nts_by_date,agen
cy_lookup) else: missing_csv_data = [] return missing_csv_data def get_dict_counts_by_date(file_name_list,csv_date_list,agency_lookup): dict_counts_by_date = {} #: Load missing dates for index, file_name in enumerate(reversed(file_name_list)): snapshot_fil...
Theyrealone/ExcelMapper
ExcelMapper/mapper.py
Python
gpl-3.0
2,950
0.036949
import xlrd from map_creator import * class MissingRuleError(Exception): pass def create_mapper(wb,table_index,col_rules,row_rules): #once based indexing excel_map = create_map(wb,table_index) for row in excel_map.rows: if not row_rules.has_key(row[0]): raise MissingRuleError("Missing row rule: ...
e,row_rule) return results def read_rules(self,row,col): self.row_rules[self.index_row_map[row]] self.col_rules[self.index_col_map[col]] return self.row_rules[self.index_row_map[row]],self.col_rules[self.index_col_map[col]] def rules_map(self):
rule_map = {} for row in self.excel_map.rows: for col in self.excel_map.cols: rule_map[(row[1],col[1])] = self.read_rules(row[1],col[1]) return rule_map
tasfe/datax-modify
release/datax.py
Python
gpl-2.0
4,840
0.007438
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ /** * (C) 2010-2011 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * */ """ import os ...
print >>sys.stderr, r"[Warning] DataX querying Job config file failed, sleep %d sec and try again." % (2**counter)
time.sleep(2**counter) continue except Exception, ex: print >>sys.stderr, str(ex) print >>sys.stderr, r"[Warning] DataX querying Job config file failed, sleep %d sec and try again." % (2**counter) time.sleep(2**counter) ...
algiopensource/l10n-spain
l10n_es_aeat_mod340/models/__init__.py
Python
agpl-3.0
971
0
# -*- coding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the L...
Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ####################################################
########################## from . import account_invoice from . import account from . import res_partner from . import mod340
flgiordano/netcash
+/google-cloud-sdk/lib/surface/dataflow/jobs/cancel.py
Python
bsd-3-clause
2,531
0.003556
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# We don't need to send the full job, because only the state can be # updated, and the other fields are ignored. job=dataflow_messages.Job( requestedState=(dataflow_messages.Job.RequestedStateValueValuesEnum .JOB_STATE_CANCELLED))) try: apitool...
date(request) log.status.Print('Cancelled job [{0}]'.format(job_ref.jobId)) except exceptions.HttpError as unused_error: log.err.Print('Failed to cancel job [{0}]'.format(job_ref.jobId))
UOSHUB/BackEnd
Website/urls.py
Python
gpl-3.0
347
0
from django.
conf.urls import url from . import views urlpatterns = [ # C
aptures special abbreviations and redirects to UOS websites url(r"^(?P<site>bb|udc|ms|uos)/?$", views.redirect_to_uos), # All website related requests link to views.layout # as the layout loads other dependencies as per request url(r"", views.layout), ]
tokunbo/behave-parallel
behave/formatter/plain.py
Python
bsd-2-clause
1,652
0
# -*- coding: utf-8 -*- from behave.formatter.base import Formatter class PlainFormatter(Formatter): """ Provides a simple plain formatter without coloring/formatting. In addition, multi-line text and tables are not shown in output (SAD). """ name = 'plain' description = 'Very basic formatter...
io.name)) def scenario_outline(self, outline): self.reset_steps() self.stream.write(u' %s: %s\n' % (outline.keyword, outline.name)) def step(self, step): self.steps.append(step) def result(self, result): step = self.steps.pop(0) # TODO right-align the keyword to
maximum keyword width? self.stream.write(u'%12s %s ... ' % (step.keyword, step.name)) status = result.status if self.show_timings: status += " in %0.2fs" % step.duration if result.error_message: self.stream.write(u'%s\n%s\n' % (status, result.error_message)) ...
AndrewBuck/osm2apt
osm2apt.py
Python
gpl-3.0
49,862
0.004533
#!/usr/bin/env python # Global variables that are user settable. shoulderWidth = 1.0 import argparse import math import copy from imposm.parser import OSMParser from shapely.geometry import * from shapely.geometry.polygon import orient from shapely.ops import cascaded_union overpassQueryFile = open('overpass_query....
junctionPoint = closestWay.geometry.interpolate(wayDistanceJunction - metersToDeg(1.0)) #junctionPoint, distance = computeNearestObject(closestWay, junctionPoints)
setbackHeading = computeHeadingAtPoint(closestWay.geometry, setbackPoint, junctionPoint) junctionHeading = computeHeadingAtPoint(closestWay.geometry, junctionPoint, Point(coord)) junctions.append((closestWay, setbackPoint, setbackHeading, junctionHeading)) for (way1, setbackPoint1, setback...
cedricB/circeCharacterWorksTools
rbfTool.py
Python
mit
9,899
0.006566
""" General descrition of your module here. """ from functools import partial from maya import OpenMaya from maya import OpenMayaUI from maya import cmds from PySide import QtCore from PySide import QtGui from shiboken import wrapInstance from shiboken import getCppPointer class RbfSettings(o...
self.connectRgbCheckBox,
self.connectAlphaCheckBox, self.useAliasCheckBox, self.createSphereCheckBox]: #Set properties widget.setChecked(True) #Assign widget to layouts self.mainLayout.addWidget(widget) #set the main lay...
ubirch/aws-tools
virtual-env/lib/python2.7/site-packages/boto/cloudtrail/layer1.py
Python
apache-2.0
17,002
0.000882
# Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights ...
roupArnException": exceptions.InvalidCloudWatchLogsLogGroupArnException, "InvalidCloudWatch
LogsRoleArnException": exceptions.InvalidCloudWatchLogsRoleArnException, "InvalidTrailNameException": exceptions.InvalidTrailNameException, "CloudWatchLogsDeliveryUnavailableException": exceptions.CloudWatchLogsDeliveryUnavailableException, "TrailNotFoundException": exceptions.TrailNotFoundExcep...
deepinsight/Deformable-ConvNets
deeplab/core/loader.py
Python
apache-2.0
9,374
0.0032
# -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2016 by Contributors # Copyright (c) 2017 Microsoft # Licensed under The Apache-2.0 License [see LICENSE for details] # Modified by Zheng Zhang # -------------------------------------------------------- impor...
def next(self): if self.iter_next(): self.get_batch_parallel() self.cur += self.batch_size return mx.io.DataBatch(data=self.data, label=self.label, pad=self.getpad(), index=self.getindex(),
provide_data=self.provide_data, provide_label=self.provide_label) else: raise StopIteration def getindex(self): return self.cur / self.batch_size def getpad(self): if self.cur + self.batch_size > self.size: return self.cur + self.batch...
StamusNetworks/scirius
rules/management/commands/kibana_export.py
Python
gpl-3.0
1,475
0
''' Copyright(C) 2016, Stamus Networks Written by Laurent Defert <lds@stamus-networks.com> This file is part of Scirius. Scirius is free software: you can redistribute it and/or modif
y 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. Scirius is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; with
out 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 Scirius. If not, see <http://www.gnu.org/licenses/>. ''' import os from django.core.management.bas...
jniediek/mne-python
mne/gui/__init__.py
Python
bsd-3-clause
3,384
0
"""Convenience functions for opening GUIs.""" # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) from ..utils import _check_mayavi_version def combine_kit_markers(): """Create a new KIT marker file by interpolating two marker files Notes ----- The functionality in...
mended way to use the GUI is through bash with:: $ mne coreg Parameters ---------- tabbed : bool
Combine the data source panel and the coregistration panel into a single panel with tabs. split : bool Split the main panels with a movable splitter (good for QT4 but unnecessary for wx backend). scene_width : int Specify a minimum width for the 3d scene (in pixels). ...
harveyc95/ProgrammingProblems
LeetCode/678_valid_parenthesis_string/checkValidString.py
Python
mit
495
0.006061
class Solution(object): def
checkValidString(self, s): lower = upper = 0 for c in s: if c == '(': lower += 1 upper += 1 elif c == ')': lower -= 1 upper -= 1 else: lower -= 1 upper += 1 ...
wer == 0
gferreira/hTools2_extension
hTools2.roboFontExt/lib/Scripts/batch folder/actions.py
Python
bsd-3-clause
152
0
# [h] apply actions import hTools2.dialogs.folder.actions reload(hTools2.dialogs.folder.actions) hTools2.dialogs.folder.actions.actionsFolderDialog
()
chdonncha/Cloud-Computing-Labs-AmazonServer
Lab11/read-aws-queue.py
Python
mit
965
0.009326
# Thi
s script created a queue # # Author - Paul Doyle Nov 2015 # # import httplib import boto.sqs import boto.sqs.queue from boto.sqs.message import Message from boto.sqs.connection import SQSConnection from boto.exception import SQSError import sys keys = httplib.HTTPConnection("ec2-52-30-7-5.eu-west-1.compute.amazonaws.c...
"GET", "/key") r1 = keys.getresponse().read().split(":") # Get the keys from a specific url and then use them to connect to AWS Service access_key_id = r1[0] secret_access_key = r1[1] # Set up a connection to the AWS service. conn = boto.sqs.connect_to_region( "eu-west-1", aws_access_key_id=access_key_id, aws_...
Winterflower/mdf
mdf/io/simplezipfile.py
Python
mit
3,174
0.001575
""" classes used for reading and writing compressed mdf objects """ from zipfile import ZipFile, ZIP_DEFLATED from tempfile import NamedTemporaryFile import logging import os _log = logging.getLogger(__name__) class SimpleZipFile(object): """ File-like object for reading from and writing to simple zipfiles ...
close because the file needs to be closed before it # can be written to the zipfile as there's no way to incremenatally write # bytes to a zipfile, and loading the whole file into memory could be
# problematic. # self._fh = NamedTemporaryFile("w+b", delete=False) if mode == "r": # unzip the whole file into the temporary file zip_fh = ZipFile(filename, "r") try: if inner_filename: self._fh.write(zip_fh.read(...
caseywstark/colab
colab/apps/object_feeds/signals.py
Python
mit
918
0.007625
from django.template.defaultfilters import slugify from django.contrib.contenttypes.models import ContentType from object_feeds.models import Action, Feed def pre_save(sender, instance, **kwargs): """ Makes sure that the feed object has a feed setup. """ opts = instance._meta feed ...
stance) model_name = unicode(opts.verbose_name) the_feed = Feed.objects.create(
content_type=content_type) setattr(instance, opts.feed_attr, the_feed) def post_save(sender, instance, created, **kwargs): """ Updates things only accessible after the instance is saved, like object_id. """ if not instance.feed.feed_object: instance.feed.feed_object = inst...
soundstorm/RDWorksFileserver
RDWorks/RDLaser.py
Python
gpl-3.0
10,961
0.058115
# encoding: utf-8 import socket import sys reload(sys) sys.setdefaultencoding('utf8') class RDLaser(object): BUF_SIZE = 4096 CLIENT_PORT = 40200 SERVER_PORT = 50200 CMD_STOP = "d801".decode("HEX") CMD_PAUSE_CONTINUE = "d803".decode("HEX") CMD_HOME_XY = "d910000000000000000000...
e("HEX") #binary CFG_Z_STEP_LENGTH = "da000041".decode("HEX") #picometer CFG_Z_MAX_SPEED = "da000043".decode("HEX") #nanometer/s CFG_Z_JUMPOFF_SPEED = "da000044".decode("HEX") #nanometer/s CFG_Z_MAX_ACC
= "da000045".decode("HEX") #nanometer/s^2 CFG_Z_BREADTH = "da000046".decode("HEX") #nanometer CFG_Z_KEY_JUMPOFF_SPEED = "da000047".decode("HEX") #nanometer/s CFG_Z_KEY_ACC = "da000048".decode("HEX") #nanometer/s^2 CFG_Z_ESTOP_ACC = "da000049".decode("HEX") #nanometer/s^2 ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/graph_Type.py
Python
mit
1,617
0.022882
""" __graph_Type.py___________________________________________________________ Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION __________________________________________________________________________ """ import tkFont from graphEntity import * from GraphicalForm import * from AT...
else: atribs = None self.graphForms = [] self.imageDict = self.getImageDict() def DrawObject(self, drawing, showGG = 0): self.dc = drawing if showGG and self.semanticObject: self.drawGGLabel(drawing) h = drawing.create_oval(self.translate([142.0, 48.0, 142.0, 48.0]), ...
connector'), outline = '', fill = '' ) self.connectors.append( h ) h = drawing.create_rectangle(self.translate([20.0, 18.0, 141.0, 79.0]), tags = self.tag, stipple = '', width = 1, outline = 'black', fill = 'gray') self.gf139 = GraphicalForm(drawing, h, "gf139") self.graphForms.append(s...
vasiliykochergin/euca2ools
euca2ools/commands/ec2/deletenetworkaclentry.py
Python
bsd-2-clause
1,948
0
# Copyright 2013-2014 Eucalyptus Systems, Inc. # # Redistribution and use of this software 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 ab
ove copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PR...
Openergy/oplus
oplus/__init__.py
Python
mpl-2.0
404
0.002475
from .version import version as __version__ from oplus.configuration import CONF from oplus.epm.api import * from oplus.weather_data.api import * from oplus.standard_outpu
t.api import * from oplus.eio import Eio from oplus.mtd import Mtd from oplus.err import Err from oplus.summary_table import Sum
maryTable from oplus.output_table import OutputTable from oplus.simulation import Simulation, simulate
dbarbier/privot
python/test/t_Normal_wrongarg.py
Python
lgpl-3.0
760
0.011842
#! /usr/bin/env python fro
m openturns import * TESTPREAMBLE() try : try : # Instanciate one distribution object meanPoint = NumericalPoint(1) meanPoint[0] = 1.0 sigma = NumericalPoint(1) sigma[0] = 1.0 R = CorrelationMatrix(1) distribution = Normal(meanPoint, sigma, R) prin...
# We try to set an erroneous covariance matrix (wrong dimension) into distribution newR = CorrelationMatrix(2) distribution.setCorrelationMatrix(newR) # Normally, we should never go here raise except : pass #except TestFailed, ex : except : import sys print "t_No...
polyaxon/polyaxon
platform/coredb/coredb/query_managers/project.py
Python
apache-2.0
2,249
0
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
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 pe
rmissions and # limitations under the License. from coredb.query_managers.manager import BaseQueryManager from polyaxon.pql.builder import ( ArrayCondition, DateTimeCondition, SearchCondition, ValueCondition, ) from polyaxon.pql.parser import ( parse_datetime_operation, parse_search_operation, ...
Microvellum/Fluid-Designer
win64-vc/2.78/Python/bin/2.78/scripts/addons_contrib/uv_magic_uv/muv_common.py
Python
gpl-3.0
1,988
0
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # 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 version. # # ...
rsion(major, minor, unused): """ Check blender version """ if bpy.app.version[0] == major and bpy.app.version[1] == minor: return 0 if bpy.app.version[0] > major: return 1 else: if bpy.app.version[1] > minor: return 1 else: return -1 def...
reas: area.tag_redraw() def get_space(area_type, region_type, space_type): """ Get current area/region/space """ for area in bpy.context.screen.areas: if area.type == area_type: break for region in area.regions: if region.type == region_type: break ...
tklovett/MaudeMiner
MaudeMiner/core/loader/devices.py
Python
mit
3,344
0.032297
from MaudeMiner.core.database import db from MaudeMiner.core.models import Device from MaudeMiner.utils import update_progress from MaudeMiner.core.loader.utils import * from MaudeMiner.settings import LINES_PER_DB_COMMIT EXPECTED_NUMBER_OF_FIELDS = 45 def load(): # ensure tables exists db.create_tables(["Devices...
evice.catalog_number = v[20] device.other_id_number = v[21] device.device_operator = v[22] device.device_availability = v[23] device.date_reported_to_manufacturer = v[24] device.device_report_product_code ...
ated_by_manufacturer = v[27] device.baseline_brand_name = v[28] device.baseline_generic_name = v[29] device.baseline_model_number = v[30] device.baseline_catalog_number = v[31] device.baseline_other_id_number = v[32] dev...
krafczyk/root
tutorials/pyroot/zdemo.py
Python
lgpl-2.1
8,180
0.066137
## \file ## \ingroup tutorial_pyroot ## This macro is an example of graphs in log scales with annotations. ## ## The presented results ## are predictions of invariant cross-section of Direct Photons produced ## at RHIC energies, based on the universality of scaling function H(z). ## ## ## These Figures were publishe...
tTextSize( 0.05 ) t.SetTextColor( 1 ) t.DrawLatex( 0.6, 0.06, 'q_{T} (Gev/c)' ) saves[ 't2' ] = t # note the label that is used! gr1 = ROOT.TGraph( NLOOP, PT, INVSIG ) g
r1.SetLineColor( 38 ) gr1.SetMarkerColor( ROOT.kBlue ) gr1.SetMarkerStyle( 21 ) gr1.SetMarkerSize( 1.1 ) gr1.Draw( 'LP' ) saves[ 'gr1' ] = gr1 # # Cross-section of direct photon production in pp collisions at 200 GeV vs Pt # energ = 200 dens = 2.25 tgrad = 90. ptmin = 4. ptmax = 64. ...
jaydenkieran/Turbo
turbo/database.py
Python
mit
2,402
0.001665
import logging import rethinkdb as r log = logging.getLogger(__name__) class Database(): def __init__(self, bot): self.bot = bot self.db_name = self.bot.config.rname self.db = None r.set_loop_type("asyncio") self.ready = False def get_db(self): """ Re...
return await r.table(table).get(primary_key).delete().run(self.db) else: # Delete all documents in the table return aw
ait r.table(table).delete().run(self.db) async def connect(self, host, port, user, password): """ Establish a database connection """ log.info("Connecting to database: {}".format(self.db_name)) try: self.db = await r.connect(db=self.db_name, host=host, port=port,...
lettersonsounds/twenty
score.py
Python
unlicense
1,251
0.031974
from pippi import dsp from pippi import tune def ping(maxlen=44100, freqs=None): out = '' if freqs is None: freqs = [ dsp.rand(20,10000) for i in range(4) ] tlen = dsp.randint(10, maxlen) tones = [ dsp.tone(length=tlen, freq=freq, amp=0.1, wavetype='random') for freq in freqs ] ...
e(len(tones)) ] out = dsp.mix([ dsp.env(''.join(tone), 'random') for tone in tones ]) out = dsp.env(out, 'random') out = dsp.pad(out, 0, dsp.randint(0, maxlen * 3)) return out #freqs = tune.fromdegrees(
[1,3,5,6,9], 6, 'a') freqs = None out = ''.join([ ping(dsp.mstf(200), freqs) for i in range(100)]) dsp.write(out, 'twenty')
RobSpectre/garfield
garfield/contacts/migrations/0007_contact_recruiter.py
Python
mit
392
0
# Generated by Django 2.0.4 o
n 2018-04-24 21:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contacts', '0006_auto_20180423_1629'), ] operations = [ migrations.AddField( model_name='contact', name='recruiter', field=models.B
ooleanField(default=False), ), ]
marcardioid/DailyProgrammer
solutions/227_Hard/solution.py
Python
mit
1,712
0.005257
def build_matrix(lines): edges = {(0, 1): '-', (0, -1): '-', (1, 0): '|', (-1, 0): '|', (1, 1): '\\', (-1, -1): '\\', (1,-1): '/', (-1, 1): '/'} connections = {} rows = [list(l.rstrip()) for l in lines[1:]] def valid(y, x): return True if y >= 0 and y < len(rows) and x >= 0 and x < len(rows[y])...
n enumer
ate(rows): for x, a in enumerate(row): if a.isalpha(): if not a in connections: connections[a] = [] for (dy, dx), edge in edges.items(): if valid(y + dy, x + dx) and rows[y + dy][x + dx] == edge: b = trac...
pydanny/djangopackages
searchv2/tests/__init__.py
Python
mit
163
0.006135
from
searchv2.tests.test_builders import * from searchv2.tests.test_models import * from searchv2.tests.test_utils import * from searchv2.tests.test_views
import *
plus3it/watchmaker
docs/conf.py
Python
apache-2.0
11,108
0
# -*- coding: utf-8 -*- """Configure Watchmaker documentation.""" from __future__ import (absolute_import, division, print_function, unicode_literals, with_statement) import os import sys # # Created by sphinx-quickstart on Thu Jun 30 20:11:36 2016. # # This file is execfile()d with the curren...
_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended
to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A...
EmanueleCannizzaro/scons
test/MSVS/vs-11.0-scc-files.py
Python
mit
3,967
0.000756
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
_ROOT='.', MSVS_SCC_PROVIDER='MSSCCI:Perforce SCM', MSVS_SCC_PROJECT_NAME='Perforce Pro
ject') testsrc = ['test1.cpp', 'test2.cpp'] testincs = ['sdk_dir\sdk.h'] testlocalincs = ['test.h'] testresources = ['test.rc'] testmisc = ['readme.txt'] env.MSVSProject(target = 'Test.vcxproj', srcs = testsrc, incs = testincs, localincs = testlocalincs, ...
gitgik/updown
api/migrations/0001_initial.py
Python
mit
1,477
0.002708
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-04 09:48 from __future__ import unicode_literals import api.utils from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [...
s.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='File', fields=[ ('datemixin_ptr', models.One
ToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='api.DateMixin')), ('file_id', models.CharField(default=api.utils.generate_uid, max_length=20)), ('name', models.CharField(max_length=255)), ...
kwikteam/global_superclustering
global_code/compute_penalty.py
Python
gpl-2.0
1,609
0.03294
import numpy as np __all__ = ['compute_penalties'] def compute_penalty(kk, clusters): '''Takes kk.clusters (clusters currently assigned) and computes the penalty''' if clusters is None: clusters = kk.clusters #print(clusters) num_cluster_membs = np.array(np.bincount(clusters), ...
e) #print('num_cluster_members', num_cluster_membs) # print('num_clusters', num_clusters) # #This now only depends on the number of clusters # #cluster_penalty = np.zeros(num_clusters) num_spikes = kk.num_spikes #D_k = kk.D_k num_kkruns = kk.num_KKruns num_bern_params = kk....
_bern_params[np.nonzero(num_cluster_membs>0)] #print('num_bern_params_used = ', num_bern_params_used) #num_bern_params = [70 71 63 63 64 62 83 79] for 8 clusters penalty_k = kk.penalty_k penalty_k_log_n = kk.penalty_k_log_n #mean_params = (np.sum(D_k)-num_kkruns)*num_clusters - 1 ...
sameerparekh/pants
src/python/pants/backend/core/tasks/markdown_to_html.py
Python
apache-2.0
15,151
0.009702
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import codecs import...
guess_lexer_for_filename(include_path, file_text) except ClassNotFound: # e.g., ClassNotFound: no lexer for filename u'BUILD' found if 'BUILD' in include_path: lexer = PythonLexer() else: lexer = TextLexer() # the boring plain-text lexer html_snippet = highlight(include_text...
return el class IncludeExcerptExtension(markdown.Extension): def __init__(self, source_path, configs=None): markdown.Extension.__init__(self, configs or {}) self.source_path = source_path def extendMarkdown(self, md, md_globals): md.inlinePatterns.add('excerpt', IncludeExce...
mistercrunch/panoramix
superset/db_engine_specs/trino.py
Python
apache-2.0
6,834
0.000585
# 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 u...
. from datetime import datetime from typing import Any, Dict, List, Optional from urllib import parse import simplejson as json from sqlalchemy.engine.url import make_url, URL from superset.db_engine_specs.base import BaseEngineSpec from superset.utils import core as utils class TrinoEngineSpec(BaseEngineSpec): ...
"PT1S": "date_trunc('second', CAST({col} AS TIMESTAMP))", "PT1M": "date_trunc('minute', CAST({col} AS TIMESTAMP))", "PT1H": "date_trunc('hour', CAST({col} AS TIMESTAMP))", "P1D": "date_trunc('day', CAST({col} AS TIMESTAMP))", "P1W": "date_trunc('week', CAST({col} AS TIMESTAMP))"...
echevemaster/fudcon
fudcon/modules/speakers/models.py
Python
mit
461
0
# -*- coding: utf-8 -*- """ fudcon.modules.speakers.models ~~~~~~~~~~~~~~~~~~~~~ Speakers models """ from fudcon.database import db class Speaker(db.Model): """ Model for listing all the attributes of the speakers """ __tablename__ = 'spea
kers' id = db.Column(db.Intege
r, primary_key=True) names = db.Column(db.String(255)) fas = db.Column(db.String(255)) bio = db.Column(db.Text()) active = db.Column(db.Boolean())
gsmcwhirter/c-simulations
docs/source/conf.py
Python
mit
8,316
0.006133
# -*- coding: utf-8 -*- # # c-simulations documentation build configuration file, created by # sphinx-quickstart on Thu Jun 19 12:55:22 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file....
rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter
. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyri...
dannyboi104/SickRage
sickbeard/tv.py
Python
gpl-3.0
117,710
0.004885
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
"_flatten_folders")) status = property(lambda self: self._status, dirty_setter("_status")) airs = property(lambda self: self._airs, dirty_setter("_airs")) startyear = property(lambda self: self._startyear, dirty_setter("_startyear")) paused = property(lambda self: self._paused, dirty_setter("_paused")) ...
tter("_subtitles")) dvdorder = property(lambda self: self._dvdorder, dirty_setter("_dvdorder")) archive_firstmatch = property(lambda self: self._archive_firstmatch, dirty_setter("_archive_firstmatch")) lang = property(lambda self: self._lang, dirty_setter("_lang")) last_update_indexer = property(lambda ...
androm3da/struct_bench
types_.py
Python
mit
505
0.011881
#!/usr/bin/env python import collections def read_only(self, name, val): raise ValueError('not supported') class SimpleObject(object): def __init__(self, a, b, c): self.a = a self.b = b self.b = c class SimpleObjectImmutable(object): def __init__(self, a,
b, c): self.a = a self.b = b self.b = c NamedTuple = collections.namedtuple('NamedTuple', ['a', 'b', 'c',]) def SimpleTuple(a, b, c): return (a, b, c) from types_c import c_st
ruct
profitware/python-sandbox-algo
sandboxalgo/binsearch.py
Python
mit
2,401
0
# -*- coding: utf-8 -*- __author__ = 'Sergey Sobko' KEY_NOT_FOUND = -1 def midpoint(imin, imax): """Returns middle point >>> midpoint(0, 0) 0 >>> midpoint(0, 1) 0 >>> midpoint(0, 2) 1 >>> midpoint(1, 1) 1 >>> midpoint(1, 2) 1 >>> midpoint(1
, 5) 3 """ middle_point = (int(imin) + int(imax)) / 2 return middle_point def binary_search(search_list, key): """Binary search algorithm >>> binar
y_search([], 1) == KEY_NOT_FOUND True >>> binary_search([1, 3, 4, 6, 8, 9, 11], 4) 2 >>> binary_search([1, 2, 3, 4, 6, 8, 9, 11], 4) 3 >>> binary_search([1, 2, 3, 4, 6, 8, 9, 11], 1) 0 >>> binary_search([1, 2, 3, 4, 6, 8, 9, 11], 11) 7 >>> binary_search([1, 2, 3, 4, 8, 9, 11...
CFDEMproject/LAMMPS
tools/moltemplate/src/ttree_lex.py
Python
gpl-2.0
82,841
0.006808
# -*- coding: iso-8859-1 -*- # Author: Andrew Jewett (jewett.aij at g mail) # http://www.chem.ucsb.edu/~sheagroup # License: 3-clause BSD License (See LICENSE.TXT) # Copyright (c) 2012, Regents of the University of California # All rights reserved. """A lexical analyzer class for simple shell-like syntaxes. ...
self.end_encountered = False #WORDTERMINATORS def push_token(self, text): "Push a token onto the stack popped by the get_token method" self.push_raw_text(text+self.prev_space_terminator) de
f push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.ins...
geimer/easybuild-framework
setup.py
Python
gpl-2.0
4,276
0.012161
# # # Copyright 2012-2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (ht...
ng.be/in_English) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # http://github.com/hpcugent/easybuild # # EasyBuild 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 Fou...
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 EasyBuild. If not, see <http://www.gnu.org/licenses/>. # # """ This script c...
aronparsons/spacewalk
client/tools/rhncfg/config_common/utils.py
Python
gpl-2.0
5,530
0.003436
# # Copyright (c) 2008--2015 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
ed.append(d) log_debug(6, "dirs_created:",dirs_created) return dirs_created def rmdir_p(path, stoppath): """ if rmdir had a -p option, this would be it. remove dir and up until empty dir is hit, or stoppath i
s reached path and stoppath have to be absolute paths """ # First normalize both paths stoppath = normalize_path(os.sep + stoppath) path = normalize_path(os.sep + path) # stoppath has to be a prefix of path if path[:len(stoppath)] != stoppath: raise OSError, "Could not remove %s: ...
eduNEXT/edx-platform
common/lib/xmodule/xmodule/modulestore/tests/test_publish.py
Python
agpl-3.0
55,886
0.002595
""" Test the publish code (mostly testing that publishing doesn't result in orphans) """ import itertools import os import re import unittest import uuid import xml.etree.ElementTree as ET from contextlib import contextmanager from shutil import rmtree from tempfile import mkdtemp import pytest import ddt from open...
split=False )
self._create_item('html', 'Html2', "<p>Hello</p>", {'display_name': 'Hollow Html'}, 'vertical', 'Vert1', split=False) # lint-amnesty, pylint: disable=line-too-long self._create_item( 'discussion', 'Discussion2', "discussion discussion_category=\"Lect...
Aluriak/MusicGenerator
generator/test/test_markov.py
Python
gpl-2.0
423
0.002364
from generator import markov def test_chain(): chain = markov.chain('acab', order=1) assert chain == {('a',): {'c': .5, 'b': .5}, ('c',): {'a': 1.}} assert 'a' == markov.random_walk(chain, 'c') assert markov.random_walk(chain, 'a') in
'cb' def test_random_walk(): chain = markov.chain('abc', order=2) assert chain == {('a', 'b'): {'c': 1.}} assert 'c' == markov.random_walk
(chain, 'ab')
Luftzig/pypatterns
setup.py
Python
mit
809
0
from setuptools import setup, find_packages setup( name="pypatterns", version="0.2.0",
packages=find_packages(), author="Yoav Luft", author_email="yoav.luft@gmail.com", description="Functional style pattern mat
ching for Python", license="MIT", url="https://github.com/Luftzig/pypatterns", test_requires=['pytest'], keywords=['functional', 'pattern matching'], classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', ...
joshjo/django-sentry
sentry/conf/defaults.py
Python
apache-2.0
2,997
0.001001
""" sentry.conf.defaults ~~~~~~~~~~~~~~~~~~~~ Represents the default values for all Sentry settings. :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import logging import os import os.path import socket ROOT = os.path.normpath(os.path.join(os.p...
= 15 ## The following settings refer
to the built-in webserver WEB_HOST = 'localhost' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'sentry.log') WEB_PID_FILE = os.path.join(ROOT, 'sentry.pid')
bswartz/manila
manila/tests/conf_fixture.py
Python
apache-2.0
2,989
0
# 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 ...
'manila.tests.fake_driver.FakeShareDriver') _safe_set_of_opts(conf, 'auth_strategy', 'noauth') _safe_set_of_opts(conf, 'zfs_share_export_ip', '1.1.1.1') _safe_set_of_opts(conf, 'zfs_service_ip', '2.2.2.2') _safe_set_of_opts(conf, 'zfs_zpool_list', ['foo', 'bar']) _safe_set_of_opts(...
a_snapshot_prefix', 'foo_prefix_') _safe_set_of_opts(conf, 'hitachi_hsp_host', '172.24.47.190') _safe_set_of_opts(conf, 'hitachi_hsp_username', 'hsp_user') _safe_set_of_opts(conf, 'hitachi_hsp_password', 'hsp_password') _safe_set_of_opts(conf, 'qnap_management_url', 'http://1.2.3.4:8080') _safe_se...
tdryer/hangups
hangups/conversation.py
Python
mit
46,809
0
"""Conversation objects.""" import asyncio import datetime import logging from hangups import (parsers, event, user, conversation_event, exceptions, hangouts_pb2) logger = logging.getLogger(__name__) CONVERSATIONS_PER_REQUEST = 100 MAX_CONVERSATION_PAGES = 100 async def build_user_conversatio...
request_header=client.get_request_header(), ) ) self_entit
y = get_self_info_response.self_entity user_list = user.UserList(client, self_entity, required_entities, conv_part_list) conversation_list = ConversationList(client, conv_states, user_list, sync_timestamp) return (user_list, conversatio...
crmauceri/VisualCommonSense
code/database_builder/tools/cmd_arguments_helper.py
Python
mit
1,911
0.030351
# Author: Edison Huang # Email: hom.tao@yahoo.com # # Example: # def main(): # from CmdArgumentsHelper import CmdArgumentsHelper; # arg_helper = CmdArgumentsHelper(); # arg_helper.add_argument('query', 'q', 'query', 1); # args = arg_helper.read_arguments(); # # query_string = args['query']; # ... mani...
ment_name] = argument_option; self.args_has_value[argument_name] = has_value; def gen_help_message(self): help_message = ''; for arg in self.args: help_message = help_message + ' -' + self.args_cmd[arg] + ' ' + '<' + arg +
'>'; return help_message; def gen_cmds(self): cmds = 'h'; for arg in self.args: cmds = cmds + self.args_cmd[arg]; if (self.args_has_value[arg]): cmds = cmds + ':'; return cmds; def gen_options(self): options = []; for arg in self.args: if (self.args_has_value[arg...
pywinauto/pywinauto
pywinauto/findbestmatch.py
Python
bsd-3-clause
20,676
0.004159
# GUI Application automation and testing library # Copyright (C) 2006-2018 Mark Mc Mahon and Contributors # https://github.com/pywinauto/pywinauto/graphs/contributors # http://pywinauto.readthedocs.io/en/latest/credits.html # All rights reserved. # # Redistribution and use in source and binary forms, with or with...
ctrl_index != 0: pr
ev_ctrl = controls[ctrl_index-1] prev_ctrl_text = prev_ctrl.window_text() if prev_ctrl.friendly_class_name() == "Static" and \ prev_ctrl.is_visible() and prev_ctrl_text and \ is_above_or_to_left(ctrl, prev_ctrl): names.append( prev_ctrl_text ...
sergey-tomin/workshop
2_tracking.py
Python
mit
2,857
0.00175
""" This script was created by Sergey Tomin for Workshop: Designing future X-ray FELs. Source and license info is on GitHub. August 2016. """ # this python library provides generic shallow (copy) and deep copy (deepcopy) operations from copy import deepcopy # import from Ocelot main modules and fun
ctions from ocelot import * # import from Ocelot graphical modules from ocelot.gui.accelerator import * from ocelot.adaptors.astra2ocelot import * # import injector lattice from ocelot.test.workshop.injector_lat
tice import * lat = MagneticLattice(cell) # initialization of Twiss object tws0 = Twiss() # defining initial twiss parameters tws0.beta_x = 29.171 tws0.beta_y = 29.171 tws0.alpha_x = 10.955 tws0.alpha_y = 10.955 # defining initial electron energy in GeV tws0.E = 0.005 # calculate twiss functions with i...
vjorlikowski/plexus
plexus/tables.py
Python
apache-2.0
11,545
0.000866
# Copyright (c) 2015 Duke University. # This software is distributed under the terms of the MIT License, # the text of which is included in this distribution within the file # named LICENSE. # # Portions of this software are derived from the "rest_router" controller # application included with Ryu (http://osrg.github.i...
all_gateway_info += table.get_all_gateway_info() return all_gateway_info def get_data(self, gw_mac=None, dst_ip=None, src_ip=None): desired_table = self[INADDR_ANY] if src_ip is not None: for table in six.itervalues(self): if table.src_address is not None: ...
s.netmask)): desired_table = table break route = desired_table.get_data(gw_mac, dst_ip) if ((route is None) and (desired_table != self[INADDR_ANY])): route = self[INADDR_ANY].get_data(gw_mac, dst_ip) return route class RoutingTab...
gltn/stdm
stdm/third_party/sqlalchemy/testing/suite/test_select.py
Python
gpl-2.0
24,377
0
from .. import config from .. import fixtures from ..assertions import eq_ from ..assertions import in_ from ..schema import Column from ..schema import Table from ... import bindparam from ... import case from ... import Computed from ... import exists from ... import false from ... import func from ... import Integer...
lf.tables.some_table self._assert_result(
select([table]) .order_by(table.c.id) .limit(bindparam("l")) .offset(bindparam("o")), [(2, 2, 3), (3, 3, 4)], params={"l": 2, "o": 1}, ) class CompoundSelectTest(fixtures.TablesTest): __backend__ = True @classmethod def define_table...
amirgeva/commit
utils.py
Python
gpl-2.0
3,355
0.000894
import os import subprocess import select from PyQt5 import QtGui, QtWidgets iconsDir = '.' def setIconsDir(dir): global iconsDir iconsDir = dir def loadIcon(name): if not name.endswith('.png'): name = name + ".png" path = os.path.join(iconsDir, name) # print "Loading '{}'".format(path)...
cmd], stdout=open('/dev/null', 'w')) return res == 0 except OSError: return False def appendOutput(output, text): # text=output.toPlainText() # output.setPlain
Text(text+added) # c=output.textCursor() # c.movePosition(QtGui.QTextCursor.End) # output.setTextCursor(c) # output.ensureCursorVisible() output.appendPlainText(text) def appendColorLine(output, line, color): line = line.decode('utf8') c = output.textCursor() c.movePosition(QtGui.QText...
open-power-ref-design-toolkit/cluster-genesis
scripts/python/inv_add_switches.py
Python
apache-2.0
1,219
0.00082
#!/usr/bin/env python3 # Copyright 2019 IBM Corp. # # 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 requir...
ns and # limitations under the License. import sys fro
m lib.inventory import Inventory from lib.logger import Logger class InventoryAddSwitches(object): def __init__(self, log, inv_file): inv = Inventory(log, inv_file) inv.add_switches() if __name__ == '__main__': """ Arg1: inventory file Arg2: log level """ LOG = Logger(__file_...
obi-two/Rebelion
data/scripts/templates/object/tangible/ship/crafted/weapon/shared_wpn_heavy_blaster.py
Python
mit
474
0.046414
#### NOT
ICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/ship/crafted/weapon/shared_wpn_heavy_blaster.iff" result.attribute_template...
GIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
ivotkv/redmsg-logger
redmsg_logger/logger.py
Python
mit
2,648
0.005665
#!/usr/bin/env python # -*- coding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2017 Ivo Tzvetkov # # 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 wit...
help='path to config file (default: %(default)s)') args = arg_parser.parse_args() with open(args.config, 'r') as file:
config = yaml.load(file) logger = Logger(config) logger.start() if __name__ == '__main__': main()
carlos-lopez-garces/mapnik-trunk
scons/scons-local-1.2.0/SCons/Tool/JavaCommon.py
Python
lgpl-2.1
12,539
0.001436
"""SCons.Tool.JavaCommon Stuff for processing Java. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation # # 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 Softw...
FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __re...
port re import string java_parsing = 1 default_java_version = '1.4' if java_parsing: # Parse Java files for class names. # # This is a really cool parser from Charles Crain # that finds appropriate class names in Java source. # A regular expression that will find, in a java file: # newli...
marios-zindilis/musicbrainz-django-models
musicbrainz_django_models/models/recording_rating_raw.py
Python
gpl-2.0
1,133
0.000883
""" .. module:: recording_rating_raw The **Recording Rating Raw** Model. PostgreSQL Definition --------------------- The :code:`recording_rating_raw` table is defined in the MusicBrainz Server as: .. code-block:: sql CREATE TABLE recording_rating_raw ( recording INTEGER NOT NULL, -- PK, r...
SMALLINT NOT NULL CHECK (rating >= 0 AND rating <= 100) ); """ from django.db import models from django.utils.encoding import python_2_unicode_compatible from .abstract__model_rating_raw import abstract__model_rating_raw @python_2_unicode_compatible class recording_rating_raw(abstract__model_rating_raw): ...
ted here, only those that present some interest in their Django implementation. :param recording: References :class:`recording`. """ recording = models.OneToOneField('recording', primary_key=True) def __str__(self): return 'Recording Rating Raw' class Meta: db_table = 'record...
jestlabs/polyglot
polyglot/heuristics.py
Python
mit
1,381
0.029689
import polyglot import yaml class Heuristics (object): """ The Heuristics class receives a path to the file that
is trying to be identified and an array of possible languages for that file. The disambiguate method will find the array with unambiguous strings of syntax for each language and check the file in question for those strings. If a match occurrs then the file is unquestionably
written in the language that the string belongs to. If no match is found then None is returned and the file wasn't determined to be of a particular language.""" def __init__(self, path, possibleLanguages): self.syntaxFile = polyglot.Polyglot.tryOpenFile ('syntax.yml') # {language1: [bits_of_syntax1, bits_of_s...
ProfessionalIT/maxigenios-website
sdk/google_appengine/lib/PyAMF-0.7.2/pyamf/sol.py
Python
mit
5,052
0.000198
# Copyright (c) The PyAMF Project. # See LICENSE
.txt for details. """ Local Shared Object implementation. Local Shared Object (LSO), sometimes
known as Adobe Flash cookies, is a cookie-like data entity used by the Adobe Flash Player and Gnash. The players allow web content to read and write LSO data to the computer's local drive on a per-domain basis. @see: U{Local Shared Object on WikiPedia <http://en.wikipedia.org/wiki/Local_Shared_Object>} @since: 0....
ESS-LLP/erpnext-medical
erpnext/stock/doctype/delivery_note/delivery_note_dashboard.py
Python
gpl-3.0
674
0.045994
from frappe import _ def get_data(): return { 'fieldname': 'delivery_note', 'non_standard_fieldnames': { 'Stock Entry': 'delivery_note_no', 'Quality Inspection': 'reference_name', 'Auto Repeat': 'reference_document', }, 'internal_links': { 'Sa
les Order': ['items', 'against_sales_order'], }, 'transactions': [ { 'label': _('Related'), 'items': ['Sales Invoice', 'Packing Slip', 'Delivery Trip'] }, { 'label': _('Reference'), 'items': ['Sales Order', 'Quality Inspection'] }, { 'label': _('Returns'), '
items': ['Stock Entry'] }, { 'label': _('Subscription'), 'items': ['Auto Repeat'] }, ] }
olduvaihand/ProjectEuler
src/python/problem388.py
Python
mit
583
0.003442
# -*- coding: utf-8 -*- # ProjectEuler/src
/python/problem388.py # # Distinct Lines # ============== # Published on Saturday, 9th June 2012, 02:00 pm # # Consider all lattice points (a,b,c) with 0 a,b,c N. From the origin # O(0,0,0) all lines are drawn to the other lattice points. Let
D(N) be the # number of distinct such lines. You are given that D(1 000 000) = # 831909254469114121. Find D(1010). Give as your answer the first nine # digits followed by the last nine digits. import projecteuler as pe def main(): pass if __name__ == "__main__": main()