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
EijiSugiura/sstoraged
src/json/unittest/jsontestrunner.py
Python
gpl-2.0
2,199
0.032287
# Simple implementation of a json test runner to run the test against json-py. import sys import os.path import json import types if len(sys.argv) != 2: print "Usage: %s input-json-file", sys.argv[0] sys.exit(3) input_path = sys.argv[1] base_path = os.path.splitext(input_path)[0] actual_path...
%s=%.16g\n' % (path,value) ) elif value is True: fout.write( '%s=true\n' % path ) elif value is False: fout.write( '%s=false\
n' % path ) elif value is None: fout.write( '%s=null\n' % path ) else: assert False and "Unexpected value type" def parseAndSaveValueTree( input, actual_path ): root = json.read( input ) fout = file( actual_path, 'wt' ) valueTreeToString( fout, root ) fout.clos...
fstagni/DIRAC
WorkloadManagementSystem/Utilities/QueueUtilities.py
Python
gpl-3.0
8,673
0.01153
"""Utilities to help Computing Element Queues manipulation """ from __future__ import absolute_import from __future__ import division import six from DIRAC import S_OK, S_ERROR from DIRAC.Core.Utilities.List import fromChar from DIRAC.Core.Utilities.ClassAd.ClassAdLight import ClassAd from DIRAC.ConfigurationSystem.C...
""" Get the list of queue descriptions merging site/ce/queue parameters and adding some derived parameters. :param dict siteDict: dictionary with configuration data as returned by Resources.getQueues() method :return: S_OK/S_ERROR, Value dictionary per queue with configuration data updated, e.g.
for SiteDirector """ queueFinalDict = {} for site in siteDict: for ce, ceDict in siteDict[site].items(): qDict = ceDict.pop('Queues') for queue in qDict: queueName = '%s_%s' % (ce, queue) queueDict = qDict[queue] queueDict['Queue'] = queue queueDict['Site'] = si...
JulienMcJay/eclock
windows/Python27/Lib/site-packages/pygments/__init__.py
Python
gpl-2.0
2,974
0.000336
# -*- coding: utf-8 -*- """ Pygments ~~~~
~~~~ Pygments is a syntax highlighting package written in Python. It is a generic syntax highlighter for general use in all kinds of software such as forum systems, wikis or other applications that need to prettify source code. Highlights are: * a wide range of common languages and markup formats...
* support for new languages and formats are added easily * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image formats that PIL supports, and ANSI sequences * it is usable as a command-line tool and as a library * ... and it highlights even Brainfuck! The `Pygments tip`_ is ins...
bronydell/VK-GFC-bot
saver.py
Python
mit
348
0
import shelve shelve_name = "data" def savePref(user, key, value): d = shelve.open(shelve_name) d[str(user) + '.' + str(key)] = value d.close() def openPref(user, key, default): d = shelve.open(shelve_name) if (str(u
ser) + '.' + str(key)) in d: retur
n d[str(user) + '.' + str(key)] else: return default
ajstarna/RicochetRobots
Brobot/experimentsFirstSolution.py
Python
bsd-2-clause
6,257
0.032603
#!/usr/bin/python ''' this file contains functions for experimenting with the different players and for running many trials and averaging results ''' from Player import RandomPlayer from MCPlayer import MCPlayer, PNGSPlayer, GreedyPlayer import Board import sys, traceback import time def runRandomPlayerFirstSol(file...
e Number of Moves Per Game = {0}".format(PNGSAverage)) print("Average Number of Moves Per Game Before Improvement = {0}".format(MCAverage)) print("Average findTime per game = {0}".format(findTime)) print("Average pngsTime per game = {0}".format(pngsTime)) print(PNGSResults) print("") ''' print("Runnin...
yerFirstSol, numGames, fileName, 16, numSamples, depth) #print(PNGSDict) print("Average Number of Moves Per Game = {0}".format(PNGSAverage)) print("Average Number of Moves Per Game Before Improvement = {0}".format(MCAverage)) print("Average findTime per game = {0}".format(findTime)) print("Average pngsTime per gam...
bumrush/blackjack
blackjack.py
Python
gpl-2.0
8,652
0.035483
#!/usr/bin/python # Copyright 2014 Justin Cano # # This is a simple Python program of the game Blackjack # (http://en.wikipedia.org/wiki/Blackjack), developed for # a coding challenge from the 2014 Insight Data Engineering # Fellows Program application. # # Licensed under the GNU General Public License, version 2.0 # ...
or choice > maxChoice: try: print "Actions:" print "-" * 10 print "[1] Hit" print "[2] Stand" if len(playerCards) == 2 and chips >= bet: "Double Down allowed" print "[3] Double Down" maxChoice += 1 choice = int(raw_input("% ")) assert 1 <= choice <= maxChoice
except (ValueError, AssertionError): print "Invalid choice! Must be [1-" + str(maxChoice) + "]" return blackjackChoices[choice] def deal(deck): """ Pops and returns the first card in deck """ card = deck[0] del deck[0] return card def rank(hand): """ Return the sum of the ranks in a hand Face cards ar...
Punto0/addons-fm
website_product_brand/__openerp__.py
Python
agpl-3.0
1,807
0.003874
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2015 Serpent Consulting Services Pvt. Ltd. (<http://www.serpentcs.com>) # Copyright (C) 2016 FairCoop (<http://fair.coop>) # # This program is f...
ater version. #
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public ...
mads-bertelsen/McCode
meta-pkgs/windows/Support/gnuplot-py-1.8/.happydoc.setup.py
Python
gpl-2.0
645
0.103876
(S'9d1d8dee18e2f5e4bae7551057c6c474' p1 (ihappydoclib.parseinfo.moduleinfo ModuleInfo p2 (dp3 S'_namespaces' p4 ((dp5 (dp6 tp7 sS'_import_info' p8 (ihappydo
clib.parseinfo.imports ImportInfo p9 (dp10 S'_named_imports' p11 (dp12 sS'_straight_imports' p13 (lp14 sbsS'_filename' p15 S'Gnuplot/setup.py' p16 sS'_docstring' p17 S'' sS'_name' p18 S'setup' p19 sS'_parent' p20 NsS'_comment_info' p21 (dp22 sS'_configuration_values' p23 (dp24 S'include_comments' p25 I1 sS'cacheFilePre...
che' p28 I1 sS'docStringFormat' p29 S'StructuredText' p30 ssS'_class_info' p31 g5 sS'_function_info' p32 g6 sS'_comments' p33 S'' sbt.
csunny/blog_project
source/apps/blog/admin/user.py
Python
mit
863
0.002317
#!usr/bin/env python # -*- coding:utf-8 -*- """ @author: magic """ from django.contrib import admin from blog.models import User from django.contrib.auth.admin import UserAdmin from django.utils.translation import ugettext, ugettext_lazy as _ class BlogUserAdmin(UserAdmin): filesets = ( (None, {'fields': ...
ersonal info'), {'fields': ('email', 'qq', 'phone')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': {'last_login', 'date_joined'}}), ) add_fieldsets = ( (...
ields': ('username', 'email', 'password1', 'password2'), }), ) admin.site.register(User, BlogUserAdmin)
helanan/Panda_Prospecting
panda_prospecting/prospecting/insights/high_lows.py
Python
mit
966
0
import csv from datetime import datetime from matplotlib import pyplot as plt # Get dates, high, and low temperatures from file. filename = 'sitka_weather_2017.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) dates, highs, lows = [], [], [] for row in reader: cu...
s, lows, facecolor='blue', alpha=0.1) # Format plot. plt.title("Daily high and low temperatures - 2017", fontsize=24) plt.xlabel('', fontsize=16) fig.autofmt_xdate() plt.ylabel("Temperature (F)", fontsize=
16) plt.tick_params(axis='both', which='major', labelsize=16) plt.show()
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/callback/full_skip.py
Python
bsd-3-clause
2,289
0.001747
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' ...
f.outlines = [] def v2_runner_on_failed(self, result, ignore_errors=False): self.display() super(CallbackModule, self).v2_runner_on_failed(result, ignore_errors) def v2_
playbook_on_task_start(self, task, is_conditional): self.outlines = [] self.outlines.append("TASK [%s]" % task.get_name().strip()) if self._display.verbosity >= 2: path = task.get_path() if path: self.outlines.append("task path: %s" % path) def v2_pla...
StratusLab/client
cli/user/code/main/python/stratuslab/cmd/stratus_detach_volume.py
Python
apache-2.0
3,765
0.003187
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Created as part of the StratusLab project (http://stratuslab.eu), # co-funded by the European Commission under the Grant Agreement # INFSO-RI-261552." # # Copyright (c) 2011, Centre National de la Recherche Scientifique (CNRS) # # Licensed under the Apache License, Vers...
tions(self.parser) super(MainProgram, self).parse() self.options, self.uuids = self.parser.parse_args() def checkOptions(self): super(MainProgram, self).checkOptions() if not self.uuids: printError('Please provide at least one persistent disk UUID to detach') i...
ions.instance < 0: printError('Please provide a VM ID on which to detach disk') try: self._retrieveVmNode() except OneException, e: printError(e) def _retrieveVmNode(self): credentials = AuthnFactory.getCredentials(self.options) self.options.cloud...
luotao1/Paddle
python/paddle/fluid/contrib/layers/metric_op.py
Python
apache-2.0
7,067
0.000849
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
[batch_sqrerr]}) helper.appen
d_op( type="elementwise_add", inputs={"X": [batch_sqrerr], "Y": [local_sqrerr]}, outputs={"Out": [local_sqrerr]}) helper.append_op( type="l1_norm", inputs={"X": [tmp_res_elesub]}, outputs={"Out": [batch_abserr]}) helper.append_op( type="el...
ComprasTransparentes/api
endpoints/proveedor.py
Python
gpl-3.0
22,914
0.00358
# coding=utf-8 import operator import json import falcon import peewee import dateutil from models import models_api from utils.myjson import JSONEncoderPlus from utils.mypeewee import ts_match class ProveedorId(object): """Endpoint para un proveedor en particular, identificado por ID""" @models_api.databa...
echa_adjudicacion_min: filter_fecha_adjudicacion.append(models_api.ProveedorOrganismoCruce.fecha_adjudicacion >= fecha_adjudicacion_min) elif fecha_adjudicacion_max: filter_fecha_adjudicacion.append(models_api.ProveedorOrganismoCruce.fecha_adjudicacion <= fecha_ad...
(operator.or_, filter_fecha_adjudicacion)) # Filtrar por organismo_adjudicador q_organismo_adjudicador = req.params.get('organismo_adjudicador', None) if q_organismo_adjudicador: if isinstance(q_organismo_adjudicador, basestring): q_organismo_adjudicador = [q_organis...
fjorba/invenio
modules/websearch/lib/websearch_templates.py
Python
gpl-2.0
196,591
0.005458
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 ...
tr, ''), 'pages' : (str, ''), 'artnum' : (str, ''), 'date' : (str, ''), 'ssn' : (str, ''), 'quarter' : (str, ''), 'url_ver' : (str, ''), 'ctx_ver' : (str, ''), 'rft_val_fmt' : (str, ''), 'rft_id' : (list, []), ...
'rft.date' : (str, ''), 'rft.volume' : (str, ''), 'rft.issue' : (str, ''), 'rft.spage' : (str, ''), 'rft.epage' : (str, ''), 'rft.pages' : (str, ''), 'rft.artnumber' : (str, ''), 'rft.issn' : (str, ''), 'rft.eissn' : (str,...
botswana-harvard/edc-describe
edc_describe/forms/select_model_form.py
Python
gpl-2.0
232
0
from django import forms class SelectModelForm(forms.Form): app_label = forms.CharField( l
abel="App label", required=Tr
ue) model_name = forms.CharField( label="Model name", required=True)
candlepin/virt-who
virtwho/daemon/daemon.py
Python
gpl-2.0
25,080
0
# -*- coding: utf-8 -*- from __future__ import print_function # daemon/daemon.py # Part of python-daemon, an implementation of PEP 3143. # # Copyright © 2008–2010 Ben Finney <ben+python@benfinney.id.au> # Copyright © 2007–2008 Robert Niederreiter, Jens Klein # Copyright © 2004–2005 Chad J. Schroeder # Copyright © 2003...
lass DaemonProcessDetachError(DaemonError, OSError): """ Exception raised when process detach fails. """ class DaemonContext(object): """ Context for turning the current program into a daemon process. A `DaemonContext` instance represents the behaviour settings and process context for the pro...
daemon. The behaviour and environment is customised by setting options on the instance, before calling the `open` method. Each option can be passed as a keyword argument to the `DaemonContext` constructor, or subsequently altered by assigning to an attribute on the instance at ...
zentralopensource/zentral
zentral/conf/config.py
Python
apache-2.0
9,328
0.000858
import base64 import itertools import json import logging import os import re import time from .buckets import get_bucket_client from .params import get_param_client from .secrets import get_secret_client logger = logging.getLogger("zentral.conf.config") class Proxy: pass class EnvProxy(Proxy): def __init...
proxy = child_proxy def get(self): return json.loads(self._child_proxy.get()) class Base64DecodeFilter(Proxy): def __init__(self, child_proxy): self._child_proxy = child_proxy def get(self): return base64.b64decode(self._child_proxy.get()) class ElementFilter(Proxy): def __...
oxy def get(self): return self._child_proxy.get()[self._key] class Resolver: def __init__(self): self._cache = {} self._bucket_client = None self._param_client = None self._secret_client = None def _get_or_create_cached_value(self, key, getter, ttl=None): ...
gpciceri/milagathos
SixWeeksPreparationForReadingCaesar/pgm/generateSintagmaProblem_6WP.py
Python
lgpl-3.0
3,153
0.024738
#! /use/bin/env python # -*- coding: utf-8 -*- '''/* generateSintagmaProblem_6WP.py * * Copyright (C) 2016 Gian Paolo Ciceri * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either...
ny later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU L...
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Author: * gian paolo ciceri <gp.ciceri@gmail.com> * * * Release: * 2016.08.24 - initial release. * */ ''' import random import time import locale import re from sixWeeksExercises import * from latinGrammarRules import * lo...
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/mpls/lsps/constrained_path/tunnels/tunnel/bandwidth/auto_bandwidth/underflow/state/__init__.py
Python
apache-2.0
29,125
0.001373
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbi
nd.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbin
d.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ class state(PybindBase): ""...
h3/django-webcore
webcore/urls/robots.py
Python
bsd-3-clause
172
0.011628
fr
om django.conf.urls.defaults import * urlpatterns = patterns('', (r'^robots.txt', 'django.views.generic.sim
ple.direct_to_template', {'template': 'robots.txt'}), )
shurain/archiver
archiver/sink.py
Python
mit
4,439
0.003379
# -*- coding: utf-8 -*- import hashlib import binascii from thrift.transport.THttpClient import THttpClient from thrift.protocol.TBinaryProtocol import TBinaryProtocol from evernote.edam.userstore import UserStore from evernote.edam.notestore import NoteStore import evernote.edam.type.ttypes as Types import evernote....
data.size = len(item.content) #FIXME better ways of doing this calculation? data.bodyHash = hashvalue data.body = item.content resource = Types.Resource() resource.mime = item.content_type resource.data = data return resource def pdf_resource(self, item): ...
md5.update(item.content) hashvalue = md5.digest() data = Types.Data() data.size = len(item.content) #FIXME better ways of doing this calculation? data.bodyHash = hashvalue data.body = item.content resource = Types.Resource() resource.mime = 'application/pdf' ...
yingxuanxuan/fabric_script
shadowsocks.py
Python
apache-2.0
2,157
0.001391
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from fabric.api import reboot, sudo, settings logging.basicConfig(level=logging.INFO) def ssserver(port, password, method): try: sudo('hash yum') sudo('hash python') sudo('yum -y update 1>/dev/null') sudo('yum -y insta...
sudo('pip install shadowsocks 1>/dev/null') sudo('hash sslocal') sudo("sed -i '/sslocal /d' /etc/rc.d/rc.local") cmd = '/usr/bin/python /usr/bin
/sslocal -s %s -p %s -k %s -m %s -b 0.0.0.0 -l %s --user nobody -d start' % \ (server_addr, server_port, server_password, method, local_port) sudo("sed -i '$a %s' /etc/rc.d/rc.local" % cmd) sudo('chmod +x /etc/rc.d/rc.local') sudo('firewall-cmd --zone=public --add-port=%s/tcp --per...
pkuwwt/pydec
Examples/HodgeDecomposition/driver.py
Python
bsd-3-clause
2,724
0.020558
""" Compute a harmonic 1-cochain basis for a square with 4 holes. """ from numpy import asarray, eye, outer, inner, dot, vstack from numpy.random import seed, rand from numpy.linalg import norm from scipy.sparse.linalg import cg from pydec import d, delta, simplicial_complex, read_mesh def hodge_decomposition
(omega): """ For a given p-cochain \omega there is a unique decomposition \omega = d(\alpha) + \delta(\beta) (+) h for p-1 cochain \alpha, p+1 cochain \beta, and harmonic p-cochain h. This function ret
urns (non-unique) representatives \beta, \gamma, and h which satisfy the equation above. Example: #decompose a random 1-cochain sc = SimplicialComplex(...) omega = sc.get_cochain(1) omega.[:] = rand(*omega.shape) (alpha,beta,h) = hodge_decomposition(omega) """ ...
angr/angr
angr/procedures/definitions/win32_aclui.py
Python
bsd-2-clause
1,451
0.004824
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling...
Int(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["psi"]), # 'Edit
Security': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi"]), # 'EditSecurityAdvanced': SimTypeFunction([SimTypePointer(SimTypeInt(signed=...
Donkyhotay/MoonPy
zope/configuration/tests/test_conditions.py
Python
gpl-3.0
3,562
0.000842
############################################################################## # # Copyright (c) 2003 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SO...
l contained elements (not otherwise conditioned) should be processed normally:: >>> "direct.true.condition" in registry True
>>> "nested.true.condition" in registry True However, when the expression evaluates to false, the conditioned element and all contained elements should be ignored:: >>> "direct.false.condition" in registry False >>> "nested.false.condition" in registry False Conditions on container elements affect the con...
akrawchyk/amweekly
amweekly/slack/tests/test_models.py
Python
mit
313
0
from django.core.e
xceptions import ValidationError from amweekly.slack.tests.factories import SlashCommandFactory import pytest pytest.mark.unit def test_slash_command_raises_with_invalid_token(settings): settings.SLACK_TOKENS = '' with pytest.rais
es(ValidationError): SlashCommandFactory()
EduPepperPDTesting/pepper2013-testing
lms/djangoapps/polls/views.py
Python
agpl-3.0
3,557
0.001125
from mitxmako.shortcuts import render_to_response from django.http import HttpResponse from .models import poll_store from datetime import datetime from django.utils import timezone import json import urllib2 from math import floor def poll_form_view(request, poll_type=None): if poll_type: return render_t...
False if poll_dict['expiration'] is not None: if poll_dict['expiration'] <=
timezone.now(): expired = True data = {'question': poll_dict['question'], 'answers': poll_dict['answers'], 'expiration': poll_dict['expiration'], 'expired': expired, 'user_answered': user_answered, 'votes': votes, 'poll_type': poll...
ryfeus/lambda-packs
Keras_tensorflow_nightly/source2.7/keras/optimizers.py
Python
mit
25,887
0.000579
from __future__ import absolute_import import six import copy from six.moves import zip from . import backend as K from .utils.generic_utils import serialize_keras_object from .utils.generic_utils import deserialize_keras_object if K.backend() == 'tensorflow': import tensorflow as tf def clip_norm(g, c, n): ...
avoid converting sparse tensor to dense if isinstance(then_expression, tf.Tensor): g_shape = copy.copy(then_expression.get_shape()) elif isinstance(then_expression, tf.IndexedSlices): g_shape = copy.copy(then_expression.dense_shape) if condition.dtype != tf.
bool: condition = tf.cast(condition, 'bool') g = tf.cond(condition, lambda: then_expression, lambda: else_expression) if isinstance(then_expression, tf.Tensor): g.set_shape(g_shape) elif isinstance(then_expression, tf.IndexedSlices)...
BobStevens/micropython
BMP085/BMP085.py
Python
mit
8,779
0.015947
#!/usr/bin/python from pyb import I2C import time # =========================================================================== # BMP085 Class # Based mostly on Adafruit_BMP085.py # For use with a Micro Python pyboard http://micropython.org # and a BMP180 Barometric Pressure/Temperature/Altitude Sensor # tested with ...
ters __BMP085_CAL_AC1 = 0xAA # R Calibration data (16 bits) __BMP085_CAL_AC2 = 0xAC # R Calibration data (16 bits) __BMP085_CAL_AC3 = 0xAE # R Calibration data (16 bits) __BMP085_CAL_AC4 = 0xB0 # R Calibration data (16 bits) __BMP085_CAL_AC5 = 0xB2...
= 0xB4 # R Calibration data (16 bits) __BMP085_CAL_B1 = 0xB6 # R Calibration data (16 bits) __BMP085_CAL_B2 = 0xB8 # R Calibration data (16 bits) __BMP085_CAL_MB = 0xBA # R Calibration data (16 bits) __BMP085_CAL_MC = 0xBC # R Calibration data (16 ...
BrendanLeber/adventofcode
2020/20-jurassic_jigsaw/code.py
Python
mit
5,544
0.002345
import math import re from collections import defaultdict def matches(t1, t2): t1r = "".join([t[-1] for t in t1]) t2r = "".join([t[-1] for t in t2]) t1l = "".join([t[0] for t in t1]) t2l = "".join([t[0] for t in t2]) t1_edges = [t1[0], t1[-1], t1r, t1l] t2_edges = [t2[0], t2[-1], t2[0][::-1],...
er = set() for l in open("monster.txt").read().split("\n"): kx = len(l) for i, ch in enumerate(l): if ch == "#": monster.add((i, ky)) ky += 1 for _ in range(2): image = flip(image) for _ in range(4): image = rotate(image) ...
or y in range(0, len(image) - ky): parts = [] for i, p in enumerate(monster): dx = x + p[0] dy = y + p[1] parts.append(image[dy][dx] == "#") if all(parts): for p in...
rpavlik/chromium
grabcmake.py
Python
bsd-3-clause
3,469
0.025368
import subprocess import os pathToGrabber = os.path.abspath("grab.mk") def getVariable(var): proc = subprocess.Popen(["make", "--silent", "-f", pathToGrabber, "GETVAR", "VARNAME=%s" % var], stdout = subprocess.PIPE) return proc.communicate()[0].strip() def getVariableList(var): return [item.strip() for item in getVa...
nt getTargetOutput("FILES") #print getTargetOutput("PROGRAM") def getSources(): return [
"%s.c" % fn.strip() for fn in getVariableList("FILES")] def getTarget(): ret = {} prog = getVariable("PROGRAM") lib = getVariable("LIBRARY") if len(prog) > 0: return prog, "add_executable", "" elif len(lib) > 0: if getVariable("SHARED") == "1": return lib, "add_library", "SHARED" else: return lib, "ad...
kexiaojiu/alien_invasion
game_functions.py
Python
gpl-3.0
11,663
0.009822
#coding=utf-8 import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_key_down_events(event,ai_settings, screen, stats, play_button, ship, aliens, bullets): """响应按键""" if event.key == pygame.K_RIGHT: #向右移动飞船 ship.movin...
#按键p开始游戏 start_game(ai_settings, screen, stats, play_button, ship, aliens, bullets) elif event.
key == pygame.K_q: #按键q退出游戏 save_high_score(stats) sys.exit() def save_high_score(stats): """保存最高分到high_score.txt""" file_name = stats.store_high_score_file_name high_score_str = str(stats.high_score) with open(file_name, 'w') as f_obj: f_obj.write(high_score_str) def c...
jinmingda/MicroorganismSearchEngine
mse/release.py
Python
mit
449
0
# -*- co
ding: utf-8 -*- # Release information about mse version = '1.0' # description = "Your plan to rule the world" # long_description = "More description about your plan" # author = "Your Name Here" # email = "YourEmail@YourDomain" # copyright = "Copyright 2011 - the year of the Rabbit" # Of it's open source, you might w...
specify these: # url = 'http://yourcool.site/' # download_url = 'http://yourcool.site/download' # license = 'MIT'
ArmchairArmada/COS125Project01
src/tests/test_assets.py
Python
mit
239
0.004184
#!/usr/bin/env python
""" Unit tests for the assets module """ # TODO: Write actual tests. import unittest import assets class TestAssets(unittest.TestCase): def setUp(self):
pass def test_getImage(self): pass
t3dev/odoo
addons/project/__manifest__.py
Python
gpl-3.0
1,315
0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Project', 'version': '1.1', 'website': 'https://www.odoo.com/page/project-management', 'category': 'Operations/Project', 'sequence': 10, 'summary': 'Organize and schedule your projects ...
ws.xml', 'views/res_config_settings_views.xml', 'views/mail_activity_views.xml', 'views/project_assets.xml', 'views/project_portal_templates.xml', 'views/project_rating_templates.xml', 'data/digest_data.xml', 'data/project_mail_template_data.xml', 'data/pr...
'test': [ ], 'installable': True, 'auto_install': False, 'application': True, }
ThomasSweijen/yadesolute2
examples/test/vtk-exporter/vtkExporter.py
Python
gpl-2.0
976
0.067623
from yade import export,polyhedra_utils mat = PolyhedraMat() O.bodies.append([ sphere((0,0,0),1), sphere((0,3,0),1), sphere((0,2,4),2), sphere((0,5,2),1.5), facet([Vector3(0,-3,-1),Vector3(0,-2,5),Vector3(5,4,0)]), facet([Vector3(0,-3,-1),Vector3(0,-2,5),Vector3(-5,4,0)]), polyhedra_utils.polyhedra(mat,(1,2,3),...
(what=[('dist','b.state.pos.norm()')]) vtkExporter.exportFacets(what=[('pos','b.state.pos')]) vtkExporter.expor
tInteractions(what=[('kn','i.phys.kn')]) vtkExporter.exportPolyhedra(what=[('n','b.id')])
AntonKhorev/spb-budget-db
4-xls/main.py
Python
bsd-2-clause
21,223
0.05248
#!/usr/bin/env python3 inputFilename='../3-db.out/db.sql' outputDirectory='../4-xls.out' import os if not os.path.exists(outputDirectory): os.makedirs(outputDirectory) from decimal import Decimal import collections import copy import sqlite3 import xlwt3 as xlwt import xlsxwriter class LevelTable: def __init__(se...
s self.levelColLists=levelColLists if type(yearsInAppendices) is dict: self.yearsInAppendices=yearsInAppendices self.years=[year for appendix,years in sorted(yearsInAppendices.items()) for year in years] else: self.yearsInAppendices={} # don't use 'numbers in appendices' self.years=yearsInAppendices ...
es)+['Итого']+[None for levelColList in self.levelColLists for col in levelColList]+[None]*len(self.years)] self.levels=[-1] self.formulaValues=collections.defaultdict(lambda: collections.defaultdict(lambda: Decimal(0))) def outputLevelRow(row,level): outRow=[None]*len(self.yearsInAppendices) outRow.append...
ktsitsikas/odemis
util/launch_xrced.py
Python
gpl-2.0
1,995
0.002506
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This custom XRCED launcher allows a small wx function to be wrapped so it provides a little extra needed functionality. XRC sometimes need to check if a node contains a filename. It does so by checking node types. This works fine, until we start working with custom co...
globals import set_debug set_debug(True) except ImportError: print >> sys.stderr, 'Check that XRCed is installed and is in PYTHONPATH' raise from wx.tools import pywxrc # The XRCEDPATH environment variable is used to define additional plugin directories xrced_pa...
is/gui/xmlh") print "'XRCEDPATH' is set to %s" % os.getenv('XRCEDPATH') # Move this to a separate launcher so it can be spread with # odemis def ncf_decorator(ncf): def wrapper(self, node): if node.firstChild and node.firstChild.nodeType == 3: if node.firstChild.nod...
MiniSEC/GRR_clone
lib/hunts/standard.py
Python
apache-2.0
36,298
0.00697
#!/usr/bin/env python # Copyright 2012 Google Inc. All Rights Reserved. """Some multiclient flows aka hunts.""" import re import stat import logging from grr.lib import access_control from grr.lib import aff4 from grr.lib import cron from grr.lib import data_store from grr.lib import flow from grr.lib import rdfv...
nt with given id. As direct write access to the data store is forbidden, we have to use flows to perform any kind of modifications. This flow delegates ACL checks to access control manager. """ # This flow can run on any client without ACL enforcement (an SUID flow). ACL_ENFORCED = False flow_typeinfo =...
URN of the hunt to execute.", name="hunt_urn"), ) @flow.StateHandler() def Start(self): """Find a hunt, perform a permissions check and run it.""" hunt = aff4.FACTORY.Open(self.state.hunt_urn, aff4_type="GRRHunt", age=aff4.ALL_TIMES, mode="rw", token=self.token)...
trichter/yam
yam/stack.py
Python
mit
3,034
0
# Copyright 2017-2019 Tom Eulenfeld, MIT license """Stack correlations""" import numpy as np import obspy from obspy import UTCDateTime as UTC from yam.util import _corr_id, _time2sec, IterTime def stack(stream, length=None, move=None): """ Stack traces in stream by correlation id :param stream: |Stream...
gether all traces) :param move: define a moving stack, float or string, default:
None -- no moving stack, if specified move usually is smaller than length to get an overlap in the stacked traces :return: |Stream| object with stacked correlations """ stream.sort() stream_stack = obspy.Stream() ids = {_corr_id(tr) for tr in stream} ids.discard(None) for id_...
lsaffre/lino-cosi
lino_cosi/lib/cosi/models.py
Python
agpl-3.0
213
0.004695
# -*- coding: UTF-8 -*- # Copyright 2011-2015 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) """ The
:x
file:`models.py` module for :ref:`cosi`. This is empty. """
theislab/scanpy
scanpy/plotting/palettes.py
Python
bsd-3-clause
4,616
0.000867
"""Color palettes in addition to matplotlib's palettes.""" from typing import Mapping, Sequence from matplotlib import cm, colors # Colorblindness adjusted vega_10 # See https://github.com/theislab/scanpy/issues/387 vega_10 = list(map(colors.to_hex, cm.tab10.colors)) vega_10_scanpy = vega_10.copy() vega_10_scanpy[2] ...
E6FF", "#FF34FF", "#FF4A46", "#008941", "#006FA6", "#A30059", "#FFDBE5", "#7A4900", "#0000A6", "#63FFAC", "#B79762", "#004D43", "#8FB0FF", "#997D87", "#5A0007", "#809693", "#6A3A4C",
"#1B4400", "#4FC601", "#3B5DFF", "#4A3B53", "#FF2F80", "#61615A", "#BA0900", "#6B7900", "#00C2A0", "#FFAA92", "#FF90C9", "#B903AA", "#D16100", "#DDEFFF", "#000035", "#7B4F4B", "#A1C299", "#300018", "#0AA6D8", "#013349", "#00846F", ...
bukun/TorCMS
tester/test_handlers/test_index_handler.py
Python
mit
448
0.004464
# -*- coding:utf-8 -*- ''' Test ''' import sys sys.path.append('.') from tornado.testing
import AsyncHTTPSTestCase from application import APP class TestSomeHandler(AsyncHTTPSTestCase): ''' Test '''
def get_app(self): ''' Test ''' return APP def test_index(self): ''' Test index. ''' response = self.fetch('/') self.assertEqual(response.code, 200)
Buggaboo/gimp-plugin-export-layers
export_layers/pygimplib/objectfilter.py
Python
gpl-3.0
11,296
0.015935
#------------------------------------------------------------------------------- # # This file is part of pygimplib. # # Copyright (C) 2014, 2015 khalim19 <khalim19@gmail.com> # # pygimplib is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
return item # Provide alias to `get_subfilter` for easier access. __getitem__ = get_subfilter def remove_subfilter(self, subfilter_name, raise_if_not_found=True): """ Remove the subfilter with the corresponding subfilter name. Parameters: * `subfilter name` - Su
bfilter name. * `raise_if_not_found` - If True, raise `ValueError` if `subfilter_name` is not found in the filter. Raises: * `ValueError` - `subfilter_name` is not found in the filter and `raise_if_not_found` is True. """ if self.has_subfilter(subfilter_name): d...
foxmask/orotangi
orotangi/api/serializers.py
Python
bsd-3-clause
597
0
from orotangi.models import Books, Notes from rest_framework import seriali
zers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer)
: class Meta: model = User fields = '__all__' class BookSerializer(serializers.ModelSerializer): class Meta: model = Books fields = '__all__' class NoteSerializer(serializers.ModelSerializer): class Meta: model = Notes fields = ('id', 'user', 'book', 'u...
neurodata/ndmg
m2g/utils/qa_utils.py
Python
apache-2.0
2,414
0.010356
#!/usr/bin/env python """ m2g.utils.qa_utils ~~~~~~~~~~~~~~~~~~~~ Contains small-scale qa utilities """ import numpy as np def get_min_max(data, minthr=2, maxthr=95): """ A function to find min,max values at designated percentile thresholds Parameters ----------- data: np array 3-d regmri...
x_dim,pad_val=255,rgb=False): """ Pads an image to be same dimensions as given max_dim Parameters -----------
image: np array image object can be multiple dimensional or a slice. max_dim: int dimension to pad up to pad_val: int value to pad with. default is 255 (white) background rgb: boolean flag to indicate if RGB and last dimension should not be padded Returns ------...
tantexian/sps-2014-12-4
sps/openstack/common/db/sqlalchemy/session.py
Python
apache-2.0
35,114
0
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this
file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app
licable 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. """Session Hand...
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated
python-packages/mne-python-0.10/examples/simulation/plot_simulate_evoked_data.py
Python
bsd-3-clause
2,787
0.000359
""" ============================== Generate simulated evoked data ============================== """ # Author: Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de> # Al
exandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mne import (read_proj, read_forward_solution, read_cov, read_label, pick_types_forward, pick_types) from mne.i
o import Raw, read_info from mne.datasets import sample from mne.time_frequency import fit_iir_model_raw from mne.viz import plot_sparse_source_estimates from mne.simulation import simulate_sparse_stc, simulate_evoked print(__doc__) ############################################################################### # Loa...
sebastiandev/biyuya
biyuya/models/filters.py
Python
mit
2,106
0.00095
import datetime import arrow def arrow_datetime(value, name): try: value = arrow.get(value).datetime except Exception as e: raise ValueError(e) return value class BaseFilter(object): # TODO: Move this class to be part of API FiltrableResource # Leaving implementation to be...
value_type = str allow_multiple = False @classmethod def condition(cls, name): return { 'name': { "$regex": '.*?{}.*?'.format(name), "$options": 'si' } } class TagFilter(Ba
seFilter): name = 'tag' value_type = str allow_multiple = True @classmethod def condition(cls, *tags, **kwargs): return { 'tags': { "$elemMatch": { "$regex": ".*?{}.*?".format('|'.join(tags)), "$options": "si" ...
knightmare2600/d4rkc0de
others/goog-mail.py
Python
gpl-2.0
2,312
0.014273
#!/usr/bin/python import sys import re import string import httplib import urllib2 import re def StripTags(text): finished = 0 while not finished: finished = 1 start = text.find("<") if start >= 0: stop = text[start:].find(">") if stop >= 0: text ...
except IOError: print "Can't connect to Google Groups!"+"" page_counter_web=0 try: print "\n\n+++++++++++++++++++++++++++++++++++++++++++++++++++++"+"" print "+ Google Web & Group Results:"+"" print "+++++++++++++++++
++++++++++++++++++++++++++++++++++++\n\n"+"" while page_counter_web < 50 : results_web = 'http://www.google.com/search?q=%40'+str(domain_name)+'&hl=en&lr=&ie=UTF-8&start=' + repr(page_counter_web) + '&sa=N' request_web = urllib2.Request(results_web) request_web.add_header('User-Agent','Mozi...
botswana-harvard/bcpp
bcpp/tests/test_views/test_enumeration.py
Python
gpl-3.0
3,020
0.001987
from django.test import TestCase, tag from member.tests.test_mixins import MemberMixin from django.contrib.auth.models import User from django.test.client import RequestFactory from django.urls.base import reverse from enumeration.views import DashboardView, ListBoardView class TestEnumeration(MemberMixin, TestCas...
DashboardView.as_view()(request) self.assertEqual(response.status_code, 200) def test_dashboard_view2(self): url = reverse('enumeration:dashboard_url', kwargs=dict( household_identifier=self.household_structure.household.household_identifier, survey=self.household_stru
cture.survey)) self.client.force_login(self.user) response = self.client.get(url) self.assertEqual(response.status_code, 200) def test_list_view1(self): url = reverse('enumeration:listboard_url') request = self.factory.get(url) request.user = self.user respon...
lap00zza/arc
api_server/arc_api/snowflake.py
Python
gpl-3.0
2,140
0.000935
""" arc - dead simple chat Copyright (C) 2017 Jewel Mahanta <jewelmahanta@gmail.com> This file is part of arc. arc 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. arc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty...
ore details. You should have received a copy of the GNU General Public License along with arc. If not, see <http://www.gnu.org/licenses/>. """ import time import math ARC_EPOCH = 1496595546533 class Snowflake: """ Arc snowflake has the following structure +------------------+-----------------+----------...
crookedreyes/py4e-specialization
course-3/chapter-13/json1.py
Python
lgpl-2.1
269
0.007435
import json data = '''{ "name" : "Chuck", "phone": { "type" : "int1", "number"
: "+1
734 303 4456" }, "email": { "hide" : "yes" } }''' info = json.loads(data) print('Name:',info["name"]) print('Hide:',info["email"]["hide"])
DxCx/nzbToMedia
libs/beets/mediafile.py
Python
gpl-3.0
56,908
0.000914
# This file is part of beets. # Copyright 2014, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
gain ratio using a reference value of 1000 units. We also # enforce the maximum value here, which is equivalent to about # -18.2dB. g1 = min(round((10 ** (gain / -10)) * 1000), 65534) # Same as above, except our reference level is 2500 units. g2 = min(round((10 ** (gain / -10)) * 2500), 65534) ...
s are unknown, but they also seem to be # unused so we just use zero. uk = 0 values = (g1, g1, g2, g2, uk, uk, peak, peak, uk, uk) return (u' %08X' * 10) % values # Cover art and other images. def _image_mime_type(data): """Return the MIME type of the image data (a bytestring). """ kind...
alexryndin/ambari
ambari-server/src/main/resources/stacks/BigInsights/4.0/hooks/before-START/scripts/params.py
Python
apache-2.0
9,467
0.007711
""" 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 use this ...
sion import format_stack_version, compare_versions from ambari_commons.os_check import OSCheck from resource_management.libraries.script.script import Script config = Script.get_config() stack_version_unformatted = str(config['hostLevelParams']['stack_version']) iop_stack_version = form
at_stack_version(stack_version_unformatted) # hadoop default params mapreduce_libs_path = "/usr/lib/hadoop-mapreduce/*" hadoop_libexec_dir = stack_select.get_hadoop_dir("libexec") hadoop_lib_home = stack_select.get_hadoop_dir("lib") hadoop_bin = stack_select.get_hadoop_dir("sbin") hadoop_home = '/usr' create_lib_snap...
tiexinliu/odoo_addons
smile_log/tools/db_logger.py
Python
agpl-3.0
2,985
0.00067
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2014 Smile (<http://www.smile.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Aff...
ass SmileDBLogger: def __init__(self, dbname, model_name, res_id, uid=0): assert isinstance(uid, (int, long)), 'uid should be an integer' self._logger = logging.getLogger('smile_log') db = RegistryManager.get(dbname)._db pid = 0 try: cr = db.cursor() ...
e("create sequence smile_log_seq") cr.execute("select nextval('smile_log_seq')") res = cr.fetchone() pid = res and res[0] or 0 finally: cr.close() self._logger_start = datetime.datetime.now() self._logger_args = {'dbname': dbname, 'model_name': mo...
DigitalCampus/django-oppia
tests/oppia/management/test_data_retention.py
Python
gpl-3.0
2,111
0
import datetime from django.contrib.auth.models import User from django.core.management import call_command from django.utils import timezone from io import StringIO from oppia.models import Tracker from oppia.test import OppiaTestCase class DataRetentionTest(OppiaTestCase): fixtures = ['tests/test_user.json'...
d"), timezone.get_current_timezone()) user.save() start_user_count = User.objects.all().count() call_command('data_retention', self.STR_NO_INPUT, stdout=out) end_user_count = User.objects.all().count() self.assertEqual(start_user_count-1, end_user_count) def tes...
r" user.last_login = timezone.make_aware( datetime.datetime.strptime('2000-01-01', "%Y-%m-%d"), timezone.get_current_timezone()) user.save() tracker = Tracker() tracker.user = user tracker.save() start_user_count = User.objects.all().count() ...
bohdan-shramko/learning-python
source/chapter09/alien_blaster.py
Python
mit
656
0.009146
# Alien Blaster # Demonstrates object interaction class Player(object): """ A player in a shooter game. """ def blast(self, enemy): print("The player blasts an enemy.\n") enemy.die() class Alien(object): """ An alien in a shooter game. """ def die(self): print("The alien gasps ...
"Yes, it's getting d
ark now. Tell my 1.6 million larvae that I loved them... \n" \ "Good-bye, cruel universe.'") # main print("\t\tDeath of an Alien\n") hero = Player() invader = Alien() hero.blast(invader) input("\n\nPress the enter key to exit.")
stfc/cvmfs-stratum-uploader
uploader/projects/admin.py
Python
apache-2.0
642
0
from django import forms from django.contrib import admin from django.contrib.admin import ModelAdmin from guardian.admin import GuardedModelAdmin from uploader.projects.models import FileSystem, Project class FileSystemAdminForm(forms.ModelForm): class Meta: model = FileSystem class ProjectAdmin(Guarde...
dmin.site.register(FileSystem, admin_class=FileSystemAdmin) admin.site.register(Project, admi
n_class=ProjectAdmin)
ktan2020/legacy-automation
win/Lib/distutils/tests/test_build_scripts.py
Python
mit
3,712
0.000808
"""Tests for distutils.command.build_scripts.""" import os import unittest from distutils.command.build_scripts import build_scripts from distutils.core import Distribution import sysconfig from distutils.tests import support from test.test_support import run_unittest class BuildScriptsTestCase(suppor...
built = os.listdir(target) for name in expected: self.assertTrue(name in built) def get_build_scripts_cmd(self, target, scripts): import sys dist = Distribution() dist.scripts = scripts dist.command_obj["build"] = supp
ort.DummyCommand( build_scripts=target, force=1, executable=sys.executable ) return build_scripts(dist) def write_sample_scripts(self, dir): expected = [] expected.append("script1.py") self.write_script(dir, "script1.py", ...
stevetjoa/algorithms
kth_smallest_loop.py
Python
mit
470
0.002128
def kth_smallest(arr, k): n = len(arr) a = 0 b = n while a < b: piv = a for i in range(a, b): if ar
r[piv] > arr[i]: arr[i], arr[piv] = arr[piv], arr[i] piv = i if piv == k: return arr[piv] elif piv < k: a = piv+1 else: b = piv-1 arr = [9, 3, 5, 6, 1, 3, 3] prin
t arr for i in range(-1, len(arr)+1): print i, kth_smallest(arr, i)
lyubomir1993/AlohaServer
Client.py
Python
apache-2.0
616
0.008117
#!/usr/bin/python import json class Client(): def __init__(self, clientHostName, clientPort, channel): self.clientHostName = clientHostName self.clientPort = clientPort self.c
lientType = self.getClientType() self.channel = channel # TO DO implement this method properly def getClientType(self): try: self.WebClient = "Web Client" self.MobileClient = "Mobile Client" return self.WebClient except ImportError as e: ...
exit(0)
arocks/edge
src/accounts/forms.py
Python
mit
3,105
0.000966
from __future__ import unicode_literals from django.contrib.auth.forms import AuthenticationForm from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, HTML, Field from authtools import forms as authtoolsforms from django.contrib.auth import forms as authform...
d"), Submit("sign_up", "Sign up", css_class="btn-warning"),
) class PasswordChangeForm(authforms.PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field("old_password", placeholder="Enter old password", autofocus=""), Fie...
effa/flocs
blocks/migrations/0005_blockmodel_difficulty.py
Python
gpl-2.0
475
0.002105
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('blocks', '0004_auto_20160305_2025'), ] operations = [ migrations.AddField( model_
name='blockmodel', name='difficulty', field=
models.FloatField(default=1.0, help_text='real number between -1 (easiest) and 1 (most difficult)'), ), ]
lenovo-network/networking-lenovo
networking_lenovo/db/migration/alembic_migrations/__init__.py
Python
apache-2.0
639
0
# Copyright (c) 2017, Lenovo. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may n
ot use this file except in compliance with the License. # You may obtain a copy of the L
icense 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 ...
mcmcplotlib/mcmcplotlib
api/generated/arviz-plot_kde-7.py
Python
apache-2.0
43
0
az.plot_kde(mu_posterior, cumula
tive=True)
pstjohn/pyefm
pyefm/ElementaryFluxVectors.py
Python
bsd-2-clause
5,857
0.002733
import pandas as pd import numpy as np import cobra from pyefm.ElementaryFluxModes import EFMToolWrapper from tqdm import tqdm class EFVWrapper(EFMToolWrapper): def create_matrices(self, extra_g=None, extra_h=None): """ Initialize the augmented stoichiometric matrix. extra_g: (n x nr) array ...
1))]), np.hstack([G, -np.eye(nt), np.atleast_2d(-h).T]) ]) def create_model_files(self, temp_dir): # Stoichiometric Matrix np.savetxt(temp_dir + '/stoich.txt', self.D, delimiter='\t') # Reaction reversibilities np.savetxt( temp_dir + '/revs.txt', np...
er_bound < 0 for r in self.model.reactions]), np.zeros((self.nt + 1))]), delimiter='\t', fmt='%d', newline='\t') # Reaction Names r_names = np.hstack([ np.array([r.id for r in self.model.reactions]), np.array(['s{}'.format(i) for i in range(se...
kmichel/po-localization
po_localization/po_file.py
Python
mit
6,436
0.001709
# coding=utf-8 from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import re from io import StringIO from .strings import escape EMBEDDED_NEWLINE_MATCHER = re.compile(r'[^\n]\n+[^\n]') class PoFile(object): def __init__(self): self.header...
return max(max(self.translations.keys()) + 1, self.MIN_NPLURALS) else: return self.MIN_NPLURALS def multiline_escape(string): if EMBEDDED_NEWLINE_MATCHER.search(string): lines = string.split('\n') return ( '""\n' + '\n'.join('"{}\\n"'.format(escape(li...
inclement/kivy
kivy/base.py
Python
mit
19,012
0
# pylint: disable=W0611 ''' Kivy Base ========= This module contains the Kivy core functionality and is not intended for end users. Feel free to look through it, but bare in mind that calling any of these methods directly may result in an unpredictable behavior as the calls access directly the event loop of an applica...
ng( 'Base: Failed to import "andr
oid" module. ' 'Could not remove android presplash.') return def post_dispatch_input(self, etype, me): '''This function is called by :meth:`EventLoopBase.dispatch_input()` when we want to dispatch an input event. The event is dispatched to all listeners and if gr...
fxb22/BioGUI
plugins/Views/BLASTView.py
Python
gpl-2.0
5,154
0.005627
import wx import listControl as lc import getPlugins as gpi from decimal import Decimal import os class Plugin(): def OnSize(self): # Respond to size change self.bPSize = self.bigPanel.GetSize() self.list.SetSize((self.bPSize[0] - 118, self.bPSize[1] - 40)) self.ButtonShow(False) ...
nel.Bind(wx.EVT_BUTTON, self.DoView
, self.buttons[-1]) def Init(self, parent, bigPanel, colorList): self.hd = os.getcwd() self.colorList = colorList self.bigPanel = bigPanel self.bPSize = self.bigPanel.GetSize() self.list = lc.TestListCtrl(self.bigPanel, -1, size = (0,0), p...
skosukhin/spack
var/spack/repos/builtin/packages/xcb-util-wm/package.py
Python
lgpl-2.1
1,996
0.000501
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
ck import * class XcbUtilWm(AutotoolsPackage): """The XCB util modules provides a number of libraries which sit on top of libxcb, the core X protocol library, and some of the extension libraries. These experimental libraries provide convenience functions and interfaces which make the raw X protocol mo...
" homepage = "https://xcb.freedesktop.org/" url = "https://xcb.freedesktop.org/dist/xcb-util-wm-0.4.1.tar.gz" version('0.4.1', '0831399918359bf82930124fa9fd6a9b') depends_on('libxcb@1.4:') depends_on('pkg-config@0.9.0:', type='build')
johnbellone/gtkworkbook
etc/socketTest.py
Python
gpl-2.0
626
0.01278
#!/usr/bin/env python import sys import optparse import socket def main(): p = optparse.OptionParser() p.add_option("--port", "-p", default=8888) p.add_option("--input", "-i", default="test.txt") options,
arguments = p.parse_args()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("localhost", options.port)) fp = open(options.input, "r") ii = 0 sock.sendall ("^0^1^sheet1^1000000^3\n") while ii < 1000000: sock.sendall ("^%d^0^sheet1^%d^0^^0\n" %(ii, ii)) ii = ii + 1 sock....
splone/splonebox-client
test/functional/test_complete_call.py
Python
lgpl-3.0
4,205
0
""" This file is part of the splonebox python client library. The splonebox python client library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License or any later version. It i...
ult.get_status(), -1) # make sure response is o
nly handled once with self.assertRaises(KeyError): core._rpc._handle_response(response) # test valid response result = plug.register(blocking=False) outgoing = msgpack.unpackb(mock_send.call_args_list[1][0][0]) response = MResponse(outgoing[1]) response.respo...
gepatino/github-indicator
ghindicator/options.py
Python
gpl-3.0
1,950
0.001539
# -*- coding: utf
-8 -*- """ github-indicator options Author: Gabriel Patiño <gepatino@gmail.com> License: Do whatever you want """ import optparse import os import xdg.BaseDirectory from ghindicator import language __v
ersion__ = (0, 0, 4) # Hack to fix a missing function in my version of xdg if not hasattr(xdg.BaseDirectory, 'save_cache_path'): def save_cache_path(resource): path = os.path.join('/', xdg.BaseDirectory.xdg_cache_home, resource) if not os.path.exists(path): os.makedirs(path) ret...
trezor/micropython
tests/extmod/vfs_blockdev.py
Python
mit
1,588
0.003778
# Test for behaviour of combined standard and extended block device try: import uos uos.VfsFat uos.VfsLfs2 except (ImportError, AttributeError): print("S
KIP") raise SystemExit class RAMBlockDevice: ERASE_BLOCK_SIZE = 512 def __init__(self, blocks): self.data = bytearray(blocks * self.ERASE_BLOCK_SIZE) def readblocks(self, block, buf, off=0): addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): bu
f[i] = self.data[addr + i] def writeblocks(self, block, buf, off=None): if off is None: # erase, then write off = 0 addr = block * self.ERASE_BLOCK_SIZE + off for i in range(len(buf)): self.data[addr + i] = buf[i] def ioctl(self, op, arg): if...
hschilling/pyOpt
examples/history.py
Python
gpl-3.0
1,731
0.023108
#!/usr/bin/env python ''' Solves Constrainted Toy Problem Storing Optimization History. min x1^2 + x2^2 s.t.: 3 - x1 <= 0 2 - x2 <= 0 -10 <= x1 <= 10 -10 <= x2 <= 10 ''' # ============================================================================= # Standard Python modules # ===========================...
opt_prob.solution(0) # Solve Problem Using S
tored History (Warm Start) slsqp.setOption('IFILE','slsqp2.out') slsqp(opt_prob, store_hst=True, hot_start='slsqp1') print opt_prob.solution(1)
stackforge/ec2-api
ec2api/cmd/api_metadata.py
Python
apache-2.0
1,007
0
# Copyright 2014 # The Cloudscaling Group, 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...
limitations under the License. """ EC2api API Metadata Server """ import sys from oslo_config import cfg from oslo_log import log as logging from ec2api import config from ec2api import service CONF = cfg.CONF def ma
in(): config.parse_args(sys.argv) logging.setup(CONF, "ec2api") server = service.WSGIService('metadata') service.serve(server, workers=server.workers) service.wait() if __name__ == '__main__': main()
ULHPC/easybuild-easyblocks
easybuild/easyblocks/m/metavelvet.py
Python
gpl-2.0
2,000
0.0025
## # This file is an EasyBuild reciPY as per https://github.com/hpcugent/easybuild # # Copyright:: Copyright 2012-2017 Uni.Lu/LCSB, NTUA # Authors:: Cedric Laczny <cedric.laczny@uni.lu>, Fotis Georgatos <fotis@cern.ch>, Kenneth Hoste # License:: MIT/GPL # $Id$ # # This work implements a part of the HPCBIOS project ...
srcfile = None # Get executable files: for i in $(find . -maxdepth 1 -type f -perm +111 -print | sed -e 's/\.\///g' | awk '{print "\""$0"\""}' | grep -vE "\.sh|\.html"); do echo -n
e "$i, "; done && echo try: os.makedirs(destdir) for filename in ["meta-velvetg"]: srcfile = os.path.join(srcdir, filename) shutil.copy2(srcfile, destdir) except OSError, err: raise EasyBuildError("Copying %s to installation dir %s fail...
Tassie-Tux/funtoo-overlay
funtoo/scripts/gentoo-compare-json.py
Python
gpl-2.0
4,518
0.035414
#!/usr/bin/python3 # This script will compare the versions of ebuilds in the funtoo portage tree against # the versions of ebuilds in the target portage tree. Any higher versions in the # target Portage tree will be printed to stdout. import portage.versions import os,sys import subprocess import json from merge_ut...
our list just because someone added it masked to the tree. It makes comparisons fairer. """ filtered = ebuilds[:] if len(ebuilds) == 0: return [] cps = portage.versions.catpkgsplit(filtered[0]) cat = cps[0] pkg
= cps[1] keywords = set(keywords) while True: fbest = portage.versions.best(filtered) if fbest == "": break retval, fkeywords = getKeywords(portdir, "%s/%s/%s.ebuild" % (cat, pkg, fbest.split("/")[1] ), warn) if len(keywords & fkeywords) == 0: filtered.remove(fbest) else: break return filtered ...
bad-ants-fleet/ribolands
docs/conf.py
Python
mit
8,549
0.005966
# -*- coding: utf-8 -*- # # ribolands documentation build configuration file, created by # sphinx-quickstart on Fri Mar 18 15:59:48 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
#sys.path.insert(0, os.path.abspath('.')) sys.path.append(os.path.abspath('..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can...
'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source fil...
jensenbox/singnet
agent/adapters/tensorflow/__init__.py
Python
mit
57
0
# adapters/tensorflow module ini
tialization goes h
ere...
floemker/django-wiki
src/wiki/plugins/links/__init__.py
Python
gpl-3.0
59
0
default_app_config = 'wi
ki.plug
ins.links.apps.LinksConfig'
sparkslabs/kamaelia
Sketches/MPS/Old/SoC/simplecube.py
Python
apache-2.0
4,689
0.025592
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
rtex3f(-1.0,1.0,1.0) glVertex3f(-1.0,1.0,-1.0) glVertex3f(1.0,1.0,-1.0) glColor3f(1.0,1.0,0.0) glVertex3f(1.0,-1.0,1.0) glVertex3f(-1.0,-1.0,1.0) glVertex3f(-1.0,-1.0,-1.0) glVertex3f(1.0,-1.0,-1.0) glEnd() glP...
p() if __name__=='__main__': from Kamaelia.Util.Graphline import Graphline Graphline( TRANSLATION = bounce3D(), ROTATION = angleIncrement(), CUBE = rotatingCube(), linkages = { ("ROTATION", "outbox") : ("CUBE", "angle"), ("TRANSLATION", "outbox") : ("CUBE", "pos...
emburse/python-quickbooks
setup.py
Python
mit
1,374
0
import codecs import os from setuptools import setup, find_packages def read(*parts): filename = os.path.join(os.path.dirname(__file__), *parts) with codecs.open(filename, encoding='utf-8') as fp: return fp.read() VERSION = (0, 3, 9) version = '.'.join(map(str, VERSION)) setup( name='python-qu...
.7', 'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], packages=find_packages(), )
vstconsulting/polemarch
polemarch/main/migrations/0033_auto_20171211_0732.py
Python
agpl-3.0
628
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2017-12-11 07:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies
= [ ('main', '0032_history_json_args'), ] operations = [ migrations.AddField( model_name='history',
name='revision', field=models.CharField(blank=True, max_length=256, null=True), ), migrations.AlterField( model_name='history', name='json_args', field=models.TextField(default='{}'), ), ]
igryski/Indices_icclim_ClipC
src/PRECIP/get_put_invar_tracking_id_python_PRECIP.py
Python
gpl-3.0
11,422
0.036508
# Import the old tracking id from the RCM file for period 19660101-19701231, # as it is the first used file to create historical indices: # (e.g. tasmin_EUR-44_IPSL-IPSL-CM5A-MR_historical_r1i1p1_SMHI-RCA4_v1_day_19660101-19701231.nc) #track_GCM_indice=$( import netCDF4 from netCDF4 import Dataset import ctypes imp...
ist, '*CCCma-CanESM2_historical*'): if fnmatch.fnmatch(file_hist, "*"+model_fout+"_historical*"): #if fnmatch.fnmatch(file_hist, "*historical*"): print "Indice where new historical invar_tracking_id goes is:", file_hist #pri
nt #print '%s' % (model) # Create Dataset from these files nc_indice_pr_hist = Dataset(out_path_RCM_pr_nbc_50km+file_hist,'a') # Insert invar_tracking_id global attributed with value on the right # (imported RCM tracking id from the single RCM file above) #nc_indice_pr_hist.comment='fun' nc...
kochetov-a/python_training
fixture/session.py
Python
apache-2.0
2,654
0.001881
# Класс-помощник для работы с сессией class SessionHelper: def __init__(self, app): self.app = app # Функция входа на сайт def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_name("user").click() wd.find_element_by_name...
def ensure_login(self, username, password): wd
= self.app.wd # Если пользователь вошел на сайт if self.is_logged_in(): # И если пользователь вошел на сайт под ожидаемым именем if self.is_logged_in_as(username): # Тогда ничего не делаем return else: # Иначе производим...
tensorflow/tensorflow
tensorflow/python/eager/lift_to_graph_test.py
Python
apache-2.0
3,531
0.004815
# Copyright 2019 The TensorFlow Aut
hors. 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 writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY K...
sayan801/indivo_server
indivo/urls/carenet.py
Python
gpl-3.0
1,997
0.022534
from django.conf.urls.defaults import * from indivo.views import * from indivo.lib.utils import MethodDispatcher urlpatterns = patterns('', (r'^$', MethodDispatcher({ 'DELETE' : carenet_delete})), (r'^/rename$', MethodDispatcher({ 'POST' : carenet_rename})), (r'^/record$', ...
patcher({ 'PUT' : carenet_apps_create, 'DELETE': carenet_apps_delete})), # Permissions Calls (r'^/accounts/(
?P<account_id>[^/]+)/permissions$', MethodDispatcher({ 'GET' : carenet_account_permissions })), (r'^/apps/(?P<pha_email>[^/]+)/permissions$', MethodDispatcher({ 'GET' : carenet_app_permissions })), # Reporting Calls (r'^/reports/minimal/procedures/$', MethodDispatch...
sixty-north/cosmic-ray
tools/inspector.py
Python
mit
491
0.002037
# This is just a simple example of how to inspect ASTs visually. # #
This can be useful for developing new operators, etc. import ast from cosmic_ray.mutating import MutatingCore from cosmic_ray.operators.comparison_opera
tor_replacement import MutateComparisonOperator code = "((x is not y) ^ (x is y))" node = ast.parse(code) print() print(ast.dump(node)) core = MutatingCore(0) operator = MutateComparisonOperator(core) new_node = operator.visit(node) print() print(ast.dump(new_node))
knuu/competitive-programming
atcoder/abc/abc003_c.py
Python
mit
137
0
N, K = map(int, in
put().split()) R = sorted(map(int, input().split())) ans = 0 for r in R[len(R)-K:]: ans = (ans + r) / 2 print(
ans)
eroicaleo/ThePythonStandardLibraryByExample
ch01Text/1.3re/ConstrainSearch.py
Python
mit
508
0
#!/usr/bin/env python3 import re text = 'This is some
text -- with punctuation.' pattern = 'is' print('Text :', text) print('Pattern:', pattern) m = re.match(pattern, text) print('Match :', m) s = re.search(pattern, text) print('Search :', s) pattern = re.compile(r'\b\w*is\w*\b') print('Text:', text) pos = 0 while True: match = pattern.search(text, pos) if...
pos = e
imownbey/dygraphs
plotkit_v091/doc/generate.py
Python
mit
867
0.00692
#!/usr/bin/python import sys import os import re sys.path.append('/home/al/sites') os.environ['DJANGO_SETTINGS_MODULE'] = '__main__' DEFAULT_CHARSET = "utf-8" TEMPLATE_DEBUG = False LANGUAGE_CODE = "en" INSTALLED_APPS = ( 'django.contrib.markup', ) TEMPLATE_DIRS = ( '/home/al/sites/liquidx/templates', ...
to_string(src, {}) open(dst, 'w').write(filled) if __name__ == "__main__": for dirname, dirs, files in os.walk('.'): if re.search('/\.svn', dirname):
continue for f in files: if f[-4:] == ".txt": newname = f.replace('.txt', '.html') make(os.path.join(dirname, f), os.path.join(dirname, newname))
allenai/document-qa
docqa/configurable.py
Python
apache-2.0
6,024
0.001992
import json from collections import OrderedDict from inspect import signature from warnings import warn import numpy as np from sklearn.base import BaseEstimator class Configuration(object): def __init__(self, name, version, params): if not isinstance(name, str): raise ValueError() if...
ctor before init = cls.__init__ if init is object.__init__: # No explicit constructor to introspect return [] init_signature = signature(init) parameters = [p for p in init_signature.parameters
.values() if p.name != 'self'] if any(p.kind == p.VAR_POSITIONAL for p in parameters): raise RuntimeError() return sorted([p.name for p in parameters]) @property def name(self): return self.__class__.__name__ @property def version(self): ...
madsbk/bohrium
bridge/py_api/bohrium_api/messaging.py
Python
apache-2.0
934
0.001071
""" Send and receive pre-defined messages through the Bohrium component stack ========================================================================= """ from ._bh_api import message as msg def statistic_enable_and_reset(): """Reset and enable the Bohrium statistic""" return msg("statistic_enable_and_reset...
return msg("statistic") def gpu_disable(): """Disable the GPU backend in the current runtime stack""" return msg("GPU: disable") def gpu_enable(): """Enable the GPU backend in the current runtime stack""" return msg("GPU: enable") def runtime_info(): """Return a YAML string describing the curr...
fo") def cuda_use_current_context(): """Tell the CUDA backend to use the current CUDA context (useful for PyCUDA interop)""" return msg("CUDA: use current context")
kassoulet/soundconverter
setup.py
Python
gpl-3.0
2,521
0.000793
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # SoundConverter - GNOME application for converting between audio formats. # Copyright 2004 Lars Wirzenius # Copyright 2005-2020 Gautier Portet # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as ...
sys try: i
mport DistUtilsExtra.auto except ImportError: sys.stderr.write('You need python-distutils-extra\n') sys.exit(1) import os import DistUtilsExtra.auto # This will automatically, assuming that the prefix is /usr # - Compile and install po files to /usr/share/locale*.mo, # - Install .desktop files to /usr/share/a...
sander76/home-assistant
tests/components/geonetnz_quakes/test_sensor.py
Python
apache-2.0
4,517
0.001328
"""The tests for the GeoNet NZ Quakes Feed integration.""" import datetime from unittest.mock import patch from homeassistant.components import geonetnz_quakes from homeassistant.components.geonetnz_quakes import DEFAULT_SCAN_INTERVAL from homeassistant.components.geonetnz_quakes.sensor import ( ATTR_CREATED, ...
k_entry_3] async_fire_time_changed(hass, utcnow + DEFAULT_SCAN_INTERVAL) await hass.async_block_till_done()
all_states = hass.states.async_all() assert len(all_states) == 4 state = hass.states.get("sensor.geonet_nz_quakes_32_87336_117_22743") attributes = state.attributes assert attributes[ATTR_CREATED] == 1 assert attributes[ATTR_UPDATED] == 2 assert attributes[ATTR_REMO...
blackball/an-test6
util/tstimg.py
Python
gpl-2.0
249
0.052209
import pyfits from numpy import * if __name__ == '__main__': W,H = 10,10 sigma = 1. X,Y = meshgrid(range(W), r
ange(H)) img = 50 + 200 * exp(-0.5 * ((X -
W/2)**2 + (Y - H/2)**2)/(sigma**2)) pyfits.writeto('tstimg.fits', img, clobber=True)
googledatalab/pydatalab
datalab/bigquery/commands/_bigquery.py
Python
apache-2.0
43,171
0.012161
# Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
the table to delete.', required=True) return delete_parser def _create_sample_subparser(parser): sample_parser = parser.subcommand('sample', 'Display a sample of the results of a BigQuery SQL query.\nThe ' '...
ariables ' 'in the query,\nif -q/--query was used, or it can contain SQL ' 'for a query.') group = sample_parser.add_mutually_exclusive_group() group.add_argument('-q', '--query', help='the name of the query to sample') group.add_argument('-t...