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
stanta/darfchain
darfchain/__manifest__.py
Python
gpl-3.0
668
0.004491
{ 'name': "Blockchain Waves Synchro", 'version': '1.0', 'depends': ['base', 'sale',
'sales_team', 'delivery', 'barcodes', 'mail', 'report',
'portal_sale', 'website_portal', 'website_payment',], 'author': "Sergey Stepanets", 'category': 'Application', 'description': """ Module for blockchain synchro """, 'data': [ 'views/setting.xml', 'data/cron.xml', 'views/clients.xml', 'views...
Kriegspiel/ks-python-api
kriegspiel_api_server/kriegspiel/migrations/0004_move_created_at.py
Python
mit
507
0
# -*- coding: utf-8 -*- # Generat
ed by Django 1.10.4 on 2017-01-13 20:45 fro
m __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('kriegspiel', '0003_auto_20170113_2035'), ] operations = [ migrations.AddField( model_name='move', ...
facebookexperimental/eden-hg
eden/hg/eden/hgext3rd_init.py
Python
gpl-2.0
497
0.002012
# Copyright (c) 2017-present, Facebook, Inc. # All Rights Reserved. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. from __future__ import absolute_import, division, print_func
tion, unicode_literals import pkgutil # Indicate that hgext3rd is a namspace package, and other python path # directories may still be
searched for hgext3rd extensions. __path__ = pkgutil.extend_path(__path__, __name__) # type: ignore # noqa: F821
AsimmHirani/ISpyPi
tensorflow/contrib/tensorflow-master/tensorflow/contrib/distributions/python/kernel_tests/mixture_test.py
Python
apache-2.0
24,371
0.006729
# Copyright 2015 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...
s, dtype=dtypes.int32) return distributions_py.Mixture(cat, components) class MixtureTest(test.TestCase): def testShapes(self): with self.test_session(): for batch_shape in ([], [1], [2, 3, 4]): dist = make_univariate_mixture(batch_shape, num_components=10) self.assertAllEqual(batch_sha...
_shape_tensor().eval()) for event_shape in ([1], [2]): dist = make_multivariate_mixture( batch_shape, num_components=10, event_shape=event_shape) self.assertAllEqual(batch_shape, dist.batch_shape) self.assertAllEqual(batch_shape, dist.batch_shape_tensor().eval()) ...
bitmovin/bitcodin-python
bitcodin/test/statistics/testcase_get_statistics_current.py
Python
unlicense
614
0.001629
__author__ = 'Dominic Miglar <dominic.miglar@bitmovin.net>' import unittest import bitcodin from bitcodin.test.bitcodin_test_case import BitcodinTestCase from bitcodin.rest import RestClient cl
ass GetStatisticsCurrentMonthTestCase(BitcodinTestCase): def setUp(self): super(GetStatisticsCurrentMonthTestCase, self).setUp() def runTest(self): response = RestClient.get(url=bitcodin.get_api_base()+'/statistics', headers=bitcodin.create_headers()) de
f tearDown(self): super(GetStatisticsCurrentMonthTestCase, self).tearDown() if __name__ == '__main__': unittest.main()
lduarte1991/edx-platform
common/djangoapps/third_party_auth/tests/specs/base.py
Python
agpl-3.0
49,331
0.003324
"""Base integration test for provider implementations.""" import unittest import json import mock from contextlib import contextmanager from django import test from django.contrib import auth from django.contrib.auth import models as auth_models from django.contrib.messages.storage import fallback from django.contri...
.context["data"]["third_party_auth"] self.assertEqual(tpa_context["errorMessage"], None) # Check that the "You've successfully signed into [PROVIDER_NAME]" message is shown. self.assertEqual(tpa_context["currentProvider"], self.PROVIDER_NAME) # Now the user enters their username and pass...
: self.user.email, 'password': 'test'} ) self.assertEqual(ajax_login_response.status_code, 200) # Then the AJAX will finish the third party auth: continue_response = self.client.get(tpa_context["finishAuthUrl"]) # And we should be redirected to the dashboard: self.assertE...
MugFoundation/versioneer
cli/versioneer.py
Python
mit
743
0.012113
#!/usr/bin/env #(C) Mugfoundation 2014 #Available under MIT license import click import hashlib c = hashlib.sha512() @click.command() @click.option('--setup', 'setup', help='Setup new
project', type=str) @click.option('-x', '--major', 'major', help='major version setter', type=int) @click.option('-y', '--minor', 'minor', help='minor version setter', type=int) @click.option('-z', '--patch', 'patch', help='patch version setter', type=int)
@click.option('-e', '--extras', 'extras', help='major version setter', type=int) @click.option('-h', '--hash', 'hash', help='file to extract the sha512 hash', type=str) @click.option('-sr', '--sign', 'sign', help='sign the release using open pgp (available only on linux)', type=str) def main():
DigitalHills/Esse
dpeer/nexus.py
Python
apache-2.0
17,520
0.00468
''' Copyright 2017 Digital Hills, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ag...
zeEpoch() ''' Push an event into the pushToPeers Queue ''' def addItemToPeerQueue(self, _peerQueueEvent, _peer, data=None): self.pushToPeers.put((_peer, _peerQueueEvent, data)) '''
Add new peer ''' def addNewPeer(self, address, port, epochTime, personalTime): # To ensure nobody attempts changing what we think about ourselves if address == "127.0.0.1": port = node_settings["port"] epochTime = str(self.next_epoch) personalT...
luojus/bankws
bankws/appresponse.py
Python
mit
15,773
0.000127
'
'' Appresponse module contains ApplicationResponse and FileDescriptor classes which are used to parse response. Usage: >>> response = ApplicationResponse(xml_message) >>> response.is_accepted() # Checks was the request accepted ''' import os import base64 import gzip import logging from lxml import etree try...
signature import validate class ApplicationResponse(): """ ApplicationResponse class is used to parse certificate responses Public methods:: is_accepted: Checks if request was accepted (responsecode 00) content: Returns content of message references: Returns filereferences list. ...
joshmoore/zeroc-ice
py/test/Ice/faultTolerance/Client.py
Python
gpl-2.0
1,608
0.006219
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved. # # This copy of Ice is licensed to you under the terms described in the # ICE_LICENSE file included in this distribution. # # *************************************...
[0]) return False ports.append(int(arg)) if len(ports) == 0: sys.stderr.write(args[0] + ": no ports specified\n") usage(args[0]
) return False try: AllTests.allTests(communicator, ports) except: traceback.print_exc() test(False) return True try: initData = Ice.InitializationData() initData.properties = Ice.createProperties(sys.argv) # # This test aborts servers, so we don't wan...
RexFuzzle/sfepy
tests/test_input_linear_viscoelastic.py
Python
bsd-3-clause
207
0.009662
input_name = '../examples/linear_elasticity/linear_viscoelastic.py' output_name_trunk = 'test_linear_viscoelast
ic' from tests_basic import TestInputEvolutionary class Test(TestInputEvolu
tionary): pass
fuspu/RHP-POS
item_utils.py
Python
mit
837
0.009558
#!/usr/bin/env python3 """ Item Related Objects. """ #-*- coding: utf-8 -*- import re from datetime import datetime from db_related import DBConnect class Item_Lookup(object): """ Returned Item Lookup Dictionary Structure: item = { upc: text description: text ...
self.upc = upc def GetBasics(self): query = '''SELECT upc, description, cost, retail, taxable, onhandqty FROM item_detailed WHERE upc=(?)''' data = [self.upc,] returnd =
DBConnect(query, data).ALL()
ahclab/greedyseg
makeliblin.py
Python
gpl-2.0
4,282
0.02639
# coding: utf-8 import sys from collections import defaultdict sys.path.append('/project/nakamura-lab01/Work/yusuke-o/python') from data.reader import dlmread def addfeature(fs, fid, name, mode): if mode == 'dev' or name in fid: fs.append(fid[name]) def main(): if len(sys.argv) != 6: print('USAGE: python3 mak...
nknown mode.\n') return # load word and pos corpus_in_pos = [x for x in dlmread(fname_pos, ' ')] for i in range(len(corpus_in_pos)): corpus_in_pos[i] = [w.split('_') for w in corpus_in_pos[i]] # load splitter tab_sp = defaultdict(lambda: []) with open(fname_splitter, 'r', encoding='utf-8') as fp: for l in...
bda: len(fid)+1) if mode == 'test': with open(fname_fid, 'r', encoding='utf-8') as fp: for l in fp: ls = l.split() k = ls[0] v = int(ls[1]) fid[k] = v # make/save training data n = 0 with open(fname_liblin, 'w', encoding='utf-8') as fp: for i in range(len(corpus_in_pos)): data = [['<s>', ...
andyzsf/django
django/db/models/fields/__init__.py
Python
bsd-3-clause
84,287
0.000641
# -*- coding: utf-8 -*- from __future__ import unicode_literals import collections import copy import datetime import decimal import math import uuid import warnings from base64 import b64decode, b64encode from itertools import tee from django.apps import apps from django.db import connection from django.db.models.lo...
errors.extend(self._check_choices()) errors.extend(self._check_db_index()) errors.extend(self._check_null_allowed_for_primary_keys()) errors.extend(self._check_backend_specific_checks(**kwargs)) return errors def _check_field_name(self): """ Check if field name is vali...
ore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith('_'): return [ checks.Error( 'Field names must not end with an underscore.', hint=None, obj=self, id='fields.E001', ...
StongeEtienne/dipy
dipy/align/tests/test_streamlinear.py
Python
bsd-3-clause
15,316
0
import numpy as np from numpy.testing import (run_module_suite, assert_, assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, ass...
_array_almost_equal(moved2[0], moved3[0], decimal=3) def test_min_v
s_min_fast_precision(): static = fornix_streamlines()[:20] moving = fornix_streamlines()[:20] static = [s.astype('f8') for s in static] moving = [m.astype('f8') for m in moving] bmd = BundleMinDistanceMatrixMetric() bmd.setup(static, moving) bmdf = BundleMinDistanceMetric() bmdf.setu...
RPGOne/Skynet
pytorch-master/torch/legacy/optim/rmsprop.py
Python
bsd-3-clause
2,014
0.001986
import torch def rmsprop
(opfunc, x, config, state=None): """ An implementation of RMSprop ARGS: - 'opfunc' : a function that takes a single input (X), the point of a evaluation, and returns f(X) and df/dX - 'x' : the initial point - 'config` : a table with configura
tion parameters for the optimizer - 'config['learningRate']' : learning rate - 'config['alpha']' : smoothing constant - 'config['epsilon']' : value with which to initialise m - 'config['weightDecay']' : weight decay - 'state' : a table describing t...
getsenic/nuimo-linux-python
nuimo/__init__.py
Python
mit
130
0.007692
from .nuimo import ControllerManager, ControllerManagerLis
tener, Controller, ControllerListen
er, GestureEvent, Gesture, LedMatrix
ricardodani/django-simple-url-shortner
simple_url_shortner/urlshortener/views.py
Python
gpl-2.0
3,074
0.001627
# -*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponsePermanentRedirect, Http404, HttpResponseRedirect from django.views.decorators.http import require_GET from django.contrib.auth import login, authenticate from django.core.urlresolvers import reverse_lazy from django.contrib...
username = request.POST['username'] password = request.POST['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, 'User registered and logged in with success.') return HttpResponseRedirect(reverse...
e: context = {'user_register_form': UserCreationForm()} return render(request, 'register.html', context) def user_url_list(user, page, limit=20): """ Returns a paginator of a queryset with users Url's. """ url_list = Url.objects.filter(user=user) paginator = Paginator(url_list, limit)...
bioinformatics-ua/catalogue
emif/utils/validate_questionnaire.py
Python
gpl-3.0
1,852
0.00432
# -*- coding: utf-8 -*- # Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ # # 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 vers...
uted in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this pro
gram. If not, see <http://www.gnu.org/licenses/>. from django.http import HttpResponse, HttpResponseRedirect from questionnaire.models import * from django.shortcuts import render_to_response, get_object_or_404 import sys from searchengine.models import * rem = 1 qu = get_object_or_404(Questionnaire, id=rem) qs...
sniperganso/python-manilaclient
manilaclient/v1/shares.py
Python
apache-2.0
1,210
0.000826
# Copyright 2012 NetApp # Copyright 2015 Chuck Fouts # 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 # #...
mport warnings from manilaclient.v2 import shares warnings.warn("Module manilaclient.v1.shares is deprecated (taken as " "a basis for manilac
lient.v2.shares). " "The preferable way to get a client class or object is to use " "the manilaclient.client module.") class MovedModule(object): def __init__(self, new_module): self.new_module = new_module def __getattr__(self, attr): return getattr(self.new_modul...
fiduswriter/fiduswriter
fiduswriter/user/migrations/0001_squashed_0003_auto_20151226_1110.py
Python
agpl-3.0
6,929
0.00101
# Generated by Django 1.11.13 on 2018-08-14 17:35 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): replaces = [ ("user", "0001_initial"), ("user", "0002_rename_account_tables"), ("user", "0003...
( "last_login", models.DateTimeField( blank=True, null=True, verbose_name="last login" ), ), ( "is_superuser", models.BooleanField
( default=False, help_text="Designates that this user has all permissions without explicitly assigning them.", verbose_name="superuser status", ), ), ( "username", ...
viraja1/grammar-check
grammar_check/__init__.py
Python
lgpl-3.0
19,319
0.000207
# -*- coding: utf-8 -*- # © 2012 spirit <hiddenspirit@gmail.com> # © 2013-2014 Steven Myint # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, either version 3 of the License, # or (at yo...
nst different rules.""" _HOST = socket.gethostbyname('localhost') _MIN_PORT = 8081 _MAX_PORT = 8083 _TIMEOUT = 60 _port = _MIN_PORT _serv
er = None _instances = WeakValueDictionary() _PORT_RE = re.compile(r"(?:https?://.*:|port\s+)(\d+)", re.I) def __init__(self, language=None, motherTongue=None): if not self._server_is_alive(): self._start_server_on_free_port() if language is None: try: ...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractDanielyangNinja.py
Python
bsd-3-clause
362
0.035912
def extractDanielyangNinja(item): ''' Parser for '
danielyang.ninja' ''' vol, chp, frag, postfi
x = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None if "WATTT" in item['tags']: return buildReleaseMessageWithType(item, "WATTT", vol, chp, frag=frag, postfix=postfix) return False
openqt/algorithms
projecteuler/pe030-digit-fifth-powers.py
Python
gpl-3.0
507
0.021696
#!/usr/bin/env python # coding=utf-8 """30. Digit fifth powers https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: > 1634 = 14 \+ 64 \+ 34 \+ 44 > 8208 = 84 \+ 24 \+ 04 \+ 84 > 9474 = 94 \+ 44 \+ 74 \+ 44 As 1 = 14 is n...
sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all
the numbers that can be written as the sum of fifth powers of their digits. """
prathamtandon/g4gproblems
Arrays/longest_increasing_subsequence_nlogn.py
Python
mit
1,625
0.004308
import unittest """ Given an unordered array of integers, find the length of longest increasing subsequence. Input: 0, 8, 4, 12, 2, 10, 6, 14, 1, 9
, 5, 13, 3, 11, 7, 15 Ou
tput: 6 (0, 2, 6, 9, 11, 15) """ """ A great explanation of the approach appears here: http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/ """ def find_ceil_index(list_of_numbers, ele): """ Returns the smallest element in list_of_numbers greater than or equal to ele. "...
hilario/trep
src/system.py
Python
gpl-3.0
46,931
0.00358
import math import inspect import numpy as np import numpy.linalg as linalg import scipy as sp import scipy.optimize import scipy.io from itertools import product import trep import _trep from _trep import _System from frame import Frame from finput import Input from config import Config from force import Force from c...
import Constraint from potential import Potential from util import dynamics_indexing_decorator
class System(_System): """ The System class represents a complete mechanical system comprising coordinate frames, configuration variables, potential energies, constraints, and forces. """ def __init__(self): """ Create a new mechanical system. """ _System.__init_...
simone-campagna/petra
petra/token_list.py
Python
apache-2.0
2,481
0.003628
__all__ = ( 'TokenList', ) import collections from .errors import TokenTypeError class TokenList(collections.Sized, collections.Iterable, collections.Container): def __init__(self, init=None, *, token_type=None): if token_type is None: token_type = object self._token_type = token_...
t an iterable".format(init)) for token in init: self.add(token) @property def token_type(self): return self._token_type def add(self, token, *, count=1): if not isinstance(token, self._token_type): raise TokenTypeError("invalid token {!r}: type is no...
(token, self._token_type.__name__)) for i in range(count): self._tokens.append(token) def pop(self): return self._tokens.popleft() def remove(self, token): for c, t in enumerate(self._tokens): if t is token: break else: ...
mitsuhiko/sqlalchemy
test/orm/test_dynamic.py
Python
mit
30,088
0.002526
from sqlalchemy.testing import eq_, is_ from sqlalchemy.orm import backref, configure_mappers from sqlalchemy import testing from sqlalchemy import desc, select, func, exc from sqlalchemy.orm import mapper, relationship, create_session, Query, \ attributes, exc as orm_exc, Session from sqlalchemy.or...
self.classes.Item) mapper(Order, orders, properties={ 'items': relationshi
p(Item, secondary=order_items, lazy="dynamic", **items_args ) }) mapper(Item, items) return Order, Item class DynamicTest(_DynamicFixture, _fixtures.FixtureTest, AssertsCompiledSQL): ...
wtamu-cisresearch/nltksite
nltkapp/views.py
Python
mit
8,449
0.034797
from django.shortcuts import render from .models import Document, Corpus from django.http import JsonResponse from django.conf import settings import json import os import re import nltk from nltk.corpus import * from nltk.collocations import * import string import logging logger = logging.getLogger('nltksite.nltkapp'...
filter(lambda w: len(w) < 3 or w.lower() in ignored_words) # return the 10 bigrams with the highest PMI method = bigram_measures.pmi if "student_t" in score: method = bigram_measures.student_t elif "chi_sq" in score: method = bigram_measures.chi_sq elif "pmi" in score: method = bigram_measures.pmi elif "li...
irling elif "jaccard" in score: method = bigram_measures.jaccard word_list = finder.nbest(method, 100) return [word_list, fdist] def trigram_collocation(words, score): ignored_words = stopwords.words('english') trigrams = nltk.trigrams(words) fdist = nltk.FreqDist(trigrams) trigram_measures = nltk.collocat...
RobinQuetin/CAIRIS-web
cairis/cairis/ReferenceContribution.py
Python
apache-2.0
1,176
0.007653
# 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...
ning permissions and limitations # under the License. class ReferenceContribution: def __init__(self,src,dest,me,cont): self.theSource = src self.theDestination = dest self.theMeansEnd = me self.theContribution = cont def source
(self): return self.theSource def destination(self): return self.theDestination def meansEnd(self): return self.theMeansEnd def contribution(self): return self.theContribution
Akrog/cinder
cinder/tests/test_coraid.py
Python
apache-2.0
33,873
0
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
handle.set_called() return handle(handle_name, url_params, data, allow_empty_response) raise FakeRpcIsNotCalled(handle_nam
e, url_params, data) class CoraidDriverTestCase(test.TestCase): def setUp(self): super(CoraidDriverTestCase, self).setUp() configuration = mox.MockObject(conf.Configuration) configuration.append_config_values(mox.IgnoreArg()) configuration.coraid_default_repository = 'default_repos...
tuturto/pyherc
src/herculeum/ui/gui/mainwindow.py
Python
mit
8,099
0.001235
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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,...
Hint, StartGameController(self.application.level_generator_factory, self.application.creature_generator, self.application.item_generator,
self.application.config.start_level)) self.splash_screen.finish(main_window) main_window.show_new_game() self.qt_app.exec_() class MainWindow(QMainWindow): """ Class for displaying main window .. versionadded:: 0.5 """ def __init__(self, application, sur...
kingvuplus/ts-gui-3
lib/python/Components/language_cache.py
Python
gpl-2.0
50,254
0.002846
LANG_TEXT = {'en_EN': {'tr_TR': 'Turkish', 'fr_FR': 'French', 'fi_FI': 'Finnish', 'pt_PT': 'Portuguese', 'fy_x-FY': 'Frisian', 'it_IT': 'Italian', 'et_EE': 'Estonian', 'no_NO': 'Norwegian', 'nl_NL': 'Dutch', 'lv_LV': 'Lat...
'fa_IR': 'Persian',
'sv_SE': '\xd8\xb3\xd9\x88\xd9\x8a\xd8\xaf\xd9\x89', 'he_IL': 'Hebrew', 'T1': '\xd9\x85\xd9\x86 \xd9\x81\xd8\xb6\xd9\x84\xd9\x83 \xd8\xa3\xd8\xb3\xd8\xaa\xd8\xae\xd8\xaf\xd9\x85 \xd8\xb0\xd8\xb1 \xd8\xa7\xd9\x84\xd8\xb3\xd9\x87\xd9\x85 \xd8\xa7\xd9\x84\xd8\xb9\xd9\x84\xd9\x88\xd9\x89 \xd8\xa3\xd9\...
glucoseinc/naumanni-server
naumanni/web/__init__.py
Python
agpl-3.0
422
0
# -*- codi
ng: utf-8 -*- """WebUI.""" from .websocket import WebsocketProxyHandler def create_webapp(naumanni, **kwargs): """App factory. :param CircleCore core: CircleCore Core :param str base_url: ベースURL :param int ws_port: Websocket Port Number :return: WebUI App :rtype: CCWebApp """ from ....
manni, **kwargs) return app
TallJimbo/mcpib
tests/builtin_strings_test.py
Python
bsd-2-clause
2,081
0.004325
# # Copyright (c) 2014, Jim Bosch # All rights reserved. # # mcpib is distributed under a simple BSD-like license; # see the LICENSE file that should be present in the root # of the source distribution. # import unittest import os import sys buildPythonPath = os.path.join(os.path.split(__file__)[0], "..", "python") i...
or, mod.return_char_ref) self.assertRaises(mcpib.ToPythonErro
r, mod.return_char_const_ref) if __name__ == "__main__": unittest.main()
flacjacket/sympy
examples/advanced/fem.py
Python
bsd-3-clause
5,414
0.035648
#!/usr/bin/env python """FEM library Demonstrates some simple finite element definitions, and computes a mass matrix $ python fem.py [ 1/60, 0, -1/360, 0, -1/90, -1/360] [ 0, 4/45, 0, 2/45, 2/45, -1/90] [-1/360, 0, 1/60, -1/90, 0, -1/360] [ 0, 2/45, -1/90, 4/45, 2/45, 0] ...
== 1: for i in range(0, order+1): x = i*h if x <= 1: set.append((x,y)) if nsd == 2: for i in range(0, order+1): x = i*h for j in range(0, order+1): y = j*h if x + y <= 1: set.append((x,y)) i...
ange(0, order+1): y = j*h for k in range(0, order+1): z = j*h if x + y + z <= 1: set.append((x,y,z)) return set def create_matrix(equations, coeffs): A = zeros(len(equations)) i = 0; j = 0 for j in range(0, len(...
yoonkiss/fMBT
utils/fmbtx11.py
Python
lgpl-2.1
26,132
0.002334
# fMBT, free Model Based Testing tool # Copyright (c) 2013-2016, Intel Corporation. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU Lesser General Public License, # version 2.1, as published by the Free Software Foundation. # # This program is dist...
lf.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen) def findItemsById(self, itemId, count=-1, searchRootItem=None, searchItems=None, onScreen=Fals
e): c = lambda item: (itemId == item._itemId or itemId == item.properties().get("AutomationId", None)) return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen) def findItemsByProperties(self, properties, count=-1, searchRootItem=None, searchIt...
Shatki/PyIMU
gost4401_81.py
Python
gpl-3.0
4,655
0.002365
# -*- coding: utf-8 -*- """ * Partial implementation of standard atmospheric model as described in * GOST 4401-81 useful for processing of data from meteorological balloon * sensors. * * Supported modelling of temperature and pressure over the altitude span from * 0 up to 51km. * * algorithm by Oleg Kocheto...
f.tab['altitude']])): break Ps = float(self.ag_table[idx][self.tab['pressure']]) Bm = float(self.ag_table[idx][self.tab['temp gradient']]) Tm = float(self.ag_table[idx][self.tab['temperature'
]]) Hb = float(self.ag_table[idx][self.tab['altitude']]) if Bm != 0: lP = log10(Ps) - (self.G / (Bm * self.R)) * log10((Tm + Bm * (geopot_H - Hb)) / Tm) else: lP = log10(Ps) - 0.434294 * (self.G * (geopot_H - Hb)) / (self.R * Tm) return pow(10, lP) def get_...
qewerty/moto.old
tools/scons/engine/SCons/Tool/sunf95.py
Python
gpl-2.0
2,167
0.00323
"""SCons.Tool.sunf95 Tool-specific initialization for sunf95, the Sun Studio F95 compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 20...
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC') env['SHF95FLAGS'] = SCons.Util.CLVar('$F95FLAGS -KPIC') def exists(env): return env.Detect(compilers) # Local Varia
bles: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
sistason/kinksorter2
src/kinksorter/settings.py
Python
gpl-3.0
4,818
0.001038
""" Django settings for untitled project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import o...
lidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIM...
USE_TZ = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(message)s', 'datefmt': '%H:%M:%S', } }, 'filters': { 'ignore_get_current_task': { '()': 'django.utils.log....
TurtleRockStudios/renderdoc_public
util/test/tests/Vulkan/VK_Indirect.py
Python
mit
14,258
0.004699
import rdtest import struct import renderdoc as rd class VK_Indirect(rdtest.TestCase): demos_test_name = 'VK_Indirect' def check_overlay(self, eventId: int, out: rd.ReplayOutput, tex: rd.TextureDisplay, save_data: rd.TextureSave): pipe: rd.PipeState = self.controller.GetPipelineState() # Che...
s(rd.MeshDataStage.VSOut) postvs_ref = { 0: {'vtx': 0, 'idx': 0, 'gl_PerVertex.gl_Position': [-0.8, -0.5, 0.0, 1.0]}, 1: {'vtx': 1, 'idx': 1, 'gl_PerVertex.gl_Position': [-0.7, -0.8, 0.0, 1.0]}, 2: {'vtx': 2, 'idx': 2, 'gl_PerVertex.gl_Position': [-0.6, -0.5,...
ck_mesh_data(postvs_ref, postvs_data) self.check(len(postvs_data) == len(postvs_ref)) # We shouldn't have any extra vertices self.check_overlay(draw.eventId, out, tex, save_data) rdtest.log.success("{} {} is as expected".format(level, draw.name)) # vkCmdDrawIndexedInd...
shimpe/frescobaldi
frescobaldi_app/debuginfo.py
Python
gpl-2.0
2,835
0.003175
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/ # # Copyright (c) 2008 - 2014 by Wilbert Berendsen # # 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 ...
nknown def python_version(): import platform return platform.python_version() @_catch_unknown def operating_system(): import platform return platform.platform() @_catch_unknown def ly_version(): import ly.pkginfo return ly.pkginfo.version @_catch_unknown def poppler_version(): import popp...
r n in popplerqt4.version()) def version_info_named(): """Yield all the relevant names and their version string.""" yield appinfo.appname, appinfo.version yield "Python", python_version() yield "python-ly", ly_version() yield "Qt", qt_version() yield "PyQt", pyqt_version() yield "sip", sip...
CurryBoy/ProtoML-Deprecated
protoml/extras/tsne/_bhtsne/__init__.py
Python
bsd-3-clause
62
0
f
rom .bhtsne import bh_tsne __all__ = ["_bhtsne", "
bh_tsne"]
unclejed613/gnuradio-projects-rtlsdr
scanner/frqedit.py
Python
gpl-2.0
2,267
0.013674
##!/usr/bin/env python from array import * import os import struct stats = os.stat('freqtest.dat') file_size = stats.st_size #print('file size ', +file_size, ' bytes') entries = file_size/4 #print('file has ', +entries, +' entries') freq_array = array('f', []) #create an array to hold the entries for a ...
requency: ') freq_array[fm-1] = new_freq for indx in range(len(freq_array)): #print the modified
list print(indx+1, +freq_array[indx]) x = raw_input("do you want to change another frequency? ") x = raw_input('continue? (y to add freqs to the list, n to save the list and exit)') #second part... we may want to add new frequencies to the list while x != "n": #s...
maurozucchelli/dipy
doc/examples/probabilistic_tracking_odfs.py
Python
bsd-3-clause
2,094
0.001433
""" ==================================== Probabilistic Tracking on ODF fields ==================================== In this example we perform probabilistic fiber tracking on fields of ODF peaks. This example requires importing example `reconst_csa.py`. """ import numpy as np from reconst_csa import * from dipy.rec...
(r, n_frames=1, out_path='csa_prob_t
racks.png', size=(600, 600)) """ .. figure:: csa_prob_tracks.png :align: center **Probabilistic streamlines applied on an ODF field modulated by GFA**. """
firebase/firebase-android-sdk
ci/fireci/fireci/commands.py
Python
apache-2.0
946
0.002114
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
ons and # limitations under the License. import click from . import gradle from . import ci_command @click.argument('task', required=True, nargs=-1) @click.option( '--gradle-opts', default='', help='GRADLE_OPTS passed to the gradle invocation.') @ci_command('gradle'
) def gradle_command(task, gradle_opts): """Runs the specified gradle commands.""" gradle.run(*task, gradle_opts=gradle_opts)
rchurch4/georgetown-data-science-fall-2015
analysis/graph/graph_creation.py
Python
mit
1,784
0.008408
# Creates graph of restaurant reviews for yelp or trip advisor. # writes graph to gml file for use in gephi # # Rob Churchill # # N
OTE: I learned to do this in my data science class last semester. If you are looking for plagiarism things, you will almost certainly find similar clustering code. # I did not copy it, I learned this specific way of doing it, and referred to my previous assignments when doing it for this project. If you would like to ...
ra files for the sole sake of showing that I haven't plagiarized. import networkx as nx import numpy as np import scipy as sp import csv folder = 'data/' file_names = ['yelp_data.csv', 'trip_advisor_data.csv'] # EDIT this line to change which website you make the graph for. True=yelp, False=TripAdvisor yelp = False ...
dupuy/ulm
ulm/urls.py
Python
bsd-3-clause
911
0
# -*- coding: utf-8 -*- """Django URLconf file for ulm""" from __future__ import unicode_literals from django.conf import settings try: # pylint: disable=E0611 from django.conf.urls import patterns, include, url except (ImportError): # Django 1.3 compatibility from django.conf.urls.defau...
comment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlp
atterns = \ patterns('', url(r'^$', laptop), url(r'^batter(?:y|ies)/$', batteries), url(r'^(?:wifi|wlan)/$', wifi), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) + static(settings.MEDIA_URL, d...
sebbASF/infrastructure-puppet
modules/mail_archives/files/scripts/site-sitemap.py
Python
apache-2.0
2,114
0.008515
#!/usr/bin/env python import os from os.path import join as pjoin import sys import subprocess def get_output(cmd): s = subprocess.Popen(cmd, stdout=subprocess.PIPE) out = s.communicate()[0] s.wait() return out.strip() # you could use os.path.walk to calculate this... or you could use du(1). def duha...
;part=%d</loc></sitemap>\n" % (HOSTNAME, name, part, i)) if count > 500: write_sitemap_footer(fp) fp.close() count = 0 fcount += 1 fp = open(BASEPATH % (fcount), 'w') write_sitemap_header(fp) wr
ite_sitemap_footer(fp)
mellanox-senior-design/docker-volume-rdma
benchmarking/book_store/bench.py
Python
apache-2.0
5,515
0.008704
import os import logging import MySQLdb import time import sys import Queue import threading import json createUserSQL = "INSERT IGNORE INTO users (name) VALUES (%s);" getUserByUsernameSQL = "SELECT * FROM users WHERE name=%s;" getAuthorByNameSQL = "SELECT * FROM authors WHERE name=%s;" createAuthorSQL = "INSERT...
nd(t) # Start all the threads for x in createBookThreads: x.start() # Wait for them to complete for x in createBookTh
reads: x.join() # Return the time it took to run logging.debug("Creating books took: "+str(time.time() - start)) return time.time() - start; def main(): logging.debug("Starting...") db = connect(); intUserTime = initilizeUsers(); intBookTime = initilizeBooks(); # cur.execute("...
artoonie/RedStatesBlueStates
redblue/viewsenators/views.py
Python
gpl-3.0
6,895
0.004206
# -*- coding: utf-8 -*- from __future__ import unicode_literals from colour import Color from django.contrib.auth.decorators import user_passes_test from django.urls import reverse from django.db.models import Sum from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse from django.shortcuts ...
text ="(unknown number)" desc = desc.replace("{{name}}", moc.firstName + " " + moc.lastName) return desc.replace("{{number}}", text) template = loader.get_template('halcyonic/index.html') if 'list' in request.GET:
clId = str(request.GET['list']) contactList = get_object_or_404(ContactList, slug=clId) else: try: contactList = ContactList.objects.get(slug='keep-children-with-their-families') except ContactList.DoesNotExist: contactList = ContactList.objects.get(title="Republ...
TAMU-CPT/galaxy-tools
tools/gff3/gff3_rebase.py
Python
gpl-3.0
4,407
0.000908
#!/usr/bin/env python import sys import logging import argparse from gff3 import feature_lambda, feature_test_qual_value from CPT_GFFParser import gffParse, gffWrite from Bio.SeqFeature import FeatureLocation log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def __get_features(child, interpro...
1 else: ns = parent.location.end - end ne = parent.location.end - start st
= -1 # Don't let start/stops be less than zero. # # Instead, we'll replace with %3 to try and keep it in the same reading # frame that it should be in. if ns < 0: ns %= 3 if ne < 0: ne %= 3 feature.location = FeatureLocation(ns, ne, strand=st) if hasattr(feature, "sub...
illicitonion/pymacaroons
pymacaroons/caveat_delegates/first_party.py
Python
mit
1,498
0
from __future__ import unicode_literals import binascii from pymacaroons import Caveat from pymacaroons.utils import ( convert_to_bytes, sign_first_party_caveat ) from .base_first_party import ( BaseFirstPartyCaveatDelegate, BaseFirstPartyCaveatVerifierDelegate ) class FirstPartyCaveatDelegate(BaseF...
aveat(encode_key, predicate) return macaroon class FirstPartyCaveatVerifierDelegate(BaseFirstPartyCaveatVerifierDelegate): def __init__(self, *args, **kwargs): super(FirstPartyCaveatVerifierDelegate, self).__init__(*args, **kwargs) def verify_first_party_caveat(self, verifier, caveat, signat...
m(callback(predicate) for callback in verifier.callbacks) return caveat_met def update_signature(self, signature, caveat): return binascii.unhexlify( sign_first_party_caveat( signature, caveat._caveat_id ) )
willsirius/DualTreeRRTStartMotionPlanning
pythonVision2/HW3_testUpdateFunction.py
Python
mit
3,774
0.023317
#!/usr/bin/env python # -*- coding: utf-8 -*- #HW3 for EECS 598 Motion Planning import time import openravepy import userdefined as us import kdtree import transformationFunction as tf from random import randrange #### YOUR IMPORTS GO HERE #### handles = []; #### END OF YOUR IMPORTS #### if not __openravepy_buil...
robot.SetActiveDOFValues([1.29023451,-2.32099996,-0.69800004,1.27843491,-2.32100002,-0.69799996]); robot.GetController().SetDesired(robot.
GetDOFValues()); waitrobot(robot) def stringToFloatList(path): path = path.split('\n') for line in xrange(len(path)): path[line] = path[line].split(',') for i in xrange(len(path[line])): path[line][i]=float(path[line][i]) return path def drawPath(path,robot,color,size): ...
jsantoso91/smartlighting
characterizeRSSI.py
Python
mit
1,721
0.012783
import sys import os import struct import binascii from time import sleep from ctypes import (CDLL, get_errno) from ctypes.util import find_library from socket import (socket, AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI, SOL_HCI, HCI_FILTER,) os.system("hciconfig hci0 down") os.system("hciconfig hci0 up") if not os.geteuid()...
sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) sock.bind((dev_id,)) err = bluez.h
ci_le_set_scan_parameters(sock.fileno(), 0, 0x10, 0x10, 0, 0, 1000); if err < 0: raise Exception("Set scan parameters failed") # occurs when scanning is still enabled from previous call # allows LE advertising events hci_filter = struct.pack( "<IQH", 0x00000010, 0x4000000000000000, 0 ) sock....
QKaiser/pynessus
pynessus/models/scanner.py
Python
apache-2.0
2,984
0.001005
""" Copyright 2014 Quentin Kaiser 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 dis...
pe = None self._status = None self._scan_count = 0 self._engine_version = None self._platform = None self._loaded_plugin_set = None self._registration_code = None self._owner = None @property def id(self): return self._id @id.setter def i...
ue) @property def uuid(self): return self._uuid @uuid.setter def uuid(self, value): self._uuid = str(value) @property def name(self): return self._name @name.setter def name(self, value): self._name = str(value) @property def type(self): ...
davinwang/caffe2
caffe2/python/workspace.py
Python
apache-2.0
19,553
0.001074
# Copyright (c) 2016-present, Facebook, 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...
Workspace.current._last_failed_op_net_position, GetNetName(net), StringifyProto(net), overwrite, ) def Predictor(init_net, predict_net): return C.Predictor(StringifyProto(init_net), StringifyProto(predict_net)) def GetOperatorCost(operator, blobs): return C.get_operator_cost(StringifyPro...
erator_once(StringifyProto(operator)) def RunOperatorsOnce(operators): for op in operators: success = RunOperatorOnce(op) if not success: return False return True def CallWithExceptionIntercept(func, op_id_fetcher, net_name, *args, **kwargs): try: return func(*args, *...
smmribeiro/intellij-community
python/testData/psi/PatternMatchingAnnotatedAssignmentLooksLikeIncompleteMatchStatement.py
Python
apache-2.0
17
0
matc
h: case =
42
CongLi/avocado-vt
setup.py
Python
gpl-2.0
3,742
0
# 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 hope that it will be useful, # bu...
TNESS FOR A PARTICULAR PURPOSE. # # See LICENSE for more details. # # Copyright: Red Hat Inc. 2013-2014 # Author: Lucas Meneghel Rodrigues <lmr@redhat.com> import
os import glob # pylint: disable=E0611 from setuptools import setup VERSION = open('VERSION', 'r').read().strip() VIRTUAL_ENV = 'VIRTUAL_ENV' in os.environ def get_dir(system_path=None, virtual_path=None): """ Retrieve VIRTUAL_ENV friendly path :param system_path: Relative system path :param virtu...
codelieche/codelieche.com
apps/article/urls/api/post.py
Python
mit
382
0.00266
# -*- coding:utf-8 -*- from django.urls import path from article.views.post import PostListApiView, PostCreateApiView, PostDetailApiView url
patterns = [ # 前缀:/api/v1/article/post/ path('create', PostCreateApiView.as_view(), name="create"),
path('list', PostListApiView.as_view(), name="list"), path('<int:pk>', PostDetailApiView.as_view(), name="detail"), ]
dirtycold/git-cola
cola/fsmonitor.py
Python
gpl-2.0
19,637
0.000662
# Copyright (c) 2008 David Aguilar # Copyright (c) 2015 Daniel Harding """Provides an filesystem monitoring for Linux (via inotify) and for Windows (via pywin32 and the ReadDirectoryChanges function)""" from __future__ import division, absolute_import, unicode_literals import errno import os import os.path import sele...
mport QtCore from qtpy.QtCore import Signal from . import core from . import gitcfg from . import gitcmds from .compat import bchr from .git import git from .i18n import N_ from .interaction import Interaction class _Monitor(QtCore.QObject): files_changed = Signal() def __init__(se
lf, thread_class): QtCore.QObject.__init__(self) self._thread_class = thread_class self._thread = None def start(self): if self._thread_class is not None: assert self._thread is None self._thread = self._thread_class(self) self._thread.start() ...
benoitsteiner/tensorflow-xsmm
tensorflow/contrib/rnn/python/kernel_tests/lstm_ops_test.py
Python
apache-2.0
21,832
0.0071
# Copyright 2016 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...
tected-access def blocks_match(sess, use_peephole): batch_size = 2 input_size = 3 cell_size = 4 sequence_length = 4 inputs = [] for _ in range(sequence_length): inp = ops.convert_to_tensor( np.random.randn(batch_size, input_size), dtype=dtypes.float32) inputs.append(inp) stacked_inputs ...
array_ops.stack(inputs) initializer = init_ops.random_uniform_initializer(-0.01, 0.01, seed=19890212) with variable_scope.variable_scope("test", initializer=initializer): # magic naming so that the cells pick up these variables and reuse them if use_peephole: wci = variable_scope.get_variable( ...
emCOMP/twinkle
twinkle/feature_extraction/pipelines.py
Python
mit
2,688
0.034226
#!/usr/bin/env python # -*- coding: utf-8 -*- from core import FeatureExtractorRegistry from twinkle.connectors.core import ConnectorRegistry class FeatureExtractorPipelineFactory(object): """ Factory object for creating a pipeline from a file """ def __init__(self): """ """ pass def buildInput(self,...
ure extractors extractors = config_data["extractors"] # add each extractor for extractor_config in extractors: extractor = self.buildExtractor(extractor_config) pipeline.addExtractor(extractor) return pipeline class FeatureExtractorPipeline(object): """ Simple feature extractor pipeline. Needs...
d. """ def __init__(self, input, output): self.feature_extractors = [] self.input = input self.output = output def addExtractor(self, extractor): """ add Extractor to the pipeline """ self.feature_extractors.append(extractor) def run(self): """ runs the pipeline """ processed_items = [...
flipagram/elasticity
setup.py
Python
mit
752
0.00133
from setuptools import setup setup( # general meta name='elasticity', version='0.7', author='Brian C. Dilley - Flipagram', author_email='brian@flipagram.com', description='Python based command line tool for managing ElasticSearch clusters.', platforms='any', url='https://github.com/Che...
_package_data=True, # the scripts scripts=['scripts/elasticity'], # wut? classifiers=['Intended Audience :: Developers'
] )
ahmadiga/min_edx
common/lib/xmodule/xmodule/crowdsource_hinter.py
Python
agpl-3.0
17,456
0.00338
""" Adds crowdsourced hinting functionality to lon-capa numerical response problems. Currently experimental - not for instructor use, yet. """ import logging import json import random import copy from pkg_resources import resource_string from lxml import etree from xmodule.x_module import XModule, STUDENT_VIEW fro...
for the crowdsource hinter module.""" has_children = True moderate = String(help='String "True"/"False" - activates moderation', scope=Scope.content, default='False') debug = String(help='String "True"/"False" - allows multiple voting', scope=Scope.content, default=...
ys. # Each value is itself a dictionary, accepting hint_pk strings as keys, # and returning [hint text, #votes] pairs as values hints = Dict(help='A dictionary containing all the active hints.', scope=Scope.content, default={}) mod_queue = Dict(help='A dictionary containing hints still awaiting approval...
csdms/wmt-exe
wmtexe/cmi/make.py
Python
mit
673
0
from __future__ import print_function import argparse import yaml from .bocca import make_project, ProjectExistsError def main(): parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help
='Project description file') parser.add_argument('--clobber', action='store_true', help='Clobber an existing project') args = parser.parse_args() try: make_project(yaml.load(arg
s.file), clobber=args.clobber) except ProjectExistsError as error: print('The specified project (%s) already exists. Exiting.' % error) if __name__ == '__main__': main()
qk4l/Flexget
flexget/api/plugins/tvmaze_lookup.py
Python
mit
6,102
0.001475
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from flask import jsonify from flask_restplus import inputs from flexget.api import api, APIResource from flexget.api.app import NotFoundError, BadRequest, etag from flexg...
_id, session=sess
ion) else: series = tvm.series_lookup(series_name=title, session=session) except LookupError as e: raise NotFoundError(e.args[0]) return jsonify(series.to_dict()) episode_parser = api.parser() episode_parser.add_argument('season_num', type=int, help='Season numb...
BBN-Q/Qlab
common/@PulseCalibration/PhaseEstimationSequence.py
Python
apache-2.0
1,148
0.004355
import argparse import sys, os import numpy as np from copy import copy parser = argparse.ArgumentParser() parser.add_argument('qubit', help='qubit name') parser.add_argument('direction', help='direction (X or Y)') parser.add_argument('numPulses', type=int, help='log2(n) of the longest sequence n') parser.add_argument(...
tude', type=float, help='pulse amplitude') args = parser.parse_args() from QGL import * q = QubitFactory(args.qubit) if args.direction == 'X': pPulse = Xtheta(q, amp=args.amplitude) mPulse = X90m(q) else: pPulse = Ytheta(q, amp=args.amplitude) mPulse = Y90m(q) # Exponentially growing repetitions of ...
for m in [ [MEAS(q)], [mPulse, MEAS(q)] ]] # tack on calibrations to the beginning seqs = [[Id(q), MEAS(q)], [X(q), MEAS(q)]] + seqs # repeat each repeated_seqs = [copy(s) for s in seqs for _ in range(2)] fileNames = compile_to_hardware(repeated_seqs, fileName='RepeatCal/RepeatCal') # plot_pulse_files(fileNames)
dhamaniasad/magnetor
magnetor.py
Python
unlicense
1,885
0.002122
import requests import urllib2 import argparse from bs4 import BeautifulSoup def get_best_torrent(query): query = urllib2.quote(query) r = requests.get('http://kat.cr/usearch/{}/'.format(query)) soup = BeautifulSoup(r.content) torrents = soup.find('table', class_='data').find_all(has_class_odd_or_even...
ne_runner(): parser = argpars
e.ArgumentParser(description='Get magnet links for torrents from the CLI') parser.add_argument('name', type=str, nargs='*', help='Name of the torrent you are looking for') args = parser.parse_args() if not args.name: parser.print_help() else: get_best_torrent(' '.join(args.name)) if __...
joshk105/daw-translator
hindenburg.py
Python
mit
5,531
0.004701
from xml.dom import minidom from object_classes import * from helpers import timeToSeconds class HindenburgInt(object): def __init__(self, project_file, version="Hindenburg Journalist 1.26.1936", version_num="1.26.1936"): self.projectFile = project_file self.version = version self.version...
de.getAttribute('Gain')) except: endValue = 0 autoEnv.addPoint(startTime, startValue) autoEnv.addPoint(endTime, endValue) plugins = track.getElementsByTagName("Plugin") for plugin in plugins:...
pluginType = "Plugin" new_plugin = current_track.addFX(plugin.getAttribute('Name'), pluginType, int(plugin.getAttribute('Id'))) if pluginType == "Native": if plugin.getAttribute('Name') == 'Compressor': new_plugin.addProperty('UID',...
yejingxin/kaggle-ndsb
configurations/featharalick_sharding_blend_pl_blend4_convroll4_doublescale_fs5_no_dropout_33_66.py
Python
mit
2,560
0.007813
import numpy as np import theano import theano.tensor as T import lasagne as nn import data import load import nn_plankton import dihedral import tmp_dnn import tta features = [ # "hu", # "tutorial", "haralick", # "aaronmoments", # "lbp", # "pftas", # "zernike_moments", # "image_siz...
ithFeaturesDataLoader( features = features, train_pred_file=train_pred_file, valid_pred_file=valid_pred_file, test_pred_file=test_pred_file, num_chunks_train=num_chunks_train, chunk_size=chunk_size) create_train_gen = lambda: data_loader.create_random_gen() create_eval_train_gen = lambda: da...
(): l0 = nn.layers.InputLayer((batch_size, data.num_classes)) l0_size = nn.layers.InputLayer((batch_size, 52)) l1_size = nn.layers.DenseLayer(l0_size, num_units=80, W=nn_plankton.Orthogonal('relu'), b=nn.init.Constant(0.1)) l2_size = nn.layers.DenseLayer(l1_size, num_units=80, W=nn_plankton.Orthogonal(...
nwjs/chromium.src
third_party/blink/tools/blinkpy/web_tests/stale_expectation_removal/queries.py
Python
bsd-3-clause
7,303
0.000685
# 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. """Web test-specific impl of the unexpected passes' queries module.""" import os import posixpath from blinkpy.web_tests.stale_expectation_removal import co...
er", @builder_name) IN UNNEST(variant) ORDER BY partition_time DESC LIMIT 50 ), results AS ( SELECT exported.id, test_id, ARRAY( SELECT value FROM tr.tags WHERE key = "raw_typ_expectation") as typ_expectations FROM `chrome-luci-data.chromium.blink_web
_tests_{builder_type}_test_results` tr, builds b WHERE exported.id = build_inv_id AND status != "SKIP" ) SELECT DISTINCT r.test_id FROM results r WHERE "Failure" IN UNNEST(typ_expectations) OR "Crash" IN UNNEST(typ_expectations) OR "Timeout" IN UNNEST(typ_expectations) """ ACTIVE_BUILDER_...
airbnb/streamalert
streamalert/scheduled_queries/main.py
Python
apache-2.0
760
0
""" Copyright 2017-present, Airbnb 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, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expres...
t for AWS Lambda. """ from streamalert.scheduled_queries.command.application import ScheduledQueries def handler(event, _): return ScheduledQueries().run(event)
e-mission/e-mission-server
emission/core/wrapper/filter_modules.py
Python
bsd-3-clause
7,166
0.016467
""" Query modules mapping functions to their query strings structured: module_name { query_string: function_for_query } """ from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division # Standard imports from future import standar...
rip_start_datetime':{"$gt":d}, "pipelineFlags":{"$exists":True}} #query = {'user_id':uid, '
type':'move','trip_start_datetime':{"$gt":d}} #print get_trip_db().count_documents(query) return get_trip_db().find(query) def getAlternativeTrips(trip_id): #TODO: clean up datetime, and queries here #d = datetime.datetime.now() - datetime.timedelta(days=6) #query = {'trip_id':trip_id, 'trip_start_...
fritzfrancisco/flumeview
FlumeView1.2.py
Python
apache-2.0
5,412
0.035292
import argparse import datetime import imutils import numpy as np import time import csv import cv2 import os.path #define variable click_frame = False divide_x = 0 divide_y = 0 channel_A = 0 channel_B = 0 area_A = 0 area_B = 0 #division fuction (divide_frame) def divide_frame(event,x,y,flags,param): global click_fr...
t(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) text = "Occupied" fish_x = x+w/2 fish_y = y+h/2 if fish_x < divide_x and fish_y < divide_y: channel_A += 1 if fish_x > divide_x and fish_y < divide_y: area_A += 1 if fish_x < divide_x and fish_y > divide_y: channel_B += 1 if fi...
mat(fps)+" fps",(25,25),cv2.FONT_HERSHEY_SIMPLEX,0.5,255) cv2.putText(frame,"{0:.2f}".format(channel_A/fps),(divide_x-width/4,divide_y-height/4),cv2.FONT_HERSHEY_SIMPLEX,fontsize,(255,255,255),thickness) cv2.putText(frame,"{0:.2f}".format(channel_B/fps),(divide_x-width/4,divide_y+height/4),cv2.FONT_HERSHEY_SIMPLEX,...
weblabdeusto/weblabdeusto
server/src/experiments/vm/user_manager/manager.py
Python
bsd-2-clause
2,115
0.008511
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2005 onwards University of Deusto # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # # This software consists of contributions made by many individual...
es> # class ConfigureError(Exception): """ Configure error of any kind. """ pass class PermanentConfigureError(ConfigureError): """ Configure error that would most likely occur again should we retry """ def __str__(self): return "PermanentConfigureError()"
class TemporaryConfigureError(ConfigureError): """ Configure error that is likely to not be permanent. Server will retry whenever this is received. """ def __str__(self): return "TemporaryConfigureError()" class UserManager(object): def __init__(self, cfg_manager): """ ...
davidhrbac/spacewalk
client/rhel/rhn-client-tools/src/up2date_client/rhnserver.py
Python
gpl-2.0
8,608
0.001859
# rhn-client-tools # # Copyright (c) 2006--2012 Red Hat, Inc. # # 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 2 of the License. # # This program is distributed in the hope t...
lf._method_name)
try: return rpcServer.doCall(method, *args, **kwargs) except xmlrpclib.Fault: raise (self.__exception_from_fault(sys.exc_info()[1]), None, sys.exc_info()[2]) except OpenSSL.SSL.Error: # TODO This should probably be moved to rhnlib and raise an # e...
jtauber/sgf
setup.py
Python
mit
552
0
from setuptools import setup setup( name="sgf", version="0.5", description="Python library for reading and writing Smart Game Format", license="MIT", url="http://github.com/jtauber/sgf", author="Jam
es Tauber", author_email="jtauber@jtauber.com", py_modules=["sgf"], classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Topic :: Game
s/Entertainment :: Board Games", "Topic :: Utilities", ], )
ruibarreira/linuxtrail
usr/lib/virtualbox/vboxshell.py
Python
gpl-3.0
120,819
0.00591
#! /usr/bin/python # -*- coding: utf-8 -*- # $Id: vboxshell.py $ """ VirtualBox Python Shell. This program is a simple interactive shell for VirtualBox. You can query information and issue comma
nds from a simple command line. It also provides you with examples on how to use VirtualBox's Python API. This shell is even somewhat documented, supports TAB-completion and history if you have Python readline installed. Finally, shell allows arbitrary custom extensions, just create .VirtualBox/shexts/ and drop your ...
re. Enjoy. P.S. Our apologies for the code quality. """ __copyright__ = \ """ Copyright (C) 2009-2013 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistrib...
great-expectations/great_expectations
tests/build_index_page.py
Python
apache-2.0
628
0
import glob json_files = glob.glob("tests/**/output/**/*.json", recursive=True) html_files = glob.glob("tests/**/output/**/*.html", recursive=True) html_list = "" for f_ in html_files: html_list += '\t<li><a href="{}">{}</li>
\n'.format( f_[6:], f_.split(".")[-2], ) json_list = "" for f_ in json_files: json_list += '\t<li><a href="{}">{}</li>\n'.format( f_[6:], f_.split(".")[-2], ) html_file = """ <html> <body> <h3>HTML</h3> <ul> {} </ul>
<br/><br/> <h3>JSON</h3> <ul> {} </ul> </body> </html> """.format( html_list, json_list ) print(html_file)
shriyanka/daemo-forum
spirit/comment/serializers.py
Python
mit
715
0.051748
from models import Comment from ..user.serializers import UserProfileSerializer from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField() class Meta: model = Comment fields = ("id","user","username", "topic","comment","comment_html"...
ly_fi
elds = ("user","comment_html","action","date","is_removed","is_modified","modified_count","likes_count") def get_username(self,obj): return obj.user.username def create(self,**kwargs): comment = Comment.objects.create(user = kwargs['user'],**self.validated_data) return comment
blueman-project/blueman
test/main/test_imports.py
Python
gpl-3.0
1,075
0.002791
import os.path import pkgutil from unittest import TestCase, TestSuite class TestImports(TestCase): def __init__(self, mod_name, import_error): name = f"test_{mod_name.replace('.', '_')}_import" def run(): try: __import__(mod_name) except ImportError as e: ...
bindings not found.", "blueman.main.PulseAudioUtils": "Could not load pulseaudio shared library", } test_cases = TestSuite() home, subpath = os.path.dirname(__file__).rsplit("/test/", 1) for package in pkgutil.iter_modules([f"{home}/
blueman/{subpath}"], f"blueman.{subpath.replace('/', '.')}."): test_cases.addTest(TestImports(package.name, expected_exceptions.get(package.name))) assert test_cases.countTestCases() > 0 return test_cases
F5Networks/f5-common-python
f5/bigiq/cm/device/licensing/__init__.py
Python
apache-2.0
1,033
0
# coding=utf-8 # # Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
ed 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. # """ REST URI ``http://localhost/mgmt/cm/device/licensi
ng/pool/regkey`` REST Kind N/A -- HTTP GET returns an error """ from f5.bigiq.cm.device.licensing.pool import Pool from f5.bigiq.resource import OrganizingCollection class Licensing(OrganizingCollection): def __init__(self, device): super(Licensing, self).__init__(device) self._meta_data['al...
unho/translate
translate/convert/flatxml2po.py
Python
gpl-2.0
3,817
0.000262
# -*- coding: utf-8 -*- # # Copyright 2018 BhaaL # # This file is part of translate. # # translate 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 lat...
root_name=root, value_name=value, key_name=key, namespace=ns) self.target_store = self.TargetStoreClass() def convert_unit(self,...
ef convert_store(self): """Convert a single source file to a target format file.""" for source_unit in self.source_store.units: self.target_store.addunit(self.convert_unit(source_unit)) def run(self): """Run the converter.""" self.convert_store() if self.target_...
zenn1989/scoria-interlude
L2Jscoria-Game/data/scripts/quests/345_MethodToRaiseTheDead/__init__.py
Python
gpl-3.0
5,090
0.0389
# Made by mtrix import sys from com.l2scoria.gameserver.model.quest import State from com.l2scoria.gameserver.model.quest import QuestState from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest qn = "345_MethodToRaiseTheDead" ADENA = 57 VICTIMS_ARM_BONE = 4274 VICTIMS_THIGH_BONE = 4275 VICTIMS_...
def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr) def onEvent (self,event,st) : htmltext = event if event == "1" : st.set("cond","1") st.setState(STARTED) htmltext = "
30970-02.htm" st.playSound("ItemSound.quest_accept") elif event == "2" : st.set("cond","2") htmltext = "30970-06.htm" elif event == "3" : if st.getQuestItemsCount(ADENA)>=1000 : st.takeItems(ADENA,1000) st.giveItems(POWDER_TO_SUMMON_DEAD_SOULS,1) ...
City-of-Bloomington/green-rental
listing/models.py
Python
agpl-3.0
2,921
0.015063
from django.db import models from django.contrib.auth.models import User from building.models import Building, Unit # Create your models here. class Listing(models.Model): """ An option to lease, rent, or sublease a specific Unit """ CYCLE_CHOICES = ( ('year', 'Year'), ('month', 'Mo...
rson = models.ForeignKey(Person)
#might be better to just use a User account #this should be required (setting blank and null to assist with migrations) user = models.ForeignKey(User, blank=True, null=True) #even though the building is available by way of the Unit #it may be easier to look at building #especially when limiting se...
rabernat/satdatatools
satdatatools/aggregator.py
Python
mit
1,349
0.005189
import numpy as np from scipy.io import netcdf_file import bz2 import os from fnmatch import fnmatch from numba import jit @jit def binsum2D(data, i, j, Nx, Ny): data_binned = np.zeros((Ny,Nx), dtype=data.dtype) N = len(data) for n in range(N): data_binned[j[n],i[n]] += data[n] return data_binn...
nlim=(-180,180), latlim=(-90,90)): self.dlon = dlon self.dlat = dlat self.lonmin = lonlim[0] self.lonmax = lonlim[1] self.latmin = latlim[0] self.latmax = latlim[1] # define grids self.lon = np.arange(self.lonmin, self.lonmax, dlon) self.lat = np.a...
max, dlat) self.Nx, self.Ny = len(self.lon), len(self.lat) self.lonc = self.lon + self.dlon/2 self.latc = self.lat + self.dlat/2 def binsum(self, data, lon, lat): """Bin the data into the lat-lon grid. Returns gridded dataset.""" i = np.digitize(lon.ravel(), self...
bryanperris/winN64dev
mips64-elf/mips64-elf/lib/el/libstdc++.a-gdb.py
Python
gpl-2.0
2,328
0.006873
# -*- python -*- # Copyright (C) 2009-2013 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later versio...
we don't # update sys.path; instead we just hope the user managed to do that # beforehand. if gdb.current_objfile () is not
None: # Update module path. We want to find the relative path from libdir # to pythondir, and then we want to apply that relative path to the # directory holding the objfile with which this file is associated. # This preserves relocatability of the gcc tree. # Do a simple normalization that remove...
ENCODE-DCC/encoded
src/encoded/tests/test_upgrade_atac_alignment_enrichment_quality_metric.py
Python
mit
467
0.002141
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2( upgrader, atac_alignment_enrichment_quality_metric_1 ): value = upgrader.upgrade( 'atac_alignment_enrichment_quali
ty_metric', atac_alignment_enrichment_quality_metric_1, current_version='1', target_version='2', ) assert value['schema_version'] =
= '2' assert 'fri_blacklist' not in value assert value['fri_exclusion_list'] == 0.0013046877081284722
epitron/youtube-dl
youtube_dl/extractor/pornovoisines.py
Python
unlicense
4,003
0.002001
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( int_or_none, float_or_none, unified_strdate, ) class PornoVoisinesIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?pornovoisines\.com/videos/show/(?P<id>\d+)/(?P<display_id>[...
average_rating = self._search_regex( r'Note\s*:\s*(\d+(?:,\d+)?)', webpage, 'average rating', fatal=False) if average_rating: average_rating = float_or_none(average_rating.replace(',', '.')) categories = self._html_search_regex( r'(?s)Catégories\s*:\s*<b>(.+?)</b>'...
ry in categories.split(',')] subtitles = {'fr': [{ 'url': subtitle, } for subtitle in settings.get('main', {}).get('vtt_tracks', {}).values()]} return { 'id': video_id, 'display_id': display_id, 'formats': formats, 'title': title, ...
Eficent/purchase-workflow
procurement_purchase_no_grouping/models/purchase_order.py
Python
agpl-3.0
1,521
0
# -*- coding: utf-8 -*- # Copyright 2015 AvanzOsc (http://www.avanzosc.es) # Copyright 2015-2016 - Pedro M. Baeza <pedro.baeza@tecnativa.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) from odoo import api, models class PurchaseOrder(models.Model): _inherit = 'purchase.order' @api.model ...
'dest_address_id', } # Restrict the empty return for these conditions if (self.env.cont
ext and self.env.context.get('grouping', 'standard') == 'order' and make_po_conditions.issubset(set(x[0] for x in args))): return self.browse() return super(PurchaseOrder, self).search( args, offset=offset, limit=limit, order=order, count=count) class Pu...
dbrattli/OSlash
oslash/typing/applicative.py
Python
apache-2.0
1,869
0.00214
from abc import abstractmethod from typing import Callable, TypeVar, Protocol from typing_extensions import runtime_checkable TSource = TypeVar('TSource') TResult = TypeVar('TResult') @runtime_checkable class Applicative(Protocol[TSource, TResult]): """Applicative. Applicative functors are functors with so...
ed up fmap. It takes a functor value that has a function in it and another functor, and extracts that function from the first functor an
d then maps it over the second one. """ raise NotImplementedError #def __mul__(self, something): # """(<*>) :: f (a -> b) -> f a -> f b. # Provide the * as an infix version of apply() since we cannot # represent the Haskell's <*> operator in Python. # """ # ...
python-acoustics/python-acoustics
acoustics/standards/iso_1996_2_2007.py
Python
bsd-3-clause
25,331
0.003948
""" ISO 1996-2:2007 ISO 1996-2:2007 describes how sound pressure levels can be determined by direct measurement, by extrapolation of measurement results by means of calculation, or exclusively by calculation, intended as a basis for assessing environmental noise. """ import numpy as np import pandas as pd from scipy....
evels as function of frequency. :type levels: :class:`pd.Series`. :param lines_classifier: Categorical indicating what each line is. :param center: Center frequency. :param bandwidth: bandwidth of critical band. :param regression_range_factor: Range factor. :returns: (Array with masking noise li
nes, slope, intercept). """ slicer = slice(center - bandwidth * regression_range_factor, center + bandwidth * regression_range_factor) levels = levels[slicer] frequencies = levels.index regression_levels = levels[line_classifier == 'noise'] slope, intercept = linregress(x=regression_levels.index...
Abhinav117/pymtl
pymtl/tools/translation/visitors.py
Python
bsd-3-clause
29,868
0.028994
#========================================================================= # visitors.py #========================================================================= from __future__ import print_function import ast, _ast import re import warnings from ..ast_helpers import get_closure_dict, print_simple_ast fro...
', 'v']: raise Exception('Unknown attribute "{}" in model "{}"' .format( node.attr, self.model.__class__ )) node._object = self.current_obj.inst if self.current_obj else None return node def visit_Name( self, node ): # Check if the name is a global constant if ...
obj = PyObj( '', self.func.func_globals[ node.id ] ) # If the name is not in closed_vars or func_globals, it's a local temporary elif node.id not in self.closed_vars: new_obj = None # If the name points to the model, this is a reference to self (or s) elif self.closed_vars[ node.id ] is self.m...
RuthAngus/chronometer
chronometer/test_MH.py
Python
mit
1,566
0.000639
""" Test the metropolis hastings algorithm. """ import numpy as np import chronometer as gc import matplotlib.pyplot as plt import corner import emcee def model(par, x): return par[0] + par[1]*x def lnlike(par, x, y, yerr, par_inds): y_mod = model(par, x) return sum(-.5*((y_mod - y)/yerr)**2) def tes...
es_like(x) * err y = .7 + 2.5*x + np.random.randn(len(x))*err # Plot the data. plt.clf() plt.errorbar(x, y,
yerr=yerr, fmt="k.") plt.savefig("data") print("Running Metropolis Hastings") N = 1000000 # N samples pars = np.array([.5, 2.5]) # initialisation t = np.array([.01, .01]) par_inds = np.arange(len(pars)) args = [x, y, yerr, par_inds] samples, par, probs = gc.MH(pars, lnlike, N, t, *arg...
sveetch/boussole
tests/002_finder/005_relativefrompaths.py
Python
mit
2,097
0
# -*- coding: utf-8 -*- import pytest from boussole.exceptions import FinderException def test_001(finder): results = finder.get_relative_from_paths("/home/foo/plop", [ "/home/foo", "/home/bar", "/etc", ]) assert results == "plop" def test_002(finder): results = finder.get_...
lip" def test_003(finder): results = finder.get_relative_from_paths("/home/foo/plop", [ "/home", "/home/fo
o", "/etc", ]) assert results == "plop" def test_004(finder): results = finder.get_relative_from_paths("/home/foo/plop", [ "/home", "/home/foo", "/home/bar", "/etc/ping", ]) assert results == "plop" def test_005(finder): results = finder.get_relative...
huggingface/transformers
utils/check_repo.py
Python
apache-2.0
30,085
0.002393
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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...
"VisualBertForVisualReasoning", "VisualBertForQuestionAnswering", "VisualBertForMultipleChoice", "TFWav2Vec2ForCTC", "TFHubertForCTC", "MaskFormerForInstanceSegmentation", ] # Update this list for models that have multiple model types for the same # model doc MODEL_TYPE_TO_DOC_MAPPING = OrderedD...
ct( [ ("data2vec-text", "data2vec"), ("data2vec-audio", "data2vec"), ] ) # This is to make sure the transformers module imported is the one in the repo. spec = importlib.util.spec_from_file_location( "transformers", os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), submodule_searc...
ishandongol/voli-fix-vetnae
videocalling/views.py
Python
mit
150
0.013333
f
rom django.http import HttpResponse from django.shortcuts import render def video_calling(request): return render(request,'video_calling.
html')
elimence/edx-platform
lms/djangoapps/simplewiki/views.py
Python
agpl-3.0
21,289
0.003852
# -*- coding: utf-8 -*- from django.conf import settings as settings from django.contrib.auth.decorators import login_required from django.core.context_processors import csrf from django.core.urlresolvers import reverse from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect, Http404 f...
f = EditForm(request.POST) if f.is_valid(): new_revision = f.save(commit=False) new_revision.article = article if reque
st.POST.__contains__('delete'): if (article.current_revision.deleted == 1): # This article has already been deleted. Redirect return HttpResponseRedirect(wiki_reverse('wiki_view', article, course)) new_revision.contents = "" new_revision.deleted = 1 ...
odejesush/tensorflow
tensorflow/tools/docs/parser_test.py
Python
apache-2.0
12,002
0.003
# Copyright 2015 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...
Module.test_function_with_args_kwargs': test_function_with_args_kwargs, 'TestModule.TestClass': TestClass, } tree = { 'TestModule': ['TestClass', 'test_function', 'test_function_with_args_kwargs'] } docs = parser.generate_markdown(full_name='TestModule', ...
tree=tree, base_dir='/') # Make sure all required docstrings are present. self.assertTrue(inspect.getdoc(module) in docs) # Make sure that links to the members are there (not asserting on exact link # text for functions). self.assertTrue('./TestModule/test_function.md' in docs) self.assertTru...