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
nielsbuwen/ilastik
ilastik/applets/counting/opCountingDataExport.py
Python
gpl-3.0
3,184
0.007538
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
r version. # # In addition, as a special exception, the copyright holders of
# ilastik give you permission to combine ilastik with applets, # workflows and plugins which are not covered under the GNU # General Public License. # # See the LICENSE file for details. License information is also available # on the ilastik web site at: # http://ilastik.org/license.html ###########################...
capergroup/bayou
tool_files/acceptpy_1_3_0/accept.py
Python
apache-2.0
9,670
0.003619
# Copyright (c) 2017 rmbar # # 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 use, copy, modify, merge, publish, distribu...
ense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "A...
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 ...
ox1omon/movement_fefu
movement_app/views.py
Python
mit
5,870
0.00233
import json from django.contrib.auth.decorators import login_required from django.contrib.auth.views import logout from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from movement_app.models import * from movement_app.logic import find_move def index(request): if requ...
e_number': userinfo.phone_number, }) else: form = UserInfoForm() # БД не заполнена. Выдаем чистую форму пользова
телю. ctx.update(dict(form=form)) return render(request, "movement_app/registration.html", ctx) form = UserInfoForm(request.POST) if form.is_valid(): # TODO Проверь джаваскриптовую парсилку инфы с карты try: userinfo = UserInfo.objects.get(userfield=request.user, ) e...
drtuxwang/system-config
bin/swell_foop_.py
Python
gpl-2.0
1,717
0
#!/usr/bin/env python3 """ Sandbox for "swell-foop" command """ import glob import os import signal import sys import network_mod import subtask_mod class Main: """ Main class """ def __init__(self) -> None: try: self.config() sys.exit(self.run()) except (EOF...
slow for very large history (.local/share/swell-foop/) if not os.path.isfile(command.get_file() + '.py'): configs = [ '/dev/dri', f'/run/user/{os.getuid()}/dconf', os.path.join(os.getenv('HOME', '/'), '.
config/dconf/user'), ] command.sandbox(configs) subtask_mod.Background(command.get_cmdline()).run() return 0 if __name__ == '__main__': if '--pydoc' in sys.argv: help(__name__) else: Main()
khalim19/gimp-plugin-export-layers
export_layers/pygimplib/__init__.py
Python
gpl-3.0
11,842
0.016298
# -*- coding: utf-8 -*- # # Copyright (C) 2014-2019 khalim19 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function, unicode_literals import inspect import os import sys import traceback PYGIMPLIB_DIRP...
imp_dependent_modules_imported = False else: _gimp_dependent_modules_imported = True from . import logging if _gimp_dependent_modules_imported: # Enable logging as early as possible to capture any unexpected errors (such # as missing modules) before pygimplib is fully initialized. logging.log_output( log...
ladder1984/backbonejs_todos_with_Django
backbonejs_todos_with_Django/wsgi.py
Python
mit
431
0.00464
""" WSGI config for backbonejs_todos_with_Django project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, se
e https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backbonejs_todos_with_Django.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_applicati
on()
nens/dpnetcdf
dpnetcdf/utils.py
Python
gpl-3.0
1,037
0
# (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import re DATASET_NAME_PATTERN = re.compile( r"""^(?P<time_zero>\d{12}) # e.g. 200506010000 _ (?P<program>DP[a-zA-Z]*) # e.g. DPR_rijn...
-z0-9]*).nc$ # e.g. RF1p0p3 """, re.X) year = re.compile( r""" _(?P<year>\d{4}[A-Z]?)_ # year can have a one character appended """, re.X) scenario = re.compile( r""" _(?P<scenario>S\dv\d)_ # scenario is optional """, re.X) def parse_dataset_name(name): """Test the regex ext...
earch = scenario.search(name) if scenario_search: d.update(scenario_search.groupdict()) return d
cellofellow/symphony
library/migrations/0009_score_type_to_choices.py
Python
agpl-3.0
1,288
0.000776
# Generated by Django 2.0.2 on 2018-03-23 22:29 from django.db import migrations, models SCORE_TYPE_MAP = {1: 'NO_SCORE', 2: 'FULL', 3: 'PIANO', 4: 'CONDENSED'} FORWARDS_QUERY = """ UPDATE library_piece SET "score_type" = %s WHERE "score_id" = %s ""...
v in SCORE_TYPE_MAP.items()] class Migration(migrations.Migration): dependencies = [
('library', '0008_auto_20180323_2228'), ] operations = [ migrations.AddField( model_name='piece', name='score_type', field=models.CharField(blank=True, choices=[('NO_SCORE', 'No Score'), ('CONDENSED', 'Condensed'), ('PIANO', 'Piano'), ('FULL', 'Full')], max_length=...
forslund/mycroft-core
mycroft/metrics/__init__.py
Python
apache-2.0
6,083
0
# Copyright 2017 Mycroft AI 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 agreed to in writin...
system, timing, additional_data=None): """Create standardized message for reporting timing. Args: ident (str): identifier of user interaction system (str): system the that's generated the report timing (stopwatch): Stopwatch object with recorded timing ...
ta) report['id'] = ident report['system'] = system report['start_time'] = timing.timestamp report['time'] = timing.time _metric_uploader.queue.put(('timing', report)) class Stopwatch: """ Simple time measuring class. """ def __init__(self): self.timestamp = None ...
kyubifire/softlayer-python
SoftLayer/CLI/vpn/ipsec/translation/add.py
Python
mit
1,435
0
"""Add an address translation to an IPSEC tunnel context.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment # from SoftLayer.CLI.exceptions import ArgumentError # from SoftLayer.CLI.exceptions import CLIHalt @click.command() @click.argument('contex...
@click.option('-n', '--note', default=None, help='Note value') @environment.pass_env def cli(env, context_id, static_ip, remote_ip, note): """Add an address translation to an IPSEC tunnel context. A separate configuration request should be made to realize changes on ...
id) translation = manager.create_translation(context_id, static_ip=static_ip, remote_ip=remote_ip, notes=note) env.out('Created translation from {} to {} #{}' .form...
czhengsci/pymatgen
pymatgen/analysis/wulff.py
Python
mit
21,287
0.000235
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module define a WulffShape class to generate the Wulff shape from a lattice, a list of indices and their corresponding surface energies, and the total area and volume of the wulff shape,the weighted su...
g, miller): self.normal = normal self.e_surf = e_surf self.normal_pt = normal_pt self.dual_pt = dual_pt self.index = index self.m_ind_orig = m_ind_orig self.miller = miller self.points = [] self.outer_lines = [] class WulffShape(...
bject): """ Generate Wulff Shape from list of miller index and surface energies, with given conventional unit cell. surface energy (Jm^2) is the length of normal. Wulff shape is the convex hull. Based on: http://scipy.github.io/devdocs/generated/scipy.spatial.ConvexHull.html Process: ...
wfxiang08/Nuitka
nuitka/codegen/templates/CodeTemplatesFrames.py
Python
apache-2.0
8,340
0.001079
# Copyright 2015, Kay Hayen, mailto:kay.hayen@gmail.com # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
ach = true; } if (needs_detach) { %(store_frame_locals)s detachFrame( exception_tb, %(frame_locals_name)s ); } } #if PYTHON_VERSION >= 300 Py_CLEAR( %(frame_identifier)s->f_exc_type ); Py_
CLEAR( %(frame_identifier)s->f_exc_value ); Py_CLEAR( %(frame_identifier)s->f_exc_traceback ); #endif Py_DECREF( %(frame_identifier)s ); // Return the
unreal666/outwiker
src/test/wikiparser/test_wikicommandattachlist.py
Python
gpl-3.0
11,139
0.000187
# -*- coding: UTF-8 -*- import os import os.path import unittest from tempfile import mkdtemp from outwiker.core.tree import WikiDocument from outwiker.core.application import Application from outwiker.core.attachment import Attachment from outwiker.pages.wiki.parser.commands.attachlist import AttachListCommand from ...
self._compareResult(titles, names, result) def testParseSortDescendName(self): self._attachFiles() text = "(:attachlist sort=descendname:)" result = self.parser.toHtml(text) titles = [ "[for_sort]", "[dir]", "
файл с пробелами.tmp", "image.jpg", "anchor.png", "add.png"] names = [ "for_sort", "dir", "файл с пробелами.tmp", "image.jpg", "anchor.png", "add.png"] self._compareResult(titles, names, result) ...
piotrdubiel/scribeserver
app/recognition/admin.py
Python
mit
220
0
from flask.ext.admin.contrib.mongoengine import ModelView from .models import Prediction from app.management.mixins import Admi
nMixin class PredictionView(AdminMixin, ModelView): col
umn_searchable_list = ('text',)
wesleykendall/django-issue
issue/tests/model_tests.py
Python
mit
22,256
0.002696
from datetime import datetime, timedelta import json from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django_dynamic_fixture import G, N from freezegun import freeze_time from mock import patch from issue.models import ( Assertion, ExtendedEnum, Issue, IssueAction, ...
watching_pattern(self, load_function): # Setup the scenario issue = G(Issue, name='success') responder = G(Responder, issue=issue, watch_pattern='error-\d+') G(ResponderAction, responder=responder, target_function='do') # Run the code
r = responder.respond(issue) # Verify expectations self.assertFalse(r) self.assertFalse(load_function.called) def test__match(self): r = Responder(watch_pattern='error-.*') self.assertTrue(r._match('error-42')) self.assertFalse(r._match('success')) def test__ge...
jperla/spark-advancers
compareResult.py
Python
bsd-3-clause
358
0.002793
#!/usr/bin/env python import
math f_truth = open('lr_good_weights.txt', 'r') f_result = open('ALRresult.log', 'r') frlines = f_result.readlines() ftlines = f_truth.readlines() c = 0 margin = 0.001 fo
r i, line in enumerate(ftlines): if math.fabs(float(line) - float(frlines[i])) > margin : c = c + 1 print c f_truth.close() f_result.close()
jokuf/hack-blog
users/forms.py
Python
mit
1,762
0
from django import forms from .models import Author class RegisterNewAuthorForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) repeated_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Author fields = ['email', 'first_name', 'last_n...
t match! ") class LoginForm(forms.Form): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput()) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) for visible in self.visible_fie
lds(): visible.field.widget.attrs['class'] = 'form-control' def clean(self): cleaned_data = super(LoginForm, self).clean() email = cleaned_data.get("email") password = cleaned_data.get("password") try: author = Author.objects.get(email=email) if ...
F483/bikesurf.org
apps/page/models.py
Python
mit
1,607
0.011201
# -*- coding: utf-8 -*- # Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com> # License: MIT (see LICENSE.TXT file) from django.db import models from django.utils.translation import ugettext as _ from django.core.validators import RegexValidator from sanitizer.models import SanitizedCharFi...
eam.name, self.name) class Meta: unique_together = (("team", "name"), ("team", "link")) ...
ing = ["order", "name"]
bheinzerling/bpemb
bpemb/__init__.py
Python
mit
25
0
from .bpemb impo
rt BPEmb
sencha/chromium-spacewalk
tools/chrome_proxy/integration_tests/chrome_proxy_pagesets/fallback_viaheader.py
Python
bsd-3-clause
701
0.00428
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import page_set as page_set_module class FallbackViaHeaderPage(page_module.Page): def...
sites """ def __init__(self): super(FallbackViaHeaderPageSet, self).__init__() self.AddPage(FallbackViaHeaderPage( 'http://chromeproxy-test.appsp
ot.com/default', self))
awakenting/gif_fitting
bbp_analysis/bluebrain_data_io.py
Python
gpl-3.0
9,533
0.004196
# coding: utf-8 import os import urllib import numpy as np import pickle from Experiment import Experiment ROOT_PATH = './full_dataset/article_4_data/grouped_ephys' ZIPFILE_PATH = './full_dataset/article_4_data' EXPM_PATH = './results/experiments/' URL = 'http://microcircuits.epfl.ch/data/released_data/' if not os....
om url and return it. """ r = urllib.request.urlopen(url) data = r.read() data = d
ata.decode(encoding='UTF-8') return data def get_genetic_cell_infos(filepath): """ Downloads genetic information from cells in the directory at filepath. """ filelist = os.listdir(filepath) raw_names = [name[0:-4] for name in filelist] cell_names = [] for name in raw_names: #...
jundongl/scikit-feast
skfeature/example/test_CMIM.py
Python
gpl-2.0
1,485
0.003367
import scipy.io from sklearn.metrics import accuracy_score from sklearn import cross_validation from sklearn import svm from skfeature.function.information_theoretical_based import CMIM def main(): # load data mat = scipy.io.loadmat('../data/colon.mat') X = mat['X'] # data X = X.astype(float) y...
assification task num_fea = 10 # number of selected features clf = svm.LinearSVC() # linear SVM correct = 0 for train, test in ss: # obtain the index of each feature on the training set idx,_,_ = CMIM.cmim(X[train], y[train], n_selected_features=num_fea) # obtain the data...
clf.fit(features[train], y[train]) # predict the class labels of test data y_predict = clf.predict(features[test]) # obtain the classification accuracy on the test data acc = accuracy_score(y[test], y_predict) correct = correct + acc # output the average classification acc...
ecolitan/fatics
venv/lib/python2.7/site-packages/MySQLdb/cursors.py
Python
agpl-3.0
17,253
0.00284
"""MySQLdb Cursors This module implements Cursors of various types for MySQLdb. By default, MySQLdb uses the Cursor class. """ import re import sys try: from types import ListType, TupleType, UnicodeType except ImportError: # Python 3 ListType = list TupleType = tuple UnicodeType = str restr = r...
o: self.messages.append((self.Warning, self._info))
warn(self._info, self.Warning, 3) def nextset(self): """Advance to the next result set. Returns None if there are no more result sets. """ if self._executed: self.fetchall() del self.messages[:] db = self._get_db() nr = db.next_resu...
dimchenkoAlexey/python_training
fixture/contact.py
Python
apache-2.0
3,347
0.001793
__author__ = 'admin' class ContactHelper: def __init__(self, app): self.app = app def create(self, contact): self.fill_contact_fields(contact) def modify(self, contact): # modify contact self.click_edit_button() self.fill_contact_fields(contact) def set_field_...
("ayear", contact.anniversary_year) self.set_field_value("address2", contact.second_address) self.set_field_value("phone2", contact.second_phone) self.set_field_value("notes", contact.notes) wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() def delete_first_c...
lected[]").click() wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click() def delete_all_contacts(self): wd = self.app.wd mass_checkbox = wd.find_element_by_id("MassCB") if not mass_checkbox.is_selected(): mass_checkbox.click() wd.find_elem...
wood-galaxy/FreeCAD
src/Mod/Plot/Plot.py
Python
lgpl-2.1
13,577
0.002652
#*************************************************************************** #* * #* Copyright (c) 2011, 2012 * #* Jose Luis Cercos Pita <jlcercos@gmail.com> * #* ...
name) def series(): """Return all the lines from a selected p
lot.""" plt = getPlot() if not plt: return [] return plt.series def removeSerie(index): """Remove a data serie from the active plot. Keyword arguments: index -- Index of the serie to remove. """ # Get active series plt = getPlot() if not plt: return plots =...
chrislee35/pypassivedns
pypassivedns/pypassivedns.py
Python
bsd-3-clause
1,538
0.006502
# -*- coding: utf-8 -*- import threading import datetime class PDNSResult: def __init__(self, source, response_time, query, answer, rrtype, ttl, firstseen, lastseen, count): self.source = source self.response_time = response_time self.query = query self.answer = answer self....
ers: t = threading.Thread(target=_query, args=(provider, item, limit)) threads.append(t) t.start()
res = [] for thread in threads: res.append(thread.join()) def _query(provider, item, limit=None): res = provider.query(item, limit) return res
pythonistas-tw/academy
web-api/maomao/usecase.py
Python
gpl-2.0
313
0
from models import DBUse test1 = DBUse() test1.f_create(account="maomao
@gmail.com", password="123321") test1.f_create(account="hahaha@gmail.com", password="abcd") user = test1.f_read(uid=2) test1.f_update(user, account="amy111@gmail.com") ul = test1.f_read
() for i in ul: test1.f_delete(i) test1.f_read()
unlessbamboo/django
unusebamboo/settings.py
Python
gpl-3.0
3,094
0
""" Django settings for un
usebamboo project. Generated by 'django-admin startproject' using Django 1.8.2. For more information on this file, see https://docs.djangoproject.
com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development ...
HIPS/Kayak
kayak/regularizers.py
Python
mit
2,109
0.006164
# Authors: Harvard Intelligent Probabilistic Systems (HIPS) Group # http://hips.seas.harvard.edu # Ryan Adams, David Duvenaud, Scott Linderman, # Dougal Maclaurin, Jasper Snoek, and others # Copyright 2014, The President and Fellows of Harvard University # Distributed under an MIT license. Se...
sum(self.X.value**2) def _local_grad(self, parent, d_out_d_self): return self.weight * 2.0 * sel
f.X.value * d_out_d_self class L1Norm(Regularizer): __slots__ = [] def __init__(self, X, weight=1.0): super(L1Norm, self).__init__(X, weight) def _compute_value(self): return self.weight * np.sum(np.abs(self.X.value)) def _local_grad(self, parent, d_out_d_self): return self.we...
sighill/shade_app
primus/migrations/0007_auto_20160418_0959.py
Python
mit
457
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-18 07:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('primus', '0006_auto_20160418_0959'), ] o
perations = [ migrations.AlterField( model_name='building',
name='modified', field=models.DateTimeField(auto_now=True), ), ]
pombredanne/numba
numba/hsa/hsaimpl.py
Python
bsd-2-clause
10,106
0.000396
from __future__ import print_function, absolute_import, division import operator from functools import reduce from llvmlite.llvmpy.core import Type import llvmlite.llvmpy.core as lc import llvmlite.binding as ll from numba.targets.imputils import implement, Registry from numba import cgutils from numba import types ...
Tuple), types.Any) def hsail_smem_alloc_array(context, builder, sig, args): shape, dtype = args return _generic_array(context, builder, shape=shape, dtype=dtype, symb
ol_name='_hsapy_smem', addrspace=target.SPIR_LOCAL_ADDRSPACE) def _generic_array(context, builder, shape, dtype, symbol_name, addrspace): elemcount = reduce(operator.mul, shape) lldtype = context.get_data_type(dtype) laryty = Type.array(lldtype, elemcount) if addrspace == ta...
andir/ganeti
test/py/cmdlib/cluster_unittest.py
Python
bsd-2-clause
96,615
0.005248
#!/usr/bin/python # # Copyright (C) 2008, 2011, 2012, 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright noti...
() self.cfg.AddNewNode() self.cfg.AddNewNode() self.ExecOpCodeExpectOpPrereqError(op, "still 2 node\(s\)") def testExistingInstances(self): op = opcodes.OpClusterDestroy() self.cfg.AddNewInstance() self.cfg.AddNewInstance() self.ExecOpCodeExpectOpPrereqError(op, "still 2 instance\(s\)...
elf.assertHooksCall([self.master.uuid], constants.GLOBAL_HOOKS_DIR, constants.HOOKS_PHASE_PRE, index=0) self.assertHooksCall([self.master.uuid], "cluster-destroy", constants.HOOKS_PHASE_POST,
nwiizo/workspace_2017
pipng/multiplexer2.py
Python
mit
4,364
0.00298
#!/usr/bin/env python3 # Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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)...
nt))
def generate_random_events(count): vehicles = (("cars",) * 11) + (("vans",) * 3) + ("trucks",) for _ in range(count): yield Event(random.choice(vehicles), random.randint(1, 3)) class Counter: def __init__(self, *names): self.anonymous = not bool(names) if self.anony...
Alternhuman/marcopolo
marcopolo/tests/test_polo_binding.py
Python
mpl-2.0
1,960
0.015816
import sys sys.path.append('/opt/marcopolo/') from bindings.polo import polo from twisted.trial import unittest from mock import MagicMock, patch class TestRegisterService(unittest.TestCase): pass class TestRegisterService(unittest.TestCase): def setUp(self): self.polo = polo.Polo() self....
lass TestRemoveService(unittest.TestCase): # def setU
p(self): # self.polo = polo.Polo() # def test_remove_success(self): # self.assertFalse(self.polo.unpublish_service("dummy")) # def test_remove_failure(self): # self.assertFalse(self.polo.unpublish("dummy")) # def test_have_service(self): # pass
tomhaoye/LetsPython
practice/practice50.py
Python
mit
87
0
#!/usr/bin/pyth
on # -*- co
ding: UTF-8 -*- import random print random.uniform(10, 30)
siosio/intellij-community
python/helpers/profiler/vmprof_profiler.py
Python
apache-2.0
2,691
0.001115
import os import shutil import tempfile import vmprof import prof_six as six from _prof_imports import TreeStats, CallTreeStat class VmProfProfile(object): """ Wrapper class that represents VmProf Python profiling backend with API matching the cProfile. """ def __init__(self): self.stats...
tree = callback(parent, node) for c in six.itervalues(node.children): self._walk_tree(node, c, callback) return tree def tree_stats_to_response(self, filename, response): tree_stats_to_response(filename, response) def snapshot_
extension(self): return '.prof' def _walk_tree(parent, node, callback): if node is None: return None tree = callback(parent, node) for c in six.itervalues(node.children): _walk_tree(tree, c, callback) return tree def tree_stats_to_response(filename, response): stats = vmp...
Opentrons/labware
api/tests/opentrons/data/testosaur.py
Python
apache-2.0
745
0
from opentrons import instruments, containers metadata = { 'protocolName': 'Testosaur', 'author': 'Opentrons <engineering@opentrons.com>', 'description': 'A variant on "Dinosaur" for testing', 'source': 'Opentrons Reposit
ory' } p200rack = containers.load('tiprack-200ul', '5', 'tiprack') # create a p200 pipette on robot axis B p300 = instruments.P300_Single( mount="right", tip_racks=[p200rack]) p300.pick_up_tip() conts = [ containers.load('96-PCR-flat', slot) for slot in ('8', '11') ] # U
ncomment these to test precision # p300.move_to(robot.deck['11']) # p300.move_to(robot.deck['6']) for container in conts: p300.aspirate(10, container[0]).dispense(10, container[-1].top(5)) p300.drop_tip()
dubourg/openturns
python/test/t_NegativeBinomial_std.py
Python
gpl-3.0
2,540
0.000787
#! /usr/bin/env python from __future__ import print_function from openturns import * TESTPREAMBLE() RandomGenerator.SetSeed(0) try: # Instanciate one distribution object distribution = NegativeBinomial(4.5, 0.7) print("Distribution ", repr(distribution)) print("Distribution ", distribution) # Is...
gards the parameters of the distribution CDF = distribution.computeCDF(point) print("cdf=%.6f" % CDF) # quantile quantile = distribution.computeQuantile(0.95) p
rint("quantile=", repr(quantile)) print("cdf(quantile)=%.6f" % distribution.computeCDF(quantile)) mean = distribution.getMean() print("mean=", repr(mean)) standardDeviation = distribution.getStandardDeviation() print("standard deviation=", repr(standardDeviation)) skewness = distribution.getSkew...
treasure-data/td-client-python
tdclient/test/dtypes_and_converters_test.py
Python
apache-2.0
7,897
0.001773
#!/usr/bin/env python """Tests for the dtypes and converters arguments to CSV import. """ import pytest from io import BytesIO from unittest import mock from tdclient import api, Client from tdclient.util import read_csv_records from tdclient.test.test_helper import gunzipb from tdclient.test.test_helper import ma...
{ "time": 200, "col1": "0002", "col2": 20.0, "col3": 2.0, "col4": "efgh", "col5": False, "col6": "", }, ] def test_dtypes_plus_converters_change_parsing(
): reader = sample_reader() result = list( read_csv_records( reader, dtypes={"col1": "str", "col6": "str",}, converters={"col2": float,} ) ) assert result == [ { "time": 100, "col1": "0001", "col2": 10.0, "col3": 1.0, ...
angea/corkami
src/java/java.py
Python
bsd-2-clause
1,502
0.009987
# simple class generator helper #Ange Albertini, BSD licence 2011 import struct def make_utf8(s): return "".join(["\x01", struct.pack(">H", len(s)), s]) def make_class(i): return "".join(["\x07", struct.pack(">H", i)]) def make_nat(name, type): return "".join(["\x0C", struct.pack(">H", name)...
k(">H", ref)]) def make_string(utf): return "".join(["\x08", struct.pack(">H", utf)]) def u4length(s): return "".join([struct.pack(">L", len(s)), s]) def u2larray(l): return "".join([struct.pack(">H", l
en(l)), "".join(l)]) GETSTATIC = "\xb2" LDC = "\x12" INVOKEVIRTUAL = "\xb6" RETURN = "\xb1" def make_classfile( magic, minor_version, major_version, pool, access_flags, this_class, super_class, interfaces, fields, methods, attributes): return "".join([ magic, stru...
sussexstudent/falmer
manage.py
Python
mit
1,026
0
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') try: from django.core.management import execute_from_command_line e
xcept ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other
# exceptions on Python 2. try: import django # noqa except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to acti...
Parisson/TimeSide
tests/unit_timeside.py
Python
agpl-3.0
5,327
0.000188
# -*- coding: utf-8 -*- import unittest import doctest import sys import time import timeside.core class _TextTestResult(unittest.TestResult): """A test result class that can print formatted text results to a stream. Used by TextTestRunner. """ separator1 = '=' * 70 separator2 = '-' * 70 de...
owAll: self.stream.writeln("SKIP : " + reason)
elif self.dots: self.stream.write('S') def printErrors(self): if self.dots or self.showAll: self.stream.writeln() self.printErrorList('ERROR', self.errors) self.printErrorList('FAIL', self.failures) def printErrorList(self, flavour, errors): for test, ...
areitz/pants
src/python/pants/backend/core/targets/resources.py
Python
apache-2.0
1,552
0.005799
# 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_imp
ort, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.base.payload import Payload from pants.base.target import Target class Resources(Target): """A set of files accessible as resources from the JVM classpath. Looking for loose files in yo...
application bundle? Those are `bundle <#bundle>`_\s. Resources are Java-style resources accessible via the ``Class.getResource`` and friends API. In the ``jar`` goal, the resource files are placed in the resulting `.jar`. """ def __init__(self, address=None, payload=None, sources=None, **kwargs): """ ...
JasonThomasData/payslip_code_test
app/models/db_connector.py
Python
mit
498
0.002008
import os from sqlalchemy.ext.declarative import dec
larative_base from sqlalchemy import
create_engine from sqlalchemy.orm import sessionmaker Base = declarative_base() class DBConnector(): ''' where every row is the details one employee was paid for an entire month. ''' @classmethod def get_session(cls): database_path = os.environ["SQL_DATABASE"] engine = create_e...
pixeltasim/IRCBot-Pixeltasim
plugins/tale.py
Python
unlicense
3,149
0.039695
from whiffle import wiki
dotapi from util import hook import re import time,threading @hook.command def tale(inp): #this is for WL use, easily adaptab
le to SCP ".tale <Article Name> -- Will return first page containing exact match to Article Name" if firstrefresh == 0: #make sure the cache actually exists return "Cache has not yet updated, please wait a minute and search again." api = wikidotapi.connection() #creates API connection api.Site = "wanderers-librar...
cemarchi/biosphere
Src/BioAnalyzer/CrossCutting/Contracts/GenePriotization/GlobalDifferentialDnaMethylationSampleRepositoryBase.py
Python
bsd-3-clause
1,566
0.012133
from abc import ABCMeta, abstractmethod from typing import Dict from Src.BioAnalyzer.CrossCutting.DTOs.GenePrioritization.GlobalDifferentialSampleDto import GlobalDifferentialSampleDto from Src.BioAnalyzer.CrossCutting.Filters.GenePrioritization.FeSingleGlobalDifferentialSample import \ FeSingleGlobalDifferentialS...
ampleRepositoryBase(MongoRepositoryBase, metaclass=ABCMeta): """ Class responsible for manipulates gene annotation file """ def __init__(self, db): """ Constructor. :param db: """ super().__init__(db, 'global_diff_dna_methylation_samples') @abstractmethod ...
mple: :return: """ pass @abstractmethod def get_one(self, fe_diff_dna_methylation_sample: FeSingleGlobalDifferentialSample, dto_class=None, include_or_exclude_fields: Dict[str, int] = None) -> FeSingleGlobalDifferentialSample: """ :param fe_dif...
nyov/mooshell
models.py
Python
mit
14,529
0.001445
from datetime import timedelta, datetime import os from django.db import models from django.db.models.signals import pre_save, post_save from django.contrib.auth.models import User from django.conf import settings from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist from ...
) LANG_HTML = ((0, 'HTML'),) LANG_CSS = ((0, 'CSS'), (1, 'SCSS')) LANG_JS = ((0, 'JavaScript'), (1, 'CoffeeScript'), (2, 'JavaScript 1.7')) class Shell(models.Model): """ Holds shell data """ PANEL_HTM
L = [i[1] for i in LANG_HTML] PANEL_CSS = [i[1] for i in LANG_CSS] PANEL_JS = [i[1] for i in LANG_JS] pastie = models.ForeignKey(Pastie, related_name='shells') version = models.IntegerField(default=0, blank=True) revision = models.IntegerField(default=0, blank=True, null=True) # authoring a...
savi-dev/heat
heat/engine/parameters.py
Python
apache-2.0
14,053
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
, COMMA_DELIMITED_LIST, JSON ) = ( 'String', 'Number', 'CommaDelimitedList', 'Json' ) PSEUDO_PARAMETERS = ( PARAM_STACK_ID, PARAM_STACK_NAME, PARAM_REGION ) = ( 'AWS::StackId', 'AWS::StackName', 'AWS::Region' ) class ParamSchema(dict): '''Parameter schema.''' def __init__(self, schema): s...
if check is None or const is None: continue check(name, value, const) def constraints(self): ptype = self[TYPE] keys = { STRING: [ALLOWED_VALUES, ALLOWED_PATTERN, MAX_LENGTH, MIN_LENGTH], NUMBER: [ALLOWED_VALUES, MAX_VALUE, MIN_VALUE], ...
sameersingh/uci-statnlp
hw2/lm.py
Python
apache-2.0
3,681
0.002173
#!/bin/python from __future__ import division from __future__ import print_function from __future__ import absolute_import import itertools from math import log import sys # Python 3 backwards compatibility tricks if sys.version_info.major > 2: def xrange(*args, **kwargs): return iter(rang...
us): """Computes the perplexity of the corpus by the model. Assumes the model uses an EOS symbol at the end of each sentence. """ numOOV = self.get_num_oov(corpus) return pow(2.0, self.entropy(corpus, numOOV)) def get_num_oov(self, corpus): vocab_set = set(...
= len(words_set - vocab_set) return numOOV def entropy(self, corpus, numOOV): num_words = 0.0 sum_logprob = 0.0 for s in corpus: num_words += len(s) + 1 # for EOS sum_logprob += self.logprob_sentence(s, numOOV) return -(1.0/num_words)*(sum_l...
o-zander/django-filer
filer/admin/folderadmin.py
Python
bsd-3-clause
53,477
0.002711
#-*- coding: utf-8 -*- from __future__ import unicode_literals import itertools import os import re from django import forms fro
m django.conf import settings as django_settings from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.util import quote, unquote, capfirst from django.core.exceptions import ValidationError from django.core.exceptions import Perm
issionDenied from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.db import router, models from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, get_object_or_404 try: from django.utils.encoding i...
piqueserver/piqueserver
piqueserver/scheduler.py
Python
gpl-3.0
1,666
0
# Copyright (c) Mathias Kaerlev 2012. # This file is part of pyspades. # pyspades 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. # ...
for more deta
ils. # You should have received a copy of the GNU General Public License # along with pyspades. If not, see <http://www.gnu.org/licenses/>. from weakref import WeakSet from twisted.internet import reactor from twisted.internet.task import LoopingCall class Scheduler: def __init__(self, protocol): self...
anksp21/Community-Zenpacks
ZenPacks.community.DistributedCollectors/setup.py
Python
gpl-2.0
2,617
0.010317
################################ # These variables are overwritten by Zenoss when the ZenPack is exported # or saved. Do not modify them directly here. # NB: PACKAGES is deprecated NAME = 'ZenPacks.community.DistributedCollectors' VERSION = '1.7' AUTHOR = 'Egor Puzanov' LICENSE = '' NAMESPACE_PACKAGES = ['ZenPacks', '...
s of Zenoss # this ZenPack is c
ompatible with compatZenossVers = COMPAT_ZENOSS_VERS, # previousZenPackName is a facility for telling Zenoss that the name # of this ZenPack has changed. If no ZenPack with the current name is # installed then a zenpack of this name if installed will be upgraded. prevZenPackName = PREV_ZENPACK_NAM...
apache/incubator-airflow
tests/providers/google/cloud/operators/test_gcs_system_helper.py
Python
apache-2.0
2,215
0
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
ines) dest.wr
itelines(lines) """ ) @staticmethod def remove_test_files(): if os.path.exists(PATH_TO_UPLOAD_FILE): os.remove(PATH_TO_UPLOAD_FILE) if os.path.exists(PATH_TO_SAVED_FILE): os.remove(PATH_TO_SAVED_FILE) if os.path.exists(PATH_TO_TRANSFORM_SCRIPT): ...
nlsynth/iroha
py/iroha/__init__.py
Python
bsd-3-clause
73
0
'''
IROHA Python package. ''' __all__ = ["iroha", "design_tool", "
axi"]
tipabu/swift
test/unit/common/test_memcached.py
Python
apache-2.0
37,888
0
# -*- coding:utf-8 -*- # Copyright (c) 20
10-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
S 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. """Tests for swift.common.utils""" from collections import defaultdict import errno from hashlib import md5 import io import ...
tinloaf/home-assistant
homeassistant/components/media_player/yamaha.py
Python
apache-2.0
13,441
0
""" Support for Yamaha Receivers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.yamaha/ """ import logging import requests import voluptuous as vol from homeassistant.components.media_player import ( DOMAIN, MEDIA_PLAYER_SCHEMA, MEDIA...
supported( self._current_source) surround_programs = self.receiver.surround_programs() if surround_programs: self._sound_mode = self.receiver.surround_program self._sound_mode_list = surround_programs else: self._sound_mode = None self....
in self._source_names.items()} self._source_list = sorted( self._source_names.get(source, source) for source in self.receiver.inputs() if source not in self._source_ignore) @property def name(self): """Return the name of the ...
oxc/Flexget
flexget/plugins/cli/t411.py
Python
mit
4,537
0.004408
from __future__ import unicode_literals, division, absolute_import from builtins import * # pylint: disable=unused-import, redefined-builtin from flexget import options, plugin from flexget.event import event from flexget.terminal import console from flexget.manager import Session try: from flexget.plugins.inter...
-5s %-5s' formatting_sub = ' %-55s %-5s %-5s' console(formatting_main % ('Name', 'PID', 'ID')) if term_type_name: console("Not yet implemented !") else: with Session() as session: categories = proxy.find_categories(category_name=category_name, is_sub_category=True, sessi...
tegory.parent_id, category.id)) for term_type in category.term_types: console(formatting_main % (term_type.name, '', term_type.id)) for term in term_type.terms: console(formatting_sub % (term.name, term_type.id, term.id)) def print_catego...
ric2b/Vivaldi-browser
chromium/ios/build/bots/scripts/xcode_util_test.py
Python
bsd-3-clause
20,961
0.004389
#!/usr/bin/env vpython # Copyright 2021 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. """Unittests for xcode_util.py.""" import logging import mock import os import unittest import test_runner_errors import test_runner_...
l.move_runtime', autospec=True) @mock.patch('xcode_util._install_runtime', autospec=True) @mock.patch('xcode_util._install_xcode', autospec=True) def test_new_mactoolchain_legacy_xcode(self, mock_install_xcode, mock_install_runtime,
mock_move_runtime): self.mock(xcode_util, '_using_new_mac_toolchain', lambda cmd: True) self.mock(xcode_util, '_is_legacy_xcode_package', lambda path: True) is_legacy_xcode = xcode_util.install(self.mac_toolchain, self.xcode_build_version, ...
jeremiahyan/odoo
addons/account_test/__manifest__.py
Python
gpl-3.0
1,166
0.005146
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (c) 2011 CCI Connect asbl (http://www.cciconnect.be) All Rights Reserved. # Philmer <philmer@cciconnect.be> { 'name': 'Accounting Consistency Tests', 'version': '1.0', 'cate...
ata': [ 'security/ir.model.access.csv', 'views/accounting_assert_test_views.xml', 'report/accounting_assert_test_reports.xml', 'data/accounting_assert_test_data.xml', 'report/report_account_test_templates.xml', ], '
installable': True, 'license': 'LGPL-3', }
letolab/airy
airy/core/db.py
Python
bsd-2-clause
116
0.008621
fr
om airy.core.conf import settings from mongoengine import * connect(getattr(settings, 'database_name', 'airy'))
robsco-git/spreadsheet_server
example_client.py
Python
gpl-2.0
2,456
0.004072
# Copyright (C) 2016 Robert Scott # 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...
lues) # Retrieve one dimensional cell range. cell_values = sc.get_cells(SHEET_NAME, "C1:C3") print(cell_values) # Set a two dimensional cell range. # Cells are set using the format: [[A1, B1, C1], [A2, B2, C2], [A3, B3, C3]] cell_values = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] sc.set_cells(SHEE...
onal cell range. cell_values = sc.get_cells(SHEET_NAME, "A1:C3") print(cell_values) # Save a spreadsheet - it will save into ./saved_spreadsheets sc.save_spreadsheet(EXAMPLE_SPREADSHEET) sc.disconnect() os.remove(os.path.join("spreadsheets", EXAMPLE_SPREADSHEET))
BitPrepared/morso
12.04/10.04/morso/PreferencesMorsoDialog.py
Python
gpl-2.0
3,829
0.00235
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # This file is in the public domain ### END LICENSE from desktopcouch.records.server import CouchDatabase from desktopcouch.records.record import Record import gtk from morso.helpers import get_builder import gettext from ge...
"" if self._preferences == None: # The dialog is
initializing. self._load_preferences() # If there were no saved preference, this. return self._preferences def _load_preferences(self): # TODO: add preferences to the self._preferences dict default # preferences that will be overwritten if some are saved self._p...
Anatoscope/sofa
applications/plugins/SofaPython/doc/SofaDays_oct2013/3_OneParticle/controller.py
Python
lgpl-2.1
195
0.030769
import Sofa import particle class Tuto3(
Sofa.PythonScriptController): # optionnally, script can create a graph... def createGraph(self,node): particle.oneParticleSample(node) ret
urn 0
calpeyser/google-cloud-python
vision/tests/unit/test_client.py
Python
apache-2.0
26,626
0
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
}, ], } credentials = _make_credentials() client = self._make_one( project=PROJECT, credentials=credentials, _use_grpc=False) vision_api = client._vision_api connection = _Connection(returned) vision_api._connection = connection ...
lts=3), ] image = client.image(content=IMAGE_CONTENT) images = ((image, features),) api_response = client._vision_api.annotate(images) self.assertEqual(len(api_response), 1) response = api_response[0] self.assertEqual( request, connection._requested[0...
lavizhao/shopping
python/create_trans_table.py
Python
gpl-2.0
2,625
0.013415
#coding: utf-8 import csv from read_conf import config import MySQLdb as mysql conn = mysql.connect(host='localhost',user='root',passwd='111111111',port=3306) cur = conn.cursor() def create_db(): count = cur.execute('create database if not exists shopping;') print "create database",count result = cur.fe...
rom trans where category = "%s" and \ company = "%s" and brand = "%s"'%(category,company,brand)) result = cur.fetchone() return result[0] def build_index(): conn.select_db('shopping') cur = conn.cursor() count = c
ur.execute('create index cindex using btree on trans(cid);') result = cur.fetchmany(count) return result if __name__ == '__main__': print "hello" data_position_conf = config("../conf/data_position.conf") drop_table() create_db() create_trans_table() insert_trans(data_position_...
quintusdias/glymur
tests/test_callbacks.py
Python
mit
3,032
0
""" Test suite for openjpeg's callback functions. """ # Standard library imports ... from io import StringIO import warnings import unittest from unittest.mock import patch # Local imports ... import glymur from . import fixtures @unittest.skipIf( fixtures.OPENJPEG_NOT_AVAILABLE, fixtures.OPENJPEG_NOT_AVAILABLE_...
s fake_out: glymur.Jp2k(self.temp_jp2_filename, data=ti
ledata, verbose=True) actual = fake_out.getvalue().strip() expected = '[INFO] tile number 1 / 1' self.assertEqual(actual, expected) def test_info_callbacks_on_read(self): """ SCENARIO: the verbose attribute is set to True EXPECTED RESULT: The info callback ha...
davidzchen/tensorflow
tensorflow/python/data/util/sparse_test.py
Python
apache-2.0
12,352
0.002995
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
((), dtypes.int32, ()),
"classes": ((), ops.Tensor, ()), "expected": ((), dtypes.int32, ()) }, { "types": ((), dtypes.int32, ()), "classes": ((), sparse_tensor.SparseTensor, ()), "expected": ((), dtypes.variant, ()) }, ) for test_case in test_cases: self.as...
xiexiao/zzz
zzz.py
Python
mit
1,198
0.013356
''' zzz ''' import os import mako.lookup import tornado.options import tornado.httpserver import tornado.web import tornado.template from tornado.options import define, options CURRENT_PATH = os.path.dirname(__file__) define('port', default=8081, help="run on the given port", type=int) define('debug', default=Fals...
T_PATH, 'templates'), settings = dict( template_path=template_path, static_path=os.path.join(CURRENT_PATH, 'static'), xsrf_cookies=True, cookie_secret=config.cookie_secret, debug=options.debug, ) app = tornado.web.Application( routes, **settings ...
app.listen(options.port) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": main()
plotly/plotly.py
packages/python/plotly/plotly/validators/histogram2d/_colorscale.py
Python
mit
495
0.00404
import _plotly_utils.basevalidators class Colorscale
Validator(_plotly_utils.basevalidators.ColorscaleValidator): def __init__(self, plotly_name="colorscale", parent_name="histogram2d", **kwargs): super(ColorscaleValidator, self).__init__( plotly_name=plotly_name, parent_name=paren
t_name, edit_type=kwargs.pop("edit_type", "calc"), implied_edits=kwargs.pop("implied_edits", {"autocolorscale": False}), **kwargs )
ribacq/utaxc
items/Monster.py
Python
gpl-3.0
519
0.04817
#!/bin/python3 # -*-coding:utf-8 -* import curses; from .Creature import Creature; from random import choice; """A module containing the Monster class""" class Monster(Creature): """The Monster class""" def __init__(self, env, y, x, char): """Constructor""" super(Monster, self).__init__(env, y, x, char, 7,...
nning_action('move'); def ra_move(self): """Move running action for the monster""" self.move(choice(('l
eft', 'right')));
helloztq/helloztq.github.io
_drafts/encrypt.py
Python
mit
2,578
0.009697
#coding:utf-8 import os, sys, io import shutil import struct _DELTA = 0x9E3779B9 def _long2str(v, w): n = (len(v) - 1) << 2 if w: m = v[-1] if (m < n - 3) or (m > n): return '' n = m s = struct.pack('<%iL' % len(v), *v) if w : return s[0:n] else : return s...
= _str2long(key.ljust(16, "\0"), Fa
lse) n = len(v) - 1 z = v[n] y = v[0] q = 6 + 52 // (n + 1) sum = (q * _DELTA) & 0xffffffff while (sum != 0): e = sum >> 2 & 3 for p in xrange(n, 0, -1): z = v[p - 1] v[p] = (v[p] - ((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z))) ...
jay-lau/magnum
magnum/db/sqlalchemy/alembic/versions/e647f5931da8_add_insecure_registry_to_baymodel.py
Python
apache-2.0
1,007
0.001986
#
Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software #
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """add insecure_registry to baymodel Revision ID: e647f5931da8 ...
mhoffma/micropython
tests/basics/unpack1.py
Python
mit
1,794
0.036232
# unpack sequences a, = 1, ; print(a) a, b = 2, 3 ; print(a, b) a, b, c = 1, 2, 3; print(a, b, c) a, =
range(1); print(a) a, b = range(2); print(a,
b) a, b, c = range(3); print(a, b, c) (a) = range(1); print(a) (a,) = range(1); print(a) (a, b) = range(2); print(a, b) (a, b, c) = range(3); print(a, b, c) (a, (b, c)) = [-1, range(2)]; print(a, b, c) # lists [] = [] [a] = range(1); print(a) [a, b] = range(2); print(a, b) [a, b, c] = range(3); print(a, b, c) # wit...
alex/warehouse
tests/unit/accounts/test_views.py
Python
apache-2.0
12,295
0
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
id_request.set_property( lambda r: str(uuid.uuid4()) if with_user else None, name="unauthenticated_userid", ) form_obj = pretend.stub( validate=pretend.call_recorder(lambda: True), username=pretend.stub(data="theuser"), ) form_class = pret...
_class=form_class) assert isinstance(result, HTTPSeeOther) assert result.headers["Location"] == "/" assert result.headers["foo"] == "bar" assert form_class.calls == [ pretend.call(pyramid_request.POST, user_service=user_service), ] assert form_obj.validate....
dianshen/python_day
s12day10/rabbitMQ_rpc_serverl.py
Python
apache-2.0
951
0.010515
#!/usr/bin/env python # -*- coding:utf-8 -*- import pika import time connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='rpc_queue') def fib(n): if n == 0: return 0 elif n == 1: return 1 else:...
od, props, body): n = int(body) print(" [.] fib(%s)" % n) response = fib(n) ch.basic_publish(exchange='', routing_key=props.reply_to, properties=pika.BasicProperties(correlation_id = \
props.correlation_id), body=str(response)) ch.basic_ack(delivery_tag = method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(on_request, queue='rpc_queue') print(" [x] Awaiting RPC requests") channel.start_consuming()
csmtco10/SRshare
Reyn/AI/Generic/crypto_fitness.py
Python
gpl-2.0
4,583
0.057822
def fitness(string, length) : strSum = 0.0 newAlpha = convert(string.gene) fhCrypt = open("crypto.txt") flippedCrypt = "" flippedCrypt = flip(fhCrypt.readline(),newAlpha) flippedCrypt = flippedCrypt.split() for word in flippedCrypt : #print "Word: %s" % word if len(word) == 1 : fhDict = open("1.txt") e...
: print "Match: %s" % line break strSum += highest fhDict.close() string.result = strSum / len(flippedCrypt) return string.result def flip (string, alpha) : temp = [] for i in range(0,len(string)) : if string[i] == "a" or string[i] == "A" : temp.append(alpha[0]) elif string[i] == "b"...
== "c" or string[i] == "C" : temp.append(alpha[2]) elif string[i] == "d" or string[i] == "D" : temp.append(alpha[3]) elif string[i] == "e" or string[i] == "E" : temp.append(alpha[4]) elif string[i] == "f" or string[i] == "F" : temp.append(alpha[5]) elif string[i] == "g" or string[i] == "G" : tem...
django-danceschool/django-danceschool
danceschool/vouchers/migrations/0004_customergroupvoucher.py
Python
bsd-3-clause
1,085
0.002765
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-08-09 02:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0020_auto_20180808_2247'), ('vouchers', '0...
name='CustomerGroupVoucher', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.CustomerGroup', verbose_name='Customer group')), ('voucher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='vouchers.Voucher', verbose_name='Voucher')), ], options={ ...
ahoarau/m3meka
python/scripts/m3qa/calibrate_head_s2r2.py
Python
mit
4,572
0.042651
#Copyright 2008, Meka Robotics #All rights reserved. #http://mekabot.com #Redistribution and use in source and binary forms, with or without #modification, are permitted. #THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS #"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #LIMITED...
3['param'], 'param_internal': { 'joint_limits': [-7.5,13.0], } } config_default_
s2_j4={ 'calib':s2r2.config_head_s2r2_actuator_j4['calib'], 'param':s2r2.config_head_s2r2_actuator_j4['param'], 'param_internal': { 'joint_limits': [-65.0,65.0], } } config_default_s2_j5={ 'calib':s2r2.config_head_s2r2_actuator_j5['calib'], 'param':s2r2.config_head_s2r2_actuator_j5['param'], 'param_internal'...
YetAnotherNerd/requests-cache
requests_cache/backends/base.py
Python
bsd-2-clause
8,344
0.001558
#!/usr/bin/env python # -*- coding: utf-8 -*- """ requests_cache.backends.base ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Contains BaseCache class which can be used as in-memory cache backend or extended to support persistence. """ from datetime import datetime import hashlib from copy import copy from io import Byt...
is None: seen = {} try: return seen[id(response)] except KeyError: pass result = requests.Response() for field in self._response_attrs: setattr(result, field, getattr(response, field, None)) result.raw._cached_conte
nt_ = result.content seen[id(response)] = result result.history = tuple(self.restore_response(r, seen) for r in response.history) return result def _remove_ignored_parameters(self, request): def filter_ignored_parameters(data): return [(k, v) for k, v in data if k not i...
PXke/invenio
invenio/legacy/bibauthorid/merge.py
Python
gpl-2.0
15,747
0.004953
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011, 2012 CERN. ## ## Invenio is free software; you ca
n redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ##
## Invenio is distributed in the hope that it will be useful, but ## WITHOUT 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 ## alo...
SICOM/rlib
src/examples/python/xml.py
Python
gpl-2.0
388
0.002577
#!/usr/bin/python
# -*- coding: ISO-8859-15 -*- import rlib myreport = rlib.
Rlib() print rlib.version myreport.add_datasource_xml("local_xml") myreport.add_query_as("local_xml", "data.xml", "data") myreport.add_report("array.xml") myreport.set_output_format_from_text("pdf") myreport.execute() print myreport.get_content_type_as_text() open('xml.pdf','wb').write(myreport.get_output())
HarkonenBade/jadepunk-chargen
jadepunk/assets.py
Python
mit
15,523
0.001611
import enum import math from .attrs import AttrTypes class AssetTypes(enum.Enum): DEVICE = "Device" TECH = "Technique" ALLY = "Ally" class Asset(object): class Prop(object): allowed_types = [] def __init__(self): self.master = None self.extra_flaw = False ...
ine)) else: return "{}".format(engine.italics(self.name())) def validate(self, val): self._type_restrict(val) self._check_max_ranks(val) def additional_flaw(self): return self.extra_flaw def cost(self): if
hasattr(self, "ranks"): return self.ranks return 1 class Feature(Prop): pass class Flaw(Prop): pass class Aspect(Feature): allowed_types = [AssetTypes.ALLY, AssetTypes.DEVICE] def __init__(self, aspect): super().__init__() ...
ceball/param
tests/API0/testdynamicparams.py
Python
bsd-3-clause
9,003
0.003443
""" Unit test for dynamic parameters. Tests __get__, __set__ and that inspect_value() and get_value_generator() work. Originally implemented as doctests in Topographica in the file testDynamicParameter.txt """ import copy import unittest import param import numbergen class TestDynamicParameters(unittest.TestCase):...
doc="nothing")
y = param.Dynamic(default=1) class TestPO2(param.Parameterized): x = param.Dynamic(default=numbergen.UniformRandom(lbound=-1,ubound=1,seed=30)) y = param.Dynamic(default=1.0) self.TestPO2 = TestPO2 self.TestPO1 = TestPO1 self.t1 = self.TestPO1() ...
fparrel/regepe
vps/regepe_flask_server.py
Python
gpl-3.0
30,280
0.024935
# -*- coding: utf-8 -*- from flask import Flask,render_template,send_file,Response,flash,request,redirect,session from werkzeug.utils import secure_filename import json import os.path import os import gzip import urllib from db import DbGetListOfDates,DbGet,DbGetComments,DbGetMulitple,DbGetNearbyPoints,DbPut,DbPutWith...
mapid in maps: (lat,lon) = DbGet(mapid,'startpoint').split(',') trackdesc = DbGet(mapid,'trackdesc') trackuser = DbGet(mapid,'trackuser') desc=trackdesc.decode('utf8') mapsout.append({'mapid':mapid,'lat':lat,'lon':lon,'user':trackuser,'desc':desc,'date':date})...
reak if(limit>-1) and (cptr>limit): break return render_template('index.html',limit=limit,maps=mapsout,GMapsApiKey=keysnpwds['GMapsApiKey']) ## GPX Export @application.route('/togpx/<mapid>') def togpx(mapid): # Read map data f=gzip.open('data/mapdata/%s.json.gz'%mapid,'rb') mapdat...
ytjia/coding-practice
algorithms/python/leetcode/tests/test_BinaryTreeMaximumPathSum.py
Python
mit
446
0.002242
# -*- coding: utf-8 -*- # Authors: Y. Jia <yt
jia.zju@gmail.com> import unittest from common.BinaryTree import BinaryTree from .. import BinaryTreeMaximumPathSum class test_BinaryTreeMaximumPathSum(unittest.TestCase): solution = BinaryTreeMaximumPathSum.Solution() def test_maxPathSum(self): self.assertEqual(self.solution.maxPathSum(BinaryTree....
if __name__ == '__main__': unittest.main()
botswana-harvard/edc-appointment
edc_appointment/exceptions.py
Python
gpl-2.0
161
0
class
AppointmentStatusError(Exception): pass class Appoint
mentCreateError(Exception): pass class AppointmentSmsReminderError(Exception): pass
lmazuel/azure-sdk-for-python
azure-batch/azure/batch/models/task_id_range.py
Python
mit
1,362
0
# co
ding=utf-8 # --------------------------------------------
------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is ...
Kiddinglife/kidding-engine
python/Doc/includes/mp_pool.py
Python
lgpl-3.0
3,892
0.002055
import multiprocessing import time import random import sys # # Functions used by test code # def calculate(func, args): result = func(*args) return '%s says that %s%s = %s' % ( multiprocessing.current_process().name, func.__name__, args, result ) def calculatestar(args): return c...
pass except StopIteration: break else: if i ==
5: raise AssertionError('expected ZeroDivisionError') assert i == 9 print('\tGot ZeroDivisionError as expected from IMapIterator.next()') print() # # Testing timeouts # print('Testing ApplyResult.get() with timeout:', end=' ') res = ...
adriennemcd/neighborhood-change-index
nc-pt1.py
Python
mit
19,716
0.005833
""" THIS SCRIPT CREATES AN INDEX OF NEIGHBORHOOD CHANGE USING USER SPECIFIED INDICATORS: 1. CALCULATE Z-SCORE FOR EACH INDICATOR 2. CALCULATE NEGATIVE Z-SCORE FOR INDICATORS THAT SHOULD DETRACT FROM SCORE (I.E. VACANCY RATE) 3. ADD INDICATORS TOGETHER FOR RAW SCO
RE 4. DEFINE CLASSIFICATION METHOD 5. ASSIGN EACH RECORD AN INDEX SCORE FROM 1-6 FOR COMPARATIVE
PURPOSES, THIS SCRIPT IS SET UP SO THAT MULTIPLE YEARS OF DATA CAN BE IN THE SAME SHAPEFILE; IN OTHER WORDS, ONE SHAPEFILE CAN BE RUN THROUGH THE TOOL MULTIPLE TIMES ON DIFFERENT YEARS OF VARIABLES WITHOUT ERRORS. To create an ArcToolbox tool with which to execute this script, do the following. 1 In ArcMap > Catal...
tensorflow/tfx
tfx/components/schema_gen/component_test.py
Python
apache-2.0
2,491
0.001204
# Copyright 2019 Google LLC. 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 a...
standard_artifacts.Schema.TYPE_NAME, schema_gen.outputs[standard_component_specs.SCHEMA_KEY].type_name)
self.assertJsonEqual( str(schema_gen.spec.exec_properties[ standard_component_specs.INFER_FEATURE_SHAPE_KEY]), str(infer_shape)) if __name__ == '__main__': tf.test.main()
mitya57/debian-buildbot
buildbot/process/builder.py
Python
gpl-2.0
25,892
0.000657
# This file is part of Buildbot. Buildbot 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 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
ildbot.buildslave.BuildSlave} @param slave: the BuildSlave that represents the buildslave as a whole @type remote: L{twisted.spread.pb.RemoteReference} @param remote: a reference to the L{buildbot.slave.bot.SlaveBuilder} @type commands: dict: string -> string, or None @param co...
(with 'self') when the slave-side builder is fully attached and ready to accept commands. """ for s in self.attaching_slaves + self.slaves: if s.slave == slave: # already attached to them. This is fairly common, since # attached() gets called...
shaunduncan/breezeminder
breezeminder/views/reminder.py
Python
mit
5,296
0.002455
from flask import (flash, redirect, render_template, request, url_for) from flask.ext.login import (current_user, fresh_login_required) from breezeminder.app import app from breezeminder.forms.reminder import Remin...
, 1))) except (IndexError, ValueError): return redirect(url_for('user.reminders.history'
, pk_hash=reminder.pk_hash)) context = { 'title': 'Reminder History', 'description': 'View Reminder Sent History', 'reminder': reminder, 'history': history } return render_template('user/reminders/history/index.html', **context) @fresh_login_required @nocache def view_his...
rebaltina/DAT210x
Module2/assignment3.py
Python
mit
1,075
0.015814
impo
rt pandas as pd # TODO: Load up the dataset # Ensuring you set the appropriate header column names # df = pd.read_csv('c:/Users/User/workspace/DAT210x/MOdule2/Datasets/servo.data', names = ['motor', 'screw', 'pgain', 'vgain', 'class']) df.head() # TODO: Create a slice that contains all entries # having a vgain equal ...
slice that contains all entries # having a motor equal to E and screw equal # to E. # of samples in) that slice: len(df[ (df.motor == 'E') & (df.screw == 'E')]) # TODO: Create a slice that contains all entries # having a pgain equal to 4. Use one of the # various methods of finding the mean vgain # value for the sa...
bit-trade-one/SoundModuleAP
lib-src/portmidi/pm_python/pyportmidi/__init__.py
Python
gpl-2.0
25
0.04
f
rom .midi import
*
feureau/Small-Scripts
Blender/Blender config/2.91/scripts/addons/XNALaraMesh/write_ascii_xps.py
Python
gpl-3.0
5,428
0.000553
# <pep8 compliant> import io import operator from . import read_ascii_xps from . import xps_const from mathutils import Vector def writeBones(xpsSettings, bones): bonesString = io.StringIO() if bones: bonesString.write('{:d} # bones\n'.format(len(bones))) for bone in bones: name...
ingIO() print('Writing Bon
es') ioStream.write(writeBones(xpsSettings, xpsData.bones).read()) print('Writing Meshes') ioStream.write(writeMeshes(xpsSettings, xpsData.meshes).read()) ioStream.seek(0) writeIoStream(filename, ioStream) if __name__ == "__main__": readfilename = r'G:\3DModeling\XNALara\XNALara_XPS\data\TESTI...
umitproject/openmonitor-aggregator
registration/forms.py
Python
agpl-3.0
6,034
0.0058
""" Forms and validation code for user registration. """ from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from registration.models import RegistrationProfile # I put this on all required fields, because it's easier to pick up # on them wit...
password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password')) password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), label=_(u'password (again)')) d...
try: user = User.objects.get(username__iexact=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(_(u'This username is already taken. Please choose another.')) def clean(self): """ Ve...
polegithub/shopping_web_python
shopping_web/manage.py
Python
mit
246
0
#!/usr/bin/env python import os import sys if __nam
e__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cms.settings") from django.core.management import execute_from_command_line execute_from_command_lin
e(sys.argv)
sigmunau/nav
python/nav/mibs/etherlike_mib.py
Python
gpl-2.0
1,422
0
# -*- coding: utf-8 -*- # # Copyright (C) 2009 UNINETT AS # # This file is part of Network Administration Visualized (NAV). # # NAV 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. # # This program is...
ense along with NAV. If not, see <http://www.gnu.org/licenses/>. # """Implements a EtherLike-MIB MibRetriever and associated functionality.""" from __future__ import absolute_import from twisted.internet import defer from . import mibretriever class EtherLikeMib(mibretriever.MibRetriever): """MibRetriever for Eth...
midumps.etherlike_mib import MIB as mib @defer.deferredGenerator def get_duplex(self): """Get a mapping of ifindexes->duplex status.""" dw = defer.waitForDeferred( self.retrieve_columns(('dot3StatsDuplexStatus',))) yield dw duplex = self.translate_result(dw.getResult...
inachen/cs171-hw4-chen-ina
ProblemGeoUSA/data_wrangle_total.py
Python
mit
1,779
0.014615
import json from pprint import pprint import time import io # from http://www.codigomanso.com/en/2011/05/trucomanso-transformar-el-tiempo-en-formato-24h-a-formato-12h-python/ def ampmformat (hhmmss): """ This method converts time in 24h format to 12h format Example: "00:32" is "12:32 AM" "13...
am else ' PM') json_data=open('allData2003_2004.json') data = json.load(json_data
) json_data.close() # k ='690150' # print data['690150'] output = {} for k in data.keys(): for d in data[k]: date = time.strptime(d['date'], "%b %d, %Y %I:%M:%S %p") if k in output: t = ampmformat('%02d:%02d:%02d' % (date.tm_hour, date.tm_min, date.tm_sec)) h = date.tm_hou...
hbussell/pinax-tracker
apps/milestones/views.py
Python
mit
10,170
0.003441
from datetime import date, datetime, timedelta from itertools import chain from operator import attrgetter from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured from django.core.urlresolvers import reverse from django.db.models import Q, get_app from django.http i...
bjects.filter(object_id=None) group_base = None milestone = get_object_or_404(milestones, id=id) if group: notify_list = group.member_queryset() else: notify_list = User.objects.all() notify_list = notify_list.exclude(id__exact=request.user.id) if not request.user.is_authenti...
is_member = group.user_is_member(request.user) else: is_member = True ## milestone tasks from tasks.models import Task from tasks import workflow from tasks.filters import TaskFilter group_by = request.GET.get("group_by") if group: tasks = group.content_objects(...