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
keenerd/namcap
Namcap/rules/fileownership.py
Python
gpl-2.0
1,345
0.015613
# # namcap rules - fileownership # Copyright (C) 2003-2009 Jason Chu <[email protected]> # # 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 y...
stributed 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 Ge
neral Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # from Namcap.ruleclass import * class package(TarballRule): na...
ai-se/x-effort
Technix/sdivUtil.py
Python
mit
2,716
0.039764
from __future__ import division,print_function import sys sys.dont_write_bytecode = True def sdiv(lst, tiny=2,cohen=0.3, num1=lambda x:x[0], num2=lambda x:x[1]): "Divide lst of (num1,num2) using variance of num2." #---------------------------------------------- class Counts(): # Add/delete counts of nu...
i.m2 += delta*(x - i.mu) def __sub__(i,x): if i.n < 2: return i.zero() i.n -= 1
delta = x - i.mu i.mu -= delta/(1.0*i.n) i.m2 -= delta*(x - i.mu) #---------------------------------------------- def divide(this,small): #Find best divide of 'this' lhs,rhs = Counts(), Counts(num2(x) for x in this) n0, least, cut = 1.0*rhs.n, rhs.sd(), None for j,x in enumerate(this): ...
wonghoifung/learning-python
spider/spider_url_producer/pb/produce_url_resp_pb2.py
Python
mit
1,934
0.00879
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: produce_url_resp.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor fr
om google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescri...
n\x16produce_url_resp.proto\x12\x06spider\"\x1f\n\x10produce_url_resp\x12\x0b\n\x03res\x18\x01 \x02(\x05') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _PRODUCE_URL_RESP = _descriptor.Descriptor( name='produce_url_resp', full_name='spider.produce_url_resp', filename=None, file=DESCRIPTOR, containing_type=...
ierror/django-js-reverse
django_js_reverse/templatetags/js_reverse.py
Python
mit
838
0
# -*- coding: utf-8 -*- from django import template from django.utils.safestring import mark_safe from django_js_reverse.core import generate_js try: from django.urls import get_resolver except ImportError: from django.core.urlresolvers import get_resolver register = template.Library() urlconf = template.V...
nf.
resolve(context) except template.VariableDoesNotExist: pass @register.simple_tag(takes_context=True) def js_reverse_inline(context): """ Outputs a string of javascript that can generate URLs via the use of the names given to those URLs. """ return mark_safe(generate_js(get_resolver(_ge...
JustinWingChungHui/electionleaflets
electionleaflets/apps/elections/admin.py
Python
mit
312
0.032051
from django.contrib import admin from elections.models impor
t Election class ElectionOptions(admin.ModelAdmin): list_display = ['name', 'country', 'active'] search_fields = ['name'] ordering = ['live_da
te'] admin.site.register( Election, ElectionOptions )
anewmark/galaxy_dark_matter
callmeanSB.py
Python
mit
1,365
0.035165
from defcuts import * from defflags import * from defclump import * import astropy.table as table indir='/Users/amandanewmark/repositories/galaxy_dark_matter/GAH/' outdir='/Users/amandanewmark/repositories/galaxy_dark_matter/lumprofplots/clumps/' datatab = table.Table.read(indir+ 'LOWZ_HSCGAMA15_apmgs.fits') band...
ss_flags', 'No Flags', 'Not Blended', 'Blended', 'blend'] daperture=[1.01,1.51,2.02,3.02,4.03,5.71,8.40,11.8,16.8,23.5] aperture=[x*0.5 for x in daperture] mincut= 17.5 maxcut=18.5 minz=0.25 maxz=0.35 colname='mag_aperture0' cutcolname='mag_aperture05' #cutcolname='mag_cmodel' datazcut, rangez=z_cut(datatab, minz...
utdata, parm, band) #this gets rid of multiple flags Flag, Not,lab= TFflag(band,Flags, newdata) TF_meanSB(Flag, Not, aperture, band, colname, lab,rangez, outdir)
rdio/sentry
src/sentry/models/event.py
Python
bsd-3-clause
5,941
0.000673
""" sentry.models.event ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import logging from django.db import models from django.utils import timezone from django.utils.datastructures import SortedDict from django.utils.tr...
) if user_data: va
lue = user_data.get('ip_address') if value: return value return None @memoize def user_ident(self): """ The identifier from a user is considered from several interfaces. In order: - User.id - User.email - User.username ...
Chandlercjy/OnePy
OnePy/sys_module/models/signals.py
Python
mit
4,404
0
from itertools import count from typing import Union from dataclasses import dataclass, field from OnePy.constants import ActionType, OrderType from OnePy.sys_module.components.exceptions import (OrderConflictError, PctRangeError) from OnePy.sys_module.metabase_env ...
nd obj_pct:
raise OrderConflictError("$ and pct can't be set together") if obj_pct: if not -1 < obj_pct < 1: raise PctRangeError("pct should be -1 < pct < 1") if name != 'price': if obj: if obj <= 0: raise ValueError(f"{name....
hb9kns/PyBitmessage
src/helper_generic.py
Python
mit
2,946
0.006789
import os import socket import sys from binascii import hexlify, unhexlify from multiprocessing import current_process from threading import current_thread, enumerate import traceback import shared from debug import logger import queues import shutdown def powQueueSize(): curWorkerQueue = queues.workerQueue.qsize...
pass return curWorkerQueue def convertIntToString(n): a = __builtins__.hex(n) if a[-1:] == 'L': a = a[:-1] if (len(a) % 2) == 0: return unhexlify(a[2:]) else: return unhexlify('0' + a[2:
]) def convertStringToInt(s): return int(hexlify(s), 16) def allThreadTraceback(frame): id2name = dict([(th.ident, th.name) for th in enumerate()]) code = [] for threadId, stack in sys._current_frames().items(): code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), threadId)) f...
gmarkall/numba
numba/cuda/tests/cudapy/test_inspect.py
Python
bsd-2-clause
7,182
0.000139
import numpy as np from io import StringIO from numba import cuda, float32, float64, int32, intp from numba.core.errors import NumbaDeprecationWarning from numba.cuda.testing import unittest, CUDATestCase from numba.cuda.testing import (skip_on_cudasim, skip_with_nvdisasm, skip_without_...
ays return a dict in future' self.assertIn(msg, str(warns.warnings[1])) def test_inspect_asm_deprecations(self): @cuda.jit((float32[::1],)) def f(x): x[0] = 0 with self.assertWarns(NumbaDeprecationWarning) as warns: f.inspect_asm(compute_capability=self.cc) ...
sertEqual(len(warns.warnings), 2) msg = 'The compute_capability kwarg is deprecated' self.assertIn(msg, str(warns.warnings[0])) msg = 'inspect_asm will always return a dict in future' self.assertIn(msg, str(warns.warnings[1])) @skip_without_nvdisasm('nvdisasm needed for inspect_sas...
Panos512/invenio
modules/bibformat/lib/elements/bfe_video_platform_suggestions.py
Python
gpl-2.0
5,845
0.00633
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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 ## ...
(', ')', '') for list_pos, rank in enumerate(ranking[1]): if rank >= threshold: similar_records.append(ranking[0][list_pos]) if shuffle: if maximum > len(similar_recor
ds): maximum = len(similar_records) return random.sample(similar_records, maximum) else: return similar_records[:maximum] def get_video_thumbnail(recid): """ Returns the URL and ALT text for a video thumbnail of a given record """ comments = get_fieldvalues(recid, '8564_z') ...
amirnissim/okqa
qa/migrations/0001_initial.py
Python
bsd-3-clause
6,711
0.008046
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Question' db.create_table('qa_question', ( ('id', self.gf('django.db.models.fiel...
ields.TextField')(max_length=255)), ('question', self.gf('django.db.models.fields.related.ForeignKey')(related_name='answers', to=orm['qa.Question'])), )) db.send_create_signal('qa', ['Answer']) def backwards(self, orm): # Deleting model 'Question' db.delete_table('qa_q...
'Answer' db.delete_table('qa_answer') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}...
Bitcoin-ABC/bitcoin-abc
test/functional/feature_block.py
Python
mit
54,112
0.001737
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Copyright (c) 2019 The Bitcoin developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test block processing.""" import copy import struct import ...
UM_BUFFER_BLOCKS_TO_GENERATE): blocks.append(self.next_blo
ck("maturitybuffer.{}".format(i))) self.save_spendable_output() self.send_blocks(blocks) # collect spendable outputs now to avoid cluttering the code later on out = [] for _ in range(NUM_OUTPUTS_TO_COLLECT): out.append(self.get_spendable_output()) # Star...
moremorefor/Logpot
logpot/auth/models.py
Python
mit
953
0.002099
#-*- coding: utf-8 -*- from logpot.ext import db from logpot.models import TimestampMixin from passlib.hash import pbk
df2_sha256 class User(db.Model, TimestampMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True, nullable=False) email = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) def is_authe...
is_anonymous(self): return False def get_id(self): return self.id @classmethod def generate_password_hash(self, password): return pbkdf2_sha256.encrypt(password) def check_password_hash(self, password): return pbkdf2_sha256.verify(password, self.password) def __st...
cloudify-cosmo/flask-securest
flask_securest/authorization_providers/role_based_authorization_provider.py
Python
apache-2.0
5,319
0.000188
######### # Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
oint,
target_method, user_roles, 'allow') def _is_denied(self, target_endpoint, target_method, user_roles): return self._evaluate_permission_by_type(target_endpoint, target_method, user_role...
svn2github/SVGKit
cgi-bin/convertsvg.py
Python
mit
3,564
0.008698
#!/usr/bin/python """ convertsvg.py 0.1 See <http://svgkit.sourceforge.net/> for documentation, downloads, license, etc. (c) 2006-2007 Jason Gallicchio. Licensed under the open source (GNU compatible) MIT License """ # Outline of code: # Read the SVG # Read the type to convert to # Read the options (width, height,...
esn't already exist in cached form, create it if not os.path.isfile(outname) or source!=open(svgname, 'r' ).read(): svgfile = open(svgname, 'w') svgfile.write(source) svgfile.
close() if type == 'svg': outname = svgname else: cmd = java+' -jar ' + batik + ' -d ' + results_dir + ' -m '+mime+' '+svgname # -dpi <resolution> -q <quality> execute_cmd(cmd) if type=='ps': inname = results_dir+md5hex+'.pdf' cmd = pdf2ps+' '+in...
windskyer/mvpn
mvpn/conf/opts.py
Python
gpl-2.0
2,699
0.000371
# Copyright 2015 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 requ...
s(module_names) _append_config_options(imported_modules, opts) return _tupleize(opts) def _list_module_names(): module_names = [] package_path = os.path.dirname(os.path.abspath(__file__)) for _, modname, ispkg in pkgutil.iter_modules(path=[package_path]): if modname == "opts" or ispkg: ...
import_modules(module_names): imported_modules = [] for modname in module_names: mod = importlib.import_module("mvpn.conf." + modname) if not hasattr(mod, LIST_OPTS_FUNC_NAME): msg = "The module 'mvpn.conf.%s' should have a '%s' "\ "function which returns the config...
praekelt/rapidpro
temba/channels/templatetags/channels.py
Python
agpl-3.0
246
0
from __future__ import un
icode_literals from django import template from temba.channels.views import get_channel_icon register = template.
Library() @register.filter def channel_icon(channel): return get_channel_icon(channel.channel_type)
wuxue/altanalyze
InteractionBuilder.py
Python
apache-2.0
45,237
0.02299
import sys, string import os.path import unique import export import gene_associations import traceback import time ################# Parse directory files def filepath(filename): fn = unique.filepath(filename) return fn def read_directory(sub_dir): dir_list = unique.read_directory(sub_dir) #add in c...
except Exception: None def verifyFile(filename): status = 'not found' try: fn=filepath(filename) for line in open(fn,'rU').xreadlines(): status = 'found';break except Exception: status = 'not found' return status def importInteractionDatabases(interactionDi...
signated by the user) """ exclude=[] for file in interactionDirs: status = verifyFile(file) if status == 'not found': exclude.append(file) for i in exclude: interactionDirs.remove(i) for fn in interactionDirs: #loop through each file in the directory to ou...
oVirt/mom
mom/Collectors/GuestIoTuneOptional.py
Python
gpl-2.0
528
0
from mom.Collectors.GuestIoTune import GuestIoTune class GuestIoTuneOptional(GuestIoTune): """ This Collector gets I
oTune statistics in the same way GuestIoTune does. The only difference is that it reports all the fields as optional and thus allows the policy to be evaluated even when the balloon device unavailable. """ def getFields(self):
return set() def getOptionalFields(self): return GuestIoTune.getFields(self).union( GuestIoTune.getOptionalFields(self))
villaverde/iredadmin
controllers/decorators.py
Python
gpl-2.0
1,054
0.001898
# Author: Zhang Huangbin <[email protected]> import web session = web.config.get('_session') def require_login(func): def proxyfunc(self, *args, **kw): if session.get('log
ged') is True: return func(self, *args, **kw) else: session.kill() raise web.seeother('/login?msg=loginRequired') return proxyfunc def require_global_admin(func): def proxyfunc(self, *args, **kw): if session.get('domainGlobalAdmin') is True: retu...
nc(self, *args, **kw) else: if session.get('logged'): raise web.seeother('/domains?msg=PERMISSION_DENIED') else: raise web.seeother('/login?msg=PERMISSION_DENIED') return proxyfunc def csrf_protected(f): def decorated(*args, **kw): inp = ...
buhe/judge
result.py
Python
agpl-3.0
368
0
class Result(object): AC = 0 WA = 1 << 0 RTE = 1 << 1 TLE = 1 << 2 MLE = 1 << 3 IR = 1 << 4 SC = 1 << 5 OLE = 1 << 6 IE = 1 << 30 def __init__(self): self.result_flag = 0 self.execution_time = 0 self.r_execution_time = 0 self.max_memory = 0 ...
put = ''
self.points = 0
GeyerA/android_external_chromium_org
chrome/tools/build/generate_policy_source.py
Python
bsd-3-clause
19,950
0.007719
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''python %prog [options] platform chromium_os_flag template platform specifies which platform source is being generated for and...
f len(args) != 3: print 'exactly platform, chromium_os flag and input file must be specified.' parser.print_help()
return 2 os = args[0] is_chromium_os = args[1] == '1' template_file_name = args[2] template_file_contents = _LoadJSONFile(template_file_name) policy_details = [ PolicyDetails(policy, os, is_chromium_os) for policy in _Flatten(template_file_contents) ] sorted_policy_details = sorted(po...
tejassp/asadmn-web
webapp/lib/logger.py
Python
unlicense
27,000
0.004148
__author__ = 'aerospike' import copy import ntpath from lib import logutil import os from lib.logsnapshot import LogSnapshot from lib.serverlog import ServerLog from lib.logreader import LogReader, SHOW_RESULT_KEY, COUNT_RESULT_KEY, END_ROW_KEY, TOTAL_ROW_HEADER from lib import terminal import re DT_FMT = "%b %d %Y %...
log_snapshot = self.create_log_snapshot(timestamp, file) self.selected_cluster_files[timestamp] = log_snapshot
self.all_cluster_files[timestamp] = log_snapshot snapshots_added += 1 else: error += ">>> Cannot add collectinfo file from asmonitor or any other log file other than collectinfo. Use the one generated by asadm (>=0.0.13). Ignoring " + file + " <<<\n" ...
AOtools/soapy
soapy/pyqtgraph/graphicsItems/ScatterPlotItem.py
Python
gpl-3.0
37,649
0.005179
from itertools import starmap, repeat try: from itertools import imap except ImportError: imap = map import numpy as np import weakref from ..Qt import QtGui, QtCore, USE_PYSIDE, USE_PYQT5 from ..Point import Point from .. import functions as fn from .GraphicsItem import GraphicsItem from .GraphicsObject import...
etSymbolCoords('t', 10, QPen(..), QBrush(..)) pm = atlas.getAtlas() """ def __init__(self): # symbol key : QRect(...) coordinates where symbol can be found in atlas. # note that the coordinate list will always be the same list object as # long as the symbol i
s in the atlas, but the coordinates may # change if the atlas is rebuilt. # weak value; if all external refs to this list disappear, # the symbol will be forgotten. self.symbolMap = weakref.WeakValueDictionary() self.atlasData = None # numpy array of atlas image self.atl...
cbitstech/Purple-Robot-Django
formatters/features_deviceinusefeature.py
Python
gpl-3.0
1,013
0.000987
# pylint: disable=line-too-long, unused-argument import json from django.template.loader import render_to_string def format_reading(probe_name, json_payload): item = json.loads(json_payload) status = item['DEVICE_ACTIVE'] if item['DEVICE_ACTIVE'] is True: status = "Active" elif item['DEVICE...
CTIVE'] is False: status = "Inactive" return status def visualize(probe_name, readings): report = [] for reading in readings: payload = json.loads(reading.payload) timestamp = payload['TIMESTAMP'] device_active = payload['DEVICE_ACTIVE'] if device_active is True...
device_active = 1 elif device_active is False: device_active = 0 rep_dict = {} rep_dict["y"] = device_active rep_dict["x"] = timestamp report.append(rep_dict) return render_to_string('visualization_device.html', {'probe_name': probe_name, 'readings': readin...
astrobin/astrobin
nested_comments/models.py
Python
agpl-3.0
2,677
0.000374
# Django from django.contrib.auth.models import User from common.utils import get_sentinel_user from toggleproperties.models import ToggleProperty try: # Django < 1.10 from django.contrib.contenttypes.generic import GenericForeignKey except ImportError: # Django >= 1.10 from django.contrib.contenttype...
blank
=True, related_name='children', on_delete=models.SET_NULL, ) deleted = models.BooleanField( default=False, ) pending_moderation = models.NullBooleanField() moderator = models.ForeignKey( User, related_name="moderated_comments", null=True, de...
stryder199/RyarkAssignments
Assignment2/ttt/archive/for_loops/for_continue.py
Python
mit
1,067
0.099344
import question_template game_type = 'input_output' source_language = 'C' parameter_list = [ ['$x1','int'],['$x2','int'],['$x3','int'],['$y0','int'], ] tuple_list = [ ['for_continue_', [0,1,2,None], [0,2,2,None], [0,4,2,None], [0,6,2,None], [0,7,2,None], [None,None,2,1], [None,None,2,2], [None...
arameter_list,tuple_li
st,global_code_template,main_code_template, argv_template,stdin_template,stdout_template)
mcus/SickRage
lib/feedparser/namespaces/itunes.py
Python
gpl-3.0
4,131
0.001695
# Support for the iTunes format # Copyright 2010-2015 Kurt McKee <[email protected]> # Copyright 2002-2008 Mark Pilgrim # All rights reserved. # # This file is a part of feedparser. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following con...
SINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import, unicode_literals ...
# Extra namespace 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes', } def _start_itunes_author(self, attrsD): self._start_author(attrsD) def _end_itunes_author(self): self._end_author() def _end_itunes_category(self): self._end_category() def _start_itunes_...
agendaTCC/AgendaTCC
tccweb/utils/storage.py
Python
gpl-2.0
415
0.004819
import unicodedata from django.core.files
.storage import FileSystemStorage class ASCIIFileSystemStorage(FileSystemStorage): """ Convert unicode characters in name to ASCII characters. """ def get_valid_name(
self, name): name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore') name = unicode(name) return super(ASCIIFileSystemStorage, self).get_valid_name(name)
maxisacson/sml-project
Henrik_Project/ensemble_methods.py
Python
mit
11,726
0.008272
import pandas as pd import numpy as np from six import iteritems from scipy import stats #from sklearn.feature_selection import SelectKBest, f_classif from sklearn.cross_validation import train_test_split from sklearn.ensemble import \ RandomForestRegressor, \ ExtraTreesRegressor, \ GradientBoostingRegr...
reco bjet3)', #'pt(reco bjet4)', 'eta(reco bjet4)', 'phi(reco bjet4)', 'm(reco bjet4)', 'pt(reco jet1)', 'eta(reco jet1)', 'phi(reco jet1)', 'm(reco jet1)', #'pt(reco jet2)', 'eta(reco jet2)', 'phi(reco jet2)', 'm(reco jet2)', 'nbjet' ] selected_displays = [ 'et(met)', 'pt(mc nuH)', 'pt(reco...
= 'et(met)' met_pred_parameter = 'pt(pred nuH)' met_reco_resolution = 'et(res met)' met_pred_resolution = 'pt(res pred nuH)' met_pred_ratio = 'pt(ratio nuH)' #mt_truth_parameter = 'mt(mc)' mt_reco_parameter = 'mt(net)' mt_pred_parameter = 'mt(pred)' pd.set_option('display.max_columns', 500) sample_200 = pd.read_csv('...
NetEaseGame/git-webhook
app/config_test.py
Python
mit
357
0
# -*- coding: utf-8 -*- DEBUG = True TES
TING = True SECRET_KEY = 'SECRET_KEY' DATABASE_URI = 'mysql+pymysql://root:[email protected]/git_webhook' CELERY_BROKER_URL = 'redis://:@127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://:@127.0.0.1:6379/0' SOCKET_MESSAGE_QUEUE = 'redis://:@127.0.0.1:6379/0' GITHUB_CLIENT_ID
= '123' GITHUB_CLIENT_SECRET = 'SECRET'
tdickers/mitmproxy
netlib/http/http2/connections.py
Python
mit
14,926
0.001072
from __future__ import (absolute_import, print_function, division) import itertools import time import hyperframe.frame from hpack.hpack import Encoder, Decoder from netlib import utils from netlib.http import url import netlib.http.headers import netlib.http.response import netlib.http.request from netlib.http.http2...
tingsFrame.MAX_HEADER_LIST_SIZE: None, } def __init__( self, tcp_handler=None, rfile=None, wfile=None, is_server=False, dump_frames=False, encoder=None, decoder=None, unhandled_frame_cb
=None, ): self.tcp_handler = tcp_handler or TCPHandler(rfile, wfile) self.is_server = is_server self.dump_frames = dump_frames self.encoder = encoder or Encoder() self.decoder = decoder or Decoder() self.unhandled_frame_cb = unhandled_frame_cb self.http2_sett...
exa-analytics/exatomic
exatomic/qe/pw/input.py
Python
apache-2.0
1,703
0.006459
# -*- coding: utf-8 -*- # Copyright (c) 2015-2022, Exa Analytics Development Team # Distributed under the terms of the Apache License 2.0 #''' #PW Module Input File Editor #==================================== # #''' #import numpy as np #from exatomic.exa import DataFrame #from exatomic import Length, Frame, Atom #from...
def parse_cell(s
elf): # ''' # Determine the type of unit cell being used. # ''' # ibrav = int(list(self.find('ibrav').values())[0].split('=')[1]) # if ibrav == 1: # a = np.float64(list(self.find('celldm(1)').values())[0].split('=')[1]) # frame = self.frame # frame['xi...
BLavery/PiBlynk
PiBlynk-py/32-bridge-in.py
Python
mit
1,523
0.013132
# This example is designed to be paired with example file 31-bridge-out.py # Run the two with DIFFERENT DEVICE TOKENS. # (They can be either in same "project" or separate projects as set at phone. Just use different tokens.) # This "in" bridge receives data directly from other RPi. # Our display shows incoming messag...
coming messages ...") blynk.on_connect(cnct_cb) ####################################################################################
## blynk.run() ###################################################################################### #At APP: # Nothing
nortikin/sverchok
nodes/object_nodes/getsetprop.py
Python
gpl-3.0
9,277
0.003342
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
y parse_to_path will fail if path is invalid ''' curr_object = globals()[path[0][1]] for t, value in path[1:]: if t == "attr": curr_object = getattr(curr_object, value) elif t == "key": curr_object = curr_object[value] return curr_object def apply_alias(eval_...
sn't an bpy path ''' if not eval_str.startswith("bpy."): for alias, expanded in aliases.items(): if eval_str.startswith(alias): eval_str = eval_str.replace(alias, expanded, 1) break if not eval_str.startswith("bpy."): raise NameError re...
claudep/pootle
pootle/core/markup/filters.py
Python
gpl-3.0
5,520
0
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from django.conf import settings from django...
rent markup filter's name.""" name = get_markup_filter()[0] return 'html' if name is None else name def get_markup_filter_display_name(): """Returns a nice version for the current markup filter's name.""" name = get_markup_filter_name() return { 'textile': u'Textile', 'markdown': u...
u'reStructuredText', }.get(name, u'HTML') def get_markup_filter(): """Returns the configured filter as a tuple with name and args. If there is any problem it returns (None, ''). """ try: markup_filter, markup_kwargs = settings.POOTLE_MARKUP_FILTER if markup_filter is None: ...
anhstudios/swganh
data/scripts/templates/object/building/player/shared_player_house_naboo_medium_style_01.py
Python
mit
479
0.045929
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/player/shared_player_house_naboo_medium_style_01.iff" result.attrib...
te_template_id = -1 result.stfName("building_name","housing_naboo_medium") #### BEGIN MODIFICATIONS #### #### EN
D MODIFICATIONS #### return result
JT5D/scikit-learn
setup.py
Python
bsd-3-clause
5,576
0.002331
#! /usr/bin/env python # # Copyright (C) 2007-2009 Cournapeau David <[email protected]> # 2010 Fabian Pedregosa <[email protected]> descr = """A set of python modules for machine learning and data mining""" import sys import os import shutil from distutils.command.clean import clean as Clean i...
2 and ('--help' in sys.argv[1:] or sys.argv[1] in ('--help-commands', 'egg_info', '--version', 'clean'))): # For these actions, NumPy is not required. # # They are required to succeed without Numpy for example when # pip is used to install Scikit when Numpy ...
ort setup except ImportError: from distutils.core import setup metadata['version'] = VERSION else: from numpy.distutils.core import setup metadata['configuration'] = configuration setup(**metadata) if __name__ == "__main__": setup_package()
Chasego/codirit
leetcode/074-Search-a-2D-Matrix/Searcha2DMatrix_001.py
Python
mit
608
0.009868
class Solution: # @param {integer[][]} matrix # @param {integer} target
# @return {boolean} def se
archMatrix(self, matrix, target): if len(matrix) == 0 or len(matrix[0]) == 0: return False m , n = len(matrix), len(matrix[0]) l, r = 0, m * n - 1 while l <= r: mid = (l + r) / 2 i, j = mid / n, mid % n if matrix[i][j]...
FiloSottile/Griffith-mirror
lib/plugins/export/PluginExportCSV.py
Python
gpl-2.0
3,429
0.005833
# -*- coding: UTF-8 -*- __revision__ = '$Id$' # Copyright (c) 2005-2007 Vasco Nunes # # 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...
'layers', 'region', 'media_num', 'vcodecs.name')
def run(self): basedir = None if self.config is not None: basedir = self.config.get('export_dir', None, section='export-csv') if not basedir: filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \ butto...
apatriciu/OpenStackOpenCL
computeOpenCL/nova/nova/tests/OpenCL/testOpenCLInterfaceMemoryObjects.py
Python
apache-2.0
4,684
0.00491
from nova.OpenCL import OpenCLContextsAPI from nova.OpenCL import OpenCLClientException from nova.OpenCL import OpenCLBuffersAPI import unittest import sys class LaptopResources: listDevicesIDs = [0] dictProperties = {} memID = 0 invalidMemID = 1 device_type = "GPU" class TestMems(unittest.TestCas...
fferProperty, retErr = self.buffers_interface.GetBufferProperties(bufferID) self.assertEqual(bufferProperty['id'], bufferID) self.assertEqual(bufferProperty['Size'], bufferSize) self.assertEqual(bufferProperty['Context'], self.contextID) retErr = self.buffe
rs_interface.ReleaseBuffer(bufferID) self.assertEqual(retErr, 0) listBuffers = self.buffers_interface.ListBuffers() self.assertEqual(listBuffers, []) def testGetUnknownContextProperties(self): # Tries to retrieve the properties of an inexistent device bufferID = 0 se...
Kryz/sentry
tests/sentry/plugins/interfaces/test_releasehook.py
Python
bsd-3-clause
1,132
0
""" sentry.plugins.base.structs ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LIC
ENSE for more details. """ from __future__ import absolute_import, print_function __all__ = ['ReleaseHook'] from sentry.models import Release from sentry.plugins import ReleaseHook from sentry.testutils import TestCase class StartReleaseTest(TestCase): def test_minimal(self): project = self.create_proj...
ok(project) hook.start_release(version) release = Release.objects.get( project=project, version=version, ) assert release.date_started class FinishReleaseTest(TestCase): def test_minimal(self): project = self.create_project() version = 'bbee...
SciTools/cartopy
examples/lines_and_polygons/always_circular_stereo.py
Python
lgpl-3.0
1,610
0
""" Custom Boundary Shape --------------------- This example demonstrates how a custom shape geometry may be used instead of the projection's default boundary. In this instance, we define the boundary as a circle in axes coordinates. This means that no matter the extent of the map itself, the boundary will always be ...
# for the map. We can pan/zoom as much as we like - the boundary will be # permanently circular. theta = np.linspace(0, 2*np.pi, 100) center,
radius = [0.5, 0.5], 0.5 verts = np.vstack([np.sin(theta), np.cos(theta)]).T circle = mpath.Path(verts * radius + center) ax2.set_boundary(circle, transform=ax2.transAxes) plt.show() if __name__ == '__main__': main()
alexlo03/ansible
lib/ansible/plugins/cliconf/enos.py
Python
gpl-3.0
2,594
0.000771
# (C) 2017 Red Hat Inc. # Copyright (C) 2017 Lenovo. # # GNU General Public License v3.0+ # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHAN
TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # Contains CLIConf Plugin methods for ENOS Modules # Lenovo Networking #
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from itertools import chain from ansible.module_utils._text import to_bytes, to_text from ansible.module_utils.network.common.utils import to_list from ansible.plugins.cliconf import CliconfBase, enable_mode...
xuru/pyvisdk
pyvisdk/do/virtual_usbxhci_controller_option.py
Python
mit
1,380
0.01087
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def VirtualUSBXHCIControllerOption(vim, *args, **kwargs): '''The VirtualUSBXHCIController...
if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expec
ted one of %s" % (name, ", ".join(required + optional))) return obj
bitmazk/django-document-library
document_library/templatetags/document_library_tags.py
Python
mit
1,256
0
"""Templatetags for the ``document_library`` app.""" from django import template from ..models import Document register = template.Library() @register.assignment_tag def get_files_for_document(document): """ Returns the available files for all languages. In case the file is already present in another ...
ext=True) def get_frontpage_documents(context): """Returns the library favs that should be shown on the front page.""" req = context.get('request') qs = Document.objects.published(req).filter(is_on_front_page=True) return qs @register.assignment_tag(takes_context=True) def get_latest_documents(context...
efaults to 5. """ req = context.get('request') qs = Document.objects.published(req)[:count] return qs
grantjenks/pyannote-core
pyannote/core/__init__.py
Python
mit
1,810
0.00387
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 CNRS # 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 ...
INGS IN THE # SOFTWARE. # AUTHORS # Hervé BREDIN - http://herve.niderb.fr from ._version import get_versions __version__ = get_versions()['version'] del get_versions PYANNOTE_URI = 'uri' PYANNOTE_MODALITY = '
modality' PYANNOTE_SEGMENT = 'segment' PYANNOTE_TRACK = 'track' PYANNOTE_LABEL = 'label' PYANNOTE_SCORE = 'score' PYANNOTE_IDENTITY = 'identity' from .time import T, TStart, TEnd from .segment import Segment, SlidingWindow from .timeline import Timeline from .annotation import Annotation from .transcription import Tra...
foursquare/pants
tests/python/pants_test/backend/codegen/ragel/java/test_ragel_gen.py
Python
apache-2.0
2,263
0.006186
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from textwrap import dedent from pants.backend.codegen.ragel.jav
a.java_ragel_library import JavaRagelLibrary from pants.backend.codegen.ragel.java.ragel_gen import RagelGen, calculate_genfile from pants.util.contextu
til import temporary_file from pants.util.dirutil import safe_mkdtemp from pants_test.task_test_base import TaskTestBase ragel_file_contents = dedent(""" package com.example.atoi; %%{ machine parser; action minus { negative = true; } action digit { val *= 10; val += fc - '0'; } main := ( '-...
OTL/ros_book_programs
ros_start/scritps/joy_twist.py
Python
bsd-2-clause
644
0.003106
import rospy from sensor_msgs.msg import Joy from geometry_msgs.msg import Twist class JoyTwist(object): def __init__(self): self._joy_sub = rospy.Subscriber('joy', Joy, self.joy_callback, queue_size=1) self._twist_pub = rospy.Publisher('cmd_vel
', Twist, queue_size=1) def joy_callback(self, joy_msg): if joy_msg.buttons[0] == 1: twist = Twist() twist.linear.x = joy_msg.axes[1] * 0.5 twist.
angular.z = joy_msg.axes[0] * 1.0 self._twist_pub.publish(twist) if __name__ == '__main__': rospy.init_node('joy_twist') joy_twist = JoyTwist() rospy.spin()
rowhit/tagfs
src/test/tagfs_test_small/test_freebase_support_query.py
Python
gpl-3.0
1,239
0.003228
# # Copyright 2012 Markus Pielmeier # # This file is part of tagfs. # # tagfs 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. # # tagfs...
elf): self.assertEqual(self.query.queryString, '{"filter":"filterValue
","selector":[]}')
Comunitea/CMNT_00098_2017_JIM_addons
picking_company_sequence/__manifest__.py
Python
agpl-3.0
632
0.00317
# -*- coding: utf-8 -*- # © 2016 Comunitea Servicios Tecnologicos (<http://www.comunitea.com>) # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Stock picking company sequence', 'version': '10.0',
'author': 'Comunitea, ', "category": "", 'license': 'AGPL-3', 'description': 'Allow different sequence per company', 'depends': [ 'stock' ], 'contributors': [ "Comunitea", "Kiko Sanchez<[email protected]>"] , "data": [ 'views/stock_picking_type.xml' ...
mo": [ ], 'test': [ ], 'installable': True }
DevynCJohnson/Pybooster
pylib/neuralnet.py
Python
lgpl-3.0
13,720
0.002041
#!/usr/bin/env python3 # -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*- # vim: set fileencoding=utf-8 filetype=python syntax=python.doxygen fileformat=unix tabstop=4 expandtab : # kate: encoding utf-8; bom off; syntax python; indent-mode python; eol unix; replace-tabs off; indent-width 4; tab-...
range(self.iterations): used_iterations = i if error <= self.error_threshold: # Error Threshold
break _sum = 0.0 for d in self.io_rules: self.run(d[0]) self._calculate_deltas(d[1]) # Adjust Weights for _layer in range(1, self.outputlayer + 1): incoming = self.outputs[_layer - 1] ...
JioCloud/oslo.config
tests/test_cfgfilter.py
Python
apache-2.0
9,272
0
# Copyright 2014 Red Hat, 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 agre...
laa) self.assertIn('bar', self.fconf.blaa) self.assertNotIn('blaa', self.conf) def test_register_cli_opt_grouped(self): self.fconf.register_cli_opt(cfg.StrOpt('foo'), group=
'blaa') self.assertIn('foo', self.fconf.blaa) self.assertNotIn('blaa', self.conf) def test_register_cli_opts_grouped(self): self.fconf.register_cli_opts([cfg.StrOpt('foo'), cfg.StrOpt('bar')], group='blaa') self.assertIn('foo', self.fconf.blaa) ...
ludusrusso/arduino-compiler-web
manage.py
Python
gpl-2.0
725
0.01931
#!/usr/bin/env python import os from app import create_app # , db # from app.models import User, Role from flask.ext.script import Manager, Shell # from flask.ext.migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Mana
ger(app) # migrate = Migrate(app, db) def make_shell_context(): return dict(app=app) # , db=db, User=User, Role=Role) manager.add_command("shell", Shell(make_context=make_shel
l_context)) # manager.add_command('db', MigrateCommand) @manager.command def test(): """Run the unit tests.""" import unittest tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests) if __name__ == '__main__': manager.run()
open-mmlab/mmdetection
configs/cascade_rcnn/cascade_mask_rcnn_x101_32x8d_fpn_mstrain_3x_coco.py
Python
apache-2.0
1,878
0
_base_ = './cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py' model = di
ct( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=8, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='pytorch', init_cfg=dict( type='Pretrained'...
2/resnext101_32x8d'))) # ResNeXt-101-32x8d model trained with Caffe2 at FB, # so the mean and std need to be changed. img_norm_cfg = dict( mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395], to_rgb=False) # In mstrain 3x config, img_scale=[(1333, 640), (1333, 800)], # multiscale_mode='range' t...
rcbops/melange-buildpackage
melange/ipv6/rfc2462_generator.py
Python
apache-2.0
1,519
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/...
t_ip(self): address = self._deduce_ip_address() next_mac = int(self._mac_address) + 1 self._mac_address = netaddr.EUI(next_mac) return address def _deduce_ip_address(self): variable_segment = self._variable_segment()
network = netaddr.IPNetwork(self._cidr) return str(variable_segment & network.hostmask | network.cidr.ip) def _variable_segment(self): mac64 = self._mac_address.eui64().words int_addr = int(''.join(['%02x' % i for i in mac64]), 16) return netaddr.IPAddress(int_addr) ^ netaddr....
svn2github/pyopt
pyOpt/pyOpt_history.py
Python
gpl-3.0
7,012
0.056047
#!/usr/bin/env python ''' pyOpt_history Holds the Python Design Optimization History Class. Copyright (c) 2008-2014 by pyOpt Developers All rights reserved. Revision: 1.0 $Date: 11/12/2009 21:00$ Developers: ----------- - Dr. Ruben E. Perez (RP) - Mr. Peter W. Jansen (PJ) History ------- v. 1.0 - Initial Class...
write ('w') mode **Keyword arguments:** - optimizer -> INST: Opimizer class instance, *Default* = None - opt_prob -> STR: Optimization Problem Name, *Default* = None Documentation last updated: April.
14, 2010 - Peter W. Jansen ''' # self.filename = filename self.mode = mode # bin_name = filename + '.bin' cue_name = filename + '.cue' #opt_name = filename + '.opt' # if self.mode == 'w': # if os.path.isfile(bin_name): os.remove(bin_name) #end if os.path.isfile(cue_nam...
berrange/nova
nova/tests/console/test_websocketproxy.py
Python
apache-2.0
4,576
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
nt) check_token.assert_called_with(mock.ANY, token="XXX") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.soc...
.return_value = "token=123-456-789" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token="123-456-789") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('<socket>') @mock.patch('nova.consoleauth.rpcapi.Con...
guerinj/expenses-api
api.py
Python
apache-2.0
1,733
0.003462
from flask import Flask from flask import jsonify, request from flask.ext import restful from flask.ext.pymongo import PyMongo, ObjectId import ipdb; app = Flask(__name__) app.config['MONGO_DBNAME'] = "expenses" mongo = PyMongo(app) api = restful.Api(app) class Expense(restful.Resource): def get(self...
"value"], _id=str(exp["_id"]), date=exp["_id"].generation_time) def post(self): ipdb.set_trace() if not 'value' in request.json or type(request.json["value"]) not in [float, int, long]: return "Bad Request", 400 expense_id = mongo.db.expenses.insert({"value": request.json["...
xpense_id = None): if expense_id is None: return "Bad Request", 400 mongo.db.expenses.remove({"_id": ObjectId(expense_id)}) return "OK", 200 api.add_resource(Expense, '/expenses/<string:expense_id>', '/expenses') if __name__ == '__main__': app.run(debug=True, host= ...
Flexget/Flexget
flexget/plugins/clients/pyload.py
Python
mit
9,436
0.001166
from urllib.parse import quote from loguru import logger from requests.exceptions import RequestException from flexget import plugin from flexget.config_schema import one_or_more from flexget.event import event from flexget.utils import json from flexget.utils.template import RenderError logger = logger.bind(name='p...
parsed = result.json() urls = entry.get('urls', []) # check for preferred hoster for name in hoster: if name in parsed: urls.extend(parsed[name]) if not config.get('multiple_hoster', self.DEFAULT_MULTIPLE_HOSTER): ...
# no preferred hoster and not preferred hoster only - add all recognized plugins if not urls and not config.get( 'preferred_hoster_only', self.DEFAULT_PREFERRED_HOSTER_ONLY ): for name, purls in parsed.items(): if name != 'BasePlugin': ...
ikn/brjaf
brjaf/ext/evthandler.py
Python
gpl-3.0
12,404
0.002338
"""Pygame event handler by J. This module consists of the EventHandler class, which is used to assign callbacks to events and keypresses in Pygame. Release: 12. Licensed under the GNU General Public License, version 3; if this was not included, you can find it here: http://www.gnu.org/licenses/gpl-3.0.txt """ ...
self._call_key_cbs(cb_data[0], key_data, press_type, mods) def add_event
_handlers (self, event_handlers): """Add more event handlers. Takes an event_handlers argument in the same form as expected by the constructor. """ for e, cbs in event_handlers.iteritems(): cbs = self._clean_cbs(cbs) try: self.event_handlers[e] += cbs ...
ATNF/askapsdp
3rdParty/casacore/casacore-1.6.0a/build.py
Python
gpl-2.0
1,801
0.004442
import os.path from askapdev.rbuild.builders import CMake as Builder import askapdev.rbuild.utils as utils # CMake doesn't know about ROOT_DIR for blas and lapack, so need to # explicitly name them. Want to use the dynamic libraries in order # to avoid link problems with missing FORTRAN symbols. platform = utils.g...
option("-DLAPACK_LIBRARIES=%s" % os.path.join(lapack, 'lib', liblapack)) # these work builder.add_option("-DCFITSIO_ROOT_DIR=%s" % cfitsio) builder.add_option("-DWCSLIB_ROOT_DIR=%s" % wcslib) # but FFTW3_ROOT_DIR don't for the include part builder.add_option("-DFFTW3_DISABLE_THREADS=ON") builder.add_option("-DFFTW3_ROO...
w3) builder.add_option("-DFFTW3_INCLUDE_DIRS=%s/include" % fftw3) builder.add_option("-DUSE_FFTW3=ON") # save some time builder.add_option("-DBUILD_TESTING=OFF") builder.nowarnings = True # Force use of raw GNU compilers. This is due to bug #5798 soon on the Cray XC30. # Builds using the newer cmake (2.8.12) fail when...
lberruti/ansible
test/units/parsing/test_unquote.py
Python
gpl-3.0
2,073
0
# coding: utf-8 # (c) 2015, Toshio Kuratomi <[email protected]> # # This file is part of Ansible # # Ansible 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 o...
CHANTABILITY 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, divi...
test generators cannot use unittest base class. # http://nose.readthedocs.org/en/latest/writing_tests.html#test-generators class TestUnquote: UNQUOTE_DATA = ( (u'1', u'1'), (u'\'1\'', u'1'), (u'"1"', u'1'), (u'"1 \'2\'"', u'1 \'2\''), (u'\'1 "2"\'', u'1 "...
OpenLinkedSocialData/gmane3
gmane-org-user-groups-linux-brazil-slackware/scripts/testTriplify2.py
Python
cc0-1.0
2,417
0.023583
import importlib, os import multiprocessing as mp from IPython.lib.deepreload import reload as dreload import gmane as g, percolation as P G=g c=P.utils.check importlib.reload(g.listDataStructures) importlib.reload(g.loadMessages) importlib.reload(g.triplifyList) importlib.reload(P.rdf) importlib.reload(P.utils) impor...
nel.general',"gmane.comp.video.ffmpeg.user","gmane.comp.mathematics.maxima.general", "gmane.politics.activism.neurogreen","gmane.comp.encr
yption.openssl.user","gmane.org.user-groups.linux.brazil.slackware", "gmane.comp.apache.user","gmane.comp.python.pygame",'gmane.science.linguistics.wikipedia.deutsch', 'gmane.politics.election-methods','gmane.linux.redhat.rpm.general','gmane.comp.db.postgresql.brasil.user'][4:]: c(list_id) ...
dmlc/tvm
python/tvm/relay/transform/fake_quantization_to_integer.py
Python
apache-2.0
15,868
0.001765
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
, TensorAffineType(expr.args[1], expr.args[2], expr.attrs.out_dtype, expr.attrs.axis), ] def register_unary_identity(op_name): def identity(expr, type_map): assert len(expr.args) == 1 arg = expr.args[0] t = type_map[arg] return [expr, t] return register_fake_quanti...
e") register_unary_identity("expand_dims") register_unary_identity("nn.max_pool2d") register_unary_identity("nn.batch_flatten") register_unary_identity("nn.depth_to_space") register_unary_identity("max") register_unary_identity("min") @register_fake_quantization_to_integer("nn.avg_pool2d") def avgpool2d(expr, type_ma...
prmtl/fuel-web
shotgun/shotgun/logger.py
Python
apache-2.0
1,285
0
# Copyright 2013 Mirantis, 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 Lic
ense 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. import logging from shotgun.settings import LOG_FILE def configure_logger(): """Conf...
mbarylsk/goldbach-partition
goldbach-fast_conf-prim_check-distr.py
Python
gpl-3.0
3,474
0.012953
# # Copyright (c) 2016 - 2017, Marcin Barylski # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of con...
s: f
or n in chunk: p1 = 3 p2 = n - p1 (p1, p2, d, iters) = gp.search_for_partition (p1, p2, lambda i: gp.delta_prime(i)) perc = int (100 * i / n_of_chunks) print (" Chunk #", i, ":", chunk, "verified (", perc, "% completed )") i+= 1 print ("DONE")
yarikoptic/NiPy-OLD
nipy/neurospin/datasets/setup.py
Python
bsd-3-clause
390
0.005128
def configuration(parent_package='',to
p_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('datasets', parent_package, top_path) config.add_subpackage('volumes') config.add_subpackage('transforms') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**confi...
ration(top_path='').todict())
kwikiel/bounce
models.py
Python
mit
427
0
from app import db class Alternative(db.Model): id = db.Column(db.Integer, primary
_key=True) experiment = db.Column(db.String(500), unique=True) copy = db.Column(db.String(2500)) def __init__(self, id, experiment, copy): self.id = id self.experiment = experiment self.copy = copy def __repr__(self): return "<Alt {0} {1} {2}>".format(self.id, self.expe...
copy)
thesave/SublimeLinter-contrib-lacheck
linter.py
Python
mit
650
0.010769
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Saverio Giallorenzo # Copyright (c) 2018 Saverio Giallorenzo # # License: MIT # from SublimeLinte
r.lint import Linter, util # or NodeLinter, PythonLinter, ComposerLinter, RubyLinter
class Lacheck(Linter): cmd = 'lacheck ${file}' error_stream = util.STREAM_BOTH regex = ( r'.+, line (?P<line>\d+): (?:(possible unwanted space at "{")|(?P<message>.+))' ) defaults = { 'selector': 'text.tex.latex - meta.block.parameters.knitr - source.r.embedded.knitr', } ...
s0r00t/ISN-DTMF
main.py
Python
gpl-3.0
2,967
0.032501
#!/usr/bin/env python3 from tkinter import * #ttk = themed tkinter (excepté sous linux visiblement) from tkinter.ttk import * from dtmf import convertDTMF from wave import open dialWindow = Tk() dialWindow.title("DTMF Dialer") #NOTE: le nombre demandé est une string car d'après le standard DTMF il peut contenir les le...
kground="white", font="serif 30", width=3, foreground="green") #le bouton pour raccrocher Style(dialWindow).configure("Hang.TButton", background="white", font="serif 30", width=3, foreground="red") def appendNumber(digit): """ Fonction appelée dès qu'un bouton de composition est pressé. """ global number if len(n...
e des fonctions définies dans dtmf.py. """ nb = number.get() if nb == '': return #on évite de créer un fichier vide si il n'y a pas de numéro finalList, spl = convertDTMF(nb, f, duree, amp) #NOTE: pourquoi utiliser une liste afin de stocker les signaux? #parce qu'ainsi writeframes n'est appelé qu'une seule fois,...
elbeardmorez/quodlibet
quodlibet/quodlibet/formats/_serialize.py
Python
gpl-2.0
6,347
0.000788
# -*- coding: utf-8 -*- # Copyright 2016 Christoph Reiter # # 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. """Code for...
return dummy if module.split(".")[0] not in ("quodlibet", "tests"): return real_type # return a straight dict subclass so that unpickle doesn't call # our __setitem__. Further down we simply change the __class__
# to our real type. if not real_type in temp_type_cache: new_type = type(name, (dict,), {"real_type": real_type}) temp_type_cache[real_type] = new_type return temp_type_cache[real_type] try: items = pickle_loads(data, lookup_func) except pickle.UnpicklingErr...
vgaonkar/GaveltonLibrary-Python
GaveltonLibrary/main.py
Python
gpl-3.0
2,980
0.007047
#main.py #Gaonkar, Vijay #vrgaonkar from __future__ import print_function from SearchEngine import SearchEngine search_engine = SearchEngine() results = [] choice = 0 while choice != 5: print("\n\t\t\t ############################### GAVELTON LIBRARY ############################### \n" "\n Welcome! Lo...
************************ ") for item in results: item.display() else: print("\n Sorry no results found with <" + search_str + "> in call number") elif choice == 2:
results = search_engine.search_by_title(search_str) if len(results) > 0: print("\t\t\t ************************** Search Results ************************** ") for item in results: item.display() else: print("\n Sorry no results found with <" + search...
mrknow/filmkodi
plugin.video.mrknow/mylib/tests_pydevd_mainloop/gui-gtk.py
Python
apache-2.0
840
0.002381
#!/usr/bin/env python """Simple GTK example to manually test event loop integration. To run this: 1) Enable the PyDev GUI event loop integration for gtk 2) do an execfile on this script 3) ensure you have a working GUI simultaneously with an interactive console """ if __name__ == '__main__': imp
ort pygtk pygtk.require('2.0') import gtk def hello_world(wigdet, data=None): print("Hello World") def delete_event(wi
dget, event, data=None): return False def destroy(widget, data=None): gtk.main_quit() window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("delete_event", delete_event) window.connect("destroy", destroy) button = gtk.Button("Hello World") button.connect("clicked", hello_worl...
vkosuri/ChatterBot
tests/logic/test_mathematical_evaluation.py
Python
bsd-3-clause
4,970
0.000402
from tests.base_case import ChatBotTestCase from chatterbot.logic import MathematicalEvaluation from chatterbot.conversation import Statement class MathematicalEvaluationTests(ChatBotTestCase): def setUp(self): super().setUp() self.adapter = MathematicalEvaluation(self.chatbot) def test_can_...
, 1) def test_e_constant(self): statement = Statement(text='What is e plus one ?') response = self.adapter.process(statement) self.as
sertEqual(response.text, 'e plus one = 3.718281') self.assertEqual(response.confidence, 1) def test_log_function(self): statement = Statement(text='What is log 100 ?') response = self.adapter.process(statement) self.assertEqual(response.text, 'log 100 = 2.0') self.assertEqua...
orende/intro-till-python
ex5d.py
Python
mit
173
0.011561
def fizzbuzz(x): return 'fizzbuzz' if x % 15 == 0 else 'fizz' if x % 3
== 0 else 'buzz' if x % 5 == 0 else x for y in [fizz
buzz(x) for x in range(1, 101)]: print y
pyblish/pyblish-nukestudio
pyblish_nukestudio/__init__.py
Python
lgpl-3.0
108
0
from .version
import * from .lib import ( show, setup, register_plugins
, add_to_filemenu, )
drufat/vispy
examples/benchmark/simple_glut.py
Python
bsd-3-clause
1,363
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # vispy: testskip # ----------------------------------------------------------------------------- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ------------------------------------------------------...
t.glutInitDisplayMode( glut.GLUT_DOUBLE | glut.GLUT_RGB
| glut.GLUT_DEPTH) glut.glutInitWindowSize(512, 512) glut.glutCreateWindow("Do nothing benchmark (GLUT)") glut.glutDisplayFunc(on_display) glut.glutKeyboardFunc(on_keyboard) t0, frames, t = glut.glutGet(glut.GLUT_ELAPSED_TIME), 0, 0 glut.glutIdleFunc(on_idle) glut.glutMainLoop()
chen940303/Diaosier_home
app/decorators.py
Python
mit
698
0.013289
#-*-coding:utf-8-*- from functools import wraps from flask import abort from flask.ext.login import current_user from models import Permission def permission_required(permission): #用于检查权限,就像检查登陆一样 def decorator(f): @wraps(f) def decorated_function(*arg
s, **kwargs): if not current_user.can(permission): abort(403) #程序如果这里出错中断,跳转 return f(*args, **kwargs) return decorated_function return decorator #闭包开发做修饰器,带参数返回两层, def admin_required(f): return permission_required(Permissio
n.ADMINISTER)(f) #检查了administer
MaximumRoot/MaxRootWeb
webMaker/maxrootweb.py
Python
mit
718
0.01532
import os import shutil def pre_read(dir): try: filelist = os.listdir(dir) for file in filelist: if os.path.isdir(file): # exception directory
if str(file) == 'webMager' or str(file) == '_site': continue
pre_read(file) else: # read *_main.maxroot file ext = str(file) if ext.endswith('_main.maxroot'): # load... a=1 except PermissionError: pass os.chdir('..') root_path = os.path.abspa...
springmerchant/pybbm
pybb/models.py
Python
bsd-2-clause
17,800
0.002303
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models, transaction, DatabaseError from django.template.defaultfilters import slugify from django.utils.encoding import python_2_unicode_compatible from django.utils.functional import cach...
), b
lank=True) post_count = models.IntegerField(_('Post count'), blank=True, default=0) readed_by = models.ManyToManyField(get_user_model_path(), through='TopicReadTracker', related_name='readed_topics') on_moderation = models.BooleanField(_('On moderation'), default=False) poll_type = models.IntegerField(_...
GetStream/stream-python
setup.py
Python
bsd-3-clause
2,165
0.000462
#!/usr/bin/env python from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand from stream import __version__, __maintainer__, __email__, __license__ import sys tests_require = ["pytest", "unittest2", "pytest-cov", "python-dateutil"] ci_require = ["black", "flake8", "pytest...
s(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(["-v", "--cov=./"]) sys.exit(errno) setup( name="stream-py...
description="Client for getstream.io. Build scalable newsfeeds & activity streams in a few hours instead of weeks.", long_description=long_description, long_description_content_type="text/markdown", license=__license__, packages=find_packages(), zip_safe=False, install_requires=install_requi...
librallu/cohorte-herald
python/herald/transports/bluetooth/__init__.py
Python
apache-2.0
1,915
0.000522
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Herald Bluetooth transport implementation :author: Luc Libralesso :copyright: Copyright 2014, isandlaTech :license: Apache License 2.0 :version: 0.0.3 :status: Alpha .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0 (the "Licen...
e 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. """ # Documentation strings format __docformat__ = "restructuredtext en" # ------------------------------------------------...
cernops/python-neutronclient
neutronclient/tests/unit/test_cli20_port.py
Python
apache-2.0
21,891
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 requ...
-server', 'opt_value': '123.123.123.123'}, {'opt_name': 'server-ip-address', 'opt_valu
e': '123.123.123.45'}] args = [netid] for dhcp_opt in extra_dhcp_opts: args += ['--extra-dhcp-opt', ('opt_name=%(opt_name)s,opt_value=%(opt_value)s' % dhcp_opt)] position_names = ['network_id', 'extra_dhcp_opts'] position_values = [n...
bloodstalker/mutator
bruiser/wasm/dwasm.py
Python
gpl-3.0
855
0.005848
#!/usr/bin/python3 import argparse import code import readline import signal import sys from parse import Argparser, premain, SigHandler_SIGINT,PythonInterpreter
from utils import ParseFlags def getWASMModule(): module_path = sys.argv[1] interpreter = PythonInterpreter() module = interpreter.parse(module_path) def main(): signal.signal(signal.SIGINT, SigHandler_SIGINT) argparser = Argparser() if argparser.args.dbg: try: premain(argp...
aseli1/dm_excel_form_builder
setup.py
Python
mit
487
0
from setupt
ools import setup setup(name='excel_form_builder', version='0.1.1', description='Convert Word/PDF documents to Excel Workbooks', url='https://github.com/aseli1/dm_excel_form_builder', author='Anthony Seliga', author_email='[email protected]', license='MIT', packages=['e...
, 'colorama', ], scripts=['bin/create_form'], zip_safe=False)
luoyetx/mxnet
example/image-classification/common/fit.py
Python
apache-2.0
12,877
0.001165
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
rn (lr, mx.lr_scheduler.MultiFactorScheduler(step=steps, factor=args.lr_factor)) def _load_model(args, rank=0): if 'load_epoch' not in args or args.load_epoch is None: return (None, None, None) a
ssert args.model_prefix is not None model_prefix = args.model_prefix if rank > 0 and os.path.exists("%s-%d-symbol.json" % (model_prefix, rank)): model_prefix += "-%d" % (rank) sym, arg_params, aux_params = mx.model.load_checkpoint( model_prefix, args.load_epoch) logging.info('Loaded mode...
peterbartha/ImmunoMod
res_mods/mods/packages/xvm_hangar/python/svcmsg.py
Python
mit
675
0.004458
import traceback
import BigWorld from gui.Scaleform.daapi.view.lobby.messengerBar.NotificationListButton import NotificationListButton from xfw import * import xvm_main.python.config as config from xvm_main.python.logger import * ### @overrideMethod(NotificationListButton, 'as_setStateS') def _NotificationListButton_as_setStateS(b...
/notificationsButtonType', 'full').lower() if notificationsButtonType == 'none': isBlinking = False counterValue = '' elif notificationsButtonType == 'blink': counterValue = '' base(self, isBlinking, counterValue)
icandigitbaby/openchange
python/openchange/provision.py
Python
gpl-3.0
31,424
0.002228
# OpenChange provisioning # Copyright (C) Jelmer Vernooij <[email protected]> 2008-2009 # Copyright (C) Julien Kerihuel <[email protected]> 2009 # # This program is free s
oftware; 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # M...
Akrog/cinder
cinder/zonemanager/drivers/brocade/brcd_fabric_opts.py
Python
apache-2.0
2,207
0
# (c) Copyright 2014 Brocade Communications Systems Inc. # All Rights Reserved. # # Copyright 2014 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # ...
'BRCD_FABRIC_EXAMPLE') LOG = logging.getLogger(__name__) def load_fabric_configurations(fabric_names): fabric_configs = {} for fabric_name in fabric_names: config = configuration.Configuration(brcd_zone_opts, fabric_name)
LOG.debug("Loaded FC fabric config %s" % fabric_name) fabric_configs[fabric_name] = config return fabric_configs
PalouseRobosub/robosub
src/rqt/rqt_control/src/rqt_control/control.py
Python
gpl-3.0
5,890
0.00034
import os import rospy import rospkg from python_qt_binding import QT_BINDING from rqt_gui_py.plugin import Plugin from python_qt_binding import loadUi from python_qt_binding.QtCore import QTimer # Attempt to load QWidget from pyqt4 try: from python_qt_binding.QtGui import QWidget # if not load from pyqt5 except ...
rqt_control/resource', 'Control.ui') # Extend the widget with all attributes and children from UI file loadUi(ui_file, self._widget) self.control_timer = QTimer(self) self.control_timer.timeout.connect(self.control_missed)
self.control_timer.start(1000) self.control_status_timer = QTimer(self) self.control_status_timer.timeout.connect(self.control_status_missed) self.control_status_timer.start(1000) # Give QObjects reasonable names self._widget.setObjectName('Control') if context....
crateio/crate.pypi
crate/pypi/processor.py
Python
bsd-2-clause
23,954
0.003381
import base64 import hashlib import logging import re import urllib import urlparse import xmlrpclib import redis import requests import lxml.html from django.conf import settings from django.core.exceptions import ValidationError from django.core.files.base import ContentFile from django.db import transaction from d...
h transaction.commit_on_success(): self.verify_and_sync_pages() if self.version is None: # Delete the entire package packages = Package.objects.filter(name=self.name
).select_for_update() releases = Release.objects.filter(package__in=packages).select_for_update() for package in packages: package.delete() else: # Delete only this release try: package = Package.objects...
CARocha/ciat_plataforma
analysis/configuration/migrations/0003_auto__del_sector__add_sector_en.py
Python
mit
6,487
0.006937
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'Sector' db.delete_table(u'configuration_sector') ...
': { 'Meta': {'object_name': 'Plataforma'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'sitio_accion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"o...
id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, u'configuration.seleccion_7a': { 'Meta': {'object_name': 'Seleccion_7a'}, u'id': ('django.db.models.fields.AutoField'...
hill1303/CCGParaphraseGenerator
novel_disambiguation/utilities/rewrite_utilities.py
Python
lgpl-2.1
17,853
0.000224
__author__ = 'Ethan A. Hill' import copy import string import re import itertools import logging from xml.etree import cElementTree as ElementTree from ..constants import ccg_values from ..models.rewrite import Rewrite from ..utilities import reversal_utilities __logger = logging.getLogger(__name__) def find_parse...
def ambiguous_parent_verb_index(node_index, parse_pair): parse, other_parse = parse_pair # Find the parent verb of the node in question from each parse parse_node = find_parse_tree_node(node_index, parse) parent_verb = parent_verb_node(parse_node, parse) other_parse_node = find_parse_tree_node(no...
rent_verb is not None: # Now see which verb is higher up in the tree if has_node_as_child(parent_verb, other_parent_verb): top_level_verb = parent_verb else: top_level_verb = other_parent_verb return top_level_verb.attrib.get('id') return None def append_rew...
harikishen/addons-server
src/olympia/amo/decorators.py
Python
bsd-3-clause
7,584
0
import datetime import functools import json from django import http from django.conf import settings from django.core.exceptions import PermissionDenied from django.db import connection, transaction import olympia.core.logger from olympia import core from olympia.accounts.utils import redirect_for_login from olympia...
return f(request, *args, **kw) raise PermissionDenied return wrapper return decorator def json_response(response, has_trans=False, status_code=200): """ Return a response as JSON. If you are just wrapping a view, then use the json_view decorator. """ if has_trans: ...
freephys/python_ase
ase/md/npt.py
Python
gpl-3.0
27,683
0.003757
'''Constant pressure/stress and temperature dynamics. Combined Nose-Hoover and Parrinello-Rahman dynamics, creating an NPT (or N,stress,T) ensemble. The method is the one proposed by Melchionna et al. [1] and later modified by Melchionna [2]. The differential equations are integrated using a centered difference meth...
2 (19
90). ''' __docformat__ = 'reStructuredText' from numpy import * import sys import time import weakref from ase.md import MolecularDynamics #from ASE.Trajectories.NetCDFTrajectory import NetCDFTrajectory # Delayed imports: If the trajectory object is reading a special ASAP version # of HooverNPT, that class is impor...
tmm1/pygments.rb
vendor/pygments-main/pygments/styles/colorful.py
Python
mit
2,778
0
# -*- coding: utf-8 -*- """ pygments.styles.colorful ~~~~~~~~~~~~~~~~~~~~~~~~ A colorful style, inspired by CodeRay. :copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, ...
#333", Operator.Word: "bold #000", Name.Builtin:
"#007020", Name.Function: "bold #06B", Name.Class: "bold #B06", Name.Namespace: "bold #0e84b5", Name.Exception: "bold #F00", Name.Variable: "#963", Name.Variable.Instance: "#33B", Name.V...
denismakogon/cloudvalidation-dashboard
cloudvalidation/ostf_tests/tables.py
Python
apache-2.0
2,739
0
from django import shortcuts from django import http from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy from horizon import tables from horizon import messages from cloudvalidation.api import cloudv class CreateJob(tables.BatchAction): name = "create" ...
est.session['tests'] = obj_ids return shortcuts.redirect('/cloudvalidation_portal/jobs/create') class ExecuteTest(tables.BatchAction): name = "execute" classes = ('btn-launch',) help_text = _("Execute test.") @staticmethod def action_present(count): return unget
text_lazy( u"Execute test", u"Execute tests", count ) @staticmethod def action_past(count): return ungettext_lazy( u"Executed test", u"Executed tests", count ) def action(self, request, datum_id): repor...
italomaia/turtle-linux
games/DigbyMarshmallow/lib/effects.py
Python
gpl-3.0
472
0.012712
import random import actor from vector import Vector as v class SmokePuff(act
or.Actor): collides = False def __init__(self,
world, pos): super(SmokePuff, self).__init__(world, pos=pos, radius=10, image_file="images/all/star.svgz") self.apply_impulse(v((random.gauss(0,2),random.gauss(0,2)))) def tick(self): super(SmokePuff, self).tick() self.radius += .5 if self.radius > 20: s...