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
jacekburys/csmith
programs/validate.py
Python
bsd-2-clause
1,157
0.025929
import math import sys import re valuePattern = re.compile('= (.+)$') def extractValue(line): match = re.search(valuePattern, line) if match: return float.fromhex(match.group(1)) else: return "ERROR" intervalPattern = re.compile('= \[(.*?), (.*?)\]') def extractInterval(line): match = re.search(interv...
atch: lower =
float.fromhex(match.group(1)) upper = float.fromhex(match.group(2)) return (lower, upper) else: return "ERROR" def isInInterval(value, lower, upper): return lower<=value and value<=upper #f1 - values, f2 - ranges f1 = open(str(sys.argv[1]), 'r') f2 = open(str(sys.argv[2]), 'r') wide = 0 total = 0 re...
call-me-jimi/taskmanager
taskmanager/lib/hDBSessionMaker.py
Python
gpl-2.0
4,630
0.019654
# create a Session object by sessionmaker import os import ConfigParser import sqlalchemy.orm # get path to taskmanager. it is assumed that this script is in the lib directory of # the taskmanager package. tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..' ) ) etcpath =...
#The engine that is connected to the database #use "echo=True" for SQL printing statements...
self.engine = sqlalchemy.create_engine( "{dialect}://{user}:{password}@{host}:{port}/{name}".format( dialect=databaseDialect, user=databaseUsername, ...
hexlism/xx_net
gae_proxy/local/proxy_handler.py
Python
bsd-2-clause
14,990
0.002935
#!/usr/bin/env python # coding:utf-8 import errno import socket import ssl import urlparse import OpenSSL NetWorkIOError = (socket.error, ssl.SSLError, OpenSSL.SSL.Error, OSError) from proxy import xlog import simple_http_client import simple_http_server from cert_util import CertUtil from config import config imp...
r): gae_support_methods = tuple(["GET", "POST", "HEAD", "PUT", "DELETE", "PATCH"]) bufsize = 256*1024 max_retry = 3 def setup(self)
: self.__class__.do_GET = self.__class__.do_METHOD self.__class__.do_PUT = self.__class__.do_METHOD self.__class__.do_POST = self.__class__.do_METHOD self.__class__.do_HEAD = self.__class__.do_METHOD self.__class__.do_DELETE = self.__class__.do_METHOD self.__class__.do_OP...
dahlstrom-g/intellij-community
python/testData/refactoring/rename/epydocRenameParameter_after.py
Python
apache-2.0
120
0
def func(bar): """ \\some comment @param bar: The parameter value.
@type bar: Its type.""
" pass
kevin-coder/tensorflow-fork
tensorflow/python/autograph/operators/control_flow.py
Python
apache-2.0
14,926
0.007571
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
loops.') def reduce_body(state, iterate): new_state = body(iterate, *state) return new_state if init_state: return ds.reduce(init_state, reduce_body) # Workaround for Datset.reduce not allowing empty state tensors - create # a dummy state variable that remains unused. def reduce_body_with_dummy...
return state ds.reduce((constant_op.constant(0),), reduce_body_with_dummy_state) return () def while_stmt(test, body, init_state, opts=None): """Functional form of a while statement. The loop operates on a so-called state, which includes all symbols that are variant across loop iterations. In what foll...
lanacioncom/ddjj_admin_lanacion
admin_ddjj_app/migrations/0001_initial.py
Python
mit
15,375
0.003187
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Bien', fields=[ ('id', models.AutoField(verbose...
eld(verbose_name='ID', serialize=Fals
e, auto_created=
p4u/magicOS
files/home/crypto/mp-agent.py
Python
gpl-3.0
2,955
0.045685
import os import json import urllib import socket import subprocess as sub import string import sys MPCONF = "/etc/magicpool.conf" MPURL = "https://magicpool.org/main/download_config/${U}/${W}/${G}" SGCONF = "/home/crypto/.sgminer/sgminer.conf" def niceprint(data): return json.dumps(data,sort_keys=True,indent=4, se...
("/tmp/get-pool.md5.1","r") md52 = open("/tmp/get-pool.md5.2","r") if md51.read() == md52.read(): print "No changes in configuration" else: print "Found changes in configuration, restarting sgminer" #os.system('echo "quit|1" | nc 127.0.0.1 4028') os.system('killall -USR1 sgminer') md51.clo
se() md52.close() def getMPconf(): try: mpconf = open(MPCONF,"r") mp = json.loads(mpconf.read()) user = mp['username'] worker = mp['workeralias'] except: user = "generic" worker = "generic" return {"user":user,"worker":worker} def getMPremote(): url = MPURL mpconf = getMPconf() gpu = getGPU() s = ...
lfzyx/ButterSalt
manage.py
Python
mit
505
0
""" RUN RUN RUN ! """ from buttersalt import create_app from flask_script import Manager, Shell app = create_
app('default') manager = Manager(app) def make_shell_context(): return dict(app=app) manager.add_command("shell", Shell(make_context=make_shell_context)) @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()
istio/tools
perf/load/auto-mtls/scale.py
Python
apache-2.0
4,271
0.000937
#!/usr/bin/env python3 # Copyright Istio Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
tations under the License. import sys import os import random import time import typing import subprocess import argparse import http.server from urllib.parse import urlparse, parse_qs TEST_NAMESPACE = 'automtls' ISTIO_DEPLOY = 'svc-0-back-istio' LEGACY_DEPLOY = 'svc-0-back-legacy' class testHTTPServer_RequestHa...
_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() query = parse_qs(urlparse(self.path).query) istio_percent = random.random() if 'istio' in query: istio_percent = float(query['istio'][0]) message = sim...
mgupta011235/TweetSafe
tfidf/train_xgboost.py
Python
gpl-3.0
7,095
0.00902
from sklearn.feature_extraction.text import TfidfVectorizer import xgboost as xgb import cPickle as pickle from string import punctuation from nltk import word_tokenize from nltk.stem import snowball import numpy as np import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.style...
oss_val.csv' # dfcv = pd.read_csv(cvpath) # Xcv = dfcv['tweet_text'].values # ycv = dfcv['label'].values # # print "transforming cross val data..." # tfidf_Xcv = vect.transform(Xcv) # tfidf_Xcvd = tfidf_Xcv.todense() # # xg_cv = xgb.DMatrix(tfidf_Xcvd, label=ycv) # print "loadin...
ain2.buffer') # xg_cv = xgb.DMatrix('xg_cv2.buffer') train_tstart = time.time() print 'training...' #parameters param = {'max_depth':4, 'eta':0.3, 'silent':1, 'objective':'binary:logistic', 'eval_metric':'auc' } #number of booste...
SKIRT/PTS
core/prep/sphconvert.py
Python
agpl-3.0
6,914
0.019818
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
(pc) M(Msun) Z(0-1) def convert_gas_ULB(infile, outfile): PARSEC = 3.08568e16 # 1 parsec (in m) AU = 1.496e11 # 1 AU (in m) CONV = (100. * AU) / PARSEC x,y,z,M,h = np.loadtxt(infil
e, usecols=(0,1,2,3,4), unpack=True) fid = open(outfile, 'w') fid.write('# SPH Gas Particles\n') fid.write('# Converted from ULB output format into SKIRT6 format\n') fid.write('# Columns contain: x(pc) y(pc) z(pc) h(pc) M(Msun) Z(0-1)\n') np.savetxt(fid, np.transpose((x*CONV,y*CONV,z*CONV,5*h*CONV,M...
cydenix/OpenGLCffi
OpenGLCffi/GLES1/EXT/EXT/discard_framebuffer.py
Python
mit
181
0.016575
from OpenGLCffi.GLES1 import par
ams @params(api='gles1', prms=['target', 'numAttachments', 'attachments']) def glDiscardFramebufferEXT(target, numAttachments, attachments): pass
homeworkprod/byceps
tests/integration/blueprints/admin/jobs/test_views.py
Python
bsd-3-clause
693
0
""" :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import pytest from tests.helpers import login_user def test_view_for_brand(jobs_admin_client): url = '/admin/jobs/' response = jobs_admin_client.get(url) assert response.status_code == 200 @pytest...
ckage') def jobs_admin(make_admin): permission_ids = { 'admin.access', 'jobs.view', } admin = make_admin('JobsAdmin', permission_ids) login_user(admin.id) return admin @pytest.fixture(scope='package') def jobs_admin_client(make_client, admin_app, jobs_admin): return make_client...
id)
eunchong/build
scripts/slave/recipe_modules/cronet/__init__.py
Python
bsd-3-clause
187
0
DEPS =
[ 'chromium', 'chromium_android', 'gsutil', 'recipe_engine/json', 'recipe_engine/path', 'rec
ipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', ]
cwant/tessagon
tests/core/test_tile.py
Python
apache-2.0
2,833
0
from core_tests_base import CoreTestsBase, FakeTessagon, FakeTileSubClass class TestTile(CoreTestsBase): # Note: these tests are highly dependent on the behavior of # FakeTessagon and FakeAdaptor def test_add_vert(self): tessagon = FakeTessagon() tile = FakeTileSubClass(tessagon, u_rang...
tile.add_vert(['top', 'left'], 0.25, 0.75) # [0.75, 0.75] is reflection of [0.25, 0.75] in U direction assert tile.blend(0.75, 0.75) == [0.875, 2.875] # Two verts added assert tile.verts['top']['left'] == tile.f(0.625, 2.875) assert tile.verts['top']['right'] == tile.f(0.8...
['right'] is None def test_add_vert_v_symmetric(self): tessagon = FakeTessagon() tile = FakeTileSubClass(tessagon, u_range=[0.5, 1.0], v_range=[2.5, 3.0], v_symmetric=True) tile.add_vert(['top', 'left'], 0.25, 0.75) # [...
nCoda/lychee
lychee/__init__.py
Python
gpl-3.0
1,444
0.00277
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #-------------------------------------------------------------------------------------------------- # Program Name: Lychee # Program Description: MEI document manager for formalized document control # # Filename: lychee/__init__.py # Purpose: ...
'converters', 'document', 'exceptions', 'logs', 'namespaces', 'signals', 'tui', 'workflow', 'vcs', 'views', ] from lychee import * from ._version import get_versions __version__ = get_ver
sions()['version'] del get_versions
aurynn/openstack-artifice
tests/test_models.py
Python
apache-2.0
6,823
0.003957
import unittest from artifice.models import usage, tenants, resources, Session from sqlalchemy import create_engine from sqlalchemy.exc import IntegrityError, InvalidRequestError from sqlalchemy.orm.exc import FlushError import os from artifice.models.usage import Usage from artifice.models.tenants import Tenant from ...
from datetime import datetime, timedelta TENANT_ID = "test tenant" RESOURCE_ID = "test resource" RESOURCE_ID_TWO = "A DIFFERENT RESOURCE" USAGE_ID = 12345 class SessionBase(unittest.TestCase): def setUp(self): engine = create_engine(os.environ["DATABASE_URL"]) Session.configure(bind=engine) ...
ef tearDown(self): self.session.rollback() for t in self.objects: try: self.session.delete(t) except InvalidRequestError: # This is fine pass self.session.commit() self.session = None class TestTenant(SessionBas...
EmadMokhtar/Django
tests/model_fields/models.py
Python
mit
12,373
0.000162
import os import tempfile import uuid from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.core.files.storage import FileSystemStorage from django.db import models from django.db.models.fields.files import Imag...
ass DurationModel(models.Model): field = models.DurationField() class NullDurationModel(models.Model): field = models.DurationField(null=True) class PrimaryKeyCharModel(models.Model): string = models.CharField(max_length=10, primary_key=True) class FksToBoo
leans(models.Model): """Model with FKs to models with {Null,}BooleanField's, #15040""" bf = models.ForeignKey(BooleanModel, models.CASCADE) nbf = models.ForeignKey(NullBooleanModel, models.CASCADE) class FkToChar(models.Model): """Model with FK to a model with a CharField primary key, #19299""" ou...
Marketing1by1/petl
petl/io/numpy.py
Python
mit
5,251
0.00019
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import from petl.compat import next, string_types from petl.util.base import iterpeek, ValuesView, Table from petl.util.materialise import columns def infer_dtype(table): import numpy as np # get numpy to infer dtype it = ...
ble = [('foo', 'bar', 'baz'), ... ('apples', 1, 2.5), ... ('oranges', 3, 4.4), ... ('pears', 7, .1)] >>> table = etl.wrap(table) >>> table.values('bar').array() array([1, 3, 7]) >>> # specify dtype
... table.values('bar').array(dtype='i4') array([1, 3, 7], dtype=int32) """ import numpy as np it = iter(vals) if dtype is None: peek, it = iterpeek(it, sample) dtype = np.array(peek).dtype a = np.fromiter(it, dtype=dtype, count=count) return a ValuesView.toarray = ...
GehirnInc/py3oauth2
py3oauth2/tests/test_utils.py
Python
mit
1,798
0
# -*- coding: utf-8 -*- from nose.tools import ( eq_, raises, ) from py3oauth2.utils import ( normalize_netloc, normalize_path, normalize_query, normalize_url, ) def test_normalize_url(): eq_(normalize_url('http://a/b/c/%7Bfoo%7D'), normalize_url('hTTP://a/./b/../b/%63/%7bfoo%7d')...
q_(normalize_netloc('user:pass@example.com', 80), 'user:pass@example.com') eq_(normalize_netloc('user:@example.com', 80), 'user@example.com') eq_(normalize_netloc(':pass@example.com', 80), ':pass@example.com') eq_(normalize_netloc('example.com:443', 80), 'example.com:443') eq_(normalize_netloc('example....
m:80', 80), 'example.com') eq_(normalize_netloc('example.com:', 80), 'example.com') def test_normalize_query(): eq_(normalize_query(''), '') eq_(normalize_query('b=c&a=b'), 'a=b&b=c') eq_(normalize_query('b&a=b'), 'a=b') eq_(normalize_query('b=&a=b'), 'a=b') eq_(normalize_query('b=%e3%81%84&a=...
fortharris/RedCenter
Extensions/VaultManager.py
Python
gpl-3.0
6,621
0.005588
import os from PyQt4 import QtCore, QtGui from Extensions.Global import sizeformat class SearchWidget(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) self._parent = parent self.setStyleSheet("""background: rgba(0, 0, 0, 50); border-radius: 0...
+ str(len(self.logDict))) # display size of total files self.sizeLabel.setText(sizeformat(self.vaultContentsSize)) self.showVaultEmptyLabel() except: self.redCenter.showMessage("Problem loading items in the vault.") self.redCenter.hideMessage() ...
else: self.vaultZeroContentLabel.show() def selectionMade(self): self.selected = self.selectedItems() if len(self.selected) > 0: self.redCenter.unlockButton.setEnabled(True) self.redCenter.deleteButton.setEnabled(True) else: s...
hack4sec/hbs-cli
tests/integration/test_HashlistsByAlgLoaderThread.py
Python
mit
8,236
0.004492
# -*- coding: utf-8 -*- """ This is part of HashBruteStation software Docs EN: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station_en Docs RU: http://hack4sec.pro/wiki/index.php/Hash_Brute_Station License: MIT Copyright (c) Anton Kuzmin <http://anton-kuzmin.ru> (ru) <http://anton-kuzmin.pro> (en) Integration tests f...
ed': 2, 'errors': '', 'parsed': 1, 'status': 'ready', 'common_by_alg': 3} hashlist_data = self.db.fetch_row("SELECT * FROM hashlists WHERE common_by_alg") assert int(self.db.fetch_one("SELECT when_loaded FROM hashlists WHERE common_by_alg")) > 0 for field in test_h...
M hashes WHERE hash = {0} AND salt={1} AND summ = {2} AND hashlist_id = 2". format(self.db.quote(_hash['hash']), self.db.quote(_hash['salt']), self.db.quote(_hash['summ'])) ) == 1 test_data = [ ( [ {'hash': 'a', 'salt': '1', 'summ': md5('a:1'), 'crack...
anhstudios/swganh
data/scripts/templates/object/weapon/melee/polearm/crafted_saber/shared_sword_lightsaber_polearm_s1_gen2.py
Python
mit
500
0.044
####
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 = Weapon() result.template = "object/weapon/melee/polearm/crafted_saber/shared_sword_lightsaber_polearm_s1_gen2.iff" res...
jakogut/python-relatorio
relatorio/templates/base.py
Python
gpl-3.0
1,717
0.000582
############################################################################### # # Copyright (c) 2007, 2008 OpenHex SPRL. (http://openhex.com) All Rights # Reserved. # # 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 ...
oStream(genshi.core.Stream): "Base class for the relatorio stre
ams." def render(self, method=None, encoding='utf-8', out=None, **kwargs): "calls the serializer to render the template" return self.serializer(self.events) def serialize(self, method='xml', **kwargs): "generates the bitstream corresponding to the template" return self.render(m...
gerencianet/gn-api-sdk-python
examples/pix_create_charge.py
Python
mit
463
0.004338
from gerencianet import Gerencianet from credentials import CREDENTIALS gn = Gerencianet(CREDENTIALS) params = { 'txid': '' } body = { 'calendario': { 'expiracao':
3600 }, 'devedor': { 'cpf': '', 'nome': '' }, 'valor': { 'original': '0.50' }, 'chave': '', 'solicitacaoPagador': 'Cobrança dos serviços prestados.' } response = gn.pix_create_charge(
params=params,body=body) print(response)
TaiSakuma/AlphaTwirl
tests/unit/selection/factories/test_AllFactory.py
Python
bsd-3-clause
685
0.020438
from alphatwirl.selection.factories.AllFactory import AllFactory from alphatwirl.selection.modules.basic import All from alphatwirl.selection.modules.basic import Any from alphatwirl.selection.modules.LambdaStr import LambdaStr import unittest ##__________________________________________________________________|| clas...
= All, LambdaStrClass = LambdaStr) obj = AllFactory(path_cfg_list, name = 'test_a
ll', **kargs) ##__________________________________________________________________||
cbrunet/fibermodes
fibermodes/slrc.py
Python
gpl-3.0
9,544
0.000105
# This file is part of FiberModes. # # FiberModes 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. # # FiberModes is distributed in the ...
**scalar** **scalar** No change **scalar** **list** List with one item **scala
r** **range** Range with one item **scalar** **code** Return the value list scalar First item of the list **list** **list** No change *list* *range* Range from first item to last item with same number of elements (but intermediate values could be different) ...
Princessgladys/googleresourcefinder
app/bubble_test.py
Python
apache-2.0
5,468
0.000549
# Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
e.en = 'foo' django_locale = 'en' return message and getattr(message, django_locale) or n class BubbleTest(unittest.TestCase): def setUp(self): self.real_auth_domain = os.environ.get('AUTH_DOMAIN', '') os.environ['AUTH_DOMAIN'] = 'test' self.real_get_message = bubble.get_message ...
e = self.real_get_message os.environ['AUTH_DOMAIN'] = self.real_auth_domain def test_value_info_extractor(self): s = model.Subject(key_name='haiti:example.org/123', type='hospital') s.set_attribute('title', 'title_foo', datetime.datetime.now(), users.User('test@examp...
DinoCow/airflow
tests/providers/amazon/aws/hooks/test_kinesis.py
Python
apache-2.0
2,545
0.001572
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distr
ibuted 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 file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses...
# # 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....
josyb/myhdl
example/uart_tx/uart_tx.py
Python
lgpl-2.1
2,870
0.009408
from myhdl import always, always_seq, block, delay, enum, instance, intbv, ResetSignal, Signal, StopSimulation @block def uart_tx(tx_bit, tx_valid, tx_byte, tx_clk, tx_rst): index = Signal(intbv(0, min=0, max=8)) st = enum('IDLE', 'START', 'DATA') state = Signal(st.IDLE) @always(tx_clk.posedg...
xaa): yield tx_clk.negedge tx_byte.next = v tx_valid.next = 1 yield tx_clk.negedge tx_valid.next = 0 yield delay(16 * 20)
raise StopSimulation return clk_gen, stimulus, uart_tx_inst dut = uart_tx_2 inst = tb(dut) inst.config_sim(trace=True) inst.run_sim(10000)
absortium/poloniex-api
setup.py
Python
mit
909
0
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='poloniex', version=...
scription='Python Poloniex API', long_description=README, url='https://github.com/absortium/poloniex.git', author='Andrey Samokhvalov', license='MIT', author_email='andrew.shvv@gmail.com', install_requires=[ 'asyncio', 'aiohttp', 'autobahn', 'pp-ez', 'requ...
'Programming Language :: Python :: 3.5', ], )
lucienfostier/gaffer
python/GafferOSLUI/OSLImageUI.py
Python
bsd-3-clause
9,411
0.040697
########################################################################## # # Copyright (c) 2013-2014, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions ...
name, valuePlug, True, plugName, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) ) if alphaValue: self.getPlug().addChild( Gaffer.NameValuePlug( name + ".A" if name else "A", alphaValue, True, plugName, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) ) def __channelLabelFromPlug( plug )...
e() elif plug.typeId() == Gaffer.Color3fPlug.staticTypeId() and plug.parent()["name"].getValue() == "": return "[RGB]" else: return plug.parent()["name"].getValue() ########################################################################## # Metadata ##############################################################...
Crystal-SDS/dashboard
crystal_dashboard/dashboards/crystal/zones/models.py
Python
gpl-3.0
192
0
class Zone: def __in
it__(self, id_zone, name, re
gion, description): self.id = id_zone self.name = name self.region = region self.description = description
endlessm/chromium-browser
third_party/catapult/netlog_viewer/netlog_viewer_build/build_for_appengine.py
Python
bsd-3-clause
1,450
0.004138
#!/usr/bin/env python # Copyright 2018 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. import glob import os import shutil import subprocess import sys netlog_viewer_root_path = os.path.abspath( os.path.join(os.pa...
". To install vulcanize on Linux: sudo apt-get install npm sudo npm install -g vulcanize '''[1:]) sys.exit(1) for fn in glob.glob(os.path.join(src_dir, "*.png")): shutil.copyfile(fn, os.path.join(out_dir, o
s.path.split(fn)[1]))
petrutlucian94/nova
nova/objects/dns_domain.py
Python
apache-2.0
2,520
0
# Copyright (C) 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...
le_classmethod def get_all(cls, contex
t): db_domains = db.dnsdomain_get_all(context) return base.obj_make_list(context, cls(context), objects.DNSDomain, db_domains)
zuun77/givemegoogletshirts
leetcode/python/897_increasing-order-search-tree2.py
Python
apache-2.0
796
0.003769
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def increasingBST(self, root: TreeNode) -> TreeNode: def dfs(node): if not node.left and not node.right: return node ...
node.right = dfs(node.right) if node.left: head = dfs(node.left) cur = head while cur.right:
cur = cur.right cur.right = node return head else: return node return dfs(root) t = TreeNode(2) t.left = TreeNode(1) tt = Solution().increasingBST(t) print(tt.val, tt.right.val)
alon/polinax
libs/external_libs/docutils-0.4/test/test_transforms/test_substitutions.py
Python
gpl-2.0
9,979
0.004109
#! /usr/bin/env python # Author: David Goodger # Contact: goodger@users.sourceforge.net # Revision: $Revision: 4233 $ # Date: $Date: 2005-12-29 00:48:48 +0100 (Thu, 29 Dec 2005) $ # Copyright: This module has been placed in the public domain. """ Tests for docutils.transforms.references.Substitutions. """ from __ini...
): parser = Parser() s = DocutilsTestSupport.TransformTestSuite(parser) s.generateTests(totest) return s totest = {} totest['substitutions'] = ((Substitutions,), [ ["""\ The |biohazard| symbol is deservedly scary-looking. .. |biohazard| image:: biohazard.png """, """\ <document source="
test data"> <paragraph> The \n\ <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition names="biohazard"> <image alt="biohazard" uri="biohazard.png"> """], ["""\ Here's an |unknown| substitution. """, """\ <document source="test ...
lfalvarez/nouabook
votainteligente/urls.py
Python
gpl-3.0
1,050
0.013333
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.conf.urls.i18n import i18n_patterns admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'votainteligente.views.home', name='home'), ...
able admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), url(r'^i18n/', include('django.conf.urls.i18n')), #url(r'^', include('elections.urls')), #('^pages/', include('fla...
#(r'^tinymce/', include('tinymce.urls')), ) urlpatterns += i18n_patterns('', url(r'^', include('elections.urls')), url(r'^page', include('flatpages_i18n.urls')), (r'^tinymce/', include('tinymce.urls')), )
wufangjie/leetcode
011. Container With Most Water.py
Python
gpl-3.0
2,524
0.001981
''' Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may...
ight: continue else: maxHeight = height[i] theBest = max(theBest, _max_area_as_short_side(i)) return max(left, theBest) def maxArea_TLE(self, height): maxlen = len(height) def _max_area_as_short_side(i): left = right ...
eight[i] * (i - j) break for j in range(maxlen - 1, i, -1): if height[j] >= height[i]: right = height[i] * (j - i) break return max(left, right) return max([_max_area_as_short_side(i) for i in range(maxlen)]) if...
zekroTJA/regiusBot
commands/cmd_log.py
Python
mit
1,480
0.004054
import os import discord import requests from utils import functions description = "Show bot log" perm = 2 async def ex(message, client): if not os.path.isfile("screenlog.0"): await client.send_message(message.channel, embed=discord.Embed(colour=discord.Color.red(), ...
wait client.send_message(message.channel, embed=discord.Embed( description="Uploading log to pastebin.com ...")) params = {"api_option": "paste", "api_dev_key": functions.get_settings()["secrets"]["pastebin"], "api_paste_code": log_full, "api_paste_private": "1", "api_paste_expire...
} paste = requests.post("https://pastebin.com/api/api_post.php", data=params).text.replace( "https://pastebin.com/", "https://pastebin.com/raw/") await client.delete_message(message_send) await client.send_message(message.channel, "**Log of `screenl...
ammongit/scripts
print-months.py
Python
mit
175
0
#!/usr/bin/
env python3 import calendar if __name__ == "__main__": for num in range(1, 13): month = calendar.month_name[num] print(f"{num:0
2} - {month}")
stczhc/neupy
examples/gd/mnist_mlp.py
Python
mit
1,266
0
import theano import numpy as np from sklearn.preprocessing import OneHotEncoder from sklearn import cross_validation, metrics, datasets from neu
py import algorithms, layers, environment environment.reproducible() theano.config.floatX = 'float32' mnist = datasets.fetch_mlda
ta('MNIST original') target_scaler = OneHotEncoder() target = mnist.target.reshape((-1, 1)) target = target_scaler.fit_transform(target).todense() data = mnist.data / 255. data = data - data.mean(axis=0) x_train, x_test, y_train, y_test = cross_validation.train_test_split( data.astype(np.float32), target.ast...
dsiddharth/access-keys
keystone/contrib/oauth1/__init__.py
Python
apache-2.0
690
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0
# # Unless required by applicable law or agreed to in writing, 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. f...
.oauth1.core import * # flake8: noqa
larrybradley/astropy
astropy/utils/iers/iers.py
Python
bsd-3-clause
46,942
0.000639
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ The astropy.utils.iers package provides access to the tables provided by the International Earth Rotation and Reference Systems Service, in particular allowing interpolation of published UT1-UTC values for given times. These are used in `astropy.time`...
S_B_README = get_pkg_data_filename('d
ata/ReadMe.eopc04_IAU2000') # LEAP SECONDS default file name, URL, and alternative format/URL IERS_LEAP_SECOND_FILE = get_pkg_data_filename('data/Leap_Second.dat') IERS_LEAP_SECOND_URL = 'https://hpiers.obspm.fr/iers/bul/bulc/Leap_Second.dat' IETF_LEAP_SECOND_URL = 'https://www.ietf.org/timezones/data/leap-seconds.lis...
zaycev/mokujin
mokujin/sourcesearch.py
Python
apache-2.0
9,946
0.001609
#!/usr/bin/env python # coding: utf-8 # Copyright (C) USC Information Sciences Institute # Author: Vladimir M. Zaytsev <zaytsev@usc.edu> # URL: <http://nlg.isi.edu/> # For more information, see README.md # For license information, see LICENSE import logging from mokujin.logicalform import POS from mokujin.index imp...
m, target_triples_freq) print "\tFOUND TARGET TRIPLES FOR %s: %d" % (term, len(target_triples)) target_triples = filter(lambda s: s[-1] >= threshold, target_triples) print "\tAFTER FILTERING (f>=%f): %d" % (threshold, len(target_triples)) target_triples = filter(lambda tr: not self.is_li...
self.find_triples_by_patterns(target_term_id, target_triples) print "\tFOUND SOURCE TRIPLES FOR %s: %d" % (term, source_triple_num) potential_sources = [] stops_ignored = 0 cnect_ignored = 0 for source_term_id, triples in source_triples.iteritems(): if source_term_id ...
weiting-chen/manila
manila/scheduler/filters/capacity_filter.py
Python
apache-2.0
5,433
0
# Copyright (c) 2012 Intel # Copyright (c) 2012 OpenStack, LLC. # Copyright (c) 2015 EMC Corporation # # 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 # # ...
"host": host_state.host}) return False else: # NOTE(xyang): Adjust free_virtual calculation based on # free and max_over_subscription_ratio. adjusted_free_virtual = ( free * host_state.max_over_subscription_ratio) ...
"Valid value should be >= 1."), {"ratio": host_state.max_over_subscription_ratio}) return False if free < share_size: LOG.warning(_LW("Insufficient free space for share creation " "on host %(host)s (requested / avail): "...
catapult-project/catapult
telemetry/third_party/altgraph/altgraph/ObjectGraph.py
Python
bsd-3-clause
6,431
0.000622
""" altgraph.ObjectGraph - Graph of objects with an identifier ========================================================== A graph of objects that have a "graphident" attribute. graphide
nt is the key for the object in the graph """ from __future__ import print_function from __future__ import absolute_import from altgraph import GraphError from altgraph.Graph import Graph from altgraph.GraphUtil import filter_stack from six.moves import map class ObjectGraph(object): """ A graph of objects th...
a "graphident" attribute. graphident is the key for the object in the graph """ def __init__(self, graph=None, debug=0): if graph is None: graph = Graph() self.graphident = self self.graph = graph self.debug = debug self.indent = 0 graph.add_node(...
harisbal/pandas
pandas/tests/extension/base/__init__.py
Python
bsd-3-clause
2,015
0
"""Base test suite for extension arrays. These tests are intended for third-party libraries to subclass to validate that their extension arrays and dtypes satisfy the interface. Moving or renaming the tests should not be done lightly. Libraries are expected to implement a few pytest fixtures to provide data for the t...
ss Your class ``TestDtype`` will inherit all the tests defined on ``BaseDtypeTests``. pytest's fixture discover will supply your ``dtype`` wherever the test requires it. You're free to implement additional tests. All the tests in these modules use ``self.assert_frame_equal`` or ``self.assert_series_equal`` for dataf...
e_equal`` and ``pandas.testing.assert_series_equal``. You can override the checks used by defining the staticmethods ``assert_frame_equal`` and ``assert_series_equal`` on your base test class. """ from .casting import BaseCastingTests # noqa from .constructors import BaseConstructorsTests # noqa from .dtype import B...
shingonoide/odoo_ezdoo
addons/http_session_redis/__init__.py
Python
agpl-3.0
1,038
0.000963
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2015
BarraDev Consulting (<http://www.barradev.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. #...
THOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu....
394954369/horizon
openstack_dashboard/api/cinder.py
Python
apache-2.0
13,116
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 OpenStack Foundation # Copyright 2012 Nebula, Inc. # Copyright (c) 2012 X.commerce, a business unit of eBay Inc. # # Licensed under the Apach...
under the License. from __future__ import absolute_import import logging from django.conf import settings from
django.utils.translation import ugettext_lazy as _ from cinderclient.v1.contrib import list_extensions as cinder_list_extensions from horizon import exceptions from horizon.utils.memoized import memoized # noqa from openstack_dashboard.api import base from openstack_dashboard.api import nova LOG = logging.getLogg...
derekjchow/models
research/object_detection/builders/model_builder.py
Python
apache-2.0
23,976
0.005172
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
er_rcnn_resnet101': frcnn_resnet_v1.FasterRCNNResnet101FeatureExtractor, 'faster_rcnn_resnet152': frcnn_resnet_v1.FasterRCNNResnet152FeatureExtractor, } def build(model_config, is_training, add_summaries=True): """Builds a DetectionModel based on the model config. Args: model_config: A model.
proto object containing the config for the desired DetectionModel. is_training: True if this model is being built for training purposes. add_summaries: Whether to add tensorflow summaries in the model graph. Returns: DetectionModel based on the config. Raises: ValueError: On invalid meta arch...
rnirmal/openstack-dashboard
django-openstack/django_openstack/middleware/keystone.py
Python
apache-2.0
2,747
0.000364
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2011 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # no...
le law or agreed to in writing, software # distributed under the License is d
istributed 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. from django.contrib import messages from django import shortcuts import openstackx import openstack ...
vnsofthe/odoo-dev
addons/ebiz_cn/ebiz.py
Python
agpl-3.0
45,688
0.013284
# -*- encoding: utf-8 -*- import time import logging from openerp import tools from dateutil.relativedelta import relativedelta from datetime import datetime, timedelta from openerp.tools.translate import _ from openerp.osv import fields,osv import json import hashlib from openerp.addons.ebiz_cn.top import setDefaultA...
rest import ItemsOnsaleGe
tRequest from openerp.addons.ebiz_cn.top.api.rest import TradesSoldIncrementGetRequest from openerp.addons.ebiz_cn.top.api.rest import ItemSkusGetRequest from openerp.addons.ebiz_cn.top.api.rest import TradesSoldGetRequest from openerp.addons.ebiz_cn.top.api.rest import TradeGetRequest from openerp.addons.ebiz_cn.top.a...
pystorm/pystorm
pystorm/serializers/json_serializer.py
Python
apache-2.0
3,417
0.000585
"""JSON implementation of pystorm serializer""" from __future__ import absolute_import, print_function, unicode_literals import io import logging import simplejson as json from six import PY2 from ..exceptions import StormWentAwayError from .serializer import Serializer log = logging.getLogger(__name__) class J...
input_stream, output_stream, reader_lock, writer_lock ) self.input_stream = self._wrap_stream(input_stream) self.output_stream = self._wrap_stream(output_stream) @staticmethod def _wrap_stream(stream): """Returns a TextIOWrapper around the given stream that handles UTF-8 ...
ffer"): return io.TextIOWrapper(stream.buffer, encoding="utf-8") elif hasattr(stream, "readable"): return io.TextIOWrapper(stream, encoding="utf-8") # Python 2.x stdin and stdout are just files else: return io.open(stream.fileno(), mode=stream.mode, encoding="...
CYBAI/servo
tests/wpt/web-platform-tests/tools/wpt/tests/test_run.py
Python
mpl-2.0
1,969
0
import tempfile import shutil import sys from unittest import mock import pytest from tools.wpt import run from tools import localpaths # noqa: F401 from wptrunner.browsers import product_list @pytest.fixture(scope="module") def venv(): from tools.wpt import virtualenv class Virtualenv(virtualenv.Virtuale...
ef test_check_environ_fail(platform): m_open = mock.mock_open(read_data=b"") with mock.patch.object(run, "open", m_open): with mock.patch.object(run.platform, "uname", return_value=(platform, "", "", "", "", "")):
with pytest.raises(run.WptrunError) as excinfo: run.check_environ("foo") assert "wpt make-hosts-file" in str(excinfo.value) @pytest.mark.parametrize("product", product_list) def test_setup_wptrunner(venv, logger, product): if product == "firefox_android": pytest.skip("Andr...
walkover/auto-tracking-cctv-gateway
gateway/firebase/fcm.py
Python
mit
1,072
0.000933
import logging import sqlite3 from pyfcm import FCMNotification def insert_token(token): try: con = sqlite3.connect('fcm.db') cur = con.cursor() cur.execute('CREATE TABLE IF NOT EXISTS tokens(token TEXT)') cur.execute('INSERT INTO tokens VALUES (?)', (token, )) con.commi...
cur = con.cursor() cur.execute('CREATE TABLE IF NOT EXISTS tokens(token TEXT)') cur.execute('SELECT * FROM tokens') registration_ids = [row for row in cur.fetchall()] if len(registration_ids) > 0: noti = FCMNotification('API-KEY') result = noti.notify_multiple_devices(registration_ids=r...
message_title=message_title, message_body=message_body) return result
emgirardin/compassion-modules
sponsorship_tracking/models/__init__.py
Python
agpl-3.0
501
0
# -*- enco
ding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: David Coninckx <david@coninckx.com> # # The licence is in the file __openerp__.py ...
nu
MTG/dunya
andalusian/api_urls.py
Python
agpl-3.0
3,931
0.008395
# Copyright 2013,2014 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Dunya # # Dunya is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the Free Software # Foundation (FSF), either version 3 of the License, or...
sian-nawba-list'), url(r'^nawba/%s$' % uuid_match, andalusian.api.NawbaDetail.as_view(), name='api-andalusian-nawba-detail'), url(r
'^form$', andalusian.api.FormList.as_view(), name='api-andalusian-form-list'), url(r'^form/%s$' % uuid_match, andalusian.api.FormDetail.as_view(), name='api-andalusian-form-detail'), url(r'^sanaa$', andalusian.api.SanaaList.as_view(), name='api-andalusian-sanaa-list'), url(r'^sanaa/(?P<pk>\d+)$', andalusia...
plotly/python-api
packages/python/plotly/plotly/validators/box/hoverlabel/_font.py
Python
mit
1,855
0.000539
import _plotly_utils.basevalidators class FontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="font", parent_name="box.hoverlabel", **kwargs): super(FontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by comma...
https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans ...
stack-of-tasks/rbdlpy
tutorial/lib/python2.7/site-packages/OpenGL/GLES1/OES/read_format.py
Python
lgpl-3.0
750
0.009333
'''OpenGL extension OES.read_format This module customises the behaviour of the OpenGL.raw.GLES1.OES.read_format to provide a more Python-friendly API The official definition of this extension is available here: http:
//www.opengl.org/registry/specs/OES/read_format.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GLES1 import _types, _glgets from OpenGL.raw.GLES1.OES.read_format import * from OpenGL.raw.GLES1.OES.read_format import _EXTENSION_NAME def glInitR...
UTOGENERATED SECTION
dchabot/ophyd
ophyd/__init__.py
Python
bsd-3-clause
946
0.014799
import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) from . import * # Signals from .signal import (Signal, EpicsSignal, EpicsSignalRO, DerivedSignal) # Positioners from .positioner import (PositionerBase, SoftPositioner) from .epics_motor import EpicsMotor from .pv_pos
itioner import (PVPositioner, PVPositionerPC) from .pseudopos import (PseudoPositioner, PseudoSingle) # Devices from .scaler import EpicsScaler from .device import (Device, Component, FormattedComponent, DynamicDeviceComponent) from .status import Statu
sBase from .mca import EpicsMCA, EpicsDXP # Areadetector-related from .areadetector import * from ._version import get_versions from .commands import (mov, movr, set_pos, wh_pos, set_lm, log_pos, log_pos_diff, log_pos_mov) from .utils.startup import setup as setup_ophyd __version__ = get_ver...
litzler/marioSokoBan
edit.py
Python
gpl-3.0
8,847
0.006107
import pygame from pygame.locals import * # pour les constan
tes touches... from constantes import * from fichiers import * from general import * from aide import * def edit(screen, levelNumber ,mode, lang, langu, levelFinal): motionX = 0 motionY =
0 alsoMario = 0 carte = [[int for lgn in range(NB_BLOCS_HAUTEUR)]for col in range(NB_BLOCS_LARGEUR)] restMario = 0 levelWord = '' clicGaucheEnCours = False clicDroitEnCours = False saved = False objectPos = pygame.Rect(0,0,0,0) exemplePos = pygame.Rect(0,0,0,0) # charger images ...
murataydos/popy
setup.py
Python
gpl-2.0
402
0
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='popy', description='Parser for GNU Po files', long_description=open('README.rst').read(), version='0.3.0', packages=['popy'], author='M
urat Aydos', author_email='murataydos@yandex.com', url='https://github.com/murataydos/popy', license='MIT', zip_safe=
False, include_package_data=True )
fboers/jumegX
jumeg_test.py
Python
bsd-3-clause
1,802
0.008324
#!/usr/bin/env python import jumeg import os.path raw_fname = "109925_CAU01A_100715_0842_2_c,rfDC-raw.fif" if not os.path.isfile(raw_fname): print "Please find the test file at the below location on the meg_store2 network drive - \ cp /data/meg_store2/fif_data/jumeg_test_data/109925_CAU01A_100715_0842_...
_standards(raw_fname) # Function to apply noise reducer jumeg.jumeg_noise_reducer.noise_reducer(raw_fname, verbose=True) # Fi
lter functions #jumeg.jumeg_preprocessing.apply_filter(raw_fname) fclean = raw_fname[:raw_fname.rfind('-raw.fif')] + ',bp1-45Hz-raw.fif' # Evoked functions #jumeg.jumeg_preprocessing.apply_average(fclean) # ICA functions #jumeg.jumeg_preprocessing.apply_ica(fclean) fica_name = fclean[:fclean.rfind('-raw.fif')] + '-i...
JoshStegmaier/django-nimbus
nimbus/views/generic.py
Python
mit
1,761
0.003407
from django.views.generic import DetailView, ListView from django.views.generic.edit import CreateView, UpdateView from .mixins import GenerateActionMixin class DetailViewWithActionStream(GenerateActionMixin, DetailView): def dispatch(self, request, *args, **kwargs): if not self.request.user.is_anonymous...
erateActionMixin, CreateView): def form_valid(self, form): to_return = super(CreateViewWithActionStream, self)
.form_valid(form) if not self.request.user.is_anonymous(): self.generate_action() return to_return def get_action_actor(self, *args, **kwargs): return self.request.user def get_action_verb(self, *args, **kwargs): return 'added' def get_action_action_object(self...
MaterialsDiscovery/PyChemia
pychemia/population/relaxstructures.py
Python
mit
19,699
0.002944
import random import uuid from math import gcd import numpy as np from ._population import Population from pychemia import Composition, Structure, pcm_log from pychemia.analysis import StructureAnalysis, StructureChanger, StructureMatch from pychemia.analysis.splitting import SplitMatch from pychemia.utils.mathematics ...
forces = np.array(entry['properties']['forces']) stress = np.array(entry['properties']['stress']) max_force = np.max(np.apply_along_axis(np.linalg.norm, 1, forces)) max_diag_stress = np.max(np.abs(stress[:3])) max_nondiag_stress ...
diag_stress def is_evaluated(self, entry_id): max_force, max_diag_stress, max_nondiag_stress = self.get_max_force_stress(entry_id) if max_force is None or max_diag_stress is None or max_nondiag_stress is None: return False elif max_force < self.target_forces and max_diag_stress ...
ben-jones/centinel
centinel/vpn/openvpn.py
Python
mit
2,675
0
#!/usr/bin/python # openvpn.py: library to handle starting and stopping openvpn instances import subprocess import threading import time class OpenVPN(): def __init__(self, config_file=None, auth_file=None, timeout=10): self.started = False self.stopped = False self.error = False ...
= self.process.stdout.readline().strip() if not line: break self.output_callback(line, self.process.terminate) def output_callback(self, line, kill_switch): """Set status of openvpn according to what we process""" self.notifications += line + "\n" ...
Sequence Completed" in line: self.started = True if "ERROR:" in line: self.error = True if "process exiting" in line: self.stopped = True def start(self, timeout=None): """Start openvpn and block until the connection is opened or there is an error...
pynag/pynag
examples/Parsers/get_service_info.py
Python
gpl-2.0
495
0.010101
#!/usr/bin/python from __future__ impo
rt absolute_import from __future__ import print_function import sys if len(sys.argv) != 3: sys.stderr.write("Usage: %s 'Host Name' 'Service Description'\n" % (sys.argv[0])) sys.exit(2) ## This is for the custom nagios module sys.path.insert(1, '../') from pynag.Parsers import config ## Create the plugin o...
() service = nc.get_service(sys.argv[1],sys.argv[2]) print(nc.print_conf(service))
nihilus/qb-sync
ext_gdb/sync.py
Python
gpl-3.0
16,046
0.002306
# # Copyright (C) 2012-2014, Quarkslab. # # This file is part of qb-sync. # # qb-sync 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. ...
/www.gnu.org/licenses/>. # #!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys import time import socket import errno import base64 import tempfile import threading import gdb try: import configparser except ImportError: import ConfigParser as configparser VERBOSE = 0 HOST = "local...
def gdb_execute(cmd): f = tempfile.NamedTemporaryFile() gdb.execute("set logging file %s" % f.name) gdb.execute("set logging redirect on") gdb.execute("set logging overwrite") gdb.execute("set logging on") try: gdb.execute(cmd) except Exception as e: gdb.execute("set loggin...
Kyziridis/recommender_system
helpers/Time.py
Python
gpl-3.0
51
0.019608
import time
def start():
return time.time()
atljohnsen/adlcoursebuilder
modules/review/stats.py
Python
apache-2.0
5,775
0.000173
# Copyright 2012 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 ...
safe_dom.Element('blockquote').add_child(
safe_dom.Element('pre').add_text('\n%s' % job.output))) else: update_message = safe_dom.Text(""" Peer review statistics update started at %s and is running now. Please come back shortly.""" % job.updated_on.strftime( HUMAN_RE...
olebole/astrometry.net
util/starutil_numpy.py
Python
bsd-3-clause
18,610
0.010586
# This file is part of the Astrometry.net suite. # Licensed under a 3-clause BSD style license - see LICENSE from numpy import * import datetime import numpy as np from functools import reduce arcsecperrad = 3600. * 180. / np.pi axistilt = 23.44 # degrees def ra_normalize(ra): return np.mod(ra, 360.) def ra_rang...
>= cos(deg2rad(radius)) def points_within_radius_range(racenter, deccenter, radiuslo, radiushi, ra, dec): d = radecdotproducts(racenter, deccenter, ra, dec) return (d <= cos(deg2rad(radiuslo))) * (d >= cos(deg2rad(radiushi))) # scalars (racenter, deccenter) in deg # arrays (ra,dec) in deg # returns array of c...
eccenter).T xyz = radectoxyz(ra, dec) return dot(xyz, xyzc)[:,0] # RA, Dec in degrees: scalars or 1-d arrays. # returns xyz of shape (N,3) def radectoxyz(ra_deg, dec_deg): ra = deg2rad(ra_deg) dec = deg2rad(dec_deg) cosd = cos(dec) xyz = vstack((cosd * cos(ra), cosd * sin(ra)...
YuxuanLing/trunk
trunk/code/study/python/Fluent-Python-example-code/15-context-mngr/mirror_gen.py
Python
gpl-3.0
1,453
0
""" A "mirroring" ``stdout`` context manager. While active, the context manager reverses text output to ``stdout``:: # BEGIN MIRROR_GEN_DEMO_1 >>> f
rom mirror_gen import looking_glass >>> with looking_glass() as what: # <1> ... print('Alice, Kitty and Snowdrop') ... print(
what) ... pordwonS dna yttiK ,ecilA YKCOWREBBAJ >>> what 'JABBERWOCKY' # END MIRROR_GEN_DEMO_1 This exposes the context manager operation:: # BEGIN MIRROR_GEN_DEMO_2 >>> from mirror_gen import looking_glass >>> manager = looking_glass() # <1> >>> manager # doctest:...
GuessWhoSamFoo/pandas
pandas/tests/extension/test_period.py
Python
bsd-3-clause
4,336
0
import numpy as np import pytest from pandas._libs.tslib import iNaT from pandas.core.dtypes.dtypes import PeriodDtype import pandas as pd from pandas.core.arrays import PeriodArray from pandas.tests.extension import base @pytest.fixture def dtype(): return PeriodDtype(freq='D') @pytest.fixture def data(dtyp...
ta def test_error(self): pass def test_
direct_arith_with_series_returns_not_implemented(self, data): # Override to use __sub__ instead of __add__ other = pd.Series(data) result = data.__sub__(other) assert result is NotImplemented class TestCasting(BasePeriodTests, base.BaseCastingTests): pass class TestComparisonOps(...
srajag/nova
nova/tests/integrated/v3/test_evacuate.py
Python
apache-2.0
3,892
0.002569
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
g_sys_metadata=mock.ANY, bdms=mock.ANY, recreate=mock.ANY, on_shared_storage=False, preserve_ephemeral=mock.ANY, host='testHost') @mock.patch('nova.conductor.manager.ComputeTaskM
anager.rebuild_instance') def test_server_evacuate_find_host(self, rebuild_mock): req_subs = { "adminPass": "MySecretPass", "onSharedStorage": 'False' } self._test_evacuate(req_subs, 'server-evacuate-find-host-req', 'server-evacuate-find-ho...
pcrews/drizzle-ci-salt
test-install.py
Python
gpl-3.0
3,724
0.005908
#!/usr/bin/python2.7 # # This file is part of drizzle-ci # # Copyright (c) 2013 Sharan Kumar M # # drizzle-ci is free software: you ca
n redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # drizzle-ci is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; wi...
warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with drizzle-ci. If not, see <http://www.gnu.org/licenses/>. # # # ========================== # Test scrip...
tparks5/tor-stem
docs/_static/example/event_listening.py
Python
lgpl-3.0
5,286
0.015513
import curses import functools from stem.control import EventType, Controller from stem.util import str_tools # colors that curses can handle COLOR_LIST = { "red": curses.COLOR_RED, "green": curses.COLOR_GREEN, "yellow": curses.COLOR_YELLOW, "blue": curses.COLOR_BLUE, "cyan": curses.COLOR_CYAN, "magenta"...
key is. :P stdscr.getch() def _handle_bandwidth_event(window, bandwidth_rates, event): # callback for when tor provides us with a BW event bandwidth_rates.insert(0, (event.read, event.written)) bandwidth_rates = bandwidth_rates[:GRAPH_WIDTH] # truncate old values _render_graph(window, bandwidth_rates) d...
upload_rates = [entry[1] for entry in bandwidth_rates] # show the latest values at the top label = "Downloaded (%s/s):" % str_tools.size_label(download_rates[0], 1) window.addstr(0, 1, label, DOWNLOAD_COLOR, curses.A_BOLD) label = "Uploaded (%s/s):" % str_tools.size_label(upload_rates[0], 1) window.addstr(...
TacticalGoat/reddit
FlairTimer/flairtimer.py
Python
mit
3,977
0.026402
#/u/GoldenSights import praw import time import datetime import sqlite3 '''USER CONFIGURATION''' APP_ID = "" APP_SECRET = "" APP_URI = "" APP_REFRESH = "" # https://www.reddit.com/comments/3cm1p8/how_to_make_your_bot_use_oauth2/ USERAGENT = "" #This is a short description of what the bot does. For example "/u/GoldenS...
flair = '' if flair == '': print(pid + ': No Flair') now = getTime(True) if (now - ptime) > DELAY: print('\tOld. Ignoring') cur.execute('INSERT INTO oldposts VALUES(?)', [pid]) else: print('\tAssigning Active Flair') post.set_flair(fla
ir_text=FLAIRACTIVE,flair_css_class=CSSACTIVE) elif flair == FLAIRACTIVE.lower(): print(pid + ': Active') now = getTime(True) if (now-ptime) > DELAY: print('\tOld. Removing Flair') post.set_flair(flair_text="",flair_css_class="") cur.execute('INSERT INTO oldposts VALU...
sonofeft/LazGUI
lazgui/laz_gui.py
Python
gpl-3.0
8,605
0.020686
#!/usr/bin/env python # -*- coding: ascii -*- r""" LazGUI helps to create Lazarus Pascal GUI project. LazGUI will place all of the required files for the Lazarus project into a subdirectory by project name. The project can be built using "lazbuild" that comes with a Lazarus install, or by opening the <project_name>....
_path, '%s.lpr'%self.project_name ) print 'Saving --> ',targ_fname with open(targ_fname, 'w') as f: f.write( lpr_obj.file_contents() ) # Create *.pas and *.lfm for each of the Form units for form in self.formL: targ_fname = os.path.join( targ_abs_path, '%...
) print 'Saving --> ',targ_fname with open(targ_fname, 'w') as f: f.write( form.pas_file_contents() ) targ_fname = os.path.join( targ_abs_path, '%s.lfm'%form.unit_name.lower() ) print 'Saving --> ',targ_fname with open(targ_fname,...
ardi69/pyload-0.4.10
pyload/plugin/account/StahnuTo.py
Python
gpl-3.0
991
0.008073
# -*- coding: utf-8 -*- import re from pyload.plugin.Account import Account class StahnuTo(Account): __name = "StahnuTo" __type = "account" __version = "0.05" __description = """StahnuTo account plugin""" __license = "GPLv3" __authors = [("zoidberg", "zoidberg@mujmail.cz")] ...
"http://www.st
ahnu.to/") m = re.search(r'>VIP: (\d+.*)<', html) trafficleft = self.parseTraffic(m.group(1)) if m else 0 return {"premium": trafficleft > 512, "trafficleft": trafficleft, "validuntil": -1} def login(self, user, data, req): html = req.load("http://www.stahnu.to/login.php", ...
google-research/lag
libml/train_sr.py
Python
apache-2.0
5,712
0.002276
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
def eval_mode(self, dataset): assert self.eval is None log_scale = utils.ilog2(self.scal
e) model = functools.partial(self.model, dataset=dataset, total_steps=1, lod_start=log_scale, lod_stop=log_scale, lod_max=log_scale) self.eval = EvalSessionPro(model, self.checkpoint_dir, **self.params) print('Eval model %s at global_step %d' % (self.__class__._...
facebookresearch/ParlAI
parlai/agents/random_candidate/random_candidate.py
Python
mit
2,698
0
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Simple agent which chooses a random label. Chooses from the label candidates if they are available. If candidates ar...
if label_candidates: label_candidates = list(label_candidates) random.shuffle(label_candidates) reply['text_candidates'] = label_candidates reply['text'] = label_candidates[0] else:
# reply with I don't know. reply['text'] = "I don't know." return reply
cntnboys/410Lab6
bookmarks/main/views.py
Python
apache-2.0
1,325
0.020377
from django.shortcuts import render from django.shortcuts import render_to_response from djan
go.template import RequestContext from django.shortcuts import redirect from main.models import Link from main.models import Tag # Create your views here. def index(request): context = RequestContext(request) links = Link.objects.all() return render_to_response('main/index.html', {'links...
s.html', {'tags': tags}, context) def tag(request, tag_name): context = RequestContext(request) the_tag = Tag.objects.get(name=tag_name) links=the_tag.link_set.all() return render_to_response('main/index.html',{'links':links, 'tag_name': '#' + tag_name}, context) def add_link(request): context = R...
WPI-CS4341/CSP
main.py
Python
mit
5,541
0.002888
""" Written by Harry Liu (yliu17) and Tyler Nickerson (tjnickerson) """ import sys import os.path import pprint from classes.bag import Bag from classes.item import Item from classes.constraint import Constraint from classes.csp import CSP from classes.solver import Solver def main(): # Read command line argument...
capacity) elif current_section == 3: # Fitting limits lower_bound = s[0] upper_bound = s[1] for b in bags: constraint = Constraint(
Constraint.BAG_FIT_LIMIT, bags=[bags[b]], min_items=lower_bound, max_items=upper_bound) bags[b].constraints.append(constraint) elif current_section == 4: # Unary inclusive name = s[0] ...
johnyf/gr1experiments
examples/bunny_many_goals/make_instances.py
Python
bsd-3-clause
2,595
0
#!/usr/bin/env python """Dump instances for bunny, in Promela and SlugsIn.""" import argparse import itertools im
port pprint import logging import re from tugs import utils log = logging.getLogger(__name__) INPUT_FILE = 'bunny.pml' PROMELA_PATH = 'pml/bunny_many_goals_{i}.txt' SLUGSIN_PATH = 'slugsin/bunny_many_goals_{i}.txt' def dump_promela(n, m): """Dump instances of Promela.""" for i in xrange(n, m): code ...
OMELA_PATH.format(i=i) with open(promela_file, 'w') as f: f.write(code) log.info('dumped Promela for {i} masters'.format(i=i)) def dump_slugsin(n, m): for i in xrange(n, m): promela_file = PROMELA_PATH.format(i=i) with open(promela_file, 'r') as f: pml_code ...
multidis/bitQuant02
setup.py
Python
mit
464
0.043103
try: from setuptools import setup except ImportError: from distutils.core import setup
config = { 'description':'End to end solution for bitcoin data gathering, backtesting, and live trading', 'author': 'ross palmer', 'url':'http://rosspalmer.gi
thub.io/bitQuant/', 'license':'MIT', 'version': '0.2.10', 'install_requires': ['SQLAlchemy','pandas','numpy','scipy','PyMySQL'], 'packages': ['bitquant'], 'scripts': [], 'name':'bitquant' } setup(**config)
mscuthbert/abjad
abjad/tools/topleveltools/graph.py
Python
gpl-3.0
2,398
0.000834
# -*- encoding: utf-8 -*- import os import subprocess def graph( expr, image_format='pdf', layout='dot', graph_attributes=None, node_attributes=None, edge_attributes=None, **kwargs ): r'''Graphs `expr` with graphviz and opens resulting image in the default image viewer. ::...
graphviz_graph = expr.__graph__(**kwargs) if gr
aph_attributes: graph.attributes.update(graph_attributes) if node_attributes: graph.node_attributes.update(node_attributes) if edge_attributes: graph.edge_attributes.update(edge_attributes) graphviz_format = str(graphviz_graph) assert image_format in ('pd...
cedadev/ndg_xacml
ndg/xacml/parsers/etree/subjectmatchreader.py
Python
bsd-3-clause
979
0.003064
"""NDG XACML ElementTree based reader for subject match type NERC DataGrid """ __author__ = "P J Kershaw" __date__ = "16/03/10" __copyright__ = "(C) 2010 Science and Technology Facilities Council" __contac
t__ = "Philip.Kershaw@stfc.ac.uk" __license__ = "BSD - see LICENSE file in top-level directory" __contact__ = "Philip.Kershaw@stfc.ac.uk" __revision__ = "$Id$" from ndg.xacml.core.match import SubjectMatch from ndg.xacml.core.attributedesignator import SubjectAttributeDesignator from ndg.xacml.parsers.etree.matchreader...
ar TYPE: XACML class type that this reader will read values into @type TYPE: abc.ABCMeta @cvar ATTRIBUTE_DESIGNATOR_TYPE: type for attribute designator sub-elements @type ATTRIBUTE_DESIGNATOR_TYPE: abc.ABCMeta """ TYPE = SubjectMatch ATTRIBUTE_DESIGNATOR_TYPE = SubjectAttributeDesignator
Kami/libcloud
libcloud/test/dns/test_auroradns.py
Python
apache-2.0
13,377
0.00015
# 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 ...
self.fail('expected a ZoneDoesNotExistError') except ZoneDoesNotExistError: pass except Exception: raise def test_create_zone_already_exist(self): try: self.driver.create_zone('exists.example.com') self.fail('expected a ZoneAl
readyExistsError') except ZoneAlreadyExistsError: pass except Exception: raise def test_list_records_non_exist(self): try: self.driver.list_records(Zone(id=1, domain='nonexists.example.com', type='NATIVE', driver=...
jorge-marques/shoop
shoop_tests/front/test_simple_search.py
Python
agpl-3.0
1,843
0.00217
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.utils import translation import pytest from shoop.front.apps.si...
s found" @pytest.mark.django_db def test_simple_search_get_ids_works(rf): prod = get_default_product() bit = prod.name[:5] request = rf.get("/") assert prod.pk in get_search_product_ids(request, bit) assert prod.pk in get_search_product_ids(request, bit) #
Should use cache @pytest.mark.django_db def test_simple_search_view_works(rf): view = SearchView.as_view() prod = create_product(sku=UNLIKELY_STRING, shop=get_default_shop()) query = prod.name[:8] # This test is pretty cruddy. TODO: Un-cruddify this test. resp = view(apply_request_middleware(rf....
joshuahellier/PhDStuff
codes/thesisCodes/kmc/customAnalysis/DensHist.py
Python
mit
2,799
0.005359
import sys import numpy import math from foldyFloatList import foldyFloatList class OOBError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) from KMCLib.PluginInterfaces.KMCAnalysisPlugin import KMCAnalysisPlugin from KMCLib.Utilities.CheckU...
ust be given as a list of relevant output processes." self.__outProc = checkSequenceOfPositiveIntegers(outProc, msg) self.__initTime = 0.0 self.__lastTime = 0.0 self.__currentTime = 0.0 def setup(self, step, time, configuration): self.__initTime = time typeList = con...
foldyFloatList()) total = 0 for i in typeList: if i in self.__spec: total += 1 self.__currTot = total self.__lastTime = time self.__currentTime = time def registerStep(self, step, time, configuration): self.__currentTime = time if ...
danielplohmann/apiscout
apiscout/db_builder/DatabaseBuilder.py
Python
bsd-2-clause
11,496
0.003392
#!/usr/bin/python ######################################################################## # Copyright (c) 2017 # Daniel Plohmann <daniel.plohmann<at>mailbox<dot>org> # All rights reserved. ######################################################################## # # This file is part of apiscout # # apiscout...
if dll_summary is not None: dll_key = self._buildDllKey(dll_summary) if dll_key not in api_db["dlls"]: api_db["dlls"][dll_key] = dll_summary num_hit_dlls += 1
api_count += len(dll_summary["exports"]) LOG.info("APIs: %d", len(dll_summary["exports"])) else: duplicate_count += 1 LOG.info("PEs examined: %d (%d duplicates, %d skipped)", pe_count, duplicate_count, s...
XertroV/nvbclient
nvbclient/tests.py
Python
mit
1,501
0.000666
import unittest import transaction from pyramid import testing from .models import DBSession class TestMyViewSuccessCondition(unittest.TestCase): def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://') from .models i...
ew(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'nvb-client') class TestMyViewFailureCondition(unittest.TestCase): def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://')...
sion.remove() testing.tearDown() def test_failing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info.status_int, 500)
suutari/shoop
shuup_tests/front/test_addressbook.py
Python
agpl-3.0
6,230
0.001605
import pytest import re from django.contrib.auth import get_
user_model from django.contrib.auth.models import User from django.core.urlresolvers import reverse from shuup.core.models import SavedAddress from shuup.core.models import get_person_contact from shuup.core.models._contacts import get_company_contact fr
om shuup.testing.factories import get_default_shop, get_address from shuup_tests.utils import SmartClient from shuup_tests.utils.fixtures import regular_user, REGULAR_USER_PASSWORD, REGULAR_USER_USERNAME regular_user = regular_user # noqa def default_address_data(): return { "saved_address-title": "Fake...
hidat/audio_pipeline
audio_pipeline/test/References.py
Python
mit
3,286
0.018564
format_testing_audio = "audio_pipeline\\test\\test_files\\audio\\tag_test_files" write_testing_audio = "audio_pipeline\\test\\test_files\\audio\\write_test_files" release_mbids = "audio_pipeline/test/test_files/test_mbids/release_mbids.json" artist_mbids = "audio_pipeline/test/test_files/test_mbids/artist_mbids.json" m...
'musicbrainz_trackid': '89715e73-cfa8-487f-8aa1-18c3b7d965b9', 'releasecountry': 'GB', 'mbid': '232775fc-277d-46e5-af86-5e01764abe5a', 'musicbrainz_releasetrackid': 'fe85af54-9982-34cc-9e0a-8d4d13a12350', 'disctotal': 1, 'artist': 'Rudi Zygadlo', 'discnumber': 1, 'artists': 'Ru...
'albumartistsort': 'Zygadlo, Rudi', 'musicbrainz_albumartistid': '48f12b43-153e-42c3-b67c-212372cbfe2b', 'releasetype': 'album', 'batchid': '50024', 'accurateripdiscid': '013-0014462a-00cb7579-bf0a3e0d-6', 'tracktotal': 13, 'catalognumber': 'ZIQ320CD', 'artistsort': '...
tgquintela/ElectionsTools
ElectionsTools/cases/previous_elections_spain_analysis.py
Python
mit
2,527
0.004353
import numpy as np import pandas as pd from ElectionsTools.Seats_assignation import DHondt_assignation from previous_elections_spain_parser import * import os pathfiles = '../data/spain_previous_elections_results/provincia/' pathfiles = '/'.join(os.path.realpath(__file__).split('/')[:-1]+[pathfiles]) fles = [pathfil...
. Compute assignations d, price = assign.assignation(pd.DataFrame(votes, columns=
parties)) d1, price1 = assign1.assignation(pd.DataFrame(votes_com, columns=parties)) d2, price2 = assign2.assignation(pd.DataFrame(votes_sp, columns=parties)) return d, d1, d2, parties def prepare2export(d, d1, d2, parties): logi = np.logical_or(np.logical_or(d.sum(0)>0, d1.sum(0)>0), d2.sum(0)>0) ...
timothyclemansinsea/smc
src/smc-build/smc-ansible/export-stripe-to-marketing-project.py
Python
gpl-3.0
667
0.005997
#!/usr/bin
/env python3 # this copies over all files in admin0:~/stripe/ to the ~/stripe folder in the statistics project import sys import os sys.path.insert(0, os.path.expanduser("~/bin/")) os.chdir(os.path.join(os.environ['SMC_ROOT'], "smc-build/smc-ansible")) # host of statistics project from smc_rethinkdb import project_hos...
ermissions os.system('ansible %s -m copy -a "src=%s dest=/projects/7561f68d-3d97-4530-b97e-68af2fb4ed13/stripe/ owner=1078872008 group=1078872008 mode=u=rw,go=" -become' % (host, src))
myisabella/LearnPythonTheHardWay
ex19.py
Python
mit
712
0.002809
# Functions and Variables def cheese_and_cra
ckers(cheese_count, boxes_of_crackers): print "You have %d cheeses!" % cheese_count print "You have %d boxes of crackers!" % boxes_of_crackers print "Man that's enough for a party!" print
"Get a blanket.\n" print "We can just give the function numbers directly:" cheese_and_crackers(20, 30) print "OR, we can use variable from our script:" amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" cheese_and_crackers(...
the-zebulan/CodeWars
tests/beta_tests/test_number_to_bytes.py
Python
mit
827
0
import unittest from katas.beta.nu
mber_to_bytes import to_bytes class NumberToBytesTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(to_bytes(0), ['00000000']) def test_equals_2(self): self.assertEqual(to_bytes(1), ['00000001']) def test_equals_3(self): self.assertEqual(to_bytes(257), ['0000000...
f): self.assertEqual(to_bytes(0x101), ['00000001', '00000001']) def test_equals_5(self): self.assertEqual(to_bytes(0x000000000101), ['00000001', '00000001']) def test_equals_6(self): self.assertEqual(to_bytes(0xffff), ['11111111', '11111111']) def test_equals_7(self): self...
OVERLOADROBOTICA/OVERLOADROBOTICA.github.io
mail/formspree-master/formspree/__init__.py
Python
mit
77
0
# -*- coding: utf-8 -*- from app import create_app form
s_app = create_ap
p()