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
fqc/django_rest_test
django_rest_test/wsgi.py
Python
mit
1,449
0.00069
""" WSGI config for django_rest_test project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLI...
ort os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "django_rest_test.settings" os.environ.setdef...
plication object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWo...
mick-d/nipype
nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py
Python
bsd-3-clause
1,674
0.0227
# AUTO-GENERATED by tools/checkspec
s.py - DO NOT EDIT from __future__ import unicode_literals from ..registration import MeasureImageSimilarity def test_MeasureImageSimilarity_inputs(): input_map = dict(args=dict(argstr='%s', ), dimension=dict(argstr
='--dimensionality %d', position=1, ), environ=dict(nohash=True, usedefault=True, ), fixed_image=dict(mandatory=True, ), fixed_image_mask=dict(argstr='%s', ), ignore_exception=dict(nohash=True, usedefault=True, ), metric=dict(argstr='%s', mandatory=True, ), ...
shanot/imp
modules/atom/test/test_clone.py
Python
gpl-3.0
1,208
0.000828
import IMP import IMP.test import IMP.core import IMP.atom class Tests(IMP.test.TestCase): def test_bonded(self): """Check close and destroy Hierarchy """ m = IMP.Model() mh = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m) nump = len(m.get_particle_indexes()) m...
) IMP.atom.destroy(mh) mh = None
self.assertEqual(0, len(m.get_particle_indexes())) def test_destroy_child(self): """Destroy of a child should update the parent""" m = IMP.Model() mh = IMP.atom.read_pdb(self.get_input_file_name("mini.pdb"), m) atoms = IMP.atom.get_by_type(mh, IMP.atom.ATOM_TYPE) self.asser...
guillaume-philippon/aquilon
lib/aquilon/worker/commands/update_machine.py
Python
apache-2.0
16,386
0.000305
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ma...
old_bstore.holder.resourcegroup.name else: resourcegroup = None if old_bstore in disk_mapping: new_bstore = disk_mapping[old_bstore] else: new_bstore = find_resource(old_bstore.__class__, new_holder, resourcegroup, old_b...
error=ArgumentError) dbdisk.backing_store = new_bstore def update_interface_bindings(session, logger, dbmachine, autoip): for dbinterface in dbmachine.interfaces: old_pg = dbinterface.port_group if not old_pg: continue old_net = old_pg.network ...
chuckatkins/legion
language/examples/mssp/gen_graph.py
Python
apache-2.0
8,232
0.008017
#!/usr/bin/env python from __future__ import print_function import argparse import array import math import os import random import sys import subprocess def create_graph(nodes, edges, verbose): if verbose: print('Creating random graph with {} nodes and {} edges...'.format(nodes, edges)) n1 = [ random.randin...
1']).tofile(f) array.array('i', g['n2']).tofile(f) array.array('f', g['length']).tofile(f) with open(os.path.join(outdir, 'graph.dot'), 'wb') as f: f.write('digraph {\n') f.write('\n'.join('{} -> {} [ style = "{}"]'.format(e1, e2, 'dotted' if e2 <= e1 else 'solid'
) for e1, e2 in zip(g['n1'], g['n2']))) f.write('\n}\n') with open(os.path.join(outdir, 'graph.txt'), 'w') as f: f.write('nodes {:d}\n'.format(g['nodes'])) f.write('edges {:d}\n'.format(g['edges'])) f.write('data edges.dat\n') sources = random.sample(xrange(g['nodes']), pro...
wubr2000/googleads-python-lib
examples/dfp/v201502/creative_template_service/get_all_creative_templates.py
Python
apache-2.0
1,984
0.008569
#!/usr/bin/python # # 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 b...
uage governing permissions and # limitations under the License. """This code example gets all creative templates. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authenticat...
ur README. """ # Import appropriate modules from the client library. from googleads import dfp def main(client): # Initialize appropriate service. creative_template_service = client.GetService( 'CreativeTemplateService', version='v201502') # Create a filter statement. statement = dfp.FilterStatement...
bjodah/PyLaTeX
examples/full.py
Python
mit
2,838
0
#!/usr/bin/python """ This example demonstrates several features of PyLaTeX. It includes plain equations, tables, equations using numpy objects, tikz plots, and figures. .. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ # begin-doc-include import numpy as np from pylate...
te(Figure(position='h!')) as kitten_pic: kitten_pic.add_image(image_filename,
width='120px') kitten_pic.add_caption('Look it\'s on its back') doc.generate_pdf('full')
qedsoftware/commcare-hq
corehq/sql_accessors/migrations/0025_update_get_ledger_values_for_cases.py
Python
bsd-3-clause
703
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from corehq.form_processor.models import CaseTransaction from corehq.sql_db.operations import RawSQLMigration
, HqRunSQL migrator = RawSQLMigration(('corehq', 'sql_accessors', 'sql_templates'), { 'TRANSACTION_TYPE_FORM': CaseTransaction.TYPE_FORM }) class Migration(migrations.Migration): dependencies = [ ('sql_accessors', '0024_update_save_ledger_values'), ] operations = [ HqRunSQL( ...
for_cases.sql'), ]
DOE-NEPA/geonode_2.0_to_2.4_migration
migrate_documents_document_modified.py
Python
gpl-2.0
2,363
0.025815
#!/usr/bin/python import os import psycopg2 import sys import django_content_type_mapping file = open("/home/" + os.getlogin() + "/.pgpass", "r") pgpasses = [] for line in file: pgpasses.append(line.rstrip("\n").split(":")) file.close() for pgpass in pgpasses: #print str(pgpass) if pgpass[0] == "54.236.235.110"...
ignments.append(None) #doc_url assignments.append(None) try: dst_cur.execute("insert into documents_document(resourcebase_ptr_id, title_en, abstract_en, purpose_en, constraints_other_en, supplemental_information_en, distribution_description_en, data_quality_statement_en, content_type_id, object_id, doc_fil...
, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", assignments) dst.commit() except Exception as error: print print type(error) print str(error) + "select resourcebase_ptr_id, content_type_id, object_id, doc_file, extension, popular_count, share_count from documents_document" print str(src_r...
PlayCircular/play_circular
apps/actividades/admin_views.py
Python
agpl-3.0
2,927
0.02188
#coding=utf-8 # Copyright (C) 2014 by Víctor Romero Blanco <info at playcircular dot com>. # http://playcircular.com/ # It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise. # You can get copies of the licen
ses here: http://www.affero.org/oagpl.html # AFFERO GENERA
L PUBLIC LICENSE is also included in the file called "LICENSE". from django.contrib import admin from django.conf import settings from configuracion.models import * from django.contrib.auth.models import User from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseNotAllowed from django.temp...
noslenfa/tdjangorest
uw/lib/python2.7/site-packages/IPython/kernel/tests/test_public_api.py
Python
apache-2.0
1,308
0.006881
"""Test the IPython.kernel public API Authors ------- * MinRK """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed ...
----------------------------------------------------------------- import nose.tools as nt from IPython.testing import decorators as dec from IPython.kernel import launcher, connect from IPython import kernel #----------------------------------------------------------------------------- # Classes and functions #----...
er" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_kcs(): for base in ("", "Blocking"): KM = base + "KernelClient" yield nt.assert_true(KM in dir(kernel), KM) @dec.parametric def test_launcher(): for name in launcher.__all__: yield nt.assert_true(name in d...
miku/vy
vyapp/plugins/box.py
Python
mit
875
0.009143
""" """ from traceback import format_exc as debug from vyapp.stdout import Stdout from vyapp.tools import exec_quiet, set_status_msg from vyapp.ask import * import sys def redirect_stdout(area): try: sys.stdout.remove(area) except ValueError: pass sys.stdout.append(Stdout(area)) set_...
', lambda event: sys.stdout.restore()), ('NORMAL', '<Key-W>', lambda event: event.widget.tag_delete(Stdout.TAG_CODE)), ('NORMAL', '<Control-w>', lambda event: exec_quiet(sys.stdout.remove, event.widget)), ('NORMAL', '<Tab>', lambda event: redirect_stdout(event.widget)))
sourlows/rating-cruncher
src/lib/click/core.py
Python
apache-2.0
65,670
0.000091
import os import sys import codecs from contextlib import contextmanager from itertools import repeat from functools import update_wrapper from .types import convert_type, IntRange, BOOL from .utils import make_str, make_default_short_help, echo from .exceptions import ClickException, UsageError, BadParameter, Abort, ...
rameters except if the value is hidden in which #: case it's not remembered. self.params = {} #: the leftover arguments. self.args = [] if obj is None and parent is not None:
obj = parent.obj #: the user object stored. self.
neurodebian/pkg-neuron
share/lib/python/neuron/neuroml/rdxml.py
Python
gpl-2.0
1,545
0.029126
try: from xml.etree import cElementTree as etree except ImportError: from xml.etree import ElementTree as etree import xml2nrn # module names derived from the namespace. Add new tags in proper namespace import neuroml import metadata import morphml import biophysics class FileWrapper: def __init__(self, sou...
t('/')[-2] tag = ns+'.'+tag[1] #namespace.element should correspond to module.func f = None try: if event == 'start': f = eval(tag) elif event == 'end': f = eval(tag + '_end') except: pass if f: x2n.locator.lineno = fw.lineno try: f(x2n, node) # handle the element when it...
the element return 0 return 1 def rdxml(fname, ho = None): f = FileWrapper(open(fname)) x2n = xml2nrn.XML2Nrn() ig = None for event, elem in etree.iterparse(f, events=("start", "end")): if ig != elem: if handle(x2n, f, event, elem) == 0: ig = elem if (ho): ho.parsed(x2n) if __nam...
gpotter2/scapy
scapy/all.py
Python
gpl-2.0
1,320
0
# This file is part of Scapy # See http://www.secdev.org/projects/scapy for more information # Copyright (C) Philippe Biondi <phil@secdev.org> # This program is published under a GPLv2 license """ Aggregate top level objects from all Scapy modules. """ from scapy.base_classes import * from scapy.config import * from ...
t * from scapy.themes import * from scapy.arch import * from scapy.interfaces import * from scapy.plist import * from scapy.fields import * from scapy.packet import * from scapy.asn1fields import * from scapy.asn1packet import * from scapy.utils import * from scapy.route import * from scapy.sendrecv import * from sca...
* from scapy.as_resolvers import * from scapy.automaton import * from scapy.autorun import * from scapy.main import * from scapy.consts import * from scapy.compat import raw # noqa: F401 from scapy.layers.all import * from scapy.asn1.asn1 import * from scapy.asn1.ber import * from scapy.asn1.mib import * from sc...
testmana2/test
Helpviewer/Bookmarks/DefaultBookmarks_rc.py
Python
gpl-3.0
2,920
0.001712
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.4.1) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x01\xf1\ \x00\ \x00\x09\x00\x78\x9c\xdd\x96\x51\x6f\x9b\x30\x10\xc7\xdf\xfb\x29\ \x3c\x1e\x9a\x4...
a4\ \xf9\xa3\xf6\x3a\x1a\xea\xd8\xdb\x03\xff\x7e\x05\xf0\x2b\xfd\xfb\ \xb8\x0a\x6c\xf5\xb3\xa3\xa4\x1a\x72\x85\x59\x94\xe3\x08\x4a\x5a\
\xd6\x93\x2a\x88\x42\xd0\x66\x12\x65\xbf\x33\x11\x1f\x93\xb8\xcc\ \xe3\x92\x85\xb0\x19\x22\xbf\xf0\x2f\x3f\xb8\xd4\x7b\xbd\xbd\x45\ \x2f\x20\x3b\x74\x5f\x5d\x03\xcb\xff\xdb\x0b\xeb\xdb\xbf\xa1\x9f\ \xf0\x0a\x67\x44\x52\xa1\x86\x09\x27\x95\x98\x5a\x95\x65\x90\x62\ \x9a\x28\x3e\x1c\xcf\xef\xbd\x5f\xb3\xc9\x9d\x3b\x40\x67...
heddle317/moto
moto/elb/models.py
Python
apache-2.0
15,471
0.001357
from __future__ import unicode_literals import datetime from boto.ec2.elb.attributes import ( LbAttributes, ConnectionSettingAttribute, ConnectionDrainingAttribute, AccessLogAttribute, CrossZoneLoadBalancingAttribute, ) from boto.ec2.elb.policies import ( Policies, OtherPolicy, ) from moto....
instance_port=( port.get('instance_port') or port['InstancePort']), ssl_certificate_id=port.get( 'ssl_certificate_id', port.get('SSLCertificateId')), ) self.listeners.append(listener) # it is unclear per the AWS document...
and set it here *shrug* backend = FakeBackend( instance_port=( port.get('instance_port') or port['InstancePort']), ) self.backends.append(backend) @classmethod def create_from_cloudformation_json(cls, resource_name, cloudformation_json, r...
carpedm20/fbchat
tests/threads/test_group.py
Python
bsd-3-clause
1,493
0
from fbchat import GroupData, User def test_group_from_graphql(session): data = { "name": "Group ABC", "thread_key": {"thread_fbid": "11223344"}, "image": None, "is_group_thread": True, "all_participants": { "nodes": [ {"messaging_actor": {"__typ...
[{"id": "1234"}], "group_approval_queue": {"nodes": []}, "approval_mode": 0, "joinable_mode": {"mode": "0", "link": ""}, "event_reminders": {"nodes": []}, } assert GroupData( session=session, id="11223344", photo=None, name="Group ABC", las...
n, id="2345"), User(session=session, id="3456"), ], nicknames={}, color="#0084ff", emoji="😀", admins={"1234"}, approval_mode=False, approval_requests=set(), join_link="", ) == GroupData._from_graphql(session, data)
switch-education/pxt
tests/pydecompile-test/baselines/enum_user_defined_bit_mask_bad_sequence.py
Python
mit
148
0.027027
/// <ref
erence path="./testBlocks/enums.ts" /> enum EnumOfFlags { W
= 1, X = 1 << 1, Z = 1 << 3 } let userDefinedTest7 = EnumOfFlags.W
psy0rz/zfs_autobackup
zfs_autobackup/TreeHasher.py
Python
gpl-3.0
2,011
0.015415
import itertools import os class TreeHasher(): """uses BlockHasher recursively on a directory tree Input and output generators are in the format: ( relative-filepath, chunk_nr, hexdigest) """ def __init__(self, block_hasher): """ :type block_hasher: BlockHasher """ ...
her.generate(file_path): yield ( os.path.relpath(file_path,start_path), chunk_nr, hash ) def compare(self, start_path, g
enerator): """reads from generator and compares blocks yields mismatches in the form: ( relative_filename, chunk_nr, compare_hexdigest, actual_hexdigest ) yields errors in the form: ( relative_filename, chunk_nr, compare_hexdigest, "message" ) """ count=0 def filt...
cadrian/microcosmos
src/net/cadrian/microcosmos/model/bugs/__init__.py
Python
gpl-3.0
1,120
0.000893
# Microcosmos: an antsy game # Copyright (C) 2010 Cyril ADRIAN <cyril.adrian@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 exclusively. # # This program is distrib...
gram. If not, see <http://www.gnu.org/licenses/>. # """ The Bugs model package provides bugs and their specific behaviour. """ from net.cadrian.microcosmos.model.bugs.antFemales import AntFemale, Target as AntFemaleTarget from net.cadrian.microcosmos.model.bugs.antQueens import AntQueen from net.cadrian.microcosmos.m...
.antWorkers import AntWorker from net.cadrian.microcosmos.model.bugs.lice import Louse
ProgrammaBol/wiggler
wiggler/ui/resources.py
Python
gpl-3.0
10,546
0
import wx import wiggler.ui.dialogs as dialogs class ResourceManager(wx.Control): def __init__(self, parent, resources, events): wx.Control.__init__(self, parent) self.parent = parent self.events = events self.resources = resources self.events.subscribe(self, ['add_costum...
'add_sheet': self.add_sheet() elif event.notice == 'del_sheet': self.del_sheet() elif event.notice == 'add_image': pass elif event.notice == 'del_image': pass elif event.notice == 'add_character': self.add_cha
racter() elif event.notice == 'del_character': self.del_character() elif event.notice == 'add_animation': pass elif event.notice == 'del_animation': pass elif event.notice == 'add_sprite': self.add_sprite() elif event.notice == 'del...
nevil-brownlee/pypy-libtrace
test/pypy-test-cases/test-bpf-filter.py
Python
gpl-3.0
780
0.007692
#!/usr/bin/env python # Thu, 13 Mar 14 (PDT) # bpf-filter.rb: Create a packet filter, # use it to print udp records from a trace # Copyright (C) 2015, Nevil Brownlee, U Auckland | WAND from plt_testing import * t = get_example_trace('anon-v4.pcap') filter = plt
.filter('udp port 53') # Only want DNS packets t.conf_filter(filter) t.conf_snaplen(500) #t.conf_promisc(True) # Remember: on a live interface, must sudo to capture # on a trace file, can't set promicuous nfp = 0; offset = 12 for pkt in t: nfp += 1 udp = pkt.udp test_println("%4d:" % (n...
fp == 4: break test_println("%d filtered packets" % nfp, get_tag())
runt18/nupic
src/nupic/algorithms/CLAClassifier.py
Python
agpl-3.0
25,671
0.006544
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
self._classifier.verbosity >= 2: print "bucket votes for {0!s}:".format((self._id)), _pFormatArray(votes) def __getstate__(self): return dict((elem, getattr(self, elem)) for elem in self.__slots__) def __setstate__(self, state): version = 0 if "_version" in state: version = state["_versi...
self._stats = array.array("f", itertools.repeat(0.0, maxBucket + 1)) for (index, value) in stats.iteritems(): self._stats[index] = value elif version == 1: state.pop("_updateDutyCycles", None) elif version == 2: pass else: raise Exception("Error while deserializing {0!s}: I...
charlesccychen/beam
sdks/python/apache_beam/transforms/window.py
Python
apache-2.0
18,027
0.007544
# # 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...
is WindowFn merges windows.""" return True @abc.abstractmethod def get_window_coder(self): raise NotImplementedError def get_transformed_output_time(self, window, input_timestamp): # pylint: disable=unused-argument """Given input time and output window, returns output time for window. If Times...
ombiner.OUTPUT_AT_EARLIEST_TRANSFORMED is used in the Windowing, the output timestamp for the given window will be the earliest of the timestamps returned by get_transformed_output_time() for elements of the window. Arguments: window: Output window of element. input_timestamp: Input timesta...
rparrapy/sugar
extensions/cpsection/updater/view.py
Python
gpl-2.0
16,181
0
# Copyright (C) 2008, One Laptop Per Child # Copyright (C) 2009, Tomeu Vizoso # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later v...
ogress_pane in self.get_children(): self.remove(self._progress_pane) self._progress_pane = None if self._update_box is None: self._update_box = UpdateBox(updates) self._update_box.refresh_button.connect( 'clicked', self.__refresh_b...
'clicked', self.__install_button_clicked_cb) self.pack_start(self._update_box, expand=True, fill=True, padding=0) self._update_box.show() def _switch_to_progress_pane(self): if self._progress_pane in self.get_children(): return if self._model.get_st...
obi-two/Rebelion
data/scripts/templates/object/tangible/loot/loot_schematic/shared_death_watch_mandalorian_belt_schematic.py
Python
mit
509
0.043222
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE
IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/loot/loot_schematic/shared_death_watch_mandalorian_belt_schematic.iff" result.attribute_template_id = -1 result.stfName("craft_item_ingredients_...
lt") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
fidencio/sssd
src/sbus/codegen/sbus_Introspection.py
Python
gpl-3.0
9,617
0
# # Authors: # Pavel Brezina <pbrezina@redhat.com> # # Copyright (C) 2017 Red Hat # # 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 yo...
: """ This is a base class for invokable objects -- methods and signals. Invokable objects has available additional attributes: - input OrderedDict -- input signature and arguments - output : OrderedDict -- output signature and arguments """ def __init__(self...
) self.key = self.getAttr("key", None) self.arguments = self.find(SBus.Argument) input = self.getInputArguments() output = self.getOutputArguments() self.input = SBus.Signature(input, self.annotations) self.output = SBus.Signature(output, self.a...
GHubgenius/clusterd
src/platform/jboss/fingerprints/JBoss5JMX.py
Python
mit
182
0.005495
from src.platform.jboss
.interfaces i
mport JMXInterface class FPrint(JMXInterface): def __init__(self): super(FPrint, self).__init__() self.version = "5.0"
pydanny/django-easy-profiles
test_project/urls.py
Python
mit
223
0.004484
from django.conf.urls.defaults import * from django.contrib import admin admin.
autodiscover() urlpatterns = patterns('', (r'^profiles/', include('easy_profiles.urls')
), (r'^admin/', include(admin.site.urls)), )
HaraldWeber/client
src/modvault/utils.py
Python
gpl-3.0
15,457
0.012292
#------------------------------------------------------------------------------- # Copyright (c) 2012 Gael Honorez. # All rights reserved. This program and the accompanying materials # are made available under the terms of the GNU Public License v3.0 # which accompanies this distribution, and is available at # http://w...
def update(self): self.setFolder(self.localfolder) if isinstance(self.version, int): self.totalname = "%s v%d" % (self.name, self.version) elif isinstance(self.version, float):
s = str(self.version).rstrip("0") self.totalname = "%s v%s" % (self.name, s) else: raise TypeError, "version is not an int or float" def to_dict(self): out = {} for k,v in self.__dict__.items(): if isinstance(v, (unicode, str, int, float)) and not k[0...
lordakshaya/pyexcel
examples/example_usage_of_internal_apis/simple_usage/series.py
Python
bsd-3-clause
2,753
0.006902
""" series.py :copyright: (c) 2014-2015 by Onni Software Ltd. :license: New BSD License, see LICENSE for more details This shows how to use **SeriesReader** to get the data in various ways But you can use them with **Reader** class as well """ import os from pyexcel.ext import ods3 from pyexcel import SeriesReader fro...
a two dimensional array in reverse # order data = to_array(reader.rrows()) print(data) # [[3.0, 6.0, 9.0], [2.0, 5.0, 8.0], [
1.0, 4.0, 7.0]] # get a two dimensional array but stack columns data = to_array(reader.columns()) print(data) # [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] # get a two dimensional array but stack columns # in reverse order data = to_array(reader.rcolumns()) print(data)...
geography-munich/sciprog
material/sub/jrjohansson/scripts/hello-world.py
Python
apache-2.0
45
0
#
!/usr/bin/env python print("Hello world!")
ep1cman/workload-automation
wlauto/devices/linux/odroidxu3_linux/__init__.py
Python
apache-2.0
1,073
0.001864
# Copyright 2014-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
# 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. # from wlauto import LinuxDevice, Parameter class OdroidXU3LinuxDevice(LinuxDevice): name = "odroidxu3_linux" desc
ription = 'HardKernel Odroid XU3 development board (Ubuntu image).' core_modules = [ 'odroidxu3-fan', ] parameters = [ Parameter('core_names', default=['a7', 'a7', 'a7', 'a7', 'a15', 'a15', 'a15', 'a15'], override=True), Parameter('core_clusters', default=[0, 0, 0, 0, 1, 1, 1, 1], ...
davogler/POSTv3
customers/migrations/0010_auto_20170124_2322.py
Python
mit
412
0.002427
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migrat
ion): dependencies = [ ('customers', '0009_recipient_type'), ] operations = [ migrations.AlterModelOptions( name='recipient', options={'ordering': ['last_name'], 'verbose_name_plural':
'Recipients'}, ), ]
jr55662003/My_Rosalind_solution
RSTR.py
Python
gpl-3.0
1,176
0.008547
''' Given: A positive integer N≤100000, a number x between 0 and 1, and a DNA string s of length at most 10 bp. Return: The probability that if N random DNA strings having the same length as s are constructed with GC-content x (see “Introduction to Random Strings”), then at least one of the strings equals s. We allo...
ne of the s
trings equals s) def random_motif_match(N, x, s): s_construct = {"A": (1 - x) / 2, "T": (1 - x) / 2, "C": x / 2, "G": x / 2} prob = 1 # probability of exactly equals to s for b in s: prob *= s_construct[b] return 1 - (1 - prob) **...
OS2World/APP-INTERNET-torpak_2
Tools/scripts/byext.py
Python
mit
3,894
0.002311
#! /usr/bin/env python """Show file statistics by extension.""" import os import sys class Stats: def __init__(self): self.stats = {} def statargs(self, args): for arg in args: if os.path.isdir(arg): self.statdir(arg) elif os.path.isfile(arg): ...
update(self.stats[ext]) cols = columns.keys() cols.sort() colwidth = {} colwidth["ext"] = max([len(ext) for ext in exts]) minwidth = 6 self.stats["TOTAL"] = {} for col in cols: total = 0 cw = max(minwidth, len(col)) for ext in e...
value = self.stats[ext].get(col) if value is None: w = 0 else: w = len("%d" % value) total += value cw = max(cw, w) cw = max(cw, len(str(total))) colwidth[col] = cw self.st...
leeseuljeong/leeseulstack_neutron
neutron/api/v2/attributes.py
Python
apache-2.0
28,875
0.000035
# Copyright (c) 2012 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
no_whitespace(data)) except Exception: valid_mac = False # TODO(arosen): The code in this file should be refactored # so it
catches the correct exceptions. _validate_no_whitespace # raises AttributeError if data is None. if not valid_mac: msg = _("'%s' is not a valid MAC address") % data LOG.debug(msg) return msg def _validate_mac_address_or_none(data, valid_values=None): if data is None: return...
obi-two/Rebelion
data/scripts/templates/object/draft_schematic/food/shared_dish_cho_nor_hoola.py
Python
mit
452
0.04646
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE T
HE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_s
chematic/food/shared_dish_cho_nor_hoola.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
jwacalex/MULTEX-EAST-PoS-Tagger
mte.py
Python
lgpl-3.0
12,810
0.009446
""" A reader for corpora whose documents are in MTE format. """ import os from functools import reduce from nltk import compat from nltk.corpus.reader import concat, TaggedCorpusReader lxmlAvailable = False try: from lxml import etree lxmlAvailable = True except ImportError: #first try c version of Element...
be used. :return: the given file(s) as a list of words and punctuation symbols. :rtype: list(str) """ return reduce(lambda a, b : a + b ,[MTEFileReader(os.path.join(self._root, f)).words() for f in self.__fileids(fileids)], []) def sents(self, fileids=None): """ :param...
each encoded as a list of word strings :rtype: list(list(str)) """ return reduce(lambda a, b : a + b ,[MTEFileReader(os.path.join(self._root, f)).sents() for f in self.__fileids(fileids)], []) def paras(self, fileids=None): """ :param fileids: A list specifying the fileids t...
charlesthomas/coinshot
setup.py
Python
mit
1,206
0.000829
#!/usr/bin/env python from setuptools import setup NAME = 'coinshot' DESCRIPTION = 'simple python module for pushover.net' VERSION = open('VERSION').read().strip() LONG_DESC = open('README.rst').read() LICENSE = "MIT License" setup( name=NAME, version=VERSION, author='Charles Thomas', author_email='ch...
table',
'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Programming Language :: Pyt...
lnhubbell/tweetTrack
streamScript/domain/get_tweets_by_user.py
Python
mit
5,107
0.000196
import os import tweepy from query_db import query_db, send_user_queries_to_db, read_in_bb_file from our_keys.twitter_keys import my_keys from itertools import chain, repeat u"""Reads in a file of cities and their bounding boxes. Queries the database to get a list of all unique users who have tweeted from that city. ...
, city=None, cap=100, data_collection=True): u"""Calls function to return a dict of cities and the unique users for each city. Iterates over the dict to extract the tweet text/locations/timestamps for each tweet, bundles results into DB-friendly tuples. Returns a list of lists of tuples.""" api_gene...
api = api_generator.next() city_tweets = [] user_count = 0 too_low_count = 0 for user in users: if user_count > cap: break if user in check_list_low_tweeters() and data_collection is True: continue history = [] # tweet_history = [] try: ...
facebookresearch/ParlAI
parlai/agents/safe_local_human/safe_local_human.py
Python
mit
4,597
0.00087
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Agent that gets the local keyboard input in the act() function. Applies safety classifier(s) to process user and par...
turn # Now check if bot was offensive bot_offensive = self.check_offensive(msg.get('text', '')) if not bot_offensive: # View bot message print( display_messages( [msg], add_fields=self.opt.get('display_add_fields', ...
splay_prettify', False), verbose=self.opt.get('verbose', False), ) ) msg.force_set('bot_offensive', False) else: msg.force_set('bot_offensive', True) print(OFFENSIVE_BOT_REPLY) def get_reply(self): reply_text = inpu...
metu-kovan/human_model
src/animator.py
Python
gpl-3.0
8,441
0.050468
#!/usr/bin/env python import roslib roslib.load_manifest('human_model') import rospy import json import tf import numpy from abc import ABCMeta,abstractmethod from tf.transformations import quaternion_multiply as quatMult,quatern
ion_conjugate from collections import deque,defaultdict,OrderedDict """Module for converting tf data to construct a human model""" def Vec(*args): """returns a vector (numpy float array) with the length of number of given arguments""" return numpy.array(args,dtype=float)
def normalize(v): """returns unit vector or quaternion""" return v/numpy.linalg.norm(v) def quatRotatePoint(q,p,o=Vec(0,0,0)): """returns point p rotated around quaternion q with the origin o (default (0,0,0)""" return quatMult( quatMult(q,numpy.append(p-o,(0,))), quaternion_conjugate(q) )[:3]+o def calcu...
henrist/aqmt
aqmt/calc_window.py
Python
mit
2,753
0.001453
#!/usr/bin/env python3 # # This file generates an estimation of window size for the # two queues for _each_ sample. It will not be exact, and # it's correctness will vary with the variation of queue delay # in the queue. # # The results are saved to: # - derived/window # each line formatted as: <sample id> <window ec...
sage: %s <test_folde
r> <rtt_ecn_ms> <rtt_nonecn_ms>' % sys.argv[0]) sys.exit(1) process_test( sys.argv[1], float(sys.argv[2]), float(sys.argv[3]), ) print('Generated win')
spaam/svtplay-dl
lib/svtplay_dl/service/vimeo.py
Python
mit
1,817
0.003302
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- import copy import json import re from svtplay_dl.error import ServiceError from svtplay_dl.fetcher.hls import hlsparse from svtplay_dl.fetcher.http import HTTP from svtplay_dl.service import OpenGraphThumbMixin from svtplay_dl.se...
n jso
ndata["request"]["files"]["hls"]["cdns"]): hls_elem = jsondata["request"]["files"]["hls"]["cdns"]["fastly_skyfire"] yield from hlsparse(self.config, self.http.request("get", hls_elem["url"]), hls_elem["url"], output=self.output) avail_quality = jsondata["request"]["files"]["...
Thingee/cinder
cinder/scheduler/weights/capacity.py
Python
apache-2.0
3,311
0.000302
# Copyright (c) 2013 eBay Inc. # Copyright (c) 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/lice...
ing to be the default.""" reserved = float(host_state.reserved_percentage) / 100 free_space = host_state.free_capacity_gb if free_space == 'infinite' or free_space == 'unknown': #(zhiteng) 'infinite' and 'unknown' are treated the same # here, for sorting purpose. ...
Weigher): def _weight_multiplier(self): """Override the weight multiplier.""" return CONF.allocated_capacity_weight_multiplier def _weigh_object(self, host_state, weight_properties): # Higher weights win. We want spreading (choose host with lowest # allocated_capacity first) to...
tropp/acq4
acq4/analysis/scripts/beamProfiler.py
Python
mit
976
0.009221
from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames)...
frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2*...
[3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure()
ithinksw/philo
philo/contrib/julian/__init__.py
Python
isc
89
0.033708
""" This ver
sion of julian is currently in development and
is not considered stable. """
asvetlov/optimization-kaunas-2017
2.py
Python
apache-2.0
463
0.006479
import timeit import pyximport; pyximpor
t.install() from mod2 import cysum, cysum2 def pysum(start, step, count): ret = start for i in range(count): ret += step return ret print('Python', timeit.timeit('pysum(0, 1, 100)', 'from __main__ import pysum')) print('Cython', ti
meit.timeit('cysum(0, 1, 100)', 'from __main__ import cysum')) print('Cython with types', timeit.timeit('cysum2(0, 1, 100)', 'from __main__ import cysum2'))
SoftwareIntrospectionLab/MininGit
pycvsanaly2/extensions/FileTypes.py
Python
gpl-2.0
6,480
0.00571
# Copyright (C) 2008 LibreSoft # # 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. # # This program is distributed in the ...
raise try: cursor.execute("create index repository_id on files(repository_id)") except MySQLdb.OperationalError, e: if e.args[0] != 1061: cursor.close() raise cursor.close...
_files_for_repository(self, repo_id, cursor): query = "SELECT ft.file_id from file_types ft, files f " + \ "WHERE f.id = ft.file_id and f.repository_id = ?" cursor.execute(statement(query, self.db.place_holder), (repo_id,)) files = [res[0] for res in cursor.fetchall()] r...
jacquesqiao/Paddle
python/paddle/fluid/tests/unittests/test_fake_quantize_op.py
Python
apache-2.0
1,823
0
# Copyright (c) 2018 PaddlePaddle 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 app...
limitations under the License. import unittest import numpy as np from op_test import OpTest class TestFakeQuantizeOp(OpTest): def setUp(self): self.op_type = "fake_quantize" self.attrs = { 'bit_length': 8, 'quantiz
e_type': 'abs_max', 'window_size': 10000 } self.inputs = { 'X': np.random.random((10, 10)).astype("float32"), 'InScales': np.zeros(self.attrs['window_size']).astype("float32"), 'InCurrentIter': np.zeros(1).astype("float32"), 'InMovingScale': np...
Veeenz/Telegram-DMI-Bot
classes/StringParser.py
Python
gpl-3.0
328
0.036585
# -*- coding: utf-8 -*- import re class StringParser(object): @staticmethod def removeCFU(stringToParse): updatedString = re.sub('\s?[0-9] CFU.*', '', stringToParse) return updatedString @stat
icmethod def startsWithUpper(stringToPa
rse): stringToParse = stringToParse[0].upper()+stringToParse[1:] return stringToParse
luisfer85/newspaper2
newspaper2/newspaper2/news/migrations/0003_event_publish_date.py
Python
apache-2.0
520
0.001923
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-22 14:42 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0002_event'), ] operations = [ migrations.AddField( model_name='event', ...
]
vorwerkc/pymatgen
pymatgen/electronic_structure/boltztrap.py
Python
mit
103,362
0.001887
""" This module provides classes to run and analyze boltztrap on pymatgen band structure objects. Boltztrap is a software interpolating band structures and computing materials properties from this band structure using Boltzmann semi-classical transport theory. Boltztrap has been developed by Georg Madsen. http://www....
self.error = [] self.run_type = run_type self.band_nb = band_nb self.spin = spin self.cond_band = cond_band self.tauref = tauref self.tauexp = tauexp self.tauen = tauen self.soc = soc self.kpt_line = kpt_line self.cb_cut = cb_cut / 100....
9, 1e20, 1e21]: self.doping.extend([1 * d, 2.5 * d, 5 * d, 7.5 * d]) self.doping.append(1e22) self.energy_span_around_fermi = energy_span_around_fermi self.scissor = scissor self.tmax = tmax self.tgrid = tgrid self._sy
jnosal/seth
seth/tests/test_versioning.py
Python
mit
6,814
0.001761
from seth import versioning from seth.tests import IntegrationTestBase from seth.classy.rest import generics class DefaultVersioningResource(generics.GenericApiView): def get(self, **kwargs): return {} class NotShowVersionResource(generics.GenericApiView): display_version = False def get(self,...
ams') class AllowVersionOnePolicy(versioning.CheckQueryParamsVersioningPolicy): default_version = '22.0' def get_allowed_version(self): return ['5.0'] class CheckQueryParamsResourceSecond(generics.GenericApiView): versioning_policy = AllowVersionOne...
et(self, **kwargs): return {} config.register_resource(CheckQueryParamsResourceSecond, '/test_allow_version') def test_no_version_in_query_params_all_versions_allowed(self): r = self.app.get('/test_query_params') self.assertEqual(r.status_int, 200) def test_wrong_versi...
SickGear/SickGear
lib/soupsieve_py3/css_types.py
Python
gpl-3.0
8,916
0.001682
"""CSS selector structure items.""" import copyreg from collections.abc import Hashable, Mapping __all__ = ( 'Selector', 'SelectorNull', 'SelectorTag', 'SelectorAttribute', 'SelectorContains', 'SelectorNth', 'SelectorLang', 'SelectorList', 'Namespaces', 'CustomSele...
') elif not is_dict and not all([isinstance(k, str) and isinstance(v, str) for k, v in arg]): raise Type
Error('CustomSelectors keys and values must be Unicode strings') super(CustomSelectors, self).__init__(*args, **kwargs) class Selector(Immutable): """Selector.""" __slots__ = ( 'tag', 'ids', 'classes', 'attributes', 'nth', 'selectors', 'relation', 'rel_type', 'contains', 'l...
danbob123/gplearn
gplearn/skutils/tests/test_validation.py
Python
bsd-3-clause
14,136
0.000283
"""Tests for input validation functions""" import warnings from tempfile import NamedTemporaryFile from itertools import product import numpy as np from numpy.testing import assert_array_equal, assert_warns import scipy.sparse as sp from nose.tools import assert_raises, assert_true, assert_false, assert_equal from ...
dim) check_array(X_ndim, allow_nd=True) # doesn't raise # force_all_finite X_inf = np.arange(4).reshape(2, 2).astype(np.float) X_inf[0, 0] = np.inf assert_raises(ValueError, check_array, X_inf) check_array(X_inf, force_all_finite=False) # no raise # nan che
ck X_nan = np.arange(4).reshape(2, 2).astype(np.float) X_nan[0, 0] = np.nan assert_raises(ValueError, check_array, X_nan) check_array(X_inf, force_all_finite=False) # no raise # dtype and order enforcement. X_C = np.arange(4).reshape(2, 2).copy("C") X_F = X_C.copy("F") X_int = X_C.asty...
mywulin/functest
functest/tests/unit/cli/test_cli_base.py
Python
apache-2.0
3,933
0
#!/usr/bin/env python # Copyright (c) 2016 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # pylint: d...
f.assertEqual(result.exit_code, 0) self.assertTrue(mock_method.called) def test_tier_list(self): with mock.patch.object(self._tie
r, 'list') as mock_method: result = self.runner.invoke(cli_base.tier_list) self.assertEqual(result.exit_code, 0) self.assertTrue(mock_method.called) def test_tier_show(self): with mock.patch.object(self._tier, 'show') as mock_method: result = self.runner.invo...
buguen/pylayers
pylayers/antprop/examples/ex_antenna5.py
Python
lgpl-3.0
2,472
0.029126
from pylayers.antprop.antenna import * from pylayers.antprop.antvsh import * import matplotlib.pylab as plt from numpy import * import pdb """ This test : 1 : loads a measured antenna 2 : applies an electrical delay obtained from data with getdelay method 3 : eva
luate the antenna vsh coefficient with a downsampling factor of 2 4 : evaluates the relative error of reconstruction (vsh3) for various values of order l 5 : display the results """ filename = 'S1R1.mat' A = Antenna(filename,
'ant/UWBAN/Matfile') B = Antenna(filename,'ant/UWBAN/Matfile') #plot(freq,angle(A.Ftheta[:,maxPowerInd[1],maxPowerInd[2]]*exp(2j*pi*freq.reshape(len(freq))*electricalDelay))) freq = A.fa.reshape(104,1,1) delayCandidates = arange(-10,10,0.001) electricalDelay = A.getdelay(freq,delayCandidates) disp('Electrical Delay = ...
Kingdread/qutebrowser
qutebrowser/browser/tabhistory.py
Python
gpl-3.0
5,900
0.003559
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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 Softwa...
enumerate(items):
if item.active: if current_idx is not None: raise ValueError("Multiple active items ({} and {}) " "found!".format(current_idx, i)) else: current_idx = i if items: if current_idx is None: raise ValueE...
sdpython/pyquickhelper
_unittests/ut_pycode/test_venv_helper.py
Python
mit
902
0
""" @brief test tree node (time=50s) """ import sys import os import unittest from pyquickhelper.loghelper import fLOG from pyquickhelper.pycode import get_temp_folder, ExtTestCase from pyquickhelper.pycode.venv_helper import create_virtual_env class TestVenvHelper(ExtTestCase): def test_venv_empty(self):...
get_temp_folder(__file__, "temp_venv_empty") out = create_virtual_env(temp, fLOG=fLOG) fLOG("-----") fLOG(out) fLOG("-----") pyt = os.path.join(temp, "Scripts") self.assertExists(pyt) lo = os.listdir(pyt) self.assertNotEmpty(lo)
if __name__ == "__main__": unittest.main()
mprochnow/mpdav
mpdav/file_backend.py
Python
gpl-3.0
12,064
0.001078
# coding: utf-8 # # This file is part of mpdav. # # mpdav 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. # # mpdav is distributed in t...
ame) f = open(filename, "wb")
if content_length: remaining = content_length while remaining > 0: buf = body.read(min(remaining, BLOCK_SIZE)) if len(buf): f.write(buf) remaining -= len(buf) else: break ...
befelix/GPy
GPy/likelihoods/link_functions.py
Python
bsd-3-clause
4,850
0.008454
# Copyright (c) 2012-2015 The GPy authors (see AUTHORS.txt) # Licensed under the BSD 3-clause license (see LICENSE.txt) import numpy as np import scipy from ..util.univariate_Gaussian import std_norm_cdf, std_norm_pdf import scipy as sp from ..util.misc import safe_exp, safe_square, safe_cube, safe_quad, safe_three_ti...
)._to_dict() input_dict["class"] = "GPy.likelihoods.link_functions.Identity" return input_dict class Probit(GPTransformation): """ .. math:: g(f) = \\Phi^{-1} (mu) """ def transf(self,f): return std_norm_cdf(f) def dtransf_df(self,f): return std_norm_pdf(f...
e_square(f)-1.)*std_norm_pdf(f) def to_dict(self): input_dict = super(Probit, self)._to_dict() input_dict["class"] = "GPy.likelihoods.link_functions.Probit" return input_dict class Cloglog(GPTransformation): """ Complementary log-log link .. math:: p(f) = 1 - e^{-e^f}...
limodou/uliweb
uliweb/contrib/develop/__init__.py
Python
bsd-2-clause
318
0.012579
def dev_nav(active=None): from
uliweb import settings out = "<span>" for i in settings.MENUS_DEVELOP.nav: if active!=i["name"]: out += "<a href='%s'>%s<a> "%(i["link"],i["title"]) else: out += "<strong>%s</strong> "%(i["title"]) out += "</span>" return ou
t
tommy-u/enable
examples/savage/toggle_demo.py
Python
bsd-3-clause
673
0.002972
import os from traits.api import HasTraits from traitsui.api import View, Item from enable.savage.trait_defs.ui.svg_button import SVGButton pause_icon = os.path.join(os.path.dirname(__file__), 'player_pause.svg') resume_icon = os.path.join(os.path.dirname(__file__), 'player_play.svg') class SVGDemo(HasTrait
s): pause = SVGButton('Pause', filename=pause_icon, toggle_filename=resume_icon, toggle_state=True, toggle_label='Resume',
toggle_tooltip='Resume', tooltip='Pause', toggle=True) trait_view = View(Item('pause')) SVGDemo().configure_traits()
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Lib/idlelib/rpc.py
Python
gpl-2.0
21,137
0.000899
"""RPC Implementation, originally written for the Python Idle IDE For security reasons, GvR requested that Idle's Python execution server process connect to the Idle process, which listens for the connection. Since Idle has only one client per server, this was not a limitation. +---------------------------------+...
andlerclass=None): if handlerclass is None: handlerclass = RPCHandler socketserver.TCPServer.__init__(self, addr, handlerclass) def server_bind(self): "Override TCPServer method, no bind() phase for connecting entity"
pass def server_activate(self): """Override TCPServer method, connect() instead of listen() Due to the reversed connection, self.server_address is actually the address of the Idle Client to which we are connecting. """ self.socket.connect(self.server_address) de...
okanasik/JdeRobot
src/tools/visualStates/samples/goforward/goforward.py
Python
gpl-3.0
4,201
0.035468
#!/usr/bin/python # -*- coding: utf-8 -*- import easyiceconfig as EasyIce import jderobotComm as comm import sys, signal sys.path.append('/usr/local/share/jderobot/python/visualHFSM_py') import traceback, threading, time from automatagui import AutomataGui, QtGui, GuiSubautomata from jderobot import MotorsPrx from jd...
return guiSubautomataList def shutDown(self): self.run1 = False def runGui(self): app = QtGui.QApplication(sys.argv) self.automataGui = AutomataGui() self.automataGui.setAutomata(self.createAutomata()) self.automataGui.loadAutomata() self.startThreads() self.automataGui.show() app.exec_() def s...
1): totala = time.time() * 1000000 # Evaluation if if(self.sub1 == "GoForward"): if(self.calculate_obstacle()): self.sub1 = "GoBack" if self.displayGui: self.automataGui.notifySetNodeAsActive('GoBack') elif(self.sub1 == "GoBack"): if(not self.calculate_obstacle()): self.sub1 =...
cloudtools/awacs
awacs/iotanalytics.py
Python
bsd-2-clause
2,141
0.000467
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS IoT Analytics" prefix = "iotanalytics" class Action(BaseAction): def __init__(self, action: str = None) -> None: ...
ion("ListTagsForResource") PutLoggingOptions = Action("PutLoggingOptions") RunPipelineActivity =
Action("RunPipelineActivity") SampleChannelData = Action("SampleChannelData") StartPipelineReprocessing = Action("StartPipelineReprocessing") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateChannel = Action("UpdateChannel") UpdateDataset = Action("UpdateDataset") UpdateDatastore = Acti...
BirkbeckCTP/janeway
jenkins/janeway_settings.py
Python
agpl-3.0
160
0.00625
INSTALLED_APPS= ["django_nose"] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' NOSE_ARGS = [ '--with-xunit', '--xunit-file=jenkins
/nosetests.xml', ]
anchore/anchore-engine
anchore_engine/analyzers/syft/handlers/python.py
Python
apache-2.0
2,570
0.002724
import os from anchore_engine.analyzers.syft.handlers.common import save_entry_to_findings from anchore_engine.analyzers.utils import dig def save_entry(findings, engine_entry, pkg_key=None): if not pkg_key: pkg_name = engine_entry.get("name", "") pkg_version = engine_entry.get( "vers...
llations (with rich metadata) return site_pkg_root = artifact["metadata"]["sitePackagesRootPath"] name = artifact["name"] # anchore engine always uses the name, however, the name may not be a top-level package # instead default to the first top-level package unless the name is listed among the...
ata", "topLevelPackages", force_default=[]) pkg_key_name = None for key_name in pkg_key_names: if name in key_name: pkg_key_name = name else: pkg_key_name = key_name if not pkg_key_name: pkg_key_name = name pkg_key = os.path.join(site_pkg_root, pkg_key_n...
matrix-org/synapse
contrib/experiments/cursesio.py
Python
apache-2.0
4,229
0.000473
# Copyright 2014-2016 OpenMarket Ltd # # 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 w...
tup(self): self.stdscr.nodelay(1) # Make non blocking self.rows, self.cols = self.stdscr.getmaxyx() self.lines = [] curses.use_default_colors() self.paintStatus(self.statusText) self.stdscr.refresh() def set_callback(self, callback): self.callback = callb...
def connectionLost(self, reason): self.close() def print_line(self, text): """add a line to the internal list of lines""" self.lines.append(text) self.redraw() def print_log(self, text): self.logLine = text self.redraw() def redraw(self): """...
m42e/jirash
lib/jirashell.py
Python
mit
48,170
0.003405
#!/usr/bin/env python # -*- coding: utf8 -*- # # A Jira shell (using the Jira XML-RPC API). # # <https://confluence.atlassian.com/display/JIRA042/Creating+a+XML-RPC+Client> # <http://docs.atlassian.com/software/jira/docs/api/rpc-jira-plugin/latest/com/atlassian/jira/rpc/xmlrpc/XmlRpcService.html> # __version__ = "1.6....
data = { "type": { "name": link_type_name }, "inwardIssue": { "key": inward_issue_key }, "outwardIssue": { "key": outward_issue_key } } res = self._jira_rest_call('POST'
, '/issueLink', headers={'content-type': 'application/json'}, data=json.dumps(data)) if res.status_code != 201: raise JiraShellError('error linking (%s, %s, %s): %s %s' % (link_type_name, inward_issue_key, outward_issue_key, res.status_code...
dol-sen/portage
repoman/pym/repoman/tests/runTests.py
Python
gpl-2.0
1,959
0.009188
#!/usr/bin/env python # runTests.py -- Portage Unit Test Functionality # Copyright 2006-2017 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import os, sys import os.path as osp import grp import platform import pwd import signal def debug_signal(signum, frame): import pdb pdb.s...
portage._internal_caller = True # Ensure that we don't instantiate portage.settings, so that tests should # work the same regardless of global configuration file state/existence. portage._disable_legacy_globals() if os.environ.get('NOCOLOR') in ('yes', 'true'): portage.output.nocolor() import repoman.tests as test...
os.environ.get("PATH", "").split(":") path = [x for x in path if x] insert_bin_path = True try: insert_bin_path = not path or \ not os.path.samefile(path[0], PORTAGE_BIN_PATH) except OSError: pass if insert_bin_path: path.insert(0, PORTAGE_BIN_PATH) os.environ["PATH"] = ":".join(path) if __name__ == "__main__"...
PMEAL/OpenPNM
tests/unit/io/STLTest.py
Python
mit
1,388
0
import os import py import pytest import numpy as np import openpnm as op from openpnm.models.misc import from_neighbor_pores @pytest.mark.skip(reason="'netgen' is only available on conda") class STLTest:
def setup_class(self): np.random.seed(10) self.net = op.network.Cubic(shape=[2, 2, 2]) self.
net["pore.diameter"] = 0.5 + np.random.rand(self.net.Np) * 0.5 Dt = from_neighbor_pores(target=self.net, prop="pore.diameter") * 0.5 self.net["throat.diameter"] = Dt self.net["throat.length"] = 1.0 def teardown_class(self): os.remove(f"{self.net.name}.stl") os.remove("custom...
sorenh/cc
nova/__init__.py
Python
apache-2.0
1,336
0.000749
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2010 Anso Labs, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); you may # ...
u 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 # distrib
uted 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. """ :mod:`nova` -- Cloud IaaS Platform ==================================...
RedHatInsights/insights-core
insights/parsers/etc_udev_rules.py
Python
apache-2.0
1,878
0.001065
""" EtcUdevRules - file ``/etc/udev/rules.d/`` ============================
============== This module is similar to the :py:mod:`insights.parsers.udev_rules` but parse .rules files under ``/etc/ude/rules.d/`` directory instead. The parsers included in this mo
dule are: UdevRules40Redhat - file ``/etc/udev/rules.d/40-redhat.rules`` -------------------------------------------------------------- """ from insights import parser from insights.core import LogFileOutput from insights.specs import Specs from insights.util import deprecated @parser(Specs.etc_udev_40_redhat_rules)...
avisingh599/NeuralModels
character-rnn/char-rnn.py
Python
mit
1,663
0.048707
import numpy as np import theano from theano import tensor as T from generateTrainDataonText import createTrain from neuralmodels.utils import permute from neuralmodels.loadcheckpoint import * from neuralmodels.costs import softmax_loss from neuralmodels.models import * from neuralmodels.predictions import OutputMaxPro...
crete from neuralmodels.layers import * def text_prediction(class_ids_reverse,p_labels): N = p_labels.shape[1] T = p_labels.shape[0] text_output = [] for i in range(N): t = '' for j in p_labels[:,i]: t = t + class_ids_reverse[j] text_output.append(t) return text_output if __name__ == '__main__': num_sa...
ples = 10000 num_validation = 100 num_train = num_samples - num_validation len_samples = 300 epochs = 30 batch_size = 100 learning_rate_decay = 0.97 decay_after=5 [X,Y,num_classes,class_ids_reverse] = createTrain('shakespeare_input.txt',num_samples,len_samples) inputD = num_classes outputD = num_classes ...
kyunooh/pingdumb
pingdumb/conf.py
Python
apache-2.0
2,422
0.002064
import getpass import json import getopt from genericpath import isfile from os.path import sep from pingdumb.main_module import url_type def read_config(): f_path = "." + sep + "pingdumb.json" if not isfile(f_path): f = open(f_path, 'w') conf = { "url": "jellyms.kr", ...
] = s_server configure["smtpUser"] = s_user configure["smtpPw"] = s_pw configure["interval"] = interval return configure def configure_to_tuple(): configure = read
_config() return configure["url"], configure["smtpServer"], \ configure["smtpUser"], configure["toEmail"], configure["interval"] def extract_password_with_argv(argv): opts, args = getopt.getopt(argv, 'p') for o, a in opts: if o == "-p": return getpass.getpass("...
Jonekee/chromium.src
native_client_sdk/src/build_tools/tests/easy_template_test.py
Python
bsd-3-clause
3,559
0.006182
#!/usr/bin/env python # 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. import cStringIO import difflib import os import sys import unittest SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) BUILD...
lines = expected.splitlines
(1) actual_lines = dst.getvalue().splitlines(1) diff = ''.join(difflib.unified_diff( expected_lines, actual_lines, fromfile='expected', tofile='actual')) self.fail('Unexpected output:\n' + diff) def testEmpty(self): self._RunTest('', '', {}) def testNewlines(self): self._...
Tuteria/Recruitment-test
config/wsgi.py
Python
mit
1,461
0
""" WSGI config for Tuteria-Application-Test project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WS...
sed by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(applica
tion)
ageek/confPyNotebooks
sklearn-scipy-2013/solutions/08B_digits_clustering.py
Python
gpl-2.0
767
0.003911
from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=10) clusters = kmeans.fit_predict(digits.data) print kmeans.cluster_centers_.shape #------------------------------------------------------------ # visualize the cluster centers fig = plt.figure(figsize=(8, 3)) for i in range(10): ax = fig.add_subplot(2...
import Isomap X_iso = Isomap(n_neighbors=10).fit_transform(digits.data)
#------------------------------------------------------------ # visualize the projected data fig, ax = plt.subplots(1, 2, figsize=(8, 4)) ax[0].scatter(X_iso[:, 0], X_iso[:, 1], c=clusters) ax[1].scatter(X_iso[:, 0], X_iso[:, 1], c=digits.target)
l33tdaima/l33tdaima
p748e/shortest_completing_word.py
Python
mit
2,378
0.009672
from typing import List from collections import defaultdict, Counter class Solution: def shortestCompletingWordV1(self, licensePlate: str, words: List[str]) -> str: # build the signature of licensePlate sig = defaultdict(int) for c in licensePlate.upper(): if c.isalpha(): ...
lter out all none letters from the plate and make sure all letters are lower case. In second line, produce Counter of each words and use Counter operater & (intersection) to extract the count of shared letters between the word and the plate. If all the counts are equal, this returns true. Then, just ext...
censePlate.lower())) return min([w for w in words if Counter(w) & pc == pc], key=len) # TESTS tests = [ { 'licensePlate': "1s3 PSt", 'words': ["step", "steps", "stripe", "stepple"], 'expected': "steps" }, { 'licensePlate': "1s3 456", 'words': ["looks", "pest...
uclouvain/OSIS-Louvain
base/migrations/0107_learningunit_learning_container.py
Python
agpl-3.0
577
0.001733
# -*- coding: utf-8 -*- # Generated by
Django 1.9 on 2017-04-28 15:02 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0106_a
uto_20170428_1119'), ] operations = [ migrations.AddField( model_name='learningunit', name='learning_container', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='base.LearningContainer'), ), ]
nathanielvarona/airflow
airflow/utils/dag_processing.py
Python
apache-2.0
49,728
0.002413
# # 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...
nicating signals self._process: Optional[multiprocessing.process.BaseProcess] = None self._done: bool =
False # Initialized as true so we do not deactivate w/o any actual DAG parsing. self._all_files_processed = True self._parent_signal_conn: Optional[MultiprocessingConnection] = None self._last_parsing_stat_received_at: float = time.monotonic() def start(self) -> None: """...
ActiveState/code
recipes/Python/439094_get_IP_address_associated_network_interface/recipe-439094.py
Python
mit
357
0.011204
import socket import fcntl import struct def get_ip_address(ifname): s = s
ocket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) >>> get_ip_address('lo') '127.0
.0.1' >>> get_ip_address('eth0') '38.113.228.130'
de-vri-es/qtile
test/test_fakescreen.py
Python
mit
15,532
0.000064
# Copyright (c) 2011 Florian Mounier # Copyright (c) 2012, 2014 Tycho Andersen # Copyright (c) 2013 Craig Barnes # Copyright (c) 2014 Sean Vig # Copyright (c) 2014 Adi Sieker # Copyright (c) 2014 Sebastien Blot # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and assoc...
16, 456) assert g["right"] == (580, 0, 20, 456) g = qtile.c.screens()[1]["gaps"] assert g["top"] == (600, 0, 300, 30) assert g["bottom"] == (600, 556, 300, 24) assert g["left"] == (600, 30, 12, 526) g = qtile.c.screens()[2]["gaps"] assert g["to
p"] == (0, 480, 500, 30) assert g["bottom"] == (0, 864, 500, 16) assert g["right"] == (460, 510, 40, 354) g = qtile.c.screens()[3]["gaps"] assert g["top"] == (500, 580, 400, 30) assert g["left"] == (500, 610, 20, 370) assert g["right"] == (876, 610, 24, 370) @fakescreen_config def test_maximiz...
thof/decapromolist
src/get_subcategories.py
Python
gpl-3.0
3,880
0.001804
# Copyright (C) 2015 https://github.com/thof # # This file is part of decapromolist. # # decapromolist 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 # any later version. #...
d 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 not, see <http://www.gnu.org/licenses/>. import json import urllib2 from lxml import html fro...
rllib2.Request('https://www.decathlon.pl/pl/menu-load-sub-categories?categoryId=394904', None, headers) req = urllib2.urlopen(req) content = req.read().decode('UTF-8') response = html.fromstring(content) for cat in response.xpath('//a'): url = cat.attrib['href'] s...
ikeikeikeike/django-impala-backend
impala/introspection.py
Python
mit
310
0
from django.db.backends import B
aseDatabaseIntrospection class DatabaseIntrospection(BaseDatabaseIntrospection): def get_table_list(self, cursor): "Returns a list of table names in the current database." cursor.execute("SHOW TABLES") return [row[0] for
row in cursor.fetchall()]
jhamman/rasmlib
rasmlib/analysis/plugins/sample.py
Python
gpl-3.0
865
0.001156
""" 2x2 plotting analysis for 2 datasets pluggin | ------------- | ------------- | | contours from | pcolor from | | both datasets | dataset 1 | | ------------- | ------------- | | pcolor diff | pcolor from | | both datasets | dataset 2 | | ------------- | ------------- | col...
leException(Exception): pass _NDATASETS = 2 _NPANNELS = 4 def run(cases, compares, domain, **kwargs): """plugin run function""" case_names = cases.keys() compare_names = compares.keys() dsets = cases.values()+compares.values() if len(dsets) != _NDATASETS: raise SampleException('Inc...
rrect number of datasets provided') # get_monthly_means(*dsets) # get_seasonal_means() # get_annual_means() # get_full_means() return def __plot(): return
plum-umd/java-sketch
java_sk/rewrite/desugar.py
Python
mit
1,242
0.002415
# import logging from ast.visit import visit as v from ast.node import Node from ast.body.methoddeclaration import MethodDeclaration from ast.stmt.minrepeatstmt import MinrepeatStmt class Desugar(object): def __init__(self): self._cur_mtd = None @v.on("node") def visit(self, node): """...
body += u""" # if (??) {{ {} }} # """.format(b) # logging.debug( # "desugaring minrepeat @ {}".format(self._cur_mtd.name)) # return to_statements(self
._cur_mtd, body) # return [node]
kfdm/gntp
test/subscribe.py
Python
mit
347
0.020173
# -*- coding: utf-8 -*- # Simple script to test sending UTF8 text with the GrowlNotifier class import logging logging.basicConfig(leve
l=logging.DEBUG)
from gntp.notifier import GrowlNotifier import platform growl = GrowlNotifier(notifications=['Testing'],password='password',hostname='ayu') growl.subscribe(platform.node(),platform.node(),12345)
soar-telescope/goodman
goodman_pipeline/images/tests/test_goodman_ccd.py
Python
bsd-3-clause
471
0
from __future__ import absolute_import from unittest import TestCase, skip from ..goodman_ccd import get_args, MainApp class MainApp
Test(TestCase): def setUp(self): self.main_app = MainApp() def test___call__(self): self.assertRaises(SystemExit, self.main_app) def test___call___show_version(self): arguments = ['--version'] args = get_args(arguments=arguments) self.assertRa
ises(SystemExit, self.main_app, args)
mbiokyle29/geno-browser
runserver.py
Python
mit
58
0
#!flask/bin/python from gb import app
app.run(debug=Tr
ue)
Jorge-Rodriguez/ansible
lib/ansible/modules/database/postgresql/postgresql_schema.py
Python
gpl-3.0
10,842
0.002583
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
database=dict(default="postgres"), cascade_drop=dic
t(type="bool", default=False), state=dict(default="present", choices=["absent", "present"]), ssl_mode=dict(default='prefer', choices=[ 'disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']), ssl_rootcert=dict(default=None), session...
NinjaMSP/crossbar
crossbar/controller/test/test_run.py
Python
agpl-3.0
42,995
0.000442
##################################################################################### # # Copyright (c) Crossbar.io Technologies GmbH # # Unless a separate license agreement exists between you and Crossbar.io GmbH (e.g. # you have purchased a commercial license), the license terms below apply. # # Should you enter ...
}, "ws": { "type": "websocket" } } } ] }, { "type": "container", ...
}, "components": [ { "type": "class", "classname": "myapp.MySession", "realm": "realm1", "transport": { "type": "websocket", ...
openstack/nomad
cyborg/api/controllers/base.py
Python
apache-2.0
2,260
0
# Copyright 2017 Huawei Technologies Co.,LTD. # 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 # # Unl...
datetime import pecan import wsme from wsme import types as wtypes from pecan import rest class APIBase(wtypes.Base): created_at = wsme.wsattr(datetime.datetime, readonly=True) """The time in UTC at which the object is created""" updated_at = wsme.wsattr(datetime.datetime, readonly=True) """The tim...
or k in self.fields if hasattr(self, k) and getattr(self, k) != wsme.Unset) class CyborgController(rest.RestController): def _handle_patch(self, method, remainder, request=None): """Routes ``PATCH`` _custom_actions.""" # route to a patch_all or get if no additional parts are a...
obi-two/Rebelion
data/scripts/templates/object/draft_schematic/space/chassis/shared_hutt_medium_s02.py
Python
mit
458
0.048035
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SE
E THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_sche
matic/space/chassis/shared_hutt_medium_s02.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
rfguri/vimfiles
bundle/ycm/third_party/ycmd/ycmd/completers/javascript/tern_completer.py
Python
mit
22,105
0.026646
# Copyright (C) 2015 ycmd contributors # # This file is part of ycmd. # # ycmd 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. # # ycmd...
request_data ).get( 'completions', [] ) def BuildDoc( completion ): doc = completion.get( 'type', 'Unknown type' ) if 'doc' in completion: doc = doc + '\n' + completion[ 'doc' ] return doc return [ responses.BuildCompletionData( completion[ 'name' ], ...
BuildDoc( completion ) ) for completion in completions ] def OnFileReadyToParse( self, request_data ): self._WarnIfMissingTernProject() # Keep tern server up to date with the file data. We do this by sending an # empty request just containing the file data try: self._P...
cvanoort/USDrugUseAnalysis
Report1/Code/afu_use30.py
Python
isc
2,851
0.020694
import csv import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats from scipy.optimize import curve_fit def countKey(key,listDataDicts): outDict = {} for row in listDataDicts: try: outDict[row[key]] += 1 except KeyError: outDict[row[key]] = 1 ...
er(tsvFile,delimiter='\t') for row in tsvReader: listDataDicts.append(row) ageFirstUseKeys = ['CIGTRY', 'SNUFTRY', 'CHEWTRY', 'CIG
ARTRY', 'ALCTRY', 'MJAGE', 'COCAGE', 'HERAGE', 'HALLAGE', 'INHAGE', 'ANALAGE', 'TRANAGE', 'STIMAGE', 'SEDAGE'] useLast30Keys = ['CIG30USE','SNF30USE','CHW30USE','CGR30USE','ALCDAYS','MJDAY30A','COCUS30A','HER30USE','HAL30USE','INHDY30A','PRDAYPMO','TRDAYPMO','STDAYPMO','SVDAYPMO'] xdata = [] ydata = [] for person in l...