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
jlhg/bdorpy
bdorpy/idfix.py
Python
mit
912
0.004386
#!/usr/bin/env python3 # # idfix.py # # Copyright (C) 2013, Jian-Long Huang # Licensed under The MIT License # http://opensource.org/licenses/MIT # # Author: Jian-Long Huang (jianlong@ntu.edu.tw) # Version: 0.1 # Created: 2013.1.7 # # Usage: idfix.py <idmap> <fasta> <output> import sys def
main(): with open(sys.argv[1], 'r') as fin, open(sys.argv[2], 'r') as ffa, open(
sys.argv[3], 'w') as fo: full_id = {} for line in ffa: if line[0] != '>': continue full_id.update({line.split()[0].split('|')[-2]: line.split()[0].split('>')[1]}) for line in fin: if line.split('\t')[1].rstrip() in full_id: fo...
pyrocko/pyrocko
test/base/test_response_plot.py
Python
gpl-3.0
2,397
0
from __future__ import absolute_import import unittest import tempfile import shutil import os import numpy as num from matplotlib import image, pyplot as plt from pyrocko import util from pyrocko.plot import response from .. import common noshow = True class ResponsePlotTestCase(unittest.TestCase): def setUp...
(fn) except util.DownloadError: return common.test_data_file_no_download(fn) def compare_with_ref(self, fname, tolerance, show=False): fpath = self.fpath(fname) fpath_ref = self.fpath_ref(fname) if not os.path.exists(fpath_ref): shutil.copy(fpath, fpath_ref)...
g_ref = image.imread(fpath_ref) self.assertEqual(img.shape, img_ref.shape) d = num.abs(img - img_ref) merr = num.mean(d) if (merr > tolerance or show) and not noshow: fig = plt.figure() axes1 = fig.add_subplot(1, 3, 1, aspect=1.) axes2 = fig.add_subplo...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/Crypto/SelfTest/Cipher/common.py
Python
gpl-3.0
65
0.015385
../../../../.
./../share/pyshared/Crypto/SelfTest/Ci
pher/common.py
MauHernandez/cyclope
cyclope/apps/medialibrary/admin.py
Python
gpl-3.0
6,248
0.001761
#!/usr/bin/env
python # -*- coding: utf-8 -*- # # Copyright 2010-2013 Código Sur Sociedad Civil. # All rights reserved. # # This file is part of Cyclope. # # Cyclope 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 ve...
d in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, ...
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/PyQt4/QtGui/__init__/QGradient.py
Python
gpl-2.0
2,965
0.009106
# encoding: utf-8 # module PyQt4.QtGui # from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so # by generator 1.135 # no doc # i
mports import PyQt4.QtCore as __PyQt4_QtCore class QGradient(): # skipped bases: <type 'sip.simplewrapper'> """ QGradient() QGradient(QGradient) """ def coordinateMode(self): # real si
gnature unknown; restored from __doc__ """ QGradient.coordinateMode() -> QGradient.CoordinateMode """ pass def setColorAt(self, p_float, QColor): # real signature unknown; restored from __doc__ """ QGradient.setColorAt(float, QColor) """ pass def setCoordinateMode(self, QGradie...
mzmmoazam/DrawBot
nlu.py
Python
apache-2.0
2,221
0.010806
import json import apiai CLIENT_ACCESS_TOKEN = 'api key' def nlu(mytext): ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN) request = ai.text_request() request.lang = 'en' # optional, default value equal 'en' # request.session_id = "<SESSION ID, UBIQUE FOR EACH USER>" request.query = myte...
int(json_obj['result']['actionIncomplete']) # print(json_obj['result']['parameters']) if json_obj['result']['metadata']['intentName'] != 'x direction y by z units': return json.dumps({"action":json_obj['result']['action'],"message":json_obj['result']['fulfillment']['speech'],'two_figures':False}) ...
del di[i] # di["two_figures"]=True result={} result['by'] = di['number'][0] del di['number'] # {'number': [10], 'triangle': 'Triangle', 'rect_direction': 'down'} for i in ['rect_direction','circle_direction','triangle_direction','rhombus_direction','hexagon_...
kevin-brown/drf-nested-viewsets
rest_nested_viewsets/routers.py
Python
mit
1,254
0
from rest_framework import routers class NestedRouter(routers.DefaultRouter): """ Custom router which hides nested URLs as they cannot be reversed. """ def get_api_root_view(self): """ Return a view to use as the API root. Ignores any URLs which do not reverse correctly. ...
rmat)
except NoReverseMatch: pass return Response(ret) return APIRoot.as_view()
SergeySatskiy/codimension
codimension/ui/parsererrors.py
Python
gpl-3.0
3,321
0
# -*- coding: utf-8 -*- # # codimension - graphics python two-way code editor and analyzer # Copyright (C) 2010-2017 Sergey Satskiy <sergey.satskiy@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softw...
reates the dialog layout""" self.resize
(600, 220) self.setSizeGripEnabled(True) verticalLayout = QVBoxLayout(self) # Info label infoLabel = FitLabel(self) sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) s...
fbacchella/ovirtcmd
samples/single_node_cluster.py
Python
apache-2.0
3,574
0.005316
import ovlib from ovlib.eventslib import event_waiter, EventsCode mac_pool = context.macpools.get("Default") try: dc = context.datacenters.get(host_name) except ovlib.OVLibErrorNotFound: dc = context.datacenters.add(data_center={'name': host_name, 'local': True, 'storage_format': 'V4', 'mac_pool': mac_pool}) ...
t o
vlib.OVLibErrorNotFound: events_returned = [] waiting_events = [EventsCode.VDS_DETECTED] with event_waiter(context, "host.name=%s" % host_name, events_returned, verbose=True, break_on=waiting_events): host = context.hosts.add(host={ 'name': host_name, 'address': host_name, 'c...
MOA-2011/enigma2-plugin-extensions-openwebif
plugin/controllers/views/mobile/movies.py
Python
gpl-2.0
8,464
0.014532
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
class movies(Template): ################################################## ## CHEETAH GENERATED METHODS def __init__(self, *args, **KWs): super(movies, self).__init__(*args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchL...
plit() for k,v in KWs.items(): if k in allowedKWs: cheetahKWArgs[k] = v self._initCheetahInstance(**cheetahKWArgs) def respond(self, trans=None): ## CHEETAH: main method generated for this template if (not trans and not self._CHEETAH__isBuffering ...
kornai/4lang
src/fourlang/lemmatizer.py
Python
mit
5,587
0.000716
import logging import os import sys from nltk.corpus import stopwords as nltk_stopwords from hunmisc.utils.huntool_wrapper import Hundisambig, Ocamorph, OcamorphAnalyzer, MorphAnalyzer # nopep8 from stemming.porter2 import stem as porter_stem from utils import get_cfg class Lemmatizer(): def __init__(self, cfg...
se
lf.cache[word] = (stem, lemma, candidates) def _lemmatize_with_stopwords(self, word, uppercase): if word == 'have': return 'HAS' elif not uppercase: return word elif word in self.stopwords: return word.upper() else: return word de...
uclouvain/OSIS-Louvain
learning_unit/views/learning_unit_class/tutor_repartition.py
Python
agpl-3.0
6,168
0.001459
############################################################################## # # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core ...
ponse() return render(request, self.template_name, { "form": form, }) def get_success_ur
l(self): return self.common_url_tabs()['url_class_tutors'] def get_success_msg(self) -> str: return _("Repartition added for %(tutor)s (%(function)s)") % { 'tutor': self.tutor.full_name, 'function': self.tutor.function_text } class TutorRepartitionRemoveView(TutorR...
matiboy/generator-django
app/templates/tasks/local/pip.py
Python
mit
1,694
0.015348
import fabric.api import fabric.tasks import fabric.colors import os class PipFreeze(fabric.tasks.Task): name = 'pip_freeze' def run(self, commit=True): fabric.api.local("pip freeze > requirements.txt") if commit: fabric.api.local("git add requirements.txt") with fabric.api.settings(warn_only=T...
it -m "New requirements"') class PipFreezeAlias(PipFreeze): name = 'lpf' class PipInstall(fabric.tasks.Task): name = 'pip_install' def run(self, package, environment=Non
e): if environment is None: environment = 'common' else: environment = environment.replace('save-', '') if environment == 'dev': environment = 'development' valid_envs = ('development', 'production', 'common', 'testing',) if environment not in valid_envs: print(fabr...
scream7/leetcode
algorithms/python/125.py
Python
apache-2.0
534
0
class Solution(object): def isPalindrome(self, s): """ :type
s: str :rtype: bool """ i = 0 j = len(s) - 1 while i <= j: if not (s[i].isalpha() or s[i].isdigit()): i += 1 elif not (s[j].isalpha() or s[j].isdigit()): j -= 1 else: if s[i].lower() != s[j].lowe...
e
openstack/watcher
watcher/tests/decision_engine/strategy/strategies/test_saving_energy.py
Python
apache-2.0
8,589
0
# -*- encoding: utf-8 -*- # Copyright (c) 2017 ZTE # # 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 agre...
k_node1 = mock.Mock(**mock_node1_dict) mock_node2 = mock.Mock(**mock_node2_dict) self.m_ironic.node.get.side_effect = [mock_node1, mock_node2] mock_hyper1 = mock.Mock() mock_hyper2 = mock.Mock() mock_hyper1.to_dict.return_value = { 'running_vms': 0, 'service': {'host...
stname_0'}, 'state': 'up'} mock_hyper2.to_dict.return_value = { 'running_vms': 0, 'service': {'host': 'hostname_1'}, 'state': 'up'} self.m_nova.hypervisors.get.side_effect = [mock_hyper1, mock_hyper2] self.strategy.get_hosts_pool() self.assertEqual(len(self.strategy.with_vm...
devassistant/dapp
test/communicator_test_case.py
Python
gpl-2.0
3,911
0.005369
import copy import pytest from dapp import protocol_version, DAPPBadMsgType, DAPPTimeOut class CommunicatorTestCase(object): pv = 'dapp_protocol_version: {0}'.format(protocol_version).encode('utf8') # a general confirmation message msg_received_lines = [b'START', b'msg_type: msg_received', pv, b'STOP'] ...
self.c.
recv_msg(timeout=1)
cnamejj/PyProc
regentest/self_status.py
Python
gpl-2.0
4,347
0.002761
#!/usr/bin/env python """Handle records from /proc/self/status data files""" import regentest as RG import ProcHandlers as PH PFC = PH.ProcFieldConstants PDC = PH.ProcDataConstants # --- # pylint: disable=R0914 def re_self_status(inprecs): """Iterate through parsed records and re-generate data file""" _...
#...+....1..
..+....2....+....3....+....4....+....5....+....6....+....7....+....8 RG.RECREATOR[PH.GET_HANDLER("/proc/self/status")] = re_self_status
hoangmle/crave-bundle-2015-07-22
metaSMT/bindings/python/examples/prime_test.py
Python
mit
1,487
0.036315
#!/usr/bin/python from metasmt.core import * from metasmt.operators import * import random default_bitwidth = 24 def prime_test(number, solver=boolector_solver(), bitwidth=default_bitwidth): a = new_bitvector( bitwidth ) b = new_bitvector( bitwidth ) ext = lambda x: zero_extend( bitwidth, x) ## a*b=c (avoid...
_value(b), ) else: r
eturn None def prime_test_operators(number, solver=boolector_solver(), bitwidth=default_bitwidth): a = new_bitvector( bitwidth ) b = new_bitvector( bitwidth ) ext = lambda x: zero_extend( bitwidth, x) ## a*b=c (avoiding overflows) solver &= ext(a) * ext(b) == bv_uint(number)[2*bitwidth] solver &= a != bv...
danjac/ownblock
ownblock/ownblock/apps/complaints/urls.py
Python
mit
192
0
from rest_
framework import routers from . import views router = routers.DefaultRouter(trailing_slash=False) router.register(r'complaints', views.ComplaintVi
ewSet) urlpatterns = router.urls
DavidAndreev/indico
indico/util/suggestions.py
Python
gpl-3.0
6,250
0.0032
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
.filter(Event.id.in_(e.id for e in attended_events)) .all()) if attending_future: score += 0.25 * len(attending_future) if debug: print '{0:+.3f} - future event count'.format(score) days_to_future_event = (attending_future[0].start_dt.date() - date...
print '{0:+.3f} - days to next future event'.format(score) return score def get_category_scores(user, debug=False): # XXX: check if we can add some more roles such as 'contributor' to assume attendance event_ids = set() event_ids.update(int(id_) for id_, roles in avatar_links....
stackforge/networking-bagpipe-l2
networking_bagpipe/tests/unit/agent/base.py
Python
apache-2.0
12,322
0
# Copyright (c) 2015 Orange. # 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 a...
m networking_bagpipe.agent.bgpvpn import constants as bgpv
pn_const from networking_bagpipe.bagpipe_bgp import constants as bbgp_const from neutron.plugins.ml2.drivers.linuxbridge.agent.common \ import constants as lnx_agt_constants from neutron.plugins.ml2.drivers.linuxbridge.agent \ import linuxbridge_neutron_agent as lnx_agt from neutron.plugins.ml2.drivers.openvsw...
domino14/Webolith
djAerolith/flashcards/urls.py
Python
gpl-3.0
157
0
from django.conf.urls import url from flashcards.views import main, new_quiz urlpatterns = [ url(r'^$', main), url(r'^api/new_quiz$', new_quiz),
]
ZeitOnline/zeit.content.text
src/zeit/content/text/testing.py
Python
bsd-3-clause
140
0
import zeit.cms.testing ZCML_LAYER = zeit.cms.testing.ZCMLL
ayer( 'ftesting.zcml', product_config=zeit.cms.testing.c
ms_product_config)
pmrowla/p101stat
tests/conftest.py
Python
bsd-3-clause
969
0
# -*- coding: utf-8 -*- """Defines fixtures available to all tests.""" import py
test from webtest import TestApp from p101stat.app import create_app from p101stat.database import db as _db from p101stat.settings import TestConfig from .factories import IdolFactory @pytest.yield_fixture(scope='functio
n') def app(): """An application for the tests.""" _app = create_app(TestConfig) ctx = _app.test_request_context() ctx.push() yield _app ctx.pop() @pytest.fixture(scope='function') def testapp(app): """A Webtest app.""" return TestApp(app) @pytest.yield_fixture(scope='function') de...
Avocarrot/i2o
manage.py
Python
mit
246
0
#!/
usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "i2o.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
nuigroup/pymt-widgets
pymt/ui/window/win_glut.py
Python
lgpl-3.0
4,290
0.000932
''' Window GLUT: windowing provider based on GLUT ''' __all__ = ('MTWindowGlut', ) import sys import os from pymt.ui.window import BaseWindow from pymt.logger import pymt_logger from pymt.base import stopTouchApp, getEventLoop from OpenGL.GLUT import GLUT_RGBA, GLUT_DOUBLE, GLUT_ALPHA, GLUT_DEPTH, \ GLUT_MULT...
tShowWindow, \ glutFullScreen, glutDestroyWindow, glutReshapeFunc, glutDisplayFunc, \ glutMotionFunc, glutGetModifiers, glutSwapBuffers, glutPostRedisplay, \ glutMainLoop class MTWindowGlut(BaseWindow): __glut_window = None def create_window(self, params): if self.__gl
ut_window is None: # init GLUT ! pymt_logger.debug('WinGlut: GLUT initialization') glutInit('') if 'PYMT_GLUT_UNITTEST' in os.environ: glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) else: glutInitDisplayMode( G...
NeuralEnsemble/NeuroTools
test/test_plotting.py
Python
gpl-2.0
5,059
0.008697
""" Unit tests for the NeuroTools.plotting module """ import matplotlib matplotlib.use('Agg') import unittest from NeuroTools import plotting import pylab import os class PylabParamsTest(unittest.TestCase): def runTest(self): # define arbitrary values fig_width_pt = 123.4 ratio = 0.12...
e(10): frames.append(numpy.random.randint(0,255,[10,10])) filename = 'deleteme.zip' if os.path.exists(filename): os.remove(filename) plotting.save_2D_movie(frames, filename, duration)
assert os.path.exists(filename) os.remove(filename) class SetLabelsTest(unittest.TestCase): def runTest(self): f = plotting.get_display(True) x = range(10) p = pylab.plot(x) plotting.set_labels(pylab, 'the x axis', 'the y axis') # set up a SimpleMultiplot...
miltonsarria/dsp-python
informatica/class_python/ejemplo_qt_server.py
Python
mit
2,390
0.017573
import os import sys from PyQt4.QtCore import * from PyQt4.QtGui import * import numpy as np import threading import time ########################################################## ########################################################## ########################################################## ##...
t=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Main: ventana principal') self.create_main_frame
() #function when close event.... ask yes or no? def closeEvent(self, event): reply = QMessageBox.question(self, 'Message', "Exit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: ...
Summerotter/furryyellowpages
app/__init__.py
Python
mit
1,090
0.00367
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.mail import Mail from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.pagedown import PageDown from config import config import os bootstrap = Bootstrap() ...
g[config_name].init_app(app) bootstrap.init_app(app) mail.init_app(app) moment.init_app(app) db.init_app(app) login_manager.init_app(app) pagedown.init_app(app) from .main import main as
main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app # #app = create_app(os.getenv('FLASK_CONFIG') or 'default')
marqsm/LED-bot
LEDBot/emojiHandler.py
Python
mit
1,723
0.002322
import pickle from os.path import dirname, exists, join import re HERE = dirname(__file__) class Emoji(): def __init__(self): self.emoji_directory = dict() self._pickle_path = join(HERE, 'emoji-dict.pickle') self.init() def init(self): if exists(self._pickle_path) and self.loa...
ady.") e
lse: self.create_dict(self.load_emoji_names()) self.dump(self._pickle_path) print("Created new pickle file with emoji dictionary.") def load_emoji_names(self): with open(join(HERE, 'emoji.txt')) as f: return f.read().splitlines() def create_dict(self, em...
mythkiven/python
demo/CET查询/learn_images.py
Python
mit
1,312
0
# coding: utf-8 """ labeled_images文件夹中: 1. 包含的文件夹名为标记名 2. 标记名下的文件夹中包含了学习图片 """ import os from sklearn import svm from PIL import Image from numpy import array from utils import * clf = None def get_image_fit_data(dir_name): """读取labeled_images文件夹的图片,返回图片的特征矩阵及相应标记""" X = [] Y = [] ...
i = Image.open(os.path.join(dir_name, name, img)) X.append(array(i).flatten()) Y.append(name) return X, Y def get_classifier_from_learn(): """学习数据获取分类器""" global clf if not clf: clf = svm.SVC() X, Y = get_image_fit_data("labeled_images...
ifier_from_learn() print(clf) PX, PY = get_image_fit_data("predict_images") for x, y in zip(PX, PY): r = clf.predict(x.reshape(1, -1)) print(r, y) if __name__ == '__main__': main()
reimandlab/ActiveDriverDB
website/search/gene.py
Python
lgpl-2.1
9,332
0.000107
from abc import ABC, abstractmethod from collections import defaultdict from Levenshtein import distance from sqlalchemy import and_ from werkzeug.utils import cached_property from models import Protein, UniprotEntry, ProteinReferences from models import Gene from database import db class GeneMatch: def __init...
s(query, phrase) @staticmethod def sort_key(isoform, phrase): return distance(isoform.full_name, phrase) class RefseqGeneSearch(ProteinSearch): """Look up a gene by isoforms RefSeq. Only numeric phrases and phrases starting with: "NM_" or "nm_" will be evaluated.
Targets: Protein.refseq Example: search for "NM_00054" should return: TP53 [with matched isoforms = Protein(refseq=NM_000546)] (among others) """ name = 'refseq' pretty_name = 'RefSeq' def search(self, phrase, sql_filters=None, limit=None): if phrase.isnumeric(): ...
klmitch/jenkins-job-builder
tests/modules/test_helpers.py
Python
apache-2.0
2,542
0
# # Copyright (c) 2016 Kien Ha <kienha9922@gmail.com> # # 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...
= yaml.load("user-input-string: hello") user_input_mappings = [('user-input-string', 'userInputString', 'user-input')] convert_mapping_to_xml( user_input_root, user_input_data, user_input_mappings, fail_required=True) ...
result, Equals('hello')) # Test missing required input required_root = XML.Element('testrequired') required_data = yaml.load("string: hello") required_mappings = [('required-string', 'requiredString', None)] self.assertRaises(MissingAttributeError, con...
SINGROUP/pycp2k
pycp2k/classes/_each323.py
Python
lgpl-3.0
1,114
0.001795
from pycp2k.inputsection import InputSection class _each323(InputSection): def __init__(self): InputSection.__init__(self) self.Just_energy = None self.Powell_opt = None self.Qs_scf = None self.Xas_scf = None self.Md = None self.Pint = None self.Meta...
e self.Band = None self.Ep_lin_solver = None self.Spline_find_coeffs = None self.Replica_eval = None self.Bsse = None self.Shell_opt = None self.Tddft_scf = None self._name = "EACH" self._keywords = {'Bsse': 'BSSE', 'Cell_opt': 'CELL_OPT', 'Just_en...
JUST_ENERGY', 'Band': 'BAND', 'Xas_scf': 'XAS_SCF', 'Rot_opt': 'ROT_OPT', 'Replica_eval': 'REPLICA_EVAL', 'Tddft_scf': 'TDDFT_SCF', 'Shell_opt': 'SHELL_OPT', 'Md': 'MD', 'Pint': 'PINT', 'Metadynamics': 'METADYNAMICS', 'Geo_opt': 'GEO_OPT', 'Spline_find_coeffs': 'SPLINE_FIND_COEFFS', 'Powell_opt': 'POWELL_OPT', 'Qs_scf'...
crate/crate-python
src/crate/client/sqlalchemy/tests/create_table_test.py
Python
apache-2.0
6,206
0
# -*- coding: utf-8; -*- # # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. Crate licenses # this file
to you under the Apach
e 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...
amartinez1/nonymous
likes/views.py
Python
mit
4,991
0.00581
# Create your views here. from django.http import HttpResponse from django.db.models import Sum from confess.models import Post from .middleware import retrieve_token from .models import Like, MtmLike2Conf from django.views.generic import TemplateView import logging from django.core import serializers import json logg...
like.save() posts.liked = True posts.total_likes = posts.total_likes + 1 posts.save() # update many to many reference object print("creating many to many relashionship obj") mtm_like_2_conf = MtmLike2Conf(confession=posts, like=like) ...
like = like.id print "saved!!!" count = posts.total_likes data = { 'count': count, 'label': label, 'user_token': user_token } result = json.dumps(data) return HttpResponse(result, content_type='...
stevenewey/wagtail
wagtail/wagtailimages/views/frontend.py
Python
bsd-3-clause
977
0.002047
from wsgiref.util import FileWrapper import
imghdr from django.shortcuts import get_object_or_404 from django.http import HttpResponse from django.core.exceptions import PermissionDenied from wagtail.wagtailimages.models import get_image_model from wagtail.wagtailimages.utils import verify_signature from wagtail.wagtailimages.exceptions import InvalidFilterSp...
get_object_or_404(get_image_model(), id=image_id) if not verify_signature(signature.encode(), image_id, filter_spec): raise PermissionDenied try: rendition = image.get_rendition(filter_spec) rendition.file.open('rb') image_format = imghdr.what(rendition.file) return Htt...
hachreak/invenio-demosite
invenio_demosite/base/fixtures/oai_harvest.py
Python
gpl-2.0
1,982
0.001514
# -*- coding: utf-8 -*- # # This file is part of Invenio Demosite. # Copyright (C) 2013 CERN. # # Invenio Demosite 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...
ivision' f3 = u'' setRecList = None setDefinition = u'c=;p1=CERN;f1=reportnumber;m1=a;p2=TH;f2=division;m2=e;p3=;f3=;m3=;' last_updated = datetime.now() id = 3 setSpec = u'cern:
theory' setDescription = u'' p3 = u'' p1 = u'CERN' setName = u'CERN theoretical papers' setCollection = u'' p2 = u'TH' m1 = u'a' m3 = u'' m2 = u'e' __all__ = ('OaiREPOSITORYData', )
spulec/moto
moto/instance_metadata/urls.py
Python
apache-2.0
207
0
from .respo
nses import InstanceMetadataResponse url_bases = ["http://169.254.169.254"] instance_metadata = InstanceMetadataResponse() url_paths = {"{0}/(?P<path>.+)":
instance_metadata.metadata_response}
callowayproject/django-massmedia
massmedia/urls.py
Python
apache-2.0
3,236
0.001236
from django.conf.urls import patterns, url from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.base import TemplateView from django.http import HttpResponseNotFound from models import Collection, Image, Video, Audio, Flash, Document, Embed media_...
?P<mediatype>\w+)/(?P<object_id>\d+)/$', generic_wrapper, name="massmedia_enlarge_detail_pk"), url( r'^(?P<mediatype>\w+)/$', generic_wrapper, kwargs={'paginate_by': 15, }, name='massmediatype_index'), url( r'^(?P<mediatype>\w+)/(?P<slug>[-\w]+)/$', ...
name="massmedia_detail_pk"), url( r'^collection/(?P<slug>[-\w]+)/(?P<type>[-\w]+)/$', 'massmedia.views.list_by_collection_by_type', name="massmedia_collection_by_type"), (r'^widget/(?P<id>\d+)/(?P<type>[-\w]+)/$', 'massmedia.views.widget'), )
beernarrd/gramps
gramps/gen/filters/rules/person/_ismorethannthgenerationancestorof.py
Python
gpl-2.0
2,942
0.006798
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2006 Donald N. Allingham # # 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 you...
ationAncestorOf(Rule): """Rule that checks for a person that is an ancestor of a specified person at least N generations away""" labels = [ _('ID:'), _('Number of generations:') ] name = _('Ancestors of <person> at least <N> generations away') category = _("Ancestral filters") de...
self.map = set() try: root_handle = db.get_person_from_gramps_id(self.list[0]).get_handle() self.init_ancestor_list(root_handle,0) except: pass def reset(self): self.map.clear() def apply(self,db,person): return person.handle in self.map ...
cpodlesny/lisbon
src/gallery/views.py
Python
mit
7,355
0.000136
from django.contrib import messages from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.core.urlresolvers import reverse from django.shortcuts import render, redirect, get_object_or_404 from django.utils.translation import ugettext_lazy as _ from helpers.models import Helpers from offe...
tor.page(paginator.num_pages) context = { 'footer
': { 'about': footer[lang], 'icon': Helpers.objects.get(id=1).footer_icon }, 'nav': { 'tour_categories_list': Category.objects.all(), 'offer_categories_list': OfferCategory.objects.all(), }, 'company': get_company(), 'title': _('Gal...
SeldonIO/seldon-server
python/seldon/vw.py
Python
apache-2.0
12,228
0.011286
import sys from fileutil import * import json from wabbit_wappa import * from subprocess import call import numpy as np import random from socket import * import threading, Queue, subprocess import time import psutil import pandas as pd from seldon.pipeline.pandas_pipelines import BasePandasEstimator from sklearn.util...
self.__dict__ = dict self.model_saved = False self.vw = None self.tailq = Queue.Queue(maxsize=1000) self.raw_predictions_thread_running=False if not self.model is None: self._start_vw_if_needed("test") def _wait_model_saved(self,fname): ...
Hack to wait for vw model to finish saving. It creates a file <model>.writing during this process """ logger.info("waiting for %s",fname) time.sleep(1) while os.path.isfile(fname): logger.info("sleeping until model is saved") time.sleep(1) def _save_mo...
GNOME/caribou
tools/convert_cldr.py
Python
lgpl-2.1
3,381
0.000592
#!/usr/bin/python from gi.repository import Gdk from xml.etree.ElementTree import ElementTree, Element import re ESCAPE_PATTERN = re.compile(r'\\u\{([0-9A-Fa-f]+?)\}') ISO_PATTERN = re.compile(r'[A-E]([0-9]+)') def parse_single_key(value): key = Element('key') uc = 0 if hasattr(__builtins__, 'unichr'): ...
in keymap.iter('map'): value = _map.get('to') key = parse_single_key(value) iso = _map.get('iso'
) if not ISO_PATTERN.match(iso): sys.stderr.write('invalid ISO key name: %s\n' % iso) continue if not iso[0] in rows: rows[iso[0]] = [] rows[iso[0]].append((int(iso[1:]), key)) # add attribute to certain keys nam...
aashish-jain/BLUED-events
plot_ipeak.py
Python
unlicense
1,306
0.029862
import csv import matplotlib.pyplot as plt import numpy as np from os import listdir directory='/media/aashish/0C0091CC0091BCE0/BLUED-D1-1/events' files=listdir(directory) count=0 completed=False while(completed==False): try: for f in files: plt.close('all') print(count,f) ...
delimiter=',') count+=1 t,i1,i2,v=[],[],[],[] i = 0 while(True): t.append(max(data[i:i+200,0])) i1.append(max(data[i:i+200,1]))
i2.append(max(data[i:i+200,2])) v.append(max(data[i:i+200,3])) i+=200 if (i == 59800): break print(max(i1),max(i2),max(v),max(t)) print(len(t),len(i1),len(i2),len(v)) _f, axarr = plt.subplots(3, sharex=True...
Likegram/study_run
server/app/views.py
Python
mit
1,803
0.001109
from django.shortcuts import render # Create your views here. from .models import Course, Student, StudentCourse from .serializers import CourseSerializer, StudentSerialiser from rest_framework import viewsets from rest_framework.decorators import detail_route, list_route from rest_framework.response import Response...
udent.objects.get(nickname=username) course = Course.objects.get(id=pk) student_course, created = StudentCourse.objects.get_or_create(student=user, course=course) StudentCourse.objects.filter(student=user).update(active=False) student_course.active = True student_cour
se.save() return Response({'success': True})
tensorflow/datasets
tensorflow_datasets/audio/gtzan/gtzan.py
Python
apache-2.0
3,225
0.003411
# codin
g=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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. """GZTAN da...
invicnaper/MWF
Utils/t/form_test.py
Python
gpl-2.0
10,150
0.033718
#!/usr/bin/env python # coding=utf-8 # # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # import httplib import sys def test(name,A,B): if A != B: print "Error :" + name print "-----Actual--" print A,"---Expected--" print B,"-------------" sys.exit(1) else: ...
=xxxxxx','invalid\nxxxxxx')
test_valid('text5','/text','_1=%d7%a9%d6%b8%d7%9c%d7%95%d7%9d','valid\nשָלום') test_valid('text6','/text','_1=%d7%a9%d7%9c','valid\nשל') test_valid('text7','/text','_1=%FF%FF','invalid\n\xFF\xFF') test_valid('text8','/text','_1=%01%01','invalid\n\x01\x01') test_valid('text9.1','/text','_1=xx%DF%7F','invalid\nxx\xDF\x7...
AlperSakarya/AWS-Import-Export-Manifest-Generator
forms.py
Python
bsd-2-clause
4,728
0.007191
from flask.ext.wtf import Form from wtforms import TextField, TextAreaField, SubmitField, PasswordField, validators, ValidationError, Sel
ectField class AWSIEFormFields(Form): deviceId = TextField(u'Device ID', validators=[validators.required()]) notificationEmail = TextField("Notification Email", [validators.email
("Please enter 7 characters to search")]) region = SelectField(u'Region', choices=[('us-east-1', 'us-east-1'), ('us-west-1', 'us-west-1'), ('us-west-2', 'us-west-2'), ('eu-west-1 ', 'eu-west-1'), ('ap-southeast-1', 'ap-southeast-1')]) acl = TextField("ACL", [validators.email("Please enter a...
tnewman/PIoT
readsensors.py
Python
mit
987
0.009119
#!/usr/bin/env python3 """ Reads all sensors configured in the PIoT sensor directory every 30 seconds. """ running = True def signal_handler(signum, frame): global running running = False # Signal handling must occur before SQLAlchemy imports # in the service layer, or the signal will not be # handle...
g_service.sensor_reading_job() while running: schedule.run_pending() time.sleep(1) if __name__ =
= '__main__': run_jobs()
zenoss/ZenPacks.community.NetWare
ZenPacks/community/NetWare/modeler/plugins/NetWareFileSystemMap.py
Python
gpl-2.0
2,147
0.011178
__doc__="""NetWareFileSystemMap FileSystemMap maps the interface and ip tables to interface objects $Id: NetWareFileSystemMap.py,v 0.9 2009/03/09 efeldman""" __version__ = '$Revision: 0.9 $'[11:-2] import re from Products.DataCollector.plugins.CollectorPlugin import SnmpPlugin, GetTableMap, GetMap from Products.Da...
for fs in fstable.values(): if not fs.has_key("nwVolSize"): continue if not self.checkColumns(fs, self.columns, log): continue if fs['nwVolSize'] > 0 and (not skipfsnames or not re.search(skipfsnames,fs['nwVolPhysicalName'])): om = self.objectMap() ...
om.id = self.prepId(fs['nwVolPhysicalName']) om.snmpindex = fs['nwVolId'] om.mount = fs['nwVolPhysicalName'] om.type = fs['nwVolFileSystemID'] om.blockSize = 1024 om.totalBlocks = fs['nwVolSize'] ...
petems/ansible-json
callback_plugins/json_logs.py
Python
mit
1,719
0.018034
# adapted from https://gist.github.com/cliffano/9868180 import os import time import json from json import JSONEncoder def json_log(res, host): if type(res) == type(dict()): if 'verbose_override' not in res: res.update({"host": host}) combined_json = JSONEncoder().encode(res) print(combined_js...
ss def playbook_on_not_import_for_host(self, host, missing_file): pass def playbook_on_play_
start(self, pattern): pass def playbook_on_stats(self, stats): pass
grimfang/lext
core/level/builder.py
Python
mit
26,314
0.00456
#!/usr/bin/python # System imports # Panda Engine imports from direct.showbase.DirectObject import DirectObject from panda3d.core import * from pandac.PandaModules import * from panda3d.bullet import * from direct.task.Task import Task from direct.interval.IntervalGlobal import * # Game imports #-----...
create light (may need sub tag for light type, but for now its just poin
tlights) # pickup = pickable object # exit = exit point # start = spawn point # wall = basic wall visual # col_wall = collision shape # physic_lift = physics based object that moves up or down # physic_door # complex_object # size = Boxes have sizes s,m,l # Make a proper bitmask list # 0x01 = w/e... cla...
pyokagan/pyglreg
setup.py
Python
mit
1,068
0
from setuptools
import setup setup(name='glreg', version='0.9.0a3',
description='OpenGL XML API registry parser', long_description=open('README.rst').read(), url='https://github.com/pyokagan/pyglreg', author='Paul Tan', author_email='pyokagan@gmail.com', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment ...
eort/OpenSesame
libopensesame/sketchpad_elements/_noise.py
Python
gpl-3.0
1,670
0.021557
#-*- coding:utf-8 -*- """ This file is part of OpenSesame. OpenSesame 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. OpenSesame is distri...
the sketchpad. """ properties = self.eval_properties() return self.canvas.no
ise_patch(properties[u'x'], properties[u'y'], env=properties[u'env'], size=properties[u'size'], stdev=properties[u'stdev'], col1=properties[u'color1'], col2=properties[u'color2'], bgmode=properties[u'bgmode'])
RoboticaBrasil/-ComputerVision
camera.py
Python
apache-2.0
336
0
From SimpleCV import Camera # Initialize the camera cam = Camera() # Loop to cont
inuo
usly get images while True: # Get Image from camera img = cam.getImage() # Make image black and white img = img.binarize() # Draw the text "Hello World" on image img.drawText("Hello World!") # Show the image img.show()
thorgate/django-esteid
esteid/mobileid/types.py
Python
bsd-3-clause
2,083
0.00096
import re from collections import namedtuple from typing import Optional from esteid import settings from esteid.constants import Languages from esteid.exceptions import InvalidIdCode, InvalidParameter from esteid.signing.types import InterimSessionData from esteid.types import PredictableDict from esteid.validators i...
PHONE_NUMBER_REGEXP = settings.MOBILE_ID_PHONE_NUMBER_REGEXP AuthenticateResult = namedtuple(
"AuthenticateResult", [ "session_id", "hash_type", "hash_value", "verification_code", "hash_value_b64", ], ) AuthenticateStatusResult = namedtuple( "AuthenticateStatusResult", [ "certificate", # DER-encoded certificate "certificate_b64", # B...
comparemetrics/GoogleAppsAccountManager
src/GoogleAppsAccountManager/group/data.py
Python
gpl-2.0
1,308
0.005352
# -*- coding: utf-8 -*- # # GoogleAppsAccountManager: group/data # Copyright (C) 2012-2013 KAMEI Yutaka # # License: GNU General Public License version 2 or later # Date: 2012-12-28, since 2012-12-28 # from GoogleAppsAccountManager import XMLNS_ATOM, XMLNS_APPS from GoogleAppsAccountManager import data, errors class ...
escription(self, new_description_utf8): return self.setValueToPropertyElement( "description" , new_description_utf8.decod
e("utf-8") )
wardi/ckanext-bcgov
ckanext/bcgov/plugin.py
Python
agpl-3.0
17,626
0.007886
# Copyright 2015, Province of British Columbia # License: https://github.com/bcgov/ckanext-bcgov/blob/master/license from ckan.common import c, _ import pylons.config as config import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit from routes.mapper import SubMapper from ckanext.bcgov.util.util im...
"get_user_toporgs": get_user_toporgs, "get_suborg_sector" : get_suborg_sector, "get_user_dataset_num" : get_user_dataset_num, "get_edc_package" : get_package_data, "is_license_open" : is_license_open, "record_type_label" : get_record_typ...
ewable, "get_espg_id" : get_espg_id, "get_user_role_orgs" : get_user_role_orgs, "get_all_orgs" : get_all_orgs, "get_facets_selected": get_facets_selected, "get_facets_unselected" : get_facets_unselected, "get_sectors_list": ...
francislpx/myblog
blog/urls.py
Python
gpl-3.0
423
0.002364
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^post/(?P<pk>[0-9]+)/$', views.detail, name='detail'), ur
l(r'^archive/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', views.archives, name='archive'), url(r'^category/(?P<pk>[0-9]+)/$', views.categories, name='category'), url(r'^tag/(?P<pk>[0-9]+)/$', views.get_posts_by_tag,
name='tag'), ]
hlzz/dotfiles
graphics/VTK-7.0.0/Imaging/Core/Testing/Python/TestROIStencil.py
Python
bsd-3-clause
3,470
0.010663
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # A script to test the vtkROIStencilSource reader = vtk.vtkPNGReader() reader.SetDataSpacing(0.8,0.8,1.5) reader.SetDataOrigin(0.0,0.0,0.0) reader.SetFileName("" + str(VTK_D...
derer(imager1) imgWin.AddRenderer(imager2) imgWin.AddRenderer(imager3) imgWin.AddRenderer(imager4) imgWin.SetSize(512,512) imgWin.Render() # --- end of scri
pt --
ilikesounds/jt_portfolio
jt_portfolio/wsgi.py
Python
mit
582
0.003436
""" WSGI config for jt_portfolio project. It exposes the WSGI callable
as a module-level variable named ``application``. For more information on this file, see https://docs.djangopr
oject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jt_portfolio.settings") application = get_wsgi_application() from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise ap...
prometx/shivuxbot
shivuxbot-scratch_pub.py
Python
mit
725
0.005517
#!/usr/bin/python3.5 import requests import urllib.request import urllib.parse import json import pprint from bittrex import Bittrex """ MARKET_SET = { 'getopenorders', 'cancel', 'sellmarket', 'selllimit', 'buymarket', 'buylimit' } ACCOUNT_SET = { 'getbalances', 'getbalance', 'get...
'withdraw', 'getorderhistory', 'getorder', 'getdeposithistory', 'getwithdrawalhistory' } """ api_key = '<bittrex api key>' api_secret = '<bittrex api secret>' #url = 'https://bittrex.com/api/v1.1/account/getbalances' bittrex = Bittrex(api_key,api_secret) call_result = call.api_query(
'account','getopenbalances') json_data = requests.get(call_result).json()
frappe/frappe
frappe/tests/test_base_document.py
Python
mit
476
0.021008
import unittest from frappe.model.base_document import BaseDocument class TestBaseDocument(unittest.TestCase): def test_docstatus(self): doc = BaseDocument({"docstatus": 0}) self.assertTrue(doc
.docstatus.is_draft()) self.assertEquals(doc.docstatus, 0) doc.docstatus = 1 self.assertTrue(doc.docstatus.is_submitted()) self.assertEquals(doc.docstatus, 1)
doc.docstatus = 2 self.assertTrue(doc.docstatus.is_cancelled()) self.assertEquals(doc.docstatus, 2)
gnulinooks/sympy
sympy/test_external/test_numpy.py
Python
bsd-3-clause
7,620
0.015879
# This testfile tests SymPy <-> NumPy compatibility # Don't test any SymPy features here. Just pure interaction with NumPy. # Always write regular SymPy tests for anything, that can be tested in pure # Python (without numpy). Here we test everything, that a user may need when # using SymPy with NumPy try: from nu...
ssert Matrix(a) != Matrix([[2, 4], [5, 2]]) a = matrix([[sin(2), 4], [5, 1]]) assert Matrix(a) == Matrix([[sin(2), 4],[5, 1]]) assert Matrix(a) != Matrix([[sin(0), 4],[5, 1]]) def test_Matrix_sum(): x, y, z = Symbol('x'), Symbol('y'), Symbo
l('z') M = Matrix([[1,2,3],[x,y,x],[2*y,-50,z*x]]) m = matrix([[2,3,4],[x,5,6],[x,y,z**2]]) assert M+m == Matrix([[3,5,7],[2*x,y+5,x+6],[2*y+x,y-50,z*x+z**2]]) assert m+M == Matrix([[3,5,7],[2*x,y+5,x+6],[2*y+x,y-50,z*x+z**2]]) assert M+m == M.add(m) def test_Matrix_mul(): x, y, z = Symbol('x')...
fedora-copr/dnf-plugins-core
plugins/repoclosure.py
Python
gpl-2.0
5,281
0.000568
# repoclosure.py # DNF plugin adding a command to display a list of unresolved dependencies # for repositories. # # Copyright (C) 2015 Igor Gnatenko # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Publi...
_unresolved(self, arch=None): unresolved = {} deps = set() available = self.base.sack.query().available() if self.base.conf.best and not self.opts.check: available = available.latest()
elif self.opts.newest or self.base.conf.best: available = available.filter(latest=True) if arch is not None: available = available.filter(arch=arch) pkgs = set() if self.opts.pkglist: available.apply() for pkg in self.opts.pkglist: ...
LangmuirSim/langmuir
LangmuirPython/ga2d/generators/iso.py
Python
gpl-2.0
2,422
0.00289
# -*- coding: utf-8 -*- """ iso.py ====== .. argparse:: :module: iso :func: create_parser :prog: iso.py .. moduleauthor:: Geoff Hutchison <geoffh@pitt.edu> """ import argparse import os from scipy import misc, ndimage import numpy as np desc = """ Generate isotropic two-phase 2D systems using Gaussian n...
ArgumentParser() parser.description = desc parser.add_argument(dest='width', default=256, type=int, metavar='dim.x', nargs='?', help='dim.x') parser.add_argument(dest='height', default=256, type=int, metavar='dim.y', nargs='?', help='dim.y') parser.add_...
nargs='?', help='radius of Gaussian blur') parser.add_argument('--seed', default=None, type=int, metavar='int', help='random number seed') parser.add_argument(dest='ofile', default=None, type=str, nargs='?', metavar='output', help='output file') return parser ...
llvtt/mongo-python-driver
tools/fail_if_no_c.py
Python
apache-2.0
842
0.002375
# Copyright 2009-2014 MongoDB, 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 th
e 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 g...
build scripts. """ import sys sys.path[0:0] = [""] import bson import pymongo if not pymongo.has_c() or not bson.has_c(): sys.exit("could not load C extensions")
phantomas1234/fbaproject
ifba/GlpkWrap/knockouts.py
Python
mit
1,226
0.00571
#!/usr/bin/env python # encoding: utf-8 """ knockouts.py Created by Nikolaus Sonnenschein on 2008-02-25. Copyright (c) 2008 Jacobs University of Bremen. All rights reserved. """ from metabolism import Metabolism from util import ImportCplex from ifba.glpki.glpki import * class KnockOut(object): """A class putti...
def knockOuts(self, listOfGenes): """Knocks out a list of genes.""" for gene in listOfGenes: self.knockOut(gene) if __name__ == '__main__': def init(path): struct = ImportCplex(path) return Metabolism(struct) def main(): import util ...
ex() print ecoli.getObjVal() main()
jedman/dedalus-leakylid
dedalus_boussinesq.py
Python
gpl-2.0
12,959
0.027317
import numpy as np import matplotlib.pyplot as plt import h5py from dedalus import public as de from dedalus.extras import flow_tools import time import argparse plt.rcParams['image.cmap'] = 'RdBu_r' parser = argparse.ArgumentParser(description='simulate a Boussinesq pulse') parser.add_argument('k', metavar = 'k', t...
.Domai
n([x_basis, z_basis], grid_dtype=np.float64) x, z = domain.grids(scales=1) xd, zd = domain.grids(scales=domain.dealias) # set up problem problem = de.IVP(domain, variables=['p','u','B','w']) problem.parameters['rho'] = 1. #kg/m^3 #problem.parameters['Nsq'] = 0.0001 #1/s; constant Nsq # non-constant coefficient N...
mdl29/tidutyzef
serveur/adminws.py
Python
lgpl-3.0
2,061
0.001941
"""Contain the socket handler for players""" from game import Game from websocket import WebSocketHandler from zone import Zone import errcode class AdminWs(WebSocketHandler): """The socket handler for websocket""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self....
son = {"setParams": self.set_params, "login": self.login, "logout": self.logout, "getParams": self.get_params, "startGame": sel
f.start_game} def open(self, *args, **kwargs): super().open(*args, **kwargs) self.login() @staticmethod def start_game(): """start the game""" Game().start_game() @staticmethod def set_params(**kwargs): """set params of the game""" params = Game().p...
wkschwartz/django
tests/gis_tests/geos_tests/test_mutable_list.py
Python
bsd-3-clause
14,848
0.000673
# Copyright (c) 2008-2009 Aryeh Leib Taurog, http://www.aryehleib.com # All rights reserved. # # Modified from original contribution by Aryeh Leib Taurog, which was # released under the New BSD license. import unittest from django.contrib.gis.geos.mutable_list import ListMixin class UserListA(ListMixin): _mytyp...
x'] * length for i, v in enumerate(items): itemList[i] = v self._list = self._mytype(itemList) def _get_single_external(self, index): return self._list[index] class UserListB(UserListA): _mytyp
e = list def _set_single(self, index, value): self._list[index] = value def nextRange(length): nextRange.start += 100 return range(nextRange.start, nextRange.start + length) nextRange.start = 0 class ListMixinTest(unittest.TestCase): """ Tests base class ListMixin by comparing a list ...
rlutz/xorn
tests/cpython/storage/ob_equality.py
Python
gpl-2.0
1,119
0
# Copyright (C) 2013-2021 Roland Lutz # # 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 ...
e rev = xorn.storage.Revision() ob0 = rev.add_object(xorn.storage.Line()) ob1,
= rev.get_objects() ob2 = rev.add_object(xorn.storage.Line()) assert ob0 is not ob1 assert ob0 == ob1 assert hash(ob0) == hash(ob1) assert ob0 is not ob2 assert ob0 != ob2 assert hash(ob0) != hash(ob2) assert ob1 is not ob2 assert ob1 != ob2 assert hash(ob1) != hash(ob2)
diego-d5000/MisValesMd
env/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/coordseq.py
Python
mit
3,266
0.001225
from ctypes import POINTER, c_double, c_int, c_uint from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import ( GEOSException, last_arg_byref, ) from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc # ## Error-checking routines spec...
tput(GEOSFunc('GEOSGeom_getCoordSeq'), [GEOM_PTR]) # Getting, setting ordinate cs_getordinate = cs_operation(GEOSFunc('GEOSCoordSeq_getOrdinate'), ordinate=True, get=True) cs_setordinate = cs_operatio
n(GEOSFunc('GEOSCoordSeq_setOrdinate'), ordinate=True) # For getting, x, y, z cs_getx = cs_operation(GEOSFunc('GEOSCoordSeq_getX'), get=True) cs_gety = cs_operation(GEOSFunc('GEOSCoordSeq_getY'), get=True) cs_getz = cs_operation(GEOSFunc('GEOSCoordSeq_getZ'), get=True) # For setting, x, y, z cs_setx = cs_oper...
strubell/Parser
lib/rnn_cells/gru_cell.py
Python
apache-2.0
2,289
0.009174
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 Timothy Dozat # # 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 ...
icense. from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from lib.rnn_cells.base_cell import BaseCell from lib import linalg #*************************************************************** class GRUCell(BaseCell): """""" #==...
=================== def __call__(self, inputs, state, scope=None): """""" with tf.variable_scope(scope or type(self).__name__): cell_tm1, hidden_tm1 = tf.split(axis=1, num_or_size_splits=2, value=state) with tf.variable_scope('Gates'): linear = linalg.linear([inputs, hidden_tm1], ...
tompko/Patrician
parse_log.py
Python
mit
5,821
0.030579
import sys import json import webbrowser # List similar commands so they end up in the same accordion list_groups = [["usermove", "time", "otim"]] groups = {} for lg in list_groups: for g in lg: groups[g] = lg white_piece_bitboards = [("White Pawn", "wp", "P"), ("White Knight","wn", "N"), ("White Bishop",...
t(log_entry["data"])) log_file.write('\t</div>\n') line = dat_file.readline() elif log_type == "board": board = json.loads(log_entry["data"]) log_file.write('\t<
h3><a href="#">Board</a></h3>\n') log_file.write('\t<div>\n') log_file.write('\t\t<div>') for pb in white_piece_bitboards: log_file.write('\t\t<div style="float: left">\n') log_file.write('\t\t\t{0}<br />\n'.format(pb[0])) fen = bitboard_to_fen(board[pb[1]], pb[2]) log_file.write(...
efforia/eos-dashboard
pandora-hub/pandora/wsgi.py
Python
lgpl-3.0
391
0
""" WSGI config for efforia project. It exposes the WSGI callable as a module-level variable named ``application``. For more
information on this file,
see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'efforia.settings') application = get_wsgi_application()
adsabs/mission-control
mc/config.py
Python
mit
1,990
0.001508
GITHUB_SIGNATURE_HEADER = 'X-Hub-Signature' GITHUB_SECRET = 'redacted' GITHUB_COMMIT_API = 'https://api.github.com/repos/adsabs/{repo}/git/commits/{hash}' GITHUB_TAG_FIND_API = 'https://api.github.com/repos/adsabs/{repo}/git/refs/tags/{tag}' GITHUB_TAG_GET_API = 'https://api.github.com/repos/adsabs/{repo}/git/tags/{has...
ted' WATCHED_REPOS = [ 'adsws', 'solr-se
rvice', 'export_service', 'graphics_service', 'recommender_service', 'citation_helper_service', 'metrics_service', 'vis-services', 'biblib-service', 'orcid-service', 'myads', 'object_service', 'harbour-service' ] # Local dependencies for the testing environment DOCKER_BRIDGE...
Azure/azure-sdk-for-python
sdk/eventhub/azure-mgmt-eventhub/azure/mgmt/eventhub/v2021_01_01_preview/models/_event_hub_management_client_enums.py
Python
mit
4,954
0.005248
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
R - possible values 'Primary' or 'PrimaryNotRe
plicating' or 'Secondary' """ PRIMARY = "Primary" PRIMARY_NOT_REPLICATING = "PrimaryNotReplicating" SECONDARY = "Secondary" class SkuName(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): """Name of this SKU. """ BASIC = "Basic" STANDARD = "Standard" PREMIUM = "Premium" c...
yellottyellott/chat-parser
chat_parser/serializers.py
Python
mit
117
0
import
json class JSONSerializer(object): def seri
alize(self, data): return json.dumps(data, indent=2)
juandc/platzi-courses
Python-Django-2016/Python/Reto/Otros-Competidores/Juan-David-Castro/pptls.py
Python
mit
4,317
0.00417
#!/usr/bin/env python # -*-coding:utf-8-*- import time from time import sleep import random depo, sus, tab, user_puntos, pc_puntos = ["piedra", "papel", "tijera", "lagarto", "spock"], "-" * 35, " " * 4, 0, 0 print """Hola! Bienvenido al juego Piedra Papel Tijera Lagarto Spock!\nEstas son las reglas:\n Las tijeras cort...
! Lagarto envenena Spock\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos) elif tu == 'spock' and pc == 'tijera': user_puntos = user_puntos + 1 print "\n Ganaste! Spock destroza las tijeras\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la ...
user_puntos = user_puntos + 1 print "\n Ganaste! Las tijeras decapitan al lagarto\nGanas un punto!!!\nTus puntos son:{}\nY los puntos de la pc son:{}\n".format(user_puntos, pc_puntos) elif tu == 'lagarto' and pc == 'papel': user_puntos = user_puntos + 1 print "\n Ganaste! El lagarto...
loulich/Couchpotato
libs/guessit/transfo/guess_video_rexps.py
Python
gpl-3.0
1,837
0.000544
#!/usr/bin/env python # -*- coding: utf-8 -*- # # GuessIt - A library for guessing information from filenames # Copyright (c) 2012 Nicolas Wack <wackou@gmail.com> # # GuessIt is free software; you can redistribute it and/or modify it under # the terms of the Lesser GNU General Public License as published by # the Free ...
span = (match.start() + span_adjust[0], match.end() + span_adjust[1] - 2) return (Guess(metadata, co
nfidence=confidence, raw=string[span[0]:span[1]]), span) return None, None def process(mtree): SingleNodeGuesser(guess_video_rexps, None, log).process(mtree)
sirex/internet-voting-registration
ivreg/views.py
Python
mit
2,644
0.000758
import json from django.http import JsonResponse, Http404 from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from ivreg.models import Voter from ivreg.forms import RegistrationForm, ValidationForm, VerifyForm from ivreg.services import generate_candidate_codes, generate...
m.is_valid(): voter = Voter.objects.create( request_id=generate_request_id(), v
oter_id=form.cleaned_data['voter_id'], ballot_id=generate_ballot_id(), candidates=json.dumps(generate_candidate_codes(CANDIDATES)) ) if request.content_type == 'application/json': return JsonResponse({'redirect': request.build_absolute_uri(voter.ge...
juruen/cavalieri
ci/ws-test/test-ws.py
Python
mit
671
0.005961
#!/usr/bin/env python import multiprocessing import subprocess import sys import time client_processes = 5 ws_processes = 20; total_processes = client_processes + ws_processes events = "5000" ws_client = "./ws-read-events.py" riemann_client = "./gener
ate-events.py" def work(i): if i < client_processes: return subprocess.call([riemann_client], shell=False) else: time.sleep(10) return subprocess.call([ws_client, "localhost:5556", events], shell=False) pool = multiprocessing.Pool(processes=total_processes) result = p...
e(total_processes)) print result sys.exit(len([i for i in result if i > 0]))
itsmeolivia/code_eval
practice/lc235.py
Python
mit
645
0
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {Tre
eNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): if not root or not p or not q: return None if max(p.val, q.val) < root.val: return self.lowestCommonAncestor(root.left, p, q) elif mi...
estCommonAncestor(root.right, p, q) else: return root
ericdill/bluesky
bluesky/simulators.py
Python
bsd-3-clause
2,750
0
from warnings import warn from bluesky.preprocessors import print_summary_wrapper def plot_raster_path(plan, x_motor, y_motor, ax=None, probe_size=None, lw=2): """Plot the raster path for this plan Parameters ---------- plan : iterable Must yield `Msg` objects and not be a co-routine x_mo...
0] if msg.obj.name == y_motor: cur_y = msg.args[0] elif cmd == 'save': traj.append((cur_x, cur_y)) x, y = zip(*traj) path, = ax.plot(x, y, marker='', linestyle='-', lw=lw) ax.set_xlabel(x_motor)
ax.set_ylabel(y_motor) if probe_size is None: read_points = ax.scatter(x, y, marker='o', lw=lw) else: circles = [mpatches.Circle((_x, _y), probe_size, facecolor='black', alpha=0.5) for _x, _y in traj] read_points = mcollections.Pat...
google/grumpy
third_party/stdlib/test/test_list.py
Python
apache-2.0
2,707
0.000739
import sys import unittest from test import test_support, list_tests class ListTest(list_tests.CommonTest): type2test = list def test_basic(self): self.assertEqual(list([]), []) l0_3 = [0, 1, 2, 3] l0_3_bis = list(l0_3) self.assertEqual(l0_3, l0_3_bis) self.assertTrue(l...
l/newlib/2002/msg00369.html self.assertRaises(MemoryError, list, xrange(sys.maxint // 2)) # This code used to segfault in Py2.4a3 x = [] x.extend(-y for y in x) self.assertEqual(x, []) def test_truth(self): super(ListTest, self).test_truth() self.assertT...
ertTrue([] is not []) def test_len(self): super(ListTest, self).test_len() self.assertEqual(len([]), 0) self.assertEqual(len([0]), 1) self.assertEqual(len([0, 1, 2]), 3) @unittest.expectedFailure def test_overflow(self): lst = [4, 5, 6, 7] n = int((sys.maxsi...
macborowy/dajsiepoznac-feed
DajSiePoznacFeed-Server/crawler/src/scrapper/feed.py
Python
mit
4,500
0.003343
# -*- coding: utf-8 -*- import logging import types import dateutil.parser import feedparser import pytz import http from html_sanitizer import HTMLSanitizer def getFeed(url): current_feed = [] content = http.get(url) feed = feedparser.parse(content) # even if content is None feedparser returns object...
(FeedParser._encode(category["term"])) return result class Da
teParser(): @staticmethod def parse(date): try: result = dateutil.parser.parse(date).astimezone(tz=pytz.UTC).replace(tzinfo=None) except ValueError: try: result = dateutil.parser.parse(date, parserinfo=DateParser.PolishParserInfo()) \ ...
Leo-G/T
app/users/test_users.py
Python
mit
4,864
0.003906
import unittest import os import sys # Add app path to module path sys.path.append(os.path.dirname(os.path.realpath(__file__).rsplit('/', 2)[0])) from app import create_app from app.users.models import Users app = create_app('config') class TestUsers(unittest.TestCase): def setUp(self): self.app = app...
rv = self.app.post
( 'users/delete/{}'.format(id), follow_redirects=True) assert 'Delete was successful' in rv.data.decode('utf-8') if __name__ == '__main__': unittest.main()
BehavioralInsightsTeam/edx-platform
lms/djangoapps/edxnotes/tests.py
Python
agpl-3.0
55,193
0.002555
""" Tests for the EdxNotes app. """ import json import urlparse from contextlib import contextmanager from datetime import datetime from unittest import skipUnless import mock import ddt import jwt from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ...
se): """ Tests for edxnotes decorator. """ def setUp(self): super(EdxNotesDecoratorTest, self).setUp() ClientFactory(name="edx-notes") # Using old mongo because of locator comparison issues (see longer # note below in EdxNotesH
elpersTest setUp. self.course = CourseFactory(edxnotes=True, default_store=ModuleStoreEnum.Type.mongo) self.user = UserFactory() self.client.login(username=self.user.username, password=UserFactory._DEFAULT_PASSWORD) self.problem = TestProblem(self.course, self.user) @patch.dict("dja...
bswartz/manila
manila/share/drivers/nexenta/ns4/nexenta_nas.py
Python
apache-2.0
5,591
0
# Copyright 2016 Nexenta Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
ot hasattr(self, '_share_
backend_name'): self._share_backend_name = None if self.configuration: self._share_backend_name = self.configuration.safe_get( 'share_backend_name') if not self._share_backend_name: self._share_backend_name = 'NexentaStor4' ...
IgowWang/ML_python3
tensorgo/mnist/mnist.py
Python
gpl-3.0
3,726
0.000281
__author__ = 'igor' """ 构建 mnist network 构建 Graph 1.inference() - Builds the model as far as is required for running the network forward to make predictions. 2.loss() -Adds to the inference model the layers required to generate loss 3.training() - Adds to the loss model the Ops required to generate and apply gradient...
weights = tf.Variable( tf.truncated_normal([hidden2_units, NUM_CLASSES], stddev=1.0 / math.sqrt(float(hidden2_units))), name='weights') biases = t
f.Variable(tf.zeros([NUM_CLASSES]), name='biases') logits = tf.matmul(hidden2, weights) + biases # 激活层是横等函数 return logits def loss(logits, labels): ''' 从logits 和labels 计算损失 :param logits: Logits tensor,float-[batch_size,NUM_CLASS] :param labels: Labels tensor...
nirizr/rematch
server/rematch/wsgi.py
Python
gpl-3.0
318
0
""" WSGI config for rematch-server project. It exposes the WSGI callable as a module-le
vel variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/dep
loyment/wsgi/ """ from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
Trinak/SuperPong
superPong/actors/components/ballAIComponent.py
Python
gpl-3.0
1,814
0.006615
''' Created on Oct 30, 2014 @author: Arrington ''' from pyHopeEngine import engineCommon as ECOM from pyHopeEngine.actors.components.aiComponent import AIComponent from superPong.actors.ballAI.ballProcesses.ballChooseStateProcess import BallChooseStateProcess from superPong.actors.ballAI.pongBallBrain import MainBall...
ame): if name == "MainBallBrain": self.brain = MainBallBrain() elif name == "BasicBallBrain": self.brain = BasicBallBrain() def setState(self, state): self.currentState.cleanUp() self.cu
rrentState = state(self.owner) self.currentState.init() def chooseState(self): if self.brain is not None: state = self.brain.think() if state is not None: self.setState(state) def update(self): if self.currentState is not Non...
nagyistoce/devide
modules/vtk_basic/vtkMergeFilter.py
Python
bsd-3-clause
550
0.003636
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkMergeFilter(Simp
leVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassMo
duleBase.__init__( self, module_manager, vtk.vtkMergeFilter(), 'Processing.', ('vtkDataSet', 'vtkDataSet', 'vtkDataSet', 'vtkDataSet', 'vtkDataSet', 'vtkDataSet'), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
Eszti/4lang
scripts/get_defs.py
Python
mit
241
0
import json import sys
data = json.load(sys.stdin) for e in data.itervalues(): if e['senses'] and e['senses'][0]
['definition']: print u"{0}\t{1}".format( e['hw'], e['senses'][0]['definition']['sen']).encode('utf-8')
hibou107/algocpp
telephone.py
Python
mit
1,349
0.002965
import sys, math # Auto-generated code below aims at helping you parse # the standard input according to the problem statement. class Tree(object): def __repr__(self): return self.val def __init__(self, val=None): self.val = val self.childs = [] def add_number(self, number): ...
The number of elements (referencing a number) stored in the structure. if __name__ == '__main__': t = Tree() t.add_number(list('0123456789')) t.add_number(list('0123')) print t.calculate() t.s
how()
wazo-pbx/xivo-auth
wazo_auth/plugins/external_auth/google/schemas.py
Python
gpl-3.0
422
0
# Copyright 2019 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-late
r from wazo_auth
import schemas from xivo.mallow import fields from xivo.mallow.validate import Length class GoogleSchema(schemas.BaseSchema): scope = fields.List(fields.String(validate=Length(min=1, max=512))) access_token = fields.String(dump_only=True) token_expiration = fields.Integer(dump_only=True)
gkc1000/pyscf
examples/ao2mo/20-eri_grad_hess.py
Python
apache-2.0
2,223
0.013045
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # import tempfi
le import numpy import h5py from pyscf import gto, scf, ao2mo ''' Integral transform
ation for irregular operators ''' mol = gto.M( verbose = 0, atom = [ [8 , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = 'ccpvdz', ) mf = scf.RHF(mol) e = mf.scf() print('E = %.15g, ref -76.0267656731' % e) # # Given four MOs, compute the MO-integral ...
genonfire/portality
accounts/migrations/0001_initial.py
Python
mit
730
0.00137
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django
.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(setti
ngs.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('point', models.IntegerField(default=1)), (...