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
niccokunzmann/first_timer_scraper
first_timer_scraper/concurrency.py
Python
agpl-3.0
1,783
0.006169
import functools import threading from concurrent.futures import ThreadPoolExecutor import traceback NUMBER_OF_THREADS = 100 def unique_step(parallel, numer_of_threads=NUMBER_OF_THREADS): """Shorten the call for calling a function after the other is completed. @serial_step def get(self, url):...
t_step(): pass When the arguments to the function are the same, the call can not be done in parallel. I
t gets executed once and the result is passed two both results. `next_step` will get executed in parallel to where it was defined in all cases. """ executor = ThreadPoolExecutor(numer_of_threads) lock = threading.RLock() requesting = {} @functools.wraps(parallel) def record_call(*ar...
wallnerryan/quantum_migrate
quantum/plugins/cisco/nexus/cisco_nexus_configuration.py
Python
apache-2.0
1,227
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2011 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache...
r: Sumit Naiksatam, Cisco Systems, Inc. # @author: Edgar Magana, Cisco Systems, Inc. # """ Configuration consolidation for the Nexus Driver This module will export the configuration parameters from the nexus.ini file """ from quantum.common.utils import find_config_file from quantum.plugins.ci
sco.common import cisco_configparser as confp CP = confp.CiscoConfigParser(find_config_file({'plugin': 'cisco'}, "nexus.ini")) NEXUS_DETAILS = CP['SWITCH'] SECTION = CP['DRIVER'] NEXUS_DRIVER = SECTION['name']
52ai/django-ccsds
tests/check_framework/test_security.py
Python
bsd-3-clause
16,867
0.001067
from django.conf import settings from django.core.checks.security import base, csrf, sessions from django.test import TestCase from django.test.utils import override_settings class CheckSessionCookieSecureTest(TestCase): @property def func(self): from django.core.checks.security.sessions import check_...
), [csrf.W016]) @override_settings(MIDDLEWARE_CLASSES=[], CSRF_COOKIE_SECURE=False) def test_with_csrf_cookie_secure_
false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE_CLASSES, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(self.func(None), []) @override_settings( MIDDLEWARE_CLASSES=["django.middleware.csrf.CsrfViewMiddleware"], C...
goldeneye-source/ges-python
stubs/GEAiSched.py
Python
gpl-3.0
2,498
0.002402
################ Copyright 2005-2016 Team GoldenEye: Source ################# # # This file is part of GoldenEye: Source's Python Library. # # GoldenEye: Source's Python Library 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 So...
int MELEE_ATTACK2 = int RANGE_ATTACK1 = int RANGE_ATTACK2 = int SPECIAL_ATTACK1 = int SPECIAL_ATTACK2 = int STANDOFF = int H
IDE_AND_RELOAD = int RELOAD = int DIE = int DIE_RAGDOLL = int MOVE_AWAY = int MOVE_AWAY_FAIL = int MOVE_AWAY_END = int FORCED_GO = int FORCED_GO_RUN = int NPC_FREEZE = int PATROL_WALK = int COMBAT_PATROL = int PATROL_RUN = int RUN_RANDOM = int FALL_TO_GROUND = int...
fcchou/CS229-project
learning/old/cp_analysis.py
Python
apache-2.0
2,588
0.007728
import cPickle as pickle score_dict = pickle.load(open('counterpoint.p')) import matplotlib.pyplot as plt import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn import cross_validation import sklearn.svm from sklearn.utils import shuffle def c...
e(cp) if cp in all_cp: all_cp[cp] += count else: all_cp[cp] = count # Get the secure Jos data jos_sec_set = set() w
ith open('../data/Josquin_secure.txt') as f: for line in f: jos_sec_set.add(line.strip()) cp_dict = {} for key in all_cp: cp_dict[key] = 0 features = [] labels = [] names = [] for name, score in score_dict.iteritems(): if name[:3] != 'Jos': # Non-Jos composer label = 0 elif name in j...
projectcalico/calico-neutron
neutron/tests/unit/test_l3_schedulers.py
Python
apache-2.0
61,087
0.000115
# Copyright (c) 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
db from neutron.extensions import l3agentscheduler as l3agent from neutron import manager from neutron.scheduler import l3_agent_scheduler from neutron.tests import base from neutro
n.tests.unit import test_db_plugin from neutron.tests.unit import test_l3_plugin from neutron.tests.unit import testlib_api from neutron.tests.unit import testlib_plugin # the below code is required for the following reason # (as documented in testscenarios) """Multiply tests depending on their 'scenarios' attribute. ...
viridia/coda
test/python/finddata.py
Python
apache-2.0
345
0.002899
import pathlib import importlib import sys __all__ = ['sample', 'sampleTxt', 'sampleBin'] this = pathlib.Path(__file__) datadir = this.par
ent.parent / 'data' loader = i
mportlib.machinery.SourceFileLoader('sample', str(datadir / 'sample.py')) sample = loader.load_module() sampleTxt = datadir / 'sample.txt' sampleBin = datadir / 'sample.bin'
djgagne/SHARPpy
sharppy/viz/SPCWindow.py
Python
bsd-3-clause
29,262
0.004067
__author__ = 'keltonhalbert, wblumberg' from sharppy.viz import plotSkewT, plotHodo, plotText, plotAnalogues from sharppy.viz import plotThetae, plotWinds, plotSpeed, plotKinematics #, plotGeneric from sharppy.viz import plotSlinky, plotWatch, plotAdvection, plotSTP, plotWinter from sharppy.viz import plotSHIP, plotST...
es) if result: self.default_prof.toFile(file_name) self.config.set('paths', 'save_txt', os.path
.dirname(file_name)) def initData(self): """ Initializes all the widgets for the window. This gets initially called by __init__ :return: """ sel
kawamuray/ganeti
lib/mcpu.py
Python
gpl-2.0
21,010
0.007139
# # # Copyright (C) 2006, 2007, 2011, 2012 Google Inc. # # This program is free software; you can redistribute it a
nd/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope
that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the F...
CodeForAfrica/grano
grano/lib/data.py
Python
mit
502
0.001992
from unicodecsv import DictReader class CSVImporter(object): """ A CSV-backed resource with the datas in it. """ def __init__(self, fh): self.reader = DictReader(fh) self.data = list(self.reader) @property def headers(self): headers = set() for row in self.data: ...
()
bollu/polymage
sandbox/apps/python/img_proc/pyramid_blend/init.py
Python
apache-2.0
3,126
0.002239
from __init__ import * import sys import os.path from PIL import Image import numpy as np from arg_parser import parse_args from printer import print_header, print_usage, print_line sys.path.insert(0, ROOT) from utils import * def init_images(app_data): print("[init.py] : initializing images...") app_args ...
image2_f = np.float32(img2) / 255.0 # create ghost zone and copy image roi # Image 1: image1_ghost = np.empty((rows+total_pad, cols+total_pad, 3), np.float32) image1_ghost[off_left:rows+off_left, off_left:cols+off_left, 0:3] = \ np.array(img1[0:rows, 0:cols, 0:3], np.float32) # clamp the ...
np.float32, 1, off_left, total_pad) # Image 2 image2_ghost = np.empty((rows+total_pad, cols+total_pad, 3), np.float32) image2_ghost[off_left:rows+off_left, off_left:cols+off_left, 0:3] = \ np.array(img2[0:rows, 0:cols, 0:3], np.float32) # clamp the boundary portions image_clam...
frappe/erpnext
erpnext/quality_management/doctype/quality_review_objective/quality_review_objective.py
Python
gpl-3.0
228
0.004386
# Copyright (c) 2019, Frappe Techn
ologies Pvt. Ltd. and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document clas
s QualityReviewObjective(Document): pass
google/clusterfuzz
src/appengine/handlers/performance_report/constants.py
Python
apache-2.0
5,306
0.000377
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
s. You need to debug the root cause for the hang and fix it. Possible causes are getting stuck on an infinite loop, some complex computation, etc.""", } QUERY_COLUMNS = [ 'actual_durati
on', 'average_exec_per_sec', 'bad_instrumentation', 'crash_count', 'expected_duration', 'leak_count', 'log_lines_from_engine', 'log_lines_ignored', 'log_lines_unwanted', 'new_units_added', 'new_units_generated', 'oom_count', 'slow_units_count', 'startup_crash_count', ...
foauth/oauth-proxy
services/deviantart.py
Python
bsd-3-clause
863
0
import foauth.providers def draft10(service, token, r): headers = r.headers or {} headers[u'Authorization'] = u'OAuth %s' %
token r.headers = headers return r class DeviantArt(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://deviantart.com/' docs_url = 'http://www.dev
iantart.com/developers/' category = 'Pictures' # URLs to interact with the API authorize_url = 'https://www.deviantart.com/oauth2/draft15/authorize' access_token_url = 'https://www.deviantart.com/oauth2/draft15/token' api_domain = 'www.deviantart.com' available_permissions = [ (None, '...
pavel-pimenov/sandbox
mediainfo/MediaInfoLib/Source/Example/HowToUse_Dll3.py
Python
mit
2,120
0.007547
## Copyright (c) MediaArea.net SARL. All Rights Reserved. # # Use of this source code is governed by a BSD-style license that can # be found in the License.html file in the root of the source tree. ## #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # Python example # # To make thi...
rint(MI.Count_Get(Stream.Audio)) print("") print("Get with Stream=General and Parameter='AudioCount'") print(M
I.Get(Stream.General, 0, "AudioCount")) print("") print("Get with Stream=Audio and Parameter='StreamCount'") print(MI.Get(Stream.Audio, 0, "StreamCount")) print("") print("Close") MI.Close()
basicScandal/raft
ui/DiffDialog.py
Python
gpl-3.0
4,244
0.004006
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'DiffDialog.ui' # # Created: Tue Aug 30 12:04:37 2011 # by: PyQt4 UI code generator 4.8.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attr...
self.verticalLayout.addLayout(self.horizontalLayout_2) self.splitter_2 = QtGui.QSplitter(DiffDialog) self.splitter_2.setOrientation(QtCore.Qt.Vertical) self.splitter_
2.setObjectName(_fromUtf8("splitter_2")) self.splitter = QtGui.QSplitter(self.splitter_2) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName(_fromUtf8("splitter")) self.leftTree = QtGui.QTreeWidget(self.splitter) self.leftTree.setObjectName(_fromUtf8("...
imbugs/stock-3
common/basic.py
Python
gpl-3.0
2,604
0.004224
import datetime as dt import re # Progress calculation and printing class Progress(object): def __init__(self, maximum): self.maximum = maximum self.last_percent = 0 def show(self, current): percent = round(current/self.maximum * 100) if percent > self.last_percent: ...
elf.f.write(data) def __del__(self): self.f.close() # Return cur
rent time timestamp def now(): return int(dt.datetime.now().strftime('%s')) # Return timestamp of datetime object def dt_timestamp(dt_obj): return int(dt_obj.strftime('%s')) # Return date object from timestamp def dt_date(timestamp): return dt.datetime.fromtimestamp(timestamp) # Function to convert resol...
camallen/aggregation
experimental/cancer/gold.py
Python
apache-2.0
1,697
0.005303
#!/usr/bin/env python __author__ = 'greghines' import pymongo import numpy as np import matplotlib.pyplot as plt import re goldX_1 = [331807.4, 3556826.0, 20072830.4, 20366014.0, 21147836.6, 24079671.8, 24666038.8, 31506987.4, 32288810.0, 38543391.6, 71282217.0, 140180342.0] goldY_1 = [0.4605457, 0.5014045,...
nd({"annotations.0":{"fileName" : "MB-3031Chrom9.txt"}}): pathString = classification["annotations"][1]["pathData"] pts = pathString.split(",") P = [] for i in range(len(pts)/2): x = pts[2*i] y = pts[2*i+1] colonIndex = x.index(":") x = float(x[colo
nIndex+1:]) colonIndex = y.index(":") bracketIndex = y.index("}") y = float(y[colonIndex+1:bracketIndex]) P.append((x,y)) print P user_points.append(P[:]) for jj in range(10): gold_x = goldX_1[jj] gold_y = goldY_1[jj] p = [] for classification in user_points...
vipmike007/avocado-vt
selftests/unit/test_libvirt_xml.py
Python
gpl-2.0
46,682
0.0003
#!/usr/bin/python import unittest import os import shutil import logging import sys from avocado.utils import process # simple magic for using scripts within a source tree basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if os.path.isdir(os.path.join(basedir, 'virttest')): sys.path.append(b...
' <graphics type="vnc" port="-1" autoport="yes"/>' ' <disk type="file" device="disk">' ' <driver name="qemu" type="qcow2"/>' ' <source file="/foo/bar/baz.qcow2"/>' ' <target de...
type="pci" domain="0x0000"' ' bus="0x00" slot="0x04" function="0x0"/>' ' </disk>' ' </devices>' ' <seclabel type="sec_type" model="sec_model">' ' <label>sec_label</label>' ...
juliovp01/ops_tools
roles/monitoring/files/ceilometer.py
Python
mit
2,011
0
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Openstack Monitoring script for Sensu / Nagios # # Copyright © 2013-2014 eNovance <licensing@enovance.com> # # Author: Mehdi Abaakouk <mehdi.abaakouk@enovance.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in ...
not meters: utils.critical("Unable to contact Ceilometer API.") if elapsed > options.critical: utils.critical("Get meters took more than %d seconds, "
"it's too long.|response_time=%d" % (options.critical, elapsed)) elif elapsed > options.warning: utils.warning("Get meters took more than %d seconds, " "it's too long.|response_time=%d" % (options.warning, elapsed)) else: utils...
astro4dev/OAD-Data-Science-Toolkit
Teaching Materials/Machine Learning/Supervised Learning/Examples/PPC/EvaluationStats.py
Python
gpl-3.0
16,967
0.009902
""" This file is part of contribution to the OAD Data Science Toolkit. This 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. The software is...
# agreement or inter-annotator agreement for qualitative (categorical) items. It is # generally t
hought to be a more robust measure than simple percent agreement # calculation since k takes into account the agreement occurring by chance. self.kappa = 0.0 # The true positives. self.TP = 0.0 # The true negatives. self.TN = 0.0 # The false positives. ...
terasaur/seedbank
src/seedbank/cli/add_command.py
Python
apache-2.0
3,950
0.002025
# # Copyright 2012 ibiblio # # 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.txt # # Unless required by applicable law or agreed to in writing...
(self): if not self._check_required_params(): return self._print('torrent_file: %s\n' % self._torrent_file) self._print('data_root: %s\n' % self._data_root) #self._print('torrent_root: ' + self._torrent_root) # Convert data_root relative path to absolute path ...
ata_root = self._data_root if not self._check_duplicate_torrent(t): return if not self._check_torrent_root_contents(t): return # TODO: check for torrent file already exists in torrent root t.save() # TODO: delete torrent file if save fails sel...
CristianCantoro/cartogram-plugin
resources.py
Python
gpl-2.0
15,867
0.000063
# -*- coding: utf-8 -*- # Resource object code # # Created: lun mar 24 20:18:44 2014 # by: The Resource Compiler for PyQt (Qt v4.8.4) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x07\xa9\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x...
8\x1c\x73\x6c\x14\xaa\xb5\x14\x04\x87\x37\x59\ \x9c\xfd\xcd\x39\x49\x68\x29\xc3\x48\x98\x34\x4e\x71\xee\x98\xa8\ \x74\x1a\x66\xd5\xe8\xe0\xfa\x43\xb1\x2e\x6d\xeb\x40\x2b\x6d\x8a\ \x9a\xd6\x45\x7b\xea\x3a\x0a\x1f\x5b\xba\x8b\xa2\x22\xf8\xe5\x81\ \xad\x94\xdc\xf9\xf0\x70\x44\xa1\xeb\xea\x11
\xae\xd5\x6f\x84\x69\ \xac\x96\x0f\xe4\xf7\x83\x29\x20\x00\x57\xee\xd1\xfe\x96\x2d\x50\ \x52\x02\x3f\x7a\xdc\x58\xfe\x47\xbe\x03\x61\x18\x3a\xfe\xb6\xcb\ \x7e\x69\xf3\x2e\xb6\x6f\x87\xe5\xcb\xc1\xef\x69\x1e\x16\x78\xbf\ \xcf\x83\x22\x2b\xdb\xa0\xf1\xd4\x13\xb5\xbc\x5c\xa7\x83\xae\x2e\ \x58\xb1\x02\xfc\x0b\xbe\x0d\xe0\x...
mzdaniel/oh-mainline
vendor/packages/twisted/twisted/lore/_version.py
Python
agpl-3.0
139
0
# This is an auto-gener
ated file. Do not edit it. from twisted.python import versions version = versions.Version('twist
ed.lore', 11, 0, 0)
dnacreative/Zeek
src/client.py
Python
mit
13,764
0.004432
import ConfigParser import datetime import Queue import logging import os import pickle import socket import sys import time import thread import traceback import modules.logger as logger import modules.protocol as protocol import modules.scrapping as scrapping sys.setrecursionlimit(10000) buffSize =...
= Queue.Queue(0) self.urlToVisit = Queue.Queue(0) # object self.scrapper = None self.config = None def connect(self, host, port): """Sets up the connection to the server (max 6 attem
ps)""" self.host = host self.port = port self.masterNodeFormattedAddr = "[" + str(self.host) + ":" + str(self.port) + "]" logger.log(logging.DEBUG, "Socket initialization") self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) for connectionAttempt in range(6...
nijel/weblate
weblate/formats/tests/test_convert.py
Python
gpl-3.0
4,423
0.000453
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
MATCH = "Hello, world!\n" EDIT_OFFSET = 1 class PlainTextFormatTest(ConvertFormatTest): FORMAT = PlainTextFormat FILE = TEST_TXT BASE = TEST_TXT MIME = "text/plain" EXT = "txt" COUNT = 5 MASK = "txt/*.txt" EXPECTED
_PATH = "txt/cs_CZ.txt" MATCH = "Hello" FIND_CONTEXT = "cs.txt:2" FIND_MATCH = "Hello, world!" EDIT_OFFSET = 1
scitran/data
scitran/data/meeg/meeg.py
Python
mit
6,305
0
""" scitran.data.meeg ================= Data format for M/EEG data using mne-python. """ import logging import tempfile import zipfile import warnings import os from os import path as op from datetime import datetime, date import shutil from mne.io import read_raw_fif from .. import data log = logging.getLogger(_...
: return self.group_id @property def nims_project(self): return self.project_name @property def nims_session_id(self): return self.session_id @property def nims_session_label(self): return self.session_id @property def nims_session
_subject(self): return self.session_subject @property def nims_acquisition_id(self): return self.acquisition @property def nims_acquisition_label(self): return self.acquisition @property def nims_acquisition_description(self): return self.acquisition @prop...
popovsn777/python_training_2
fixture/application.py
Python
apache-2.0
807
0.006196
__author__ = 'popov.sn' from selenium.webdriver.firefox.webdriver import WebDriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import Conta
ctHelper class Application: def __init__(self): self.wd = WebDriver() self.wd.implicitly_wait(2) self.session = SessionHelper(self) self.group = GroupHelper(self)
self.contact = ContactHelper(self) def is_valid(self): try: self.wd.current_url return True except: return False def open_home_page(self): # open home page wd = self.wd # wd.get("http://localhost/addressbook/addressbook/") ...
harry-7/addons-server
src/olympia/github/tests/test_tasks.py
Python
bsd-3-clause
2,079
0
import
json from django.test.utils import override_settings import mock from olympia.amo.templatetags.jinja_helpers import absolutify from olympia.amo
.tests import AMOPaths from olympia.amo.urlresolvers import reverse from olympia.files.models import FileUpload from olympia.github.tasks import process_results, process_webhook from olympia.github.tests.test_github import GithubBaseTestCase @override_settings(GITHUB_API_USER='key', GITHUB_API_TOKEN='token') class Te...
icgc-dcc/egasub
tests/conftest.py
Python
gpl-3.0
9,299
0.012259
import pytest import httpretty import logging class callcounted(object): """Decorator to determine number of calls for a method""" def __init__(self,method): self.method=method self.counter=0 def __call__(self,*args,**kwargs): self.counter+=1 return self.method(*args,**kwa...
_alias?idType=ALIAS&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']), body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}', content_type="application/json") httpretty.register_uri(httpretty.GET, "%spolicies/policy_alias?idType=ALIAS&skip...
[{ "id":"12345" }]}}', content_type="application/json") httpretty.register_uri(httpretty.GET, "%ssamples?status=SUBMITTED&skip=0&limit=0" % (ctx.obj['SETTINGS']['apiUrl']), body='{"header" : {"code" : "200"}, "response" : {"result" : [{ "id":"12345" }]}}', ...
ticapix/gallim
gallim/auth/facebook.py
Python
bsd-2-clause
6,920
0.007225
import json import logging import tornado.auth import tornado.gen import tornado.options import tornado.web import urllib.parse import uuid from gallim.shared import BaseHandler # client browser gallim reverse service FB # + + ...
| # +----------------------|-------------------------------------|----------------------------------->| # | | | /reverse_session_url/*?code
=<code> | # | | |<-----------------------------------+ # | redirect request on gallim_url | | # |<-----------------------------------------------------------+ ...
metamx/Diamond
src/collectors/mongodb/mongodb.py
Python
mit
12,462
0.000642
# coding=utf-8 """ Collects all number values from the db.serverStatus() command, other values are ignored. #### Dependencies * pymongo """ import diamond.collector from diamond.collector import str_to_bool import re import zlib try: import pymongo pymongo # workaround for pyflakes issue #13 except Impo...
ublish_transformed(data, base_prefix) if str_to_bool(self.config['simple']): data = self._extract_simple_data(data) self._publish_dict_with_prefix(data, base_prefix) db_name_filter = re.compile(self.config['databases']) ignored_collections = re.compile(se...
CRC32 * self.config[ 'collection_sample_rate'] for db_name in conn.database_names(): if not db_name_filter.search(db_name): continue db_stats = conn[db_name].command('dbStats') db_prefix = base_prefix + ['databases', db_name...
pastebt/yeast
testcase/test_tpl.py
Python
gpl-2.0
16,760
0.000716
import sys import unittest sys.path.append('../yeast') import tpl class TestParser(unittest.TestCase): def setup(self, data=None): self.mp = tpl.MyHtmlParser() if data: self.mp.feed(data) def test_data1(self): self.setup() self.mp.feed("abc") self.assertTr...
agNode)) self.assertEqual(ret[0]['id'], 'a') ret = tpl.select('#b', self.func) self.assertEqual(ret, []) def test_id1(self): s
elf._test_id1("<b id='a' b='2'> </b>") self._test_id1("<html><b class='c' b='2' id='a'> </b></html>") self._test_id1("<html><b class='c' b='2' id='a'> <div/> </b></html>") def test_id2(self): self.setup() self.mp.feed("<a id='b' b='2'> </a>") ret = tpl.select('#a', self.func...
anderson7ru/bienestarues
signosvitalesapp/apps.py
Python
mit
107
0
from django.apps impo
rt AppConfig class SignosvitalesappConfig(AppConfig): name = 'signosvitalesa
pp'
samueldotj/TeeRISC-Simulator
src/arch/x86/isa/insts/simd64/integer/compare/compare_and_write_minimum_or_maximum.py
Python
bsd-3-clause
3,427
0
# Copyright (c) 2007 The Hewlett-Packard Development Company # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implemen...
D OF THE POSSIBILITY OF SUCH DAMAGE.
# # Authors: Gabe Black microcode = ''' def macroop PMINUB_MMX_MMX { mmini mmx, mmx, mmxm, size=1, ext=0 }; def macroop PMINUB_MMX_M { ldfp ufp1, seg, sib, disp, dataSize=8 mmini mmx, mmx, ufp1, size=1, ext=0 }; def macroop PMINUB_MMX_P { rdip t7 ldfp ufp1, seg, riprel, disp, dataSize=8 mmini...
ingydotnet/peglite-py
tests/test_import.py
Python
bsd-2-clause
215
0.009302
fro
m package.unittest import * class TestImport(TestCase): def test_import(self): import peglite self.assertTrue(True, 'peglite module imported cl
eanly') if __name__ == '__main__': main()
Azure/azure-sdk-for-python
sdk/resourcehealth/azure-mgmt-resourcehealth/azure/mgmt/resourcehealth/v2015_01_01/_microsoft_resource_health.py
Python
mit
4,936
0.003241
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
tyStatusesOperati
ons from .operations import ChildResourcesOperations from .operations import Operations from . import models class MicrosoftResourceHealth(object): """The Resource Health Client. :ivar availability_statuses: AvailabilityStatusesOperations operations :vartype availability_statuses: azure.mgmt.resourceheal...
bejar/kemlglearn
kemlglearn/cluster/consensus/test.py
Python
mit
905
0.007735
""" .. module:: test test ************* :Description: test :Authors: bejar :Version: :Created on: 10/02/2015 9:50 """ __author__ = 'bejar' from MeanPartition import MeanPartitionClustering from kemlglearn.datasets import cluster_generator import matplotlib.pyplot as plt from sklearn.datasets import make_blo...
s, make_circles nc = 15 X, y = cluster_generator(n_clusters=nc, sepval=0.2, numNonNoisy=100, numNoisy=10, rangeN=[150, 200]) # print X[:,:-2] # #print X,y # X, y = mak
e_blobs(n_samples=1000, n_features=20, centers=nc, random_state=2) gkm = MeanPartitionClustering(n_clusters=nc, n_components=40, n_neighbors=3, trans='spectral', cdistance='ANMI') res, l = gkm.fit(X, y) fig = plt.figure() # ax = fig.gca(projection='3d') # pl.scatter(X[:, 1], X[:, 2], zs=X[:, 0], c=gkm.labels_, s=2...
gabberthomson/fm_finpy
fixedcouponbond_project.py
Python
mit
1,921
0.003123
from datetime import date from openpyxl import load_workbook if __name__ == '__main__': wb = load_workbook('FixedCouponBond.xlsx') ws = wb.active # Take the input parameters today = ws['C2'].value.date() # OIS Data ois_startdate = today ois_maturities = [] ois_mktquotes = [] for c...
s.append(cell[0].value.date()) ndps.append(cell[1].value) # Bond data nominals = [] start_dates = [] end_dates = [] cpn_frequency = [] coupons = [] recovery_rates = [] for cell in list(ws.iter_rows('E5:J19')): nominals.append(cell[0].value) start_dates.append(ce...
es.append(cell[5].value) # YOUR CODE HERE .... # In the coupon calculation use 30e360 convention to compute the accrual period (i.e. tau) # The result of your code must be a variables of type list named # output_npv. The length of this list has to be the equal to the number of bonds # i.e len(nomi...
ericholscher/django
tests/timezones/tests.py
Python
bsd-3-clause
55,186
0.002138
from __future__ import unicode_literals import datetime import os import re import sys from unittest import skipIf import warnings from xml.dom.minidom import parseString try: import pytz except ImportError: pytz = None from django.conf import settings from django.core import serializers from django.core.url...
Feature, skipUnlessDBFeature from django.test.utils import override_s
ettings, requires_tz_support from django.utils import six from django.utils import timezone from .forms import EventForm, EventSplitForm, EventLocalizedForm, EventModelForm, EventLocalizedModelForm from .models import Event, MaybeEvent, Session, SessionEvent, Timestamp, AllDayEvent # These tests use the EAT (Eastern...
Azure/azure-sdk-for-python
sdk/aks/azure-mgmt-devspaces/azure/mgmt/devspaces/models/_models_py3.py
Python
mit
19,905
0.002813
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
': True}, 'name': {'readonly': True}, 'type': {'readonly': True},
'sku': {'required': True}, 'provisioning_state': {'readonly': True}, 'host_suffix': {'readonly': True}, 'data_plane_fqdn': {'readonly': True}, 'target_container_host_api_server_fqdn': {'readonly': True}, 'target_container_host_resource_id': {'required': True}, 'target...
projectcalico/calico-neutron
neutron/tests/unit/nec/test_security_group.py
Python
apache-2.0
3,731
0.000268
# Copyright 2013, NEC 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
copy()) super(NecSecurityGroupsTestCase, self).setUp(PLUGIN_NAME) plugin = manager.NeutronManager.get_plugin() self.notifier = plugin.notifier self.rpc = plugin.callback_sg def tearDown(self): super(NecSecurityGroupsTestCase, self).tearDown() ...
erRpcCallBack( test_sg_rpc.SGServerRpcCallBackTestCase, NecSecurityGroupsTestCase): pass class TestNecSecurityGroups(NecSecurityGroupsTestCase, test_sg.TestSecurityGroups, test_sg_rpc.SGNotificationTestMixin): def test_security_group_get_port_fr...
vg/netsukuku
pyntk/test/test_inet.py
Python
gpl-2.0
2,216
0.002256
## # This file is part of Netsukuku # (c) Copyright 2008 Daniele Tricoli aka Eriol <eriol@mornie.org> # # This source code is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation; either version 2 of the License, # or ...
pip = inet.str_to_pip(self.ps)
self.assertEqual(inet.pip_to_ip(pip), 16909060) def testIPToPip(self): ''' Test conversion ip --> pip ''' ip = inet.pip_to_ip(inet.str_to_pip(self.ps)) self.assertEqual(inet.ip_to_pip(ip), '\x01\x02\x03\x04') def testIPToStr(self): ''' Test conversion ip --> str ''' ...
ohsnapitsnathan/brainkit
brainkit.py
Python
gpl-2.0
48,178
0.019781
from __future__ import division from itertools import islice, tee import headset import time import urllib2 import numpy as np import msvcrt imprintSham=False current_milli_time = lambda: int(round(time.time() * 1000)) stimModes={"F4":0,"C4":1,"O2":2,"C3":3,"F3":4,"O1":5,"Reference electrode":6} electrodeName...
print("There seems to be a problem with the EasyGui installation. Please download and install it.") raw_input() quit() try: import serial except ImportError: print("There seems to be a pr
oblem with the PySerial installation. Please download and install it.") raw_input() quit() import math import os import subprocess import thread import time def connectStim(): accepted=False choice="" while not accepted: thePorts=headset.getPorts() if len(thePorts) <...
KM4YRI/pyFldigi
pyfldigi/appmonitor.py
Python
gpl-3.0
6,913
0.003616
"""TBD """ import os import sys import time import subprocess import xmlrpc.client class ApplicationMonitor(object): """Responsible for launching, monitoring, and terminating the FLDIGI application process, using subprocess.Popen() :param hostname: The FLDIGI XML-RPC server's IP address or hostname (usuall...
ldigi. Is it installed?') elif len(fldigi_versions) == 1: path = os.path.join(os.environ["ProgramFiles(x86)"], fldigi_versions[0]) # Check to see if fldigi.exe is in the folder if 'fldigi.exe' in os.listdir(path): return os.path.join(path,...
digi.exe') else: raise Exception('Found more than one version of fldigi. Uninstall one.') else: # Assume all other OS's are smart enough to place fldigi in PATH return 'fldigi' def is_running(self): """Uses the python subprocess module object to see if FLDI...
fernando1980/viewAttributes
viewAttributes/view_Attributes_dialog.py
Python
gpl-3.0
2,071
0.001931
# -*- coding: utf-8 -*- """ /*************************************************************************** viewAttributesDialog A QGIS plugin Show attributes of a field selected stored in a shapefile. ------------------- begin : 2017-0...
neral Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************...
butes_dialog_base.ui')) class viewAttributesDialog(QtGui.QDialog, FORM_CLASS): def __init__(self, parent=None): """Constructor.""" super(viewAttributesDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doi...
DolphinDream/sverchok
nodes/solid/sweep_face.py
Python
gpl-3.0
4,476
0.00916
# This file is part of project Sverchok. It's copyrighted by the contributors # recorded in the version control history of the file, available from # its original location https://github.com/nortikin/sverchok/commit/master # # SPDX-License-Identifier: GPL3 # License-Filename: LICENSE import numpy as np import bpy fro...
erchok.utils.surface.freecad import surface_to_freecad, is_solid_face_surface from sverchok.utils.dummy_nodes import add_dummy from sverchok.dependencies import FreeCAD if FreeCAD is None: add_dummy('SvSweepSolidFaceNode', 'Sweep Fa
ce (Solid)', 'FreeCAD') else: import Part from FreeCAD import Base from Part import BRepOffsetAPI class SvSweepSolidFaceNode(bpy.types.Node, SverchCustomTreeNode): """ Triggers: Solid Face Revolution Tooltip: Make a Solid by sweeping a Face along Curve """ bl_idname = 'SvSweepSolidFace...
n4hy/gnuradio
volk/gen/make_c.py
Python
gpl-3.0
3,494
0.004865
# # Copyright 2010-2011 Free Software Foundation, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This progra...
ing += r""" struct volk_machine *get_machine(void) { extern struct volk_machine *volk_machines[]; exte
rn unsigned int n_volk_machines; static struct volk_machine *machine = NULL; if(machine != NULL) return machine; else { unsigned int max_score = 0; unsigned int i; for(i=0; i<n_volk_machines; i++) { if(!(volk_machines[i]->caps & (~volk_get_lvarch()))) { ...
jmdana/py3google
pygoogle.py
Python
mit
9,074
0.009698
#!/usr/bin/python """ Google AJAX Search Module http://code.google.com/apis/ajaxsearch/documentation/reference.html Needs Python 2.6 or later """ try: import json except ImportError as e: import simplejson as json except ImportError as e: print(e) exit() import sys import urllib.request, urllib.parse, ...
eb Search Specific Arguments #http://code.google.com/apis/ajaxsearch/documentation/reference.html#_fonje_web #SAFE,FILTER """ SAFE This optional argument supplies the search
safety level which may be one of: * safe=active - enables the highest level of safe search filtering * safe=moderate - enables moderate safe search filtering (default) * safe=off - disables safe search filtering """ SAFE_ACTIVE = "active" SAFE_MODERATE = "moderate" SAFE_OFF = "off" """ FILTER ...
syscoin/syscoin
test/functional/feature_nulldummy.py
Python
mit
7,351
0.004897
#!/usr/bin/env python3 # Copyright (c) 2016-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test NULLDUMMY softfork. Connect to a single node. Generate 2 blocks (save the coinbases for later). G...
bmit(self.nodes[0], test6txs, with_witness=True, accept=True) def block_submit(self, node, txs, *, with_witness=False, accept): tmpl = node.getblocktemplate(NORMAL_GBT_REQUEST_PARAMS) assert_equal(tmpl['previousblockhash'], self.lastblockhash) assert_equal(tmpl['height'], self.lastblockheig...
time + 1, txlist=txs) if with_witness: add_witness_commitment(block) block.solve() assert_equal(None if accept else NULLDUMMY_ERROR, node.submitblock(block.serialize().hex())) if accept: assert_equal(node.getbestblockhash(), block.hash) self.lastblockh...
ibm-cds-labs/pixiedust
pixiedust/display/chart/renderers/bokeh/__init__.py
Python
apache-2.0
888
0.003378
# ------------------------------------------------------------------------------- # Copyright IBM Corp. 2017 # # L
icensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Lic...
OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------- import bokeh from .bkBarChartDisplay import * from .bkLineChartDisplay import * from .bkScatt...
kitefishlabs/synaesthetic
python/video.py
Python
gpl-2.0
4,517
0.007084
import numpy as np import cv2 from time import clock from numpy import pi, sin, cos import common class VideoSynthBase(object): def __init__(self, size=None, noise=0.0, bg = None, **params): self.bg = None self.frame_size = (640, 480) if bg is not None: self.bg = cv2.imread(bg, ...
arams>' ''' try: source = int(source) except ValueError: pass else: return cv2.VideoCapture(source) source = str(source).strip() if source.startswith('synth'): ss = filter(None, source.split(':')) params = dict( s.split('=') for s in ss[1:]
) try: Class = classes[params['class']] except: Class = VideoSynthBase return Class(**params) return cv2.VideoCapture(source) presets = dict( empty = 'synth:', lena = 'synth:bg=../cpp/lena.jpg:noise=0.1', chess = 'synth:class=chess:bg=../cpp/lena.jpg:noise=0.1:size=640x480' )...
FlorianLudwig/python-yawp
yawp/template.py
Python
bsd-3-clause
4,325
0.001387
# Copyright (c) 2010, Florian Ludwig <dino@phidev.org> # see LICENSE """Helpers for code generation based on genshi [0] There are good code generator tools out there like cog [1]. But if you already use genshi in your project this module might help you integrating code generation into your build and deploy process us...
de='r'): """Add filenumbers to ev
ery line as comment Returns filelike object """ _fileobj = open(fpath, mode) tmpl_cls = get_template(fpath) if tmpl_cls == ActionscriptTemplate: comment_start = '/*' comment_end = '*/' last_symbole = ';' elif tmpl_cls == MarkupTemplate: comment_start = '<!-...
arogozhnikov/OBDT
tests/test_simple_pruner.py
Python
mit
1,116
0
from __future__ import division, print_function, absolute_import __author__ = 'Alex Rogozhnikov' import numpy from pruning import simple_pruner, utils from hep_ml.losses import CompositeLossFunction, MSELossFunction def test_pruner(mx_filename='../data/formula.mx', higgs_filename='../data/training.cs...
ame, 'rb') as mx:
formula_mx = mx.read() X, y, w = utils.get_higgs_data(higgs_filename) X = numpy.array(X, dtype='float32') # checking workability, not quality simple_pruner.canonical_pruning(X, y, w, initial_mx_formula=formula_mx, loss_function=CompositeLossFunction(), ...
KorolevskyMax/TestFrameworkTemplate
helpers/app_helpers/app_session.py
Python
mit
1,768
0.001131
import re from bs4 import BeautifulSoup from nose.tools import assert_equal, assert_in, assert_true import pages import requests APP_URL = 'https://www.github.com' ADMIN_CREDENTIALS = {'username': 'admin@example.com', 'password': 'pk$321'} ROOT_CREDENTIALS = {'username': 'root', 'password': '123456'} API_URLS_MAP = {...
t)[0] def _get_data_key(source_name, payload, response): name_key_source_map = { 'page': '[name]', 'partner': '[name]', 'product': '[title]', } key_part = name_key_source_map[source_name] name = payload[[k for k in payload.keys() if key_part in k][0]] soup = BeautifulSoup(r...
trs = soup.findAll(lambda tag: tag.name == 'tr' and 'data-key' in tag.attrs) tr = [tr for tr in trs if name in tr.text][0] return tr['data-key']
blaskovic/utilities
vutbr-portal/news.py
Python
gpl-2.0
515
0.005825
#!/usr/bin/python import requests import time s = requests.session() login_data = { 'LDAPlogin':'xblask00',
'LDAPpasswd':'CHANGEME', 'special_p4_form': '1', 'login_form': '1', 'sentTime': str(int(time.time())), 'sv[fdkey]': 'BR0qqTALg9', } #print login_data s.post('https://www.vutbr.cz/login/in', login_data) r2 = s
.get('https://www.vutbr.cz/studis/student.phtml?sn=aktuality_predmet') print r2.content
RamonGuiuGou/l10n-spain
l10n_es_aeat_mod340_cash_basis/wizard/__init__.py
Python
agpl-3.0
1,096
0
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2016 Factor Libre S.L. (http://factorlibre.com) # Kiko Peiro <francisco.peiro@factorlibre.com> # # # This program is free sof...
# 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.org/licenses/>. # #######################################...
records
Nic30/hwtHls
tests/io/axiStream/axisParseIf_test.py
Python
mit
3,663
0.001092
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from math import ceil import unittest from hwt.hdl.types.bits import Bits from hwt.hdl.types.struct import HStruct from hwt.simulator.simTestCase import SimTestCase from hwtHls.platform.virtual import VirtualHlsPlatform from hwtLib.amba.axis import axis_send_bytes from p...
(Bits(16), "v0"), (Bits(16), "v1"), ) T4 = HStruct( (Bits(16), "v0"), (Bits(32), "v1"), ) ref = [] ALL_Ts = [T1, T2, T4] for _ in range(N): T = self._rand.choice(ALL_Ts) v1_t = T.field_by_name["v1"].dt...
bit_length()) d = { "v0": v1_t.bit_length() // 8, "v1": v1 } if v1_t.bit_length() in (16, 32): ref.append(v1) v = T.from_py(d) w = v._dtype.bit_length() v = v._reinterpret_cast(Bits(w)) v...
mPowering/django-orb
orb/views.py
Python
gpl-3.0
30,008
0.002399
import os from collections import defaultdict from django.conf import settings from django.contrib import messages from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.core.urlresolvers import reverse from django.db.models import Count, Q from django.http import HttpResponseRedirect, Http404...
source_view(request, resource.slug) def resource_view(request, resource_slug): resource = get_object_or_404( Resource.objects.approved(user=request.user), slug=resource_slug) if resource.status == Resource.ARCHIVED: messages.error(request, _( u"This resource has been archived by t...
.APPROVED: messages.error(request, _( u"This resource is not yet approved by the ORB Content" u" Review Team, so is not yet available for all users to view")) options_menu = [] if resource_can_edit(resource, request.user): om = {} om['title'] = _(u'Edit') ...
e-mission/e-mission-server
emission/core/wrapper/incident.py
Python
bsd-3-clause
925
0.014054
from __future__ import unicode_literals from __future__ import print_function from __future
__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * import logging import emission.core.wrapper.wrapperbase as ecwb class Incident(ecwb.WrapperBase): props = {"loc": ecwb.WrapperBase.Access.RO, # geojson represen...
estamp representation of the point "stress": ecwb.WrapperBase.Access.RO, # stress level (0 = no stress, 100 = max stress) "local_dt": ecwb.WrapperBase.Access.RO, # searchable datetime in local time "fmt_time": ecwb.WrapperBase.Access.RO # formatted time } enums = {} ...
42ity/fty-core
tests/CI/shared.py
Python
gpl-2.0
2,130
0.002347
# Copyright (C) 2014 - 2020 Eaton # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in t...
d have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51
Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #! \file shared.py # \brief shared routines for CI tests written in python # \author Michal Vyskocil <MichalVyskocil@Eaton.com> import MySQLdb def parse_ip_a_s(out): """ parse output of command ip a(ddr) s(how) return - list of tuple ...
Tinkerforge/brickv
src/brickv/plugin_system/plugins/imu/imu_3d_widget.py
Python
gpl-2.0
2,398
0.002086
# -*- coding: utf-8 -*- """ IMU Plugin Copyright (C) 2015 Olaf Lüke <olaf@tinkerforge.com> Copyright (C) 2015 Matthias Bolte <matthias@tinkerforge.com> Copyright (C) 2019 Erik Fleckstein <erik@tinkerforge.com> imu_3d_widget.py: IMU OpenGL representation This program is free software; you can redistribute it and/or mo...
LITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA. """ import sys import ctypes import ctypes.util import math import array import os from PyQt5.QtGui import QMatrix4x4, QQuaternion from brickv.utils import get_resources_path from brickv.render_widget import RenderWidget class IMU3DWidget(RenderWidget): def __init_...
Doteveryone/LegislationTagger
manage.py
Python
agpl-3.0
3,236
0.004944
from flask_script import Manager, prompt_bool from legitag import app, models import feedparser from mongoengine import connect, DoesNotExist from time import sleep import re manager = Manager(app) @manager.command def resetdatabase(): "Delete all data, reset everything" if prompt_bool("Are you absolutely cer...
DB_DB'], host=app
.config['MONGODB_HOST'], port=app.config['MONGODB_PORT']) db.drop_database(app.config['MONGODB_DB']) print("Deleted all collections from database ...") @manager.command def generateleaguetable(): ledger = {} legislations = models.Legislation.objects() for legislation in legislations: f...
Genovo/OTPSetup
otpsetup/client/lib/buttonable_model_admin.py
Python
gpl-3.0
2,534
0.018942
#by mamat and tsaylor on djangosnippets.org import re from django.conf.urls.defaults import patterns, url from django.contrib import admin from django.http import HttpResponseRedirect from django.utils.functional import update_wrapper class Button(object): def __init__(self, func): self.func_name = func.fun...
f change_view(self, request, object_id, extra_context={}): if '/' in object_id: object_id = object_id[:object_id.find('/')] buttons = self.buttons if callable(buttons): buttons = buttons(request, object_id) buttons = map(Button, buttons) extra_context['buttons'] ...
l is not None: res = re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)', url) if res: buttons = self.buttons if callable(buttons): buttons = buttons() print res.group('command') if res.group('command') in [b.func_name for b in buttons]: ...
izrik/tudor
tests/persistence_t/in_memory/models/attachment_t/test_attachment_repr.py
Python
gpl-2.0
443
0.002257
#!/usr/bin/env python import unittest from persistence.in_memory.models.attachment import Attachment class AttachmentReprTest(unittest.TestCase): def test_generates_repr_string(self): # given
att = Attachment(pa
th='/path/to/file') att.id = 123 #when r = repr(att) # then self.assertEqual('Attachment(\'/path/to/file\', id=123)', r) # TODO: test other paths, other ids, None
euphorie/Euphorie
src/euphorie/client/tests/test_survey_integration.py
Python
gpl-2.0
5,946
0.000673
# coding=utf-8 from datetime import datetime from euphorie.client import model from euphorie.client.tests.utils import addAccount from euphorie.client.tests.utils import addSurvey from euphorie.content.tests.utils import BASIC_SURVEY from euphorie.testing import EuphorieIntegrationTestCase from lxml import html from pl...
with api.env.adopt_user(user=survey_session.account): with self._get_view( "publication_date", traversed_survey_session, survey_session ) as view: # The view is not callable but # has traversable allowed attributes
self.assertRaises(ViewNotCallableError, view) # We have some default values that will be changed # when publishing/unpublishing the session self.assertEqual(survey_session.last_publisher, None) self.assertEqual(survey_session.published, None) ...
antoinecarme/sklearn2sql_heroku
tests/regression/freidman2/ws_freidman2_XGBRegressor_sqlite_code_gen.py
Python
bsd-3-clause
129
0.015504
fro
m sklearn2sql_heroku.tests.regression import generic as reg_gen reg_gen.test_model("XGBRegressor" , "freidman2" , "s
qlite")
ClimateImpactLab/DataFS
tests/test_version_metadata.py
Python
mit
2,807
0
from __future__ import absolute_import import os import pytest from tests.resources import has_special_dependencies if has_special_dependencies: import xarray as xr import pandas as pd import numpy as np class TestVersionedMetadata(object): def test_versioned_metadata_open(self, api, opener, tempdi...
s, reason='Modules unable to install') def test_version_metadata_with_streaming(self, api, opener): np.random.seed(123) times = pd.date_range('2000-01-01', '2001-12-31', name='
time') annual_cycle = np.sin(2 * np.pi * (times.dayofyear / 365.25 - 0.28)) base = 10 + 15 * np.array(annual_cycle).reshape(-1, 1) tmin_values = base + 3 * np.random.randn(annual_cycle.size, 3) tmax_values = base + 3 * np.random.randn(annual_cycle.size, 3) ds = xr.Dataset({'tmi...
LevinJ/CodeSamples
python/images/findpeak.py
Python
gpl-2.0
253
0.011858
from scipy import signal impor
t numpy as np import matplotlib.pyplot as plt xs = np.arange(0, np.pi, 0.05) plt.plot(xs) data = np.sin(xs) plt.plot(data) peakind = signal.find_peaks_cwt
(data, np.arange(1,10)) print(peakind, xs[peakind], data[peakind])
mantarayforensics/mantaray
Tools/Python/simplekml/icon.py
Python
gpl-3.0
9,513
0.001367
""" simplekml Copyright 2011 Kyle Lancaster This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribut...
refreshinterval (float) -- time between refreshes (default None) viewrefreshmode (string) -- one of [ViewRefreshMode] constants(default None) viewrefreshtime (float) -- time to refresh after camera stop (default None) viewboundscale (float) -- extent to request (default None) viewformat (strin...
-- x position of icon palette (default None) gxy (int) -- y position of icon palette (default None) gxh (int) -- height of icon palette (default None) gxw (int) -- width of icon palette (default None) Properties: Same as arguments. ...
pytorch/vision
torchvision/ops/poolers.py
Python
bsd-3-clause
12,720
0.003302
import warnings from typing import Optional, List, Dict, Tuple, Union import torch import torch.fx import torchvision from torch import nn, Tensor from torchvision.ops.boxes import box_area from ..utils import _log_api_usage_once from .roi_align import roi_align # copying result_idx_in_level to a specific index in ...
l, eps) class LevelMapper: """Determine which FPN level each RoI in a set of RoIs should map to based on the heuristic in the FPN pape
r. Args: k_min (int) k_max (int) canonical_scale (int) canonical_level (int) eps (float) """ def __init__( self, k_min: int, k_max: int, canonical_scale: int = 224, canonical_level: int = 4, eps: float = 1e-6, ): ...
Incogniiito/Chrononaut
squad/demo_prepro.py
Python
apache-2.0
1,321
0.009084
import argparse import json import os import nltk # data: q, cq, (dq), (pq), y, *x, *cx # shared: x, cx, (dx), (px), word_counter, char_counter, word2vec # no metadata from collections import Counter from tqdm import tqdm from squad.utils import get_word_span, process_tokens, get_word_idx def prepro(par...
i = [[list(xij) for xij in xi]] qi = word_tokenize(question) cqi = [list(qij) for qij in qi] yi = [[(0, 0), (0, 0)]] cyi = [[0, 0]] answers = [] q.append(qi) cq.append(cqi) y.append(yi) cy.append(cyi) x.append(xi) cx.append(xi) ids.append(0) idxs.a
ppend(len(idxs)) answerss.append(answers) data = {'q': q, 'cq': cq, 'y': y, 'x': x, 'cx': cx, 'cy': cy, 'p': [paragraph], 'idxs': idxs, 'ids': ids, 'answerss': answerss} return data if __name__ == "__main__": main()
cevaris/pants
contrib/cpp/src/python/pants/contrib/cpp/register.py
Python
apache-2.0
1,198
0.005008
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.build_gra...
urn BuildFileAliases( targets={ 'cpp_library': CppLibrary, 'cpp_binary': CppBinary, } ) def register_goals(): task(name='cpp', action=CppCompile).install('compile') task(name='cpplib', action=CppLibraryCreate).install('binary') task(name='cpp', action=
CppBinaryCreate).install('binary') task(name='cpp', action=CppRun).install('run')
soneups/scratchcode
stockrun.py
Python
gpl-3.0
777
0.018018
#!/usr/bin/env python # Python script to retrieve stock information, price and change since last open. # # this file -- https://raw.githubusercontent.com/soneups/scratchcode/master/stockrun.py # # 27-J
an-2015 v1.0 initial script # HT - http://www.instructables.com/id/Getting-St
ock-Prices-on-Raspberry-Pi-Python/?ALLSTEPS import sys import time import os import ystockquote os.system('clear') # stock symbol from the command line def StockLookup (symbol): allinfo = ystockquote.get_all(symbol) price = float(allinfo["price"]) change = float(allinfo["change"]) percent = change/(chang...
sunny414/tryton-client
tryton/common/cellrendererinteger.py
Python
gpl-3.0
1,058
0.004726
#This file is
part of Tryton. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. import gobject from cellrenderertext import CellRendererText import locale class CellRendererInteger(
CellRendererText): def on_start_editing(self, event, widget, path, background_area, cell_area, flags): editable = super(CellRendererInteger, self).on_start_editing(event, widget, path, background_area, cell_area, flags) editable.set_alignment(1.0) editable.connec...
saitoha/PyDRCS
drcs/wcwidth.py
Python
gpl-3.0
16,031
0.039923
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
typographically to allocate two character cells to characters such # as for instance EM SPACE or VOLUME INTEGRAL, whic
h cannot be # represented adequately with a single-width glyph. The following # routines at present merely assign a single-cell width to all # neutral characters, in the interest of simplicity. This is not # entirely satisfactory and should be reconsidered before # establishing a formal standard in this area. At the mo...
dls-controls/pymalcolm
malcolm/modules/demo/util.py
Python
apache-2.0
1,261
0
import numpy as np from scanpointgenerator import Point def make_gaussian_blob(width, height): """Make a Gaussian Blob with float values in range 0..1""" x, y = np.meshgrid(np.linspace(-1, 1, width), np.linspace(-1, 1, height)) d = np.sqrt(x * x + y * y) blob = np.exp(-(d ** 2)) return blob def ...
point.positions[x_names[0]] y = point.positions[y_names
[0]] elif names: # Otherwise use what we have x = point.positions[names[0]] y = point.positions[names[-1]] else: # No points, make something up x = 0 y = 0 # Return a value between 0 and 1 based on a function that gives interesting # pattern on x and y in ...
fbradyirl/home-assistant
homeassistant/components/ign_sismologia/__init__.py
Python
apache-2.0
36
0
"
""The ign_sismologia component
."""
pgjones/nusoft
packages/hyperk/wcsim_dev.py
Python
mit
3,401
0.007351
#!/usr/bin/env python # # WCSimDev # # The HyperK WCSim development version # # Author P G Jones - 2014-06-20 <p.g.jones@qmul.ac.uk> : New file. #################################################################################################### import nusoft.package.local as local_package import os import nusoft.envfi...
:type system: :class:`nusoft.system.System` instance :param repository: local name of the repository the package is from """ super(WCSimDev, self).__init__("wcsim-dev", syst
em, repository) self._root = "root_v5.34.10" self._geant4 = "geant4.9.4.p04" self._clhep = "clhep-2.1.0.1" def get_dependencies(self): """ Return a list of dependency names :returns: list of dependency package names :rtype: list """ return ["make", "g...
whutch/atria
tests/core/test_pickle.py
Python
mit
3,789
0
# -*- coding: utf-8 -*- """Tests for pickle serialization and storage.""" # Part of Clockwork MUD Server (https://github.com/whutch/cwmud) # :copyright: (c) 2008 - 2017 Will Hutcheson # :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt) from os.path import exists, join from shutil import rmtree i...
om a pickle store.""" assert exists(self.pickle_path) assert self.store._h
as("test") self.store._delete("test") assert not exists(self.pickle_path) assert not self.store._has("test")
ufjfeng/leetcode-jf-soln
python/211_add_and_search_word-data_structure_design.py
Python
mit
2,445
0.001227
""" Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. For example: addWord("bad") addWord("dad") ...
def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ return self.searchTail(word, self.root) # Your WordDictionary object will be i...
'dad') a.addWord('mad') print(a.search("pad")) print(a.search("bad")) print(a.search(".ad")) print(a.search("b.."))
hirofumi0810/tensorflow_end2end_speech_recognition
models/recurrent/layers/batch_normalization.py
Python
mit
1,447
0.003455
#! /usr/bin/env python # -*- coding: utf-8 -*- import tensorflow as tf def batch_norm(inputs, name_scope, is_training, epsilon=1e-3, decay=0.99): with tf.variable_scope(name_scope): size = inputs.get_shape().as_list()[1] gamma = tf.get_variable( 'gamma', [size], initializer=tf.consta...
zer(0.1)) # beta = tf.get_variable('beta', [size], initializer=tf.constant_initializer(0)) beta = tf.get_variable('beta', [size]) pop_mean = tf.get_variable('pop_mean', [size], initializer=tf.zeros_initializer(), trainable=False) pop_var = tf.get_varia...
initializer=tf.ones_initializer(), trainable=False) batch_mean, batch_var = tf.nn.moments(inputs, [0]) train_mean_op = tf.assign( pop_mean, pop_mean * decay + batch_mean * (1 - decay)) train_var_op = tf.assign( pop_var, pop_var * decay + batch...
opalytics/opalytics-ticdat
ticdat/testing/testmodel.py
Python
bsd-2-clause
10,941
0.016452
from ticdat import TicDatFactory, Model, utils from ticdat.model import cplex, gurobi, xpress from ticdat.testing.ticdattestutils import dietSolver, nearlySame, netflowSolver from ticdat.testing.ticdattestutils import fail_to_debugger, flagged_as_run_alone import unittest import os import inspect def _codeFile() : ...
actory = TicDatFactory( my_draft = [['Player Name'], ['Draft Position', 'Position', 'Planned Or Actual', 'Starter Or Reserve']]) dat = dataFactory.sql.create_tic_dat_from_sql(os.path.join(_codeDir(), sqlFile
), freeze_it=True) assert dataFactory.good_tic_dat_object(dat) assert not dataFactory.find_foreign_key_failures(dat) assert not dataFactory.find_data_type_failures(dat) expected_draft_position = {} # for our purposes, its fine to assume all those drafted by someone else are drafted # prior to...
F5Networks/f5-openstack-heat-plugins
test/functional/f5_sys_iappservice/test_sys_iappservice.py
Python
apache-2.0
3,853
0.00026
# Copyright 2015-2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
u), a server image with a node server # pre-installed and networks. def itest_create_complete_lb_deploy(HeatStack, mgmt_r
oot): hc, stack = HeatStack( os.path.join(TEST_DIR, 'lb_deploy.yaml'), 'lb_deploy_test', parameters={ 'bigip_ip': symbols.bigip_ip, 'bigip_un': symbols.bigip_un, 'bigip_pw': symbols.bigip_pw }, teardown=False ) assert mgmt_root.tm.s...
rago1/arXiv-text-extracter
test_extractTextFromTex.py
Python
gpl-3.0
10,998
0.020276
from arXivExtracter.extractTextFromTex import extractText, compileRegex, sortArgs from xml.dom import minidom import unittest import os class TestSortArgs(unittest.TestCase): def testDefault(self): self.assertEqual(sortArgs([]), (False,[],["word","hword"],False,False,False,False), ...
tputFile(self): self.assertEqual(sortArgs(["--output", "/Users/paolo/Desktop/output.txt"]), (False,[],["word","hword"],False,False, "/Users/paolo/Desktop/output.txt", False)) def testOutputFileIncorrectUsage(self): self.assertEqual(sortArgs(["--out...
sktop/output.tex", "/Users/paolo/Desktop/output.tex")) def testInputFile(self): self.assertEqual(sortArgs(["/Users/paolo/Desktop/file.tex"]), (False,[],["word","hword"],False,False,False, "/Users/paolo/Desktop/file.tex")) def testErrorInlineMath(self)...
jlconnor/wsgistack
wack/http/__init__.py
Python
mit
62
0
# -*- coding: utf-8 -*- # Copyright © 2008-2011 Varyant, LL
C
lonelyjoeparker/real-time-phylogenomics
wales_analyses/phylogenome_wales/SNAP-predicted/parse_SNAP_genes_to_TAIR.py
Python
gpl-2.0
5,878
0.019394
# To implement this: # Load the list of TAIR genes to use as keys # For each BLAST hit: # parse subject gene # parse query up to _Basecall as read_UID, compare to current_read_UID + subject gene # parse length (ignore if length < X) for e.g. X = 500? # if we've not seen this gene subject/read combo, inc...
reads_by_gene[k], '[_]', len(reads_by_gene[k]) # recall that reads_by_gene is a list of read UIDs e.g. set(['2f32fe5f-7f51-4455-b5c7-71a8dfc
f8880', '3df2b437-f55b-4d11-9187-f50728cc10c5']) etc for read in reads_by_gene[k]: read_alignment = k + read if read in times and read_alignment in blast_results: read_channel_info = times[read][1].split("_") # may as well output read and channel #s as clean ints while we're here print "%s\t%s\t%s\t%s\t%s\t%...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/aio/operations/_web_application_firewall_policies_operations.py
Python
mit
20,812
0.004949
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
ion policies within a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either WebApplicationFirewallPo...
sponse) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_11_01.models.WebApplicationFirewallPolicyListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.WebApplicationFirewallPolicyListResult"] ...
MKLab-ITI/news-popularity-prediction
news_popularity_prediction/datautil/common.py
Python
apache-2.0
2,435
0.000821
__author__ = 'Georgios Rizos (georgerizos@iti.gr)' import os import inspect import multiprocessing try: import cPickle as pickle except ImportError: import pickle import news_popularity_prediction def get_package_path(): """ Returns the folder path that the package lies in. :return: folder_path...
rows. """ with open(file_path, encoding=encoding) as file_object: for line in file_object: words = line.strip().split(separator) yield words def store_pickle(file_path, data): """ Pickle some data to a given path. :param file_path: Tar
get file path. :param data: The python object to be serialized via pickle. :return: None """ pkl_file = open(file_path, 'wb') pickle.dump(data, pkl_file) pkl_file.close() def load_pickle(file_path): """ Unpickle some data from a given path. :param file_path: Target file path. ...
briney/abstar
abstar/utils/basespace.py
Python
mit
11,356
0.003963
#!/usr/bin/python # filename: basespace.py # # Copyright (c) 2015 Bryan Briney # License: The MIT license (http://opensource.org/licenses/MIT) # # 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...
s = self.api.getSamplesByProject(project_id, queryPars=query_params) if not s: break samples.extend(s) offset += 1 return samples def _get_files(self): files = [] samples = self._get_samples(self.project_id) for sample in sample...
files.extend(self.api.getFilesBySample(sample.Id, queryPars=self.params)) return files def download(self, direc): if all([self.project_id is None, self.project_name is None]): self.project_id, self.project_name = self._user_selected_project_id() files = self._get_files(...
daniel2101/fleosa
fleosa/report/__init__.py
Python
gpl-3.0
1,219
0.000821
# -*- coding: utf-8 -*- ############################################################################## # # Desarrollado por rNet Soluciones # Jefe de Proyecto: Ing. Ulises Tlatoani Vidal Rieder # Desarrollador: Ing. Salvador Daniel Pelayo Gómez. # Analista: Lic. David Padilla Bobadilla # ###################...
ore details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.g
nu.org/licenses/>. # ############################################################################## import report_cp
vinodc/evernote
src/evernote/edam/userstore/constants.py
Python
bsd-2-clause
199
0.005025
# # Autogenerated by Thrift # # DO NOT EDIT UNLESS YOU ARE SURE THA
T YOU KNOW WHAT YOU ARE DOING # from thrift.Thrift import * from ttypes impo
rt * EDAM_VERSION_MAJOR = 1 EDAM_VERSION_MINOR = 20
andreasjansson/head-in-the-clouds
headintheclouds/__init__.py
Python
gpl-3.0
1,735
0.003458
import sys import re import collections from fabric.api import * # pylint: disable=W0614,W0401 import fabric.api as fab env.disable_known_h
osts = True env.node_providers = {} env.providers = {} env.roledefs = collections.defaultdict(list) env.name_prefix = getattr(env, 'name_prefix', 'HITC-') # hack tocheck if the user has provided -H option _has_hosts_option = bool(env.host
s) def add_provider(name, module): for node in module.all_nodes(): if not node.get('ip', None): continue ip = node['ip'] role = re.sub('-[0-9]+$', '', node['name']) env.roledefs[role].append(ip) if env.roles: if role in env.roles: en...
jgmanzanas/CMNT_004_15
project-addons/vt_flask_middleware/app.py
Python
agpl-3.0
289
0
# -*- coding: utf-8 -*- """ Main application object and sha
red configuration. Contains singleton objects that need to be imported by se
veral modules. """ from flask import * # # Create and configure the application object. # app = Flask(__name__) app.config.from_object('config.Config')
bitcoin-hivemind/hivemind
qa/rpc-tests/python-hivemindrpc/setup.py
Python
mit
622
0.001608
#!/usr/bin/env pyt
hon2 from distutils.core import setup setup(name='python-hivemindrpc', version='0.1', description='Enhanced version of python
-jsonrpc for use with Hivemind', long_description=open('README').read(), author='Jeff Garzik', author_email='<jgarzik@exmulti.com>', maintainer='Jeff Garzik', maintainer_email='<jgarzik@exmulti.com>', url='http://www.github.com/jgarzik/python-hivemindrpc', packages=['hivemindrp...
andrewalexander/cloud-custodian
c7n/commands.py
Python
apache-2.0
9,335
0.000321
# Copyright 2016 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
esource: { category: resource_mapping[resource][category]}} print(yaml.safe_dump(output)) return # # Handle item #
item = components[2].lower() if item not in resource_mapping[resource][category]: print('{} is not in the {} list for resource {}'.format( item, category, resource), file=sys.stderr) sys.exit(2) if len(components) == 3: cls = resource_mapping[resource]['classes'][category][...
vsoch/expfactory-python
expfactory/battery.py
Python
mit
18,863
0.013784
''' battery.py: part of expfactory package Functions to generate batteries ''' from expfactory.vm import custom_battery_download, get_jspsych_init, get_stylejs from expfactory.experiment import get_experiments, load_experiment from expfactory.utils import copy_directory, get_template, \ sub_template, get_installd...
will create a battery from a template and list of experiments :param battery_dest: is the output folder for your battery. This folder MUST NOT EXIST. If not specified, a temp directory will be used :param battery_repo: location of psiturk-battery repo to use as a template.
If not specified, will be downloaded to a temporary directory :param experiment_repo: location of a expfactory-experiments repo to check for valid experiments. If not specified, will be downloaded to a temporary directory :param experiments: a list of experiments, meaning the "exp_id" variable in the config.jso...
ZachOhara/Project-Euler
python/p011_p020/problem011.py
Python
gpl-3.0
1,427
0.034338
from common import fileio def main(): ADJ = 4 fileio.FILE_ADDRESS = "../../res/problem011/grid.txt" matrix = fileio.readFileAsMatrix() products = [] products.extend(checkVertical(matrix, ADJ)) products.extend(checkHorizontal(matrix, ADJ)) products.extend(checkDiagonal(matrix, ADJ)) products.extend(checkReverse...
product *= matrix[i + pos][j + pos] productList.append(product) return productList def checkReverseDiagonal(matrix, adj): productList = [] for i in range(len(matrix) - 1, -1, -1): for j in range(len(matrix[i]) - adj): product = 1 for pos in range(adj): product *= matrix[i - pos][j + pos] produc...
product = 1 for col in range(adj): product *= matrix[i][j + col] productList.append(product) return productList if __name__ == '__main__': main()
googleapis/python-bigtable
samples/quickstart/main.py
Python
apache-2.0
1,868
0.001606
#!/usr/bin/env python # Copyright 2018 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...
ASIS, # 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. # [START bigtable_quickstart] import argparse from google.cloud import bigtable def main(project_id="project-id", instance_id="insta...
bigtable.Client(project=project_id) # Connect to an existing Cloud Bigtable instance. instance = client.instance(instance_id) # Open an existing table. table = instance.table(table_id) row_key = "r1" row = table.read_row(row_key.encode("utf-8")) column_family_id = "cf1" column_id = ...
wazo-pbx/xivo-tools
bus-tools/generate-new-tenant-event.py
Python
gpl-3.0
2,518
0.000794
#!/usr/bin/env python3 # Copyright 2020-2021 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later import kombu import os import requests import urllib3 from argparse import ArgumentParser from wazo_auth_client import Client as AuthClient from xivo_bus.resources.auth.events import Tenan...
'name': event.name, 'origin_uuid': os.getenv('XIVO_UUID'), 'data': event.marshal(), } producer.publish(event_data, routing_key=event.routing_key) def _build_event(tenant_uuid, tenant): body = {'uuid':
tenant_uuid, 'name': tenant['name']} # The slug was not in the body of a tenant before 21.04 slug = tenant.get('slug') if slug: body['slug'] = slug return TenantCreatedEvent(**body) def _get_tenants_infos(tenants): config = _load_config() auth_client = AuthClient(**config['auth']) ...